text:
Q: Why is my function not reaching this forEach loop? I am trying to add to my firestore database when a user signs up, but for some reason the code simply isn't reaching the forEach loop. I've tried adding a bunch of logging as you can see below. The logs show that it reached console.log('_createUser: 1.1'); but it never reaches console.log('_createUser: 2');. Why isn't it doing the forEach loop?
Note - the function finishes with status code 200.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
// import { error } from 'firebase-functions/lib/logger';
admin.initializeApp();

exports.createUser = functions.https.onCall(async (data, context) => {
  console.log('_createUser: ');
  const uid = context?.auth?.uid;
  if (uid) {
    const username = data.user;
    const email = data.email;
    console.log('_createUser: 1');
    //Check to see if that username already exists
    const qData = await admin.firestore().collection('users').where('username', '==', username).limit(1).get();
    console.log('_createUser: 1.1');
    qData.forEach(doc => {
      console.log('_createUser: 2');
      const otherUsername = doc.get('username').toString();
      if (otherUsername) {
        console.log('_createUser: Username is already in use.');
        return 'Username is already in use.'
      }
      else {
        console.log('_createUser: 3');
        //Create collection for this user's friends list
        const friendsColl = 'friends_' + uid;
        const friendsDoc = admin.firestore().collection(friendsColl).doc();
        friendsDoc.set({
          //Forces the collection to exist
          exists: 1,

          //Other useful data
          createDate: admin.firestore.FieldValue.serverTimestamp(),
          modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
          ownerUsername: username,
          ownerUID: uid, //
          rowType: 'B', //N = normal, B = backend (created for server side reasons)
        })
        .then(() => {
          console.log("Document successfully written!");
        })
        .catch((error) => {
          console.error("Error writing document: ", error);
        });
        console.log('_createUser: 4');
        const userDoc = admin.firestore().collection('users').doc(uid); // use uid as document ID
        userDoc.set({
          createDate: admin.firestore.FieldValue.serverTimestamp(),
          modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
          username: username,
          email: email,
          stat: 1, //0 = banned, 1 = normal
          uid: uid,
          friendsColl: friendsColl,
        })
        .then(() => {
          console.log("Document successfully written!");
        })
        .catch((error) => {
          console.error("Error writing document: ", error);
        });
        return console.log('_createUser_finished');
      };
    });
  }
  else {
    return console.log('_createUser_Error: User is not authorized');
  };
});

A: The qData object is a QuerySnapshot. The documents returned by the query can be accessed from the docs property. So, you need to update qData.forEach(doc => { to qData.docs.forEach(doc => {.
Just curious, why not use a Firebase Auth trigger function for this? You can write a function that would run each time a user is created, without having to do anything on your end. Take a look at this.

A: Because you don't resolve Promise. Use this format.
qData.then(snap => {
  snap.forEach(doc=>{
  ...
  })
})

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
// import { error } from 'firebase-functions/lib/logger';
admin.initializeApp();

exports.createUser = functions.https.onCall(async (data, context) => {
  console.log('_createUser: ');
  const uid = context?.auth?.uid;
  if (!uid) {
    console.log('_createUser_Error: User is not authorized');
    return
  }
  const username = data.user;
  const email = data.email;
  console.log('_createUser: 1');
  //Check to see if that username already exists
  const qData = await admin.firestore().collection('users').where('username', '==', username).limit(1).get();
  console.log('_createUser: 1.1');
  qData.then(snapShot => {
    snapShot.forEach(doc => {
      console.log('_createUser: 2');
      const otherUsername = doc.get('username').toString();
      if (otherUsername) {
        console.log('_createUser: Username is already in use.');
        return 'Username is already in use.'
      }
      else {
        console.log('_createUser: 3');
        //Create collection for this user's friends list
        const friendsColl = 'friends_' + uid;
        const friendsDoc = admin.firestore().collection(friendsColl).doc();
        friendsDoc.set({
          //Forces the collection to exist
          exists: 1,

          //Other useful data
          createDate: admin.firestore.FieldValue.serverTimestamp(),
          modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
          ownerUsername: username,
          ownerUID: uid, //
          rowType: 'B', //N = normal, B = backend (created for server side reasons)
        })
        .then(() => {
          console.log("Document successfully written!");
        })
        .catch((error) => {
          console.error("Error writing document: ", error);
        });
        console.log('_createUser: 4');
        const userDoc = admin.firestore().collection('users').doc(uid); // use uid as document ID
        userDoc.set({
          createDate: admin.firestore.FieldValue.serverTimestamp(),
          modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
          username: username,
          email: email,
          stat: 1, //0 = banned, 1 = normal
          uid: uid,
          friendsColl: friendsColl,
        })
        .then(() => {
          console.log("Document successfully written!");
        })
        .catch((error) => {
          console.error("Error writing document: ", error);
        });
        return console.log('_createUser_finished');
      };
    })
  })
})


text:
Q: SQL query (if column contains certain value move it to another column) I'm relatively new to sql, so forgive me if my explanation isn't too clear. The column "invoice date week id" in the picture below shows in what week of a specific quarter a purchase was made. What I would like to do is this:
I would like to export all instances of W11,W12,and W13 into a new column called last3weeks. In other words, if the column contains week 11(W11), week 12(W12), and week 13(W13), then move it to a new created column called 'last3weeks'.
enter image description here

A: I recommend using Sql IF THEN ELSE statement.
here's an example for that,
CREATE FUNCTION IncomeLevel ( monthly_value INT )
RETURNS varchar(20)

BEGIN

   DECLARE income_level varchar(20);

   IF monthly_value <= 4000 THEN
      SET income_level = 'Low Income';

   ELSEIF monthly_value > 4000 AND monthly_value <= 7000 THEN
      SET income_level = 'Avg Income';

   ELSE
      SET income_level = 'High Income';

   END IF;

   RETURN income_level;

END; //

you will just need to put on the condition you want ( W11 || W12 || W13 ) and set the value to a new column you can design by "as".

redpajama_set_name: RedPajamaStackExchange


text:
Q: barcode ending in line-break intermittent I'm currently building an application that will be making use of barcodes, but the scans are behaving a little strangely and sometimes ending in a line break and sometimes not, so 4 scans of ABC123 might scan into
ABC123
ABC123ABC123
ABC123
Any ideas how to make it consistent at all? I can't find anything about it online and it's proving to be more of a pain than i'd hoped.
Symbology used is Code39
Edit: should add that ideally it will end in a carriage return every time


text:
Q: How to access store in the mounted() method with NUXT.js? I am working on my NUXT.js project with Open Street Map and I want to access store in the mounted() method. I received error that store is not defined in the mounted() method namespace. How can I access it?
@/assets/js/utils.js
const utils = {

//...

updateMap(context) {
    let _context = context;

    const checkMapObject = setInterval(() => {
      if (_context.$refs.map) {
        _context.map = _context.$refs.map.mapObject;
        clearInterval(checkMapObject);

        //console.log(_context.map);

        if (process.browser) {
          L = require('leaflet');
          console.log("MAP OBJECT INITED");

          delete L.Icon.Default.prototype._getIconUrl;

          L.Icon.Default.mergeOptions({
            iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
            iconUrl: require('leaflet/dist/images/marker-icon.png'),
            shadowUrl: require('leaflet/dist/images/marker-shadow.png'),
          });

          for (let marker of this.getMapMarkers(_context.store.state.pollingStations)) {
            L.marker(marker).addTo(_context.map)
          }
        }
      }
    }, 100);
  },

// ...

}

export default utils;

index.vue
<template>
   ...
</template>

<script>

...

import utils from '@/assets/js/utils'

export default {
  // ...

  mounted() {
    utils.updateMap(this)
  },

  // ...
}
</script>

And I have received this error:
Uncaught TypeError: Cannot read property 'state' of undefined

A: *

*First of all, you shall be able to read from its Vue component instance in mounted(). such as

mounted() {
  this.$store;
}

*But the problem is this.$store is not guaranteed to be available at the time of mounted() being called.

While i am still figuring it out, I debug and notice that this.$store is not immediately available but will be available after certain time of mounted.

As of today, there is no official documentation that I could found describing at what point Vuex will be ready in the lifecycle. But I think fetch and its state  looks promising. I will try and report back.

A: As $store is not enable immediately and you can't determine it, you can test it and us it only when available using this :
mounted() {
    while (!this.$store) {
      // Do nothing
    }
    this.$store.commit('xxxx/xxx');
},

*

*The while loop will loops again and again untill this.$store is not resolved to undefined anymore.

*As the while loop is not looping anymore, the this.$store.commit('xxxx/xxx'); line will be executed !!

With the help of this little trick, I can use this.$store as soon as it is available, directly with the help of the mounted method.


text:
Q: No service for type 'Type' has been registered I have a database context that I am registering and seeding. However, I get the error:

System.InvalidOperationException: 'No service for type
'AnnouncementContext' has been registered.'

DB registering/seeding
private static void SeedDatabase(IHost host)
        {
            var scopeFactory = host.Services.GetRequiredService<IServiceScopeFactory>();
            using var scope = scopeFactory.CreateScope();
            var announcementContext = scope.ServiceProvider.GetRequiredService<AnnouncementContext>(); // exception occurs here

            if (announcementContext.Database.EnsureCreated()) {
                try {
                    SeedData.Initialize(announcementContext);
                }
                catch (Exception ex) {
                    var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "A database seeding error occurred.");
                    ErrorLogger.logError(ex);
                }
            }
        }

Context class
public class AnnouncementContext : DbContext {
        public AnnouncementContext(DbContextOptions<AnnouncementContext> options)
            : base(options) {
        }

        public DbSet<Announcement> Announcements { get; set; }
    }

What is causing this error and how can I fix it?

A: The code in your DB registering/seeding section is not registering any DB or DbContext. It is trying to get a reference of already registered DbContext (in your case AnnouncementContext). So, the question is, have you already registered it? The error message indicates, you have not.
In most common scenario, you are supposed to register the AnnouncementContext in the ConfigureServices() method of the Startup class like -
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    // this is the DbContext registration code
    services.AddDbContext<AnnouncementContext>(
        options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));
}

For more on this - DbContext in dependency injection for ASP.NET Core


text:
Q: What are the chances that a Wither will drop a Nether Star? I have been thinking about battling the Wither. Are the drop chances of a Nether Star 100% or should I reconsider the fight?

A: The Wither drops one star upon death and there is a 100% chance that is will do so.

A: If you kill the Wither, it is guaranteed to drop one Nether Star and some XP. From the Minecraft Wiki page for the Wither:

Drops
The wither drops 1 nether star upon death. The Looting enchantment does not work on the wither. It drops 50 experience when killed by a player or tamed wolf.


text:
Q: Adding Objects to a List, cant assign to Add because it is a group method Currently getting an error with the below code, and I don't know how to fix it!
This is the error:
Cannot assign to 'Add' because it is a 'method group'
Here is my App.xaml.cs:
public partial class App : Application
{
    //Public list of users and form can access
    List<User> LoggedUsers = new List<User>();

    //First startup of the application
    public void Application_Startup(object sender, StartupEventArgs e)
    {
        //First startup, display the login form
        LoginWindow FirstLogin = new LoginWindow();
        FirstLogin.ShowDialog();

        //If the login form was closed properly, handle the user
        if (FirstLogin.DialogResult == true)
        {
            //Add the user to the list of logged users
            User returned = FirstLogin.returnUser;

            //Create temp duplicate for testing
            User tmp = new User();
            tmp.Email = "email@gmail.com";
            tmp.FirstName = "John";
            tmp.LastName = "Johnson";
            tmp.ID = "01";
            tmp.Permissions = 1;

            LoggedUsers.Add = tmp;
            LoggedUsers.Add = returned;
        }
    }
}

And here is my LoginWindow.xaml.cs which the User Object is returned from when closed (returned):
//Give App access to user object outside of this form
public User returnUser
{
    get
    {
        return user;
    }
}

//Public user object, start empty
User user = new User();

//Check the login
private void doLogin(string username, string password)
{
    //User logged in, add data to user object
    user.Email = "email@gmail.com";
    user.FirstName = "John";
    user.LastName = "Johnson";
    user.ID = "01";
    user.Permissions = 1;

    //Close the form with dialog result "true"
    this.DialogResult = true;
    this.Close();
}

And the class, incase you need that:
//Logged in users class
Public Class User
{
    public string ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public Int16 Permissions { get; set; }
}

Adding a duplicate object to the List for some testing purposes when I have fixed this.

A: List.Add() is a method not a property:
LoggedUsers.Add(tmp);
LoggedUsers.Add(returned);


text:
Q: Deploy multiple apps with "shared private" Qt frameworks on OS X I have a set of applications that work together. It should be possible to start each of these applications individually by the user (i.e. one application provides a monitoring feature, another a configuration feature etc), therefore I would like them to show up in the Applications folder as different applications (possibly within a directory).
The applications are based on Qt5, so I would like to package Qt along with the applications privately to ensure that Qt is present and available. On the other hand I would like to make sure that I only include a single copy of Qt to avoid bloating the system.
I am using a package installer, due to the inclusion of a LaunchDaemon as well.
How do I place the Qt frameworks needed in order to avoid having multiple copies?
Here's the naive way:
/Applications/
    MyCompany/
        Foo.app/
            Contents/
                Info.plist (must use its own plist to specify some properties)
                MacOS/
                    foo
                Frameworks/
                    Qt-Goes-Here??
        Bar.app/
            Contents/
                Info.plist
                MacOS/
                    bar
                Frameworks/
                    Qt-Goes-Here?? - Or can this be a link to the other location?

Since I am not a Mac-guru, any input (including informing me that I am trying something stupid) is very welcome!

A: There are two possibilities here, the first is
/Library

and the second
/Library/Application Support

If you look there, you'll find folders with contents for various applications. You should be able to create a folder there and add the Qt Framework, then update your applications to point to that using install_name_tool
The docs state the following for /Library: -

The Library directory is the top-level directory for storing private
  app-related data and preferences. There are several Library
  directories scattered throughout the system but you should always use
  the one located inside the current home directory. Do not store files
  directly at the top-level of the Library directory. Instead, store
  them in one of the specific subdirectories described in this table. In
  OS X v10.7 and later, the Finder hides the Library directory in the
  user's home folder by default. Therefore, you should never store files
  in this directory that you want the user to access. To get the path to
  this directory use the NSLibraryDirectory search path key with the
  NSUserDomainMask domain.

For /Library/Application Support: -

The Application Support directory is where your app stores any type of
  file that supports the app but is not required for the app to run,
  such as document templates or configuration files. The files should be
  app-specific but should never store user data. This directory is
  located inside the Library directory. Never store files at the top
  level of this directory: Always put them in a subdirectory named for
  your app or company. If the resources apply to all users on the
  system, such as document templates, place them in /Library/Application
  Support. To get the path to this directory use the
  NSApplicationSupportDirectory search path key with the
  NSLocalDomainMask domain. If the resources are user-specific, such as
  workspace configuration files, place them in the current user's
  ~/Library/Application Support directory. To get the path to this
  directory use the NSApplicationSupportDirectory search path key with
  the NSUserDomainMask domain.

The full documentation can be found here.


text:
Q: How to write sum query in jpa? i have a query in mySql that i want to write in my controller.
SELECT sum(`column`='value') ,b.`date`  FROM table b WHERE b.user= 'user1' and b.`date` between '2019-07-21' and '2019-07-26' group by b.`date`

this is the equivalent in jpa
@Transactional
@Modifying
@Query("SELECT sum(column='value') ,b.date  FROM myclasse b WHERE b.user= :user and b.date between :dt1 and :dt2 group by b.date")
    List<Object[]> function( String user,@Param("dt1")Date dt1,@Param("dt2")Date dt2);

i expect the same result as phpmyadmin result but i get this error:

Caused by: java.lang.IllegalArgumentException:
  org.hibernate.hql.internal.ast.QuerySyntaxException: expecting CLOSE,
  found '=' near line 1, column 23 [SELECT SUM(column='value') ,b.date
  FROM com.project.Myclass b WHERE b.user= :user and b.date between :dt1
  and :dt2 group by b.date]     at
  org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
  ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]   at
  org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
  ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]   at
  org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
  ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]   at
  org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:729)
  ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]   at
  org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
  ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]   at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  ~[na:1.8.0_161]   at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  ~[na:1.8.0_161]   at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  ~[na:1.8.0_161]   at java.lang.reflect.Method.invoke(Unknown Source)
  ~[na:1.8.0_161]   at
  org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350)
  ~[spring-orm-5.1.8.RELEASE.jar:5.1.8.RELEASE]     at
  com.sun.proxy.$Proxy118.createQuery(Unknown Source) ~[na:na]  at
  org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:87)
  ~[spring-data-jpa-2.1.9.RELEASE.jar:2.1.9.RELEASE]    ... 76 common
  frames omitted

A: Replace the boolean expression with a CASE expression:
SELECT
    b.date,
    COUNT(CASE WHEN some_col = 'some_value' THEN 1 END) AS cnt
FROM table_b b
WHERE b.user = 'user1' AND b.date BETWEEN '2019-07-21' AND '2019-07-26'
GROUP BY b.date;

The syntax sum(column = 'value') is particular to MySQL (and maybe a few other databases, such as Postgres), but does not appear to be supported by JPA.


text:
Q: too many fields in an android activity I have searched a lot for this but doesn't find anything helpful. My question is I have about 13 textviews with text fields as given below. I want them to be in one activity so the user can scroll down to fill all the fields. Help me how to handle this.
Name
Organization
Country
City
Contact#
Address
Zip
Amount
Duration
Card#
Currency
Expiry Date

A: The XML layout you are looking for is the <ScrollView> although it can have one and only one child element. This means that you will wrap your <Linear/RelativeLayout> in the <ScrollView> so that your xml will resemble:
<ScrollView>
     <LinearLayout> <!-- or <RelativeLayout> -->
          <!-- all of your textviews and edit texts, etc. -->
     </LinearLayout>
<ScrollView>

A: I would use a scrollview with the textviews in it so that the user can scroll down to see the rest of the information

A: What about using <ScrollView>?
You just have to surround the part of your UI you want to be scrollable in the xml with a ScrollView element...
http://developer.android.com/reference/android/widget/ScrollView.html


text:
Q: Auto hide feature for collapsable pane I want to integrate auto-hide logic to my collapsable pane. Do you know how to do that in JavaFX? Any small example will work for me. I can integrate into my code.
I know the controlFX code but it will be hard to integrate that code in my existing code.
So if you know any small standalone example please share it with me.
Kind Regards,


text:
Q: How to know when element has been scrolled to the bottom According to the first answer to the question at Stackoverflow, it can be known when element.innerHeight + element.scrollTop is greater than or equal to element.offsetHeight. Shouldn't it be element.innerHeight + element.scrollTop is greater than or equal to element.scrollHeight? offsetHeight just includes the padding while calculating the visible height, what we want here is to find whether the scrolled height plus the visible height equals the total height, isn't the total height given by scrollHeight?

A: In general, yes. However, that question is about the page specifically, and the <body> element doesn't actually scroll; the viewport does.
Try it out: make sure this page scrolls, then open a console:
> document.body.offsetHeight === document.body.scrollHeight
true


text:
Q: I can't find libtool command on my MacOSX,10.7.x I can't find libtool command.I tried to run $man libtool,Terminal returned "No manual entry for libtool"
So I tried to download libtool from GNU site and install it... Still I can't find the libtool command.
Any help would be appreciated.

A: If you actually successfully compiled libtool, did you do the following:
./configure --prefix=/usr
make
make install

I otherwise can highly recommend using homebrew to install any standard library that did not come with Mac OS X: http://brew.sh
After setting it up, you could install libtool by typing:
brew install libtool

A: maybe this work
I find my libtool within the following path
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool


text:
Q: Upgrading to MySQL 5.7.15 crashes on Ubuntu 16.04 Last night I tried to upgrade my Ubuntu OS and MySQL 5.7.15 was one of the changes. It seems upgrading is successfull because mysql is propely working, but installation proccess has stop working with this message:
This installation of MySQL is already upgraded to 5.7.15,
use --force if you still need to run mysql_upgrade

I can't cancel the installation proccess in reqular way and just have to kill it. So it may cause some problem and also for every other installation (in the future) it tries to do it again.
How to prevent this upgrade or solve it?

A: I managed to fix this without having to purge everything. It seems the problem is that the sys schema database was never created, so here's the solution:

*

*Clone https://github.com/mysql/mysql-sys and cd into the cloned folder.

*In a terminal, run mysql -u root -p < ./sys_57.sql (or sys_56.sql, depending on your version)

Enjoy mysql_upgrade working again. I guess this probably was, an upgrading scripts mess-up.

A: If your root@localhost account has no password then there is a bug in the postinstall process as stated here
(see particularly the last comment of the thread)

*

*purge all TMP* files in /var/lib/mysql-files

*edit the file /var/lib/dpkg/info/mysql-server-5.7.postinst and comment (using #) the line 370 :
echo "ALTER USER 'root'@'localhost' IDENTIFIED WITH 'auth_socket';" >> "$initfile"

*run again sudo dpkg --configure -a

A: I had this issue too. Every time I started apt get and installed the process would hang after or during the DB update. None of the other solutions here worked.
In the end I purged
sudo apt purge mysql-server mysql-server-5.7

And followed the manual install from the instructions for mysql here
I then overwrote the data directory with my old data
sudo cp -Rfv /var/lib/mysql /usr/local/mysql/data

and finally added a systemd service like this
/lib/systemd/system/mysql.service
[Unit]
Description=MySQL Server
After=syslog.target
After=network.target

[Service]
Type=simple
PermissionsStartOnly=true
ExecStartPre=/bin/mkdir -p /var/run/mysqld
ExecStartPre=/bin/chown mysql:mysql -R /var/run/mysqld
ExecStart=/usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --plugin-dir=/usr/lib/mysql/plugin --log-error=/var/log/mysql/error.log --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock --port=3306
TimeoutSec=300
PrivateTmp=true
User=mysql
Group=mysql
WorkingDirectory=/usr

[Install]
WantedBy=multi-user.target

Then ran
# systemctl daemon-reload
# systemctl enable mysql
# systemctl start mysql

Then everything seemed to be working as before and mysql was not breaking system updates
The downside, of course, is that I'll need to do manual updates in the future.

A: This solution solved my problem:

*

*Back-up your database files with permissions:
sudo cp -avt /your/backup/directory /var/lib/mysql /etc/mysql/my.cnf

*Delete mysql files:
sudo rm -rv /etc/mysql

*Remove MySQL completely via running:
sudo apt purge mysql-server mysql-server-5.7 mysql-server-core-5.7 mysql-client-5.7 mysql-client-core-5.7

Use of Synaptic is recommended.

*Create these folders:
sudo mkdir -p /etc/mysql/conf.d

mysql setup didn't do it automatically and I don't know why.

*Install MySQL again
sudo apt install mysql-server

I used sudo apt install lamp-server^ instead to install other dependencies for PHP development.

*Stop MySQL:
sudo service mysql stop

*Restore databases and files:
sudo cp -a /your/backup/directory/mysql /var/lib
sudo cp /your/backup/directory/my.cnf /etc/mysql

*Restart MySQL:
sudo service mysql start

A: An easy solution is to sudo killall mysqld while the apt-get operation is running.
The apt operation just kept on running without any errors after that(!)


text:
Q: how i can find the number of occurrence of word in an sentence in java script i wrote an java script program that must do the following things : it must take the sentence from the text in the form and then find the number of occurrence of each word in the sentence alphabetically in table as following:
this : 5 times
the : 2 times .....and so on

but in reality my program do the following and doesn't show the result when search button clicked and if we take the function  button-pressed() lonely  it works as the following:
this :1
this :2
this:3
this:4
this:5
the:1
the:2....and so on

i want to appear the last values without the redundant values ,so any help please this is my code :

<form id = "searchForm" action = "">

The string to search is:

Enter Sentence  You Wnt To Find The Occurrence Of Each Word In It :
<input id = "inputVal" type = "text" />
<input name = "search" type = "button" value = "Search" onclick = "buttonPressed()" />

</form>

A: You can also use this:
"mijn naam is niels, niels is mijn naam".split("niels").length - 1
// Will return 2

Which will split on the word, and you will have the number of matches

A: the main problem that you're trying to output during calculation, your document.writeln statements are inside for loop
you need to move them out:
for(var i = 0; i< arr.length; i++) {
    var num = arr[i];
    counts[num] = (counts[num] ? counts[num] : 0) + 1 ;
}

document.writeln("
");
document.writeln("

Search's Results:

");
for (var i in counts) {
    document.writeln("
"+i+" :	"+counts[i]+"
");
}
document.writeln("

");

NOTE: please read about htmlencode and document.writeln functions, you're doing wrong output, as you're writing to the end of document, for your particular task is ok, but usually you need to do output into particular place on page, for this you will need to assign innerHTML of some div


text:
Q: Mongoose MongoDB updating a nested array I have the following schema and I'm trying to update the heart_rates and glucose_levels arrays by adding a new entry:
"days": [
{

    "day": "16-12-2020",
    "data": {
        "average_score": 80,
        "metabolic_score": 80,
        "cardio_score": 80,
        "heart_rates": [{
            "start_date": "timestamp",
            "end_date": "timestamp",
            "value": 100
        }],
        "glucose_levels": [{
            "start_date": "timestamp",
            "end_date": "timestamp",
            "value": 100
        }],
        "weekly_health_recap": {
            "id": "",
            "start_date": "timestamp",
            "end_date": "timestamp",
            "rating": "Excellent"
        },
        "summaries": [{
            "type": "meal",
            "actions": [
                "sweets", "fruits"
            ],
            "title": "",
            "start_date": "",
            "end_date": ""
        }],
        "articles": [{
            "id": "",
            "name": "",
            "text": "",
            "image_url": ""
        }]
    }
}
]

I tried various solutions, however they didn't give the expected results.
Currently, I'm using the following code to find if there is an existing entry for the day, if there is not, I'm creating it using findByIdAndUpdate and upsert, if there is already a day entry then I'm using update and push to add a new entry in the heart_rates array. The problem is that the update inserts the new entry in some other day entry and not the one that I'm querying for.
exports.updateDayHeartrate = async (req, res) => {
    User.find({ "_id": req.body._id, "days.day": req.body.day}, function (err, docs) {
      if (err){
          return done(err);
      }

      if (docs.length > 0) {
        User.update({"_id": req.body._id, "days.day": req.body.day},
          {$push: {"days.0.data.heart_rates": req.body.data}},
            (err, user) => {
              if (err) {
                res.status(500).send({ message: err });
                return;
              }
              else if (user) {
                res.status(200).send("Updated!")
              }
            }
        )
      }
      else{
        User.findByIdAndUpdate(req.body._id,
        {$push: {"days": {"day": req.body.day, "data": {"heart_rates": req.body.data}}}},
        {upsert:true, new:true, setDefaultsOnInsert: true},
          (err, user) => {
            if (err) {
              res.status(500).send({ message: err });
              return;
            }
            else if (user) {
              res.status(200).send("Updated!")
            }
          }
        );
      }
    });

};


text:
Q: Как настроить корректное построение маршрута на карте(MKMapKit)? Строю маршрут между двумя точками, вместо маршрута по автодороге строится маршрут напрямую.

Что нужно настроить, чтобы маршрут строился по автодороге?

A: Создаем
 MKPolyline *lines;

Пример моей корявой функции. Где latitude,longitude - куда нам нужно проложить путь, curPosition.coordinate.latitude,curPosition.coordinate.longitude - откуда.
-(void)routeGo:(double)latitude long:(double)longitude
    {
        NSArray *pointsArray = [mapview overlays];

        [mapview removeOverlays:pointsArray];
        MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(curPosition.coordinate.latitude,curPosition.coordinate.longitude) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ];

        MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];
        [srcMapItem setName:@""];

        MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(latitude, longitude) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ];

        MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destination];
        [distMapItem setName:@""];

        MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
        [request setSource:srcMapItem];
        [request setDestination:distMapItem];
        [request setTransportType:MKDirectionsTransportTypeAny];

        MKDirections *direction = [[MKDirections alloc]initWithRequest:request];

        [direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
            NSLog(@"response = %@",response);
            NSArray *arrRoutes = [response routes];
            [arrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                MKRoute *rout = obj;

                MKPolyline *line = [rout polyline];
                lines = line;
                NSLog(@"Rout Name : %@",rout.name);
                NSLog(@"Total Distance (in Meters) :%f",rout.distance);

                NSArray *steps = [rout steps];

                NSLog(@"Total Steps : %d",[steps count]);

                [steps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                    NSLog(@"Rout Instruction : %@",[obj instructions]);
                    NSLog(@"Rout Distance : %f",[obj distance]);
                }];
            }];
        }];
    }

У тебя есть выбор как проложить:
//[request setTransportType:MKDirectionsTransportTypeAny]
MKDirectionsTransportTypeAutomobile //Будто ты на автомобиле
MKDirectionsTransportTypeWalking    //Пешком
MKDirectionsTransportTypeAny

Отображаем наш путь
[self.mapview addOverlay:lines];

Прошу прощение если криво - вырвано из моей программы. Если будут вопросы или ошибки обращайся :)


text:
Q: Changing cursor speed inside a div tag I want to change the cursor speed inside some div tags, to give a better user experience in my web site. I have already changed the image of the cursor, I want to change slow down the cursor. Is there a way to do that?

A: I do not think this is possible to control the cursor with Javascript. But you could, however, hide the cursor using
cursor: none;

and then do some JavaScript to emulate a slower moving cursor made with HTML/CSS. But this would be much more work than it is worth, and probably wouldn't work out very well anyway.

A: Doing this using pure javascript might be a challenge but you can try incorporating this feature slowing down the cursor's speed while holding CTRL using the AutoHotKey script.
You need AutoHotKey installed to perform this but it's free and open-source.

A: You can't directly control the pointer speed via any DOM API, nor do I expect such an API will become available due to accessibility issues and probable click-jacking abuse.
That being said, in many modern browsers there is an API called Pointer Lock, where you can request control over pointer movements. Using this, you could emulate a slower cursor by taking over the cursor movements and positioning a fake cursor.


text:
Q: Determining whether an angle is between two given angles on the unit circle
I am trying to find a way to determine whether an angle is between two given angles where all angles are provided as vectors on the unit circle i.e.: $\mathbf{a}=(\cos(\theta),\sin(\theta))$
Note that by inbetween I mean on the arc of the smaller of the two segments of the unit circle formed by the vectors we want to check between.
Specifically I do not want to obtain the angles from the given vectors by applying the inverse trig functions I just want to work with the given vectors.
I think the following is true if and only if the angle $\mathbf{c}$ is between $\mathbf{a}$ and $\mathbf{b}$: $$|\mathbf{a} + \mathbf{b} - \mathbf{c}|\leq 1$$
but I'm having trouble proving it. Is this statement true and can you prove it?

A: It's true (except possibly for edge cases).
It is fairly obvious if you draw a diagram with two unit circles - one at the origin with vectors $\mathbf{a}$ and $\mathbf{b}$ in it, and the other unit circle centred at $\mathbf{a}+\mathbf{b}$ and which contains the vector $-\mathbf{c}$. Vectors $\mathbf{a}$ and $\mathbf{b}$ will then point to the intersections of the unit circles.
For $|\mathbf{a} + \mathbf{b} - \mathbf{c}| < 1$ to hold, the head of $-\mathbf{c}$ must lie inside the first unit circle, and this happens exactly when it lies on the circular arc between the two intersection points. Therefore by symmetry of the paralellogram the same is true for $\mathbf{c}$ when placed at the origin. Those intersection points are pointed at by $\mathbf{a}$ and $\mathbf{b}$, so $|\mathbf{a} + \mathbf{b} - \mathbf{c}| < 1$ iff $\mathbf{c}$ lies strictly between $\mathbf{a}$ and $\mathbf{b}$.

Note that you used a $\le$ sign, but you'll have to think about whether that is what you want or if strict inequality is better. Does $\mathbf{a}$ itself lie between $\mathbf{a}$ and $\mathbf{b}$? And in the case of $\mathbf{a}=-\mathbf{b}$, does every unit vector lie between them or none at all?


text:
Q: Getting name of running display server in python How could I get name in Python of the display server that is used in current Linux session?
I want to know if user uses Xorg or Wayland for example.

A: You will need an Xlib Display pointer and a way to call ServerVendor() and possibly VendorRelease().
With pygtk, you can use gdk_x11_display_get_xdisplay() to get a Display *.
Update: I stand corrected: gtkmm has a binding to this function but pygtk apparently does not.
The library still might provide access to the information returned by ServerVendor() (a quick search shows several calls but most of them seem to be used for compatibility workarounds).
Even Python-Xlib does not seem to provide a binding to ServerVendor(). You may have to write your own module.

A: I don't know precisely what this does with Wayland, but you may be able to use xdpyinfo like so:
import subprocess

p = subprocess.Popen(['xdpyinfo'], stdout=subprocess.PIPE)
for line in p.communicate()[0].split('\n'):
    if line.startswith('vendor'):
        k, v = line.split(':')
        v = v.strip()
        print "%s=%s" % (k, v)


text:
Q: C# Wrong char at the beginning of a binary file I'm trying to write a string into a binary file, everything is correct but the 2 first chars are wrong (ù.). It goes like this :
Her is the code of the function:
public static void WriteFile(string filePath, string content)
    {
        try
        {
            using (BinaryWriter binWriter = new BinaryWriter(File.Open(filePath, FileMode.Create)))
            {
                binWriter.Write(content);
            }
        }
        catch (Exception err)
        {
            Console.WriteLine(err);
        }
    }

Thanks for the help


text:
Q: Codeigniter active record " symbol How can I escape " (double quotes) with Codeignniter Acitve Record?
$query_string = 'double " quotes';
$sql = "SELECT * FROM name WHERE email LIKE "%'.$query_string.'%" ";
$query = $this->db->query($sql);

I get mysql error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%" OR email like "%"%"
Any suggestions how ti fix that

A: You can escape any character by putting a \ before it.
So \"

A: Even better, you can bind the parameters!
$query_string = '%double " quotes%';
$sql = "SELECT * FROM name WHERE email LIKE ?";
$query = $this->db->query($sql, array($query_string));


text:
Q: Toggle information pulled from MySQL with jQuery Ajax I am displaying playlists (from a MySQL db). Playlists contain films. I would like to display all films from a playlist when the playlist is clicked. When the playlist is clicked again I would like the films to fold back.
Moreover, I would like the loading icon to be displayed while the data is being downloaded from the database.
Here is the HTML/PHP for displaying playlists/films:
$i = 1;
while($pList = mysqli_fetch_array($playlists))
{
    echo "

         Playlist ".$i.": ".$pList["title"]."
";
    echo "

";
    echo "

";
    $i++;
}

and here is the script that I am currently using:
$("body").on("click", ".plist", function(e) {
    e.preventDefault();
    var clickedID = this.id.split("-");
    var pID = clickedID[1];
    //alert("Playlist clicked: " + pID);
    var myData = 'plistToView='+ pID;

    jQuery.ajax({
        type: "POST",
        url: "response.php",
        dataType:"text",
        data:myData,
        beforeSend: function(){
            $.get("preloader_JS.html", function (data) {
                $("#loaderDiv-"+pID).append(data);
            });
        },
        success:function(response){
            $("#loaderDiv-"+pID).hide()
            $('#films-'+pID).hide().append(response).slideDown();
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(thrownError);
        }
    });
});

The films are displayed correctly but I don't know how to hide them back when the playlist is clicked again.
Furthermore, I cannot get the loading icon (preloader_JS.html) working on the second playlists after I display information from the first one. (also getting the icon everytime does not seem to make sense - afterall it is the same icon, so I could just get it once and the display it from the same 'source'. Don't really know how to achieve that though.
Any help would be useful!

A: You have to somehow save state. You can do something like:
$("body").on("click", ".plist", function(e) {
 $this = $(this);
if( $this.data('visible') ){
    $this.data('visible',false)
    $this.hide();

success:function(response){
  $("#loaderDiv-"+pID).data('visible',true)
      ....
        }

A: After a little hint from @raam86 I managed to solve my problem on my own.
I stored the information about the current playlist state ($this.data('visible'))
and the information whether the films from current list have already been downloaded ($this.data('downloaded')).
Thanks for help!
here is the code:
$("body").on("click", ".plist", function(e) {
    e.preventDefault();
    var clickedID = this.id.split("-");
    var pID = clickedID[1];
    //alert("Playlist clicked: " + DbNumberID);
    var myData = 'plistToView='+ pID;

    $this = $(this);

    if($this.data('visible') ){
        $this.data('visible',false);
        $('#films-'+pID).slideUp();
    } else if ($this.data('downloaded') && (!$this.data('visible')))
    {
        $this.data('visible',true);
        $('#films-'+pID).slideDown();
    }
    else
    {
        jQuery.ajax({
            type: "POST",
            url: "response.php",
            dataType:"text",
            data:myData,
            beforeSend: function(){
                $.get("preloader_JS.html", function (data) {
                    $("#loaderDiv-"+pID).append(data);
                });
            },
            success:function(response){
                $("#loaderDiv-"+pID).hide();
                $this.data('visible',true);
                $this.data('downloaded', true);
                $('#films-'+pID).hide().append(response).slideDown();
            },
            error:function (xhr, ajaxOptions, thrownError){
                alert(thrownError);
            }
        });
    }


text:
Q: how to resolve {"rows":{"length":10},"rowsAffected":0} the problem is that the SELECT query returns this {"rows":{"length":10},"rowsAffected":0}, I specify that length is the number of occurrences that I added

//create data base end able, it work
async createDatabase(){
      await this.sqlite
      .create({
       name:'myCollecte',
       location: 'default',
     })
     .then(async (c)=>{
       this.db= c;

     })

     await this.createTable();
  }
async createTable(){

   await this.db.executeSql(`CREATE TABLE IF NOT EXISTS ${this.tables.commune} (
    idcommune INTEGER PRIMARY KEY AUTOINCREMENT, code VARCHAR(100) NOT NULL, libelle VARCHAR(100) NOT NULL)`,[])

 }
//function get all

async findAll(){
            let sql=`SELECT * FROM ${this.tables.commune} ORDER BY idcommune DESC`;
           return this.db.executeSql(sql, [])
          }

I expect a bed from my database


text:
Q: XCODE 4.6.3 & iPhone simulator v6.1 I have XCODE 4.6.3 installed but couldn't launch iPhone apps on iPhone 6.1 simulator.
It crashed every time I'm trying to debug with phrase "The simulated application quit."
I checked installed simulators and there are all up to 6.0 (4.3, 5.0, 5.1, 6.0). There is no 6.1 installed and I don't know how to install it and why it wasn't installed with XCODE 4.6.3
Thanks for any suggestions!
Alex

A: I just resolved the issue.
Go to the "~/Library/Application Support/iPhone Simulator" folder and delete 6.1 subfolder with corrupted simulator state.
Hope it'll help someone.


text:
Q: log4j StringMatchFilter configuration I want to log the message containing "Here is DEBUG"
my log4j2.xml is like this:

<Appenders>
    <!-- Console Appender -->
<Console name="console" target="SYSTEM_OUT">
    <PatternLayout pattern="%-5p %c{1} - %m%n" />
</Console>
    <!--RollingFile Appender-->
<RollingFile name="rollingFile"  fileName="${sys:catalina.base}/logs/${project.name}.log" filePattern="${sys:catalina.base}/logs/${project.name}-%i.log">
        <PatternLayout>
            <Pattern>%p %d{dd-MMMMMMMMM-yyyy HH:mm:ss:SSS} %m %n%n</Pattern>
        </PatternLayout>
        <Policies>
            <SizeBasedTriggeringPolicy size="500kb" />
        </Policies>
        <DefaultRolloverStrategy max="5" />
</RollingFile>
<filter class="org.apache.log4j.varia.StringMatchFilter">
        <param name="StringToMatch" value="Here is DEBUG" />
        <param name="AcceptOnMatch" value="true" />
</filter>
</Appenders>
<Loggers>
    <Root level="debug">
        <!--AppenderRef ref="console" /-->
        <AppenderRef ref="rollingFile" />
    </Root>
</Loggers>

and my java code is :
        log.info("Here is DEBUG");
        log.info("XXXXXXXXXXXX");
        log.warn("this is a warning");
        log.error("this is an error");
But I still got everything in the log.

A: OK I figured it out. log4j 1 and 2 are very different on the configuration. in 2, the filter should look like
<RegexFilter regex="DEBUG .*" onMatch="ACCEPT" onMismatch="DENY"/>


text:
Q: How to get values of specif tag from webpage in VB.net using WebRequest So basically i want receive data of webpage but only of specific class name elements or tag name values.

1111

2222

3333

4444

5555

From above i want all the values of tag name strong or elements of abc class.
So my output should be something like this

1111
  2222
  3333
  4444
  5555

I have created following
Dim inStream As StreamReader
Dim request As WebRequest = WebRequest.Create("url here")
Dim response As WebResponse = request.GetResponse
inStream = New StreamReader(response.GetResponseStream())
Dim str As String = inStream.ReadToEnd()
Textbox1.Text = str

but as you can see it's fetch whole page but i just want specif tag or class name elements.
Any help will be appreciated.

A: You can use the Html Agility Pack to parse HTML.
Example: (should be enough to get you started)
Dim html =

1111

2222

3333

4444

5555

Dim htmlDoc = new HtmlAgilityPack.HtmlDocument()

htmlDoc.LoadHtml(html.ToString())

For Each node In htmlDoc.DocumentNode.SelectNodes("//div[@class='abc']//strong")
    Console.WriteLine(node.InnerText.ToString())
Next

Result:

1111
2222
3333
4444
5555


text:
Q: How to use matlab to solve ordinary differential equations with coupled intermediate variables inside? I have a problem which can be simplified to the statement below (the real equations and functions are much more complicated):
System: dot_X1 = -A*X1; dot_X2 = B*(X2-5) + u;
dot_ means differentiate with time t, X1 and X2 are system states respectively, A and B are both intermediate variables, u is the system control input which can be a ramp or step input defined by myself.
I know how to use ode to solve normal similar problems when A and B and not coupled, for example, when A and B are only functions of X1, X2 and u respectively. But now in my problem, A and B are coupled, like:
A = f(X1, X2, u, B), B = g(X1, X2, u, A), f and g are very complicated functions.
Now in every time interval when solving the ode problem, for example, [0s, 0.01s], I have to calculate both A and B in order to use ode function in matlab. But since A and B are coupled and f and g are very complicated, I don't know how to deal with this.
Could you give me some help? Thanks a lot!

A: You either need to solve this coupling as a system of non-linear equations using Newton's method or a pre-packaged solver of matlab.
Or you can consider the system as a system of differential-algebraic equations
(X1',X2') = F(t,(X1,X2),(A,B),u)
        0 = G(t,(X1,X2),(A,B),u)

and use the appropriate solver packages DASSL or DAEPACK or similar. See http://www.scholarpedia.org/article/Differential-algebraic_equations


text:
Q: document.addEventListender test not working using Jest and Enzyme Example component:
class Modal extends Component {
  componentDidMount() {
    document.addEventListener('keydown', this.onEscPress, false);
  }

  componentWillUnmount() {
    document.addEventListener('keydown', this.onEscPress, false);
  }

  @bind onEscPress(event) {
    if (event.keyCode === 27) {
      this.props.onClose();
    }
  }

  render() {

...

  }
}

My test:
const closeModal = jest.fn();
const wrapper = shallow(<Modal onClose={closeModal} />);

it('executes the `onClose` function when `esc` key is pressed', () => {
  const modal = wrapper.find('.modal');
  modal.simulate('keydown', { keyCode: 27 });
  expect(closeModal).toBeCalled();
});

But my test fails because closeModal() doesn't get run...


text:
Q: Our Cocoapods library page is redirected to github page I created a new pod, and pushed it to cocoapods by issuing command,
pod trunk push AIQKit.podspec

After a while, I go to cocoapods.org, can find it by searching AIQKit. but when I tried access
https://cocoapods.org/pods/AIQKit
I was always redirected to github page even after I updated 4 versions in cocoapods.
Report
1. What did you do?
Then release our library by issuing command below,

$> git add -A && git commit -m "Release 0.9.4"

$> git tag '0.9.4'

$> git push --tags

$> pod lib lint AIQKit.podspec

$> pod trunk push AIQKit.podspec

then I got output,

 Congrats

 AIQKit (0.9.4) successfully published
 February 5th, 09:48
 https://cocoapods.org/pods/AIQKit
 Tell your friends!

2. What did you expect to happen?
When I access AIQKit page,
https://cocoapods.org/pods/AIQKit
I should see page for it.
3. What happened instead?
But reality is that I was redirected to github page
https://github.com/iqnect-org/aiqkit-ios
I can find the AIQKit from cocoapods page search, and I can use AIQKit by adding AIQKit into Podfile
4. CocoaPods Environment

    Stack
       CocoaPods : 1.4.0
            Ruby : ruby 2.3.3p222 (2016-11-21 revision 56859) [universal.x86_64-darwin17]
        RubyGems : 2.5.2
            Host : Mac OS X 10.13.3 (17D102)
           Xcode : 9.2 (9C40b)
             Git : git version 2.15.1
    Ruby lib dir : /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib
    Repositories : master - https://github.com/CocoaPods/Specs.git @ 713cb9c62547df8651141d41b306b6c42c182fdd
    Installation Source
    Executable Path: /usr/local/bin/pod
    Plugins
    cocoapods-deintegrate : 1.0.2
    cocoapods-plugins     : 1.0.0
    cocoapods-search      : 1.0.0
    cocoapods-stats       : 1.0.0
    cocoapods-trunk       : 1.3.0
    cocoapods-try         : 1.1.0
    Project that demonstrates the issue
    https://github.com/iqnect-org/aiqkit-ios

A: Finally problem was solved just correct all compiler error. So just make sure there is no any compiler error in example project before you publish


text:
Q: How do you get a shrine I was reading an article about the shrines in dragon vale but I could not figure out how to get them.

A: You buy the shrine under the 'Buildings' section in shops.
You have to go to shop and navigate to 'Buildings'.


text:
Q: Joining table with address data to a shapefile (buildings) in QGIS The aim is to show all mineral oil deposits of an specific area.
First I have the buildings as a shapefile. The address of every building is divided in City, street and housenumber. So there are three different attributes.
And I got a table with all addresses that have a mineral oil deposit. ( I know how to import it into QGIS as a csv-file). In this table the address is also divided in three attributes as in the shapefile of the buildings.
The problem is I have no single attribute that could be used for a join. Do you know any easy possibility to join them? Maybe to put the attribute street and the house number in one attribute?

A: If the attribute table cannot be used to join the data together, you can use join by location from Vector -> Data Management Tools -> Join attributes by location.

You need to select the target layer whether it is building layer or oil field layer and select in the Join vector layer the other layer.
If the data do not have any coordinates and just the address, you can use mmqgis plugin and use Geocode to get the location based on address. You can refer to How to Geocode Addresses Using QGIS for more information.


text:
Q: Is it considered a bad coding practice to write methods/properties that support (only) testing? When I write (unit) tests I always try to avoid for example microsoft fakes because then the edit&continue feature no longer works. However this often requires refactoring... and sometimes methods or properties that exist only to support (unit) tests. An example:
With fakes I could do in each test method simply this:
ShimMyClass.InitializedGet = () => false;

but without fakes I need to write an internal method ResetInitialized() visible only to the (unit) test assembly.

As to:

*

*Would you rather make private stuff internal/public for tests, or use some kind of hack like PrivateObject?

*Is it a bad practice to modify code strictly for testing purposes
I won't make any private methods public to support unit testing but write them only for unit testing. Such methods would not have any other pupose but to be called in a unit test. ResetInitialized would never be called during a normal workflow but only by a unit test.
In other words: if I didn't create the unit test I would never have to write this additional helper method/property. It will never be called by anything other then a unit test.

Example
I have a class that I initialize when the application starts and subsequent initializations are skipped. The initialization takes place internally when the first feature is used. In this case I'm not able to test more then one test case at a time. I need to be able to reset it to let the tests run automatically.
Would it be bad to make it actually also resetable but the only user of this feature would be the unit test?

A:
In other words: if I didn't create the unit test I would never have to
  write this additional helper method/property. It will never be called
  by anything other then a unit test.

A quick answer - you should not modify your source code to cater your tests.
Also rule of thumb: if a piece of code/method/class/functionality will never be called - remove it. Don't comment out, don't make it private - remove it.
However it is perfectly fine to write new mocks/stubs or fake method in your tests that would monkeypatch/overload/replace the original functionality.
Testsing/implementation should follow 80/20 rule meaning that approximatelly 80% of your development time will go on writing tests (unit, intergration, end-to-end, call any..) And it is completely obvious that if you are chaning the interface of your methods, then you will have to update your fakers or unit test structure.

A: Another answer: yes, you should absolutely modify your source code to cater to your tests.
Testing fulfills the function of improving and maintainig the quality of your code base. Therefore, making tests easier, or possible, to write, is a valid goal with positive business value, just like writing business code. It's logically inconsistent to spend time writing tests and simultaneously claiming that it is never justifiable to change business code for the sake of the test suite.
As always, this is a matter of trade-offs. Obviously you shouldn't make your code much less maintainable for a small improvement in test writing. But a small or zero expansion of the business code for a big improvement in test writing can absolutely be justified.
Lots of developers make the mistake of thinking that since test code isn't shipped to the customer, it's somehow not really part of the code base and needn't be as well-written and reliable as the business code. This couldn't be more wrong; we do testing solely because it helps us create better programs, so it cannot have zero value - otherwise it would be negligent of us to write any tests at all.

A: You need to make your code testable. That's rule number one. Anything else is pandering to the rabble who say, "we don't need no stinkin' tests."
If you need to re-initialize something, there is a possibility that the lifecycle for your code-under-test is the problem. When you create a new object instance, does it not cleanly initialize to the state you want?
If you have hidden state, you may have to add state-monitoring variables that are only used for testing.


text:
Q: Creating a Macro to Index Data from Government Website
I provide the link here: http://quickstats.nass.usda.gov/results/320F1D82-1064-30F1-809E-F77E509EC508. I would like to learn how to perform this task using a macro/script in Excel VBA. The problems which I have been unable to overcome myself are:
1) Not all the weeks in the year are represented in the data. I am not sure how to sort the data by particular week, not sure what command I would need.
2) Is is possible to the Excel function VLOOKUP in my vba script in order to select all the distinct values, say Week14 or Week15, before performing the calculation for each week? If so, how is it incorporated? My idea was to just perform a VLOOKUP in the macro to search for the five different crop conditions.
My first question on this topic was about how to download the information off the website, see Building a Macro to Download Data off a Website into Excel. I suggest that this is the first button, "download", and then there should be a second button to sort the data called "sort".
CommandButton_1 is for download data, see linked question.
Private Sub CommandButton1_Click()

Dim thisWb, downloadWb As Workbook
Set thisWb = ActiveWorkbook

Set downloadWb = Workbooks.Open("http://quickstats.nass.usda.gov/data/spreadsheet/4C43034A-0EAA-3171-B4FC-84CC95FC6E0C.csv")

downloadWb.Worksheets(1).Range("A1:U2613").Copy Destination:=thisWb.Worksheets(3).Range("A8")

downloadWb.Close

End Sub

This works very well. Now the second button (Sort Data) it was suggested below that
Private Sub CommandButton2_Click()

Public Function WeekTotal(Condition As String, Table As Range) As Integer
Dim rRow As Range
Dim xVal As Integer

xVal = 0
For Each rRow In Table.Rows
        If InStr(LCase(rRow.Cells(1, 10).Value), "very") > 0 And LCase(Condition) = "poor" Then
            'skip if row includes 'very', but the condition is 'poor' and not 'very poor'
        ElseIf InStr(LCase(rRow.Cells(1, 10).Value), LCase(Condition)) > 0 Then
            xVal = xVal + rRow.Cells(1, 13).Value
        End If
Next rRow

WeekTotal = xVal

End Function

End Sub

This does not seem to work. Here is a picture, slightly altered width of columns, of what I am trying to deal with.

A: In my opinion, a macro is over-complicating a simple problem.

*

*Simply add a new column with a VLOOKUP on the value that corresponds to your rating. To accomplish this, you will need a reference range that can provide such a value. (See screenshot 1).

*In a new worksheet, list your weeks, and use SUMIF to calculate the total of the values in your vlookup column for each corresponding week. (See screenshot 2).
If you need to do a more sophisticated calculation, then provide additional detail and I'll modify this answer to help.

A: *

*I45 = "Excellent"

*J2:J36 is the Data Item column

*M2:M36 is the Value column

=SUM(IF(ISERROR(SEARCH(I45,$J$2:$J$36)),0,$M$2:$M$36))
Returns: 14
This is an array formula, so you have to press Ctrl+Shift+Enter, not just Enter. (You will know you did it correctly because it will look like this in the formula bar: {=SUM(IF(ISERROR(SEARCH(I45,$J$2:$J$36)),0,$M$2:$M$36))}
It automatically adds { and } when you press Ctrl+Shift+Enter - you do not type them in.
What this formula does:
Search("Excellent", $J$2) would look for the string "Excellent" in J2 and return the position it found the string or an error if it did not find the string. We don't care about the actual value - we just want to know if it throws an error or not. We turn this into an array by using $J$2:$J$36. You can't see it, but what this actually does is return an array of values that might look like this :
{44;#VALUE!;#VALUE!;#VALUE!;#VALUE!;44;#VALUE!;#VALUE!;#VALUE!;#VALUE!;44;#VALUE!;#VALUE!;#VALUE!;#VALUE!;44;#VALUE!;#VALUE!;#VALUE!;#VALUE!;44;#VALUE!;#VALUE!;#VALUE!;#VALUE!;44;#VALUE!;#VALUE!;#VALUE!;#VALUE!;44;#VALUE!;#VALUE!;#VALUE!;#VALUE!}
By using ISERROR(SEARCH("Excellent", $J$2:$J$36)) we change that internal array into this:
{FALSE;TRUE;TRUE;TRUE;TRUE;FALSE;TRUE;TRUE;TRUE;TRUE;FALSE;TRUE;TRUE;TRUE;TRUE;FALSE;TRUE;TRUE;TRUE;TRUE;FALSE;TRUE;TRUE;TRUE;TRUE;FALSE;TRUE;TRUE;TRUE;TRUE;FALSE;TRUE;TRUE;TRUE;TRUE}
If it fails to find "Excellent", ISERROR will be TRUE, so we want to find the value for all the FALSE values in this array. We do this using IF. If the SEARCH is an error, 0, else give us the value another array - $M$2:$M$36 (the value column).
=IF(ISERROR(SEARCH("Excellent", $J$2:$J$36)), 0,$M$2:$M$36)
This gives us the following:
{2;0;0;0;0;2;0;0;0;0;2;0;0;0;0;2;0;0;0;0;2;0;0;0;0;2;0;0;0;0;2;0;0;0;0}
Since your sample data had 2 for excellent for each week.
Finally we add SUM() around it all to sum up the values.
=SUM(IF(ISERROR(SEARCH("Excellent", $J$2:$J$36)), 0,$M$2:$M$36))
Again, since this is an array formula, if you just hit enter with this formula, it will return 0, but if you hit Ctrl+Shift+Enter it will give you the correct result of 14.

A: If you want to use VBA, simply as practice, here is how you could use a custom formula.
To use this function you would type the following into a cell:
=WeekTotal("Excellent",$A$2:$M$36)
VBA code:
Public Function WeekTotal(Condition As String, Table As Range) As Integer
Dim rRow As Range
Dim xVal As Integer

xVal = 0
For Each rRow In Table.Rows
        If InStr(LCase(rRow.Cells(1, 10).Value), "very") > 0 And LCase(Condition) = "poor" Then
            'skip if row includes 'very', but the condition is 'poor' and not 'very poor'
        ElseIf InStr(LCase(rRow.Cells(1, 10).Value), LCase(Condition)) > 0 Then
            xVal = xVal + rRow.Cells(1, 13).Value
        End If
Next rRow

WeekTotal = xVal

End Function


text:
Q: Javascript function that finds match in an array I'm beginning to learn Javascript, and I want to create a function that can sort through an array and compare two values (probably string values).
For example, if there are 50 different words, but there are two "banana" words, I want to know that. Any help on this would be appreciated. Thanks!

A: You can use filter to find all items that satisfies a filter function. I believe that by sort, you meant traverse or iterate.
E.g.
var words = ['test', 'banana', 'banana', 'other'];

var bananaCount = words.filter(function (word) {
    return word == 'banana';
}).length;

console.log(bananaCount); //2

The function needs to work without explicitly stating the word
  'banana'. The function needs to find 'banana' programmatically - Team6Labs

Well, you can just adapt the above exemple:
countOfWord(words, 'banana'); //2

function countOfWord(words, word) {
    return words.filter(function (w) {
        return w == word;
    }).length;
}


text:
Q: Comparison of different way of implementing the elbow method I am confused as I see different ways to implement the elbow method to identify the correct number of clusters in Kmean and they produce slightly different results.
One method is described here Sklearn kmeans equivalent of elbow method
and is using kmeans_inertia_ the other methos is described here https://pythonprogramminglanguage.com/kmeans-elbow-method/
and is using the following command.
distortions.append(sum(np.min(cdist(X, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) / X.shape[0])
 I am wondering what does Kmeans_inertia_ does ? and are both implementation correct ?

A: There is no "correct" for something that is not at all well-defined.
The elbow method is an extremely crude heuristic for which I am not aware of any formal definition, nor a reference.
Both methods will supposedly most often yield the same k...
But by the concept of k-means, the "correct" way to use it is with squared errors, not with Euclidean distance. Because k-means minimizes squared errors, it does not minimize Euclidean distances (try to prove this! You can't because there are counterexamples).

A: Both the scikit-Learn User Guide on KMeans and Andrew Ng's CS229 Lecture notes on k-means indicate that the elbow method minimizes the sum of squared distances between cluster points and their cluster centroids.  The sklearn documentation calls this "inertia" and points out that it is subject to the drawback of inflated Euclidean distances in high-dimensional spaces.  Ng calls this minimization of the "distortion function".  One can, however, find examples of the definition of distortion being "the average of the squared distances from the cluster centers of the respective clusters" (emphasis mine) in contrast to "inertia" being the sum of the squared distances.  While confusing, and  confirming these terms are not consistently defined, it suggests to me both work.

A: Reading the documentation for KMeans you can see that both distortion and inertia both are the sum of distance for each point to its center.

A: I find many examples around that use this formula, claiming that they calculate the distortion. However in my understanding is seems wrong:
distortions.append(sum(np.min(cdist(X, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) / X.shape[0])

If you want to calculate the sum of squared distances, it should be:
distortions.append(sum(np.min(cdist(X, kmeanModel.cluster_centers_, 'euclidean'), axis=1)**2) / X.shape[0])


text:
Q: Make alias take icon of the .app it points to
*

*I have a blah.app, and on desktop there is an alias to this app

*I went to blah.app/Contents/Resources and replace the icon with my icon, same name

*I went to blah.app/ and created a new folder next to the blah.app/Contents folder, this made the blah.app icon update to show mine however the icon of the alias file on desktop did not change.

Any ideas on why this is so? I know I can drag the icon over this alias file, but im trying to figure out whats going on here, why isn't taking my icon? :(
Thanks!

A: As noted in my comment from earlier, you can make an alias of the alias and it will acquire the icon from the original source... for some reason.

The following example is with folders... so it's not the exact situation in the question, but I think it illustrates the point:

A: I was having the same issue with an alias on the desktop of a .pvm file. I found I could change the icon in its original folder, but when I moved it to the desktop it reverted. I tried changing the name of the alias back to its original name as noted above, and the changed icon came back, but I didn't want the long name. I tried making an alias of the alias as noted above, and that worked, but as soon as I removed the .pvm extension on the name it reverted again. Ultimately, I could change the name to anything and keep the new icon as long as the name included the .pvm extension.

A: Either, in a Terminal: killall Finder
Or, from the Apple menu, Log Out and then log back in.
Either should cause the Alias to show the correct icon.
In the event the Alias doesn't update after this then delete the Alias and recreate it.


text:
Q: Utilizing GPU fails with tensorflow and CUDA with process finished with exit code -1073740791 (0xC0000409) I try to use my GPU for the first time to run a model with Tensorflow it exits whenever training starts with message:
Epoch 1/15
2022-05-07 00:46:23.749793: I tensorflow/stream_executor/cuda/cuda_dnn.cc:366] Loaded cuDNN version 8303

Process finished with exit code -1073740791 (0xC0000409)

My setup:
GTX 1650
tensorflow 2.7.0
CUDA 11.5
cudNN 8.3.3
Python 3.8.0
Here is the model and the preprocessing:
model = tf.keras.models.Sequential([
        tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(150, 150, 3)),
        tf.keras.layers.MaxPooling2D(2, 2),
        tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
        tf.keras.layers.MaxPooling2D(2,2),
        tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
        tf.keras.layers.MaxPooling2D(2,2),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(512, activation='relu'),
        tf.keras.layers.Dense(1, activation='sigmoid')
    ])

model.compile(loss='binary_crossentropy',
              optimizer=RMSprop(learning_rate=0.001),
              metrics=['accuracy'])

from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale=1 / 255)
validation_datagen = ImageDataGenerator(rescale=1 / 255)

train_generator = train_datagen.flow_from_directory(
    './horse-or-human/',  # This is the source directory for training images
    target_size=(150, 150),  # All images will be resized to 150x150
    batch_size=128,
    # Since you used binary_crossentropy loss, you need binary labels
    class_mode='binary')

validation_generator = validation_datagen.flow_from_directory(
    './validation-horse-or-human/',  # This is the source directory for training images
    target_size=(150, 150),  # All images will be resized to 150x150
    batch_size=32,
    # Since you used binary_crossentropy loss, you need binary labels
    class_mode='binary')

history = model.fit(
    train_generator,
    steps_per_epoch=8,
    epochs=15,
    verbose=1,
    validation_data=validation_generator,
    validation_steps=8)


text:
Q: AccessViolationException in .NET Core 5 with Advantage Data Provider I need to connect to Advantage Database for a Worker I'm working on.
I'm using the NuGet package Advantage.Data.Provider like so:
var conn = new AdsConnection("Data Source=\\Users\\[mypath];Initial Catalog=Test.add; User ID=adssys; Password=passw; ServerType=LOCAL");

if (conn.State == ConnectionState.Closed)
{
    conn.Open();
}
return conn;

After adding lots of .dll in System32 to fix other errors, I'm now stuck in this one:

Exception has occurred: CLR/System.AccessViolationException Ocorreu
uma exceção sem tratamento do tipo "System.AccessViolationException"
em Advantage.Data.Provider.dll: 'Attempted to read or write protected
memory. This is often an indication that other memory is corrupt.'

I can't get it to work. I've tried using others NuGets like AdoNetCore.AseClient and iAnywhere.Data.SQLAnywhere, but they also cause errors.
If anyone could help me with this error or has a better solution to my problem, I would appreciate it.
I'm using VS Code and C#.

A: What ended up working for me was:
First just like @Pieterjan said-

*

*Use the NuGet package Advantage.Data.Provider (Version 8.10.1.2)

*Install the .NET Data Provider corresponding to my DB version (https://devzone.advantagedatabase.com/dz/content.aspx?Key=20&Release=16&Product=4&Platform=11)

Then-

*

*Get ace32.dll, adsloc32.dll, axcws32.dll and adslocal.cfg from C:\Program Files (x86)\Advantage 10.10\ARC and put it in an environment path location (like System32, but it would be recommended to create a new one just for this)

*Run the project with dotnet run -r win-x86
Apparently the NuGet package can only be run with x86, I think that was the main problem

A: Install the Advantage Database Server dataprovider (ADS 8.1 provider)
Use the following code to create a database connection:
var connection = System.Data.Common.DbProviderFactories.GetFactory("Advantage.Data.Provider").CreateConnection();
connection.ConnectionString = "DATA SOURCE=C:\Ads\Databases\Example.add;ServerType=remote;USER ID=ADSSYS;PASSWORD=xxx;";
connection.Open();

var command = connection.CreateCommand();
command.CommandTask = "";
foreach (var param in Parameters) {
    var par = command.CreateParameter();
    par.ParameterName = "";
    par.Value = "";
    // par.DbType = System.Data.DbType.Boolean
    command.Parameters.Add(par);
}

Modify your app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    ...
    <system.data>
        <DbProviderFactories>
            <clear />
            <add name="Advantage Data Provider" invariant="Advantage.Data.Provider" description="" type="Advantage.Data.Provider.AdsFactory, Advantage.Data.Provider, Version=9.10.2.21, Culture=neutral, PublicKeyToken=e33137c86a38dc06" />
        </DbProviderFactories>
    </system.data>
</configuration>

Can you try that last part about the app.config?
If you did all this, and it still doesn't work, then it'll be an ADS version mismatch. Versions of:

*

*Advantage Database Server

*.NET Advantage Provider

*XML-tag that registers the database provider in your app.config

have to match.


text:
Q: Linear Algebra notation What does this notation mean? Is it just dividing each element per colum with the respective column length. Something like dividing by norm() in Matlab.

A: It's redefining the symbol like you suggested.  Something like v = v + 1 in Matlab.  The new value of v is defined in terms of the old value, but then you ignore the old value going forward.

A: You are dividing the vector (column) $v_j$ by its norm, which is $\langle v_j,v_j\rangle^{\frac12}$, that way each new vector $v_j'$ of your matrix has length 1.


text:
Q: Change element display none back to default style value JS I have a function in JS that hides the element parsed:
function hide(id){
  document.getElementById(id).style.display = "none";
}

How can I create a function that brings back the element to the default style value. For instance a div display property is "block" as for an image is "inline-block", other elements are "inline" or lists are "list-item" How can I bring them back their default state?
function show(id){
  document.getElementById(id).style.display = "?????";
}

I know how to do it in Jquery but it is not an option.
In CSS there might be styles for the elements including style:none, which need to be overwritten to the default value.
Since there is CSS in my example making style.display = '' eliminates the style added with JS but gets back to whatever style is added in CSS, I want to bring it back to its default value even before assigning styles with CSS.
I tried this as it was suggested in a link in one of the comments:
elem = document.getElementById(id);
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("display");

but in this case 'theCSSprop' returns "none" for a div, when I expect "block"
Any ideas?
Thanks.

A: You need just assign it to empty value:
document.getElementById(id).style.display = "";

Or using removeProperty method:
document.getElementById(id).style.removeProperty( 'display' );

But note that removeProperty will not work on IE<9.
If you want to get original CSS value you will need probably to get it from empty  element. I created example on jsFiddle how to get current value using getComputedStyle and iframe value on jsFiddle.
Please note that getComputedStyle not support old versions of IE. It support IE9+.
For IE8 you should use Element.currentStyle

A: Note:
If you define display:none; for a class or tag (either in a separate css file or in the head section), the above methods won't work.
Then you will have to determine which type of tag + class it is and manually assign the value specific to it.

These are examples of what may not work:
// In many cases this won't work:
function ShowHide_WillRarelyWork(id, bDisplay) {
    // Note: This will fail if parent is of other tag than element.
    var o = document.getElementById(id);
    if (o == null) return;
    //
    if (bDisplay) {
        o.style.display = 'inherit';
        o.style.visibility = true;
    }
    else {
        o.style.display = 'none';
    }
} // ShowHide_WillRarelyWork(...)

// This will work in most, but not all, cases:
function ShowHide_MayWork(id, bDisplay) {
    // Note: This will fail if element is declared as 'none' in css.
    var o = document.getElementById(id);
    if (o == null) return;
    //
    if (bDisplay) {
        o.style.display = null;
        o.style.visibility = true;
    }
    else {
        o.style.display = 'none';
    }
} // ShowHide_MayWork(...)

This is long but will most probably work:
function getDefaultDisplayByTag(sTag) {
    // This is not fully implemented, as that would be very long...
    // See http://www.w3.org/TR/CSS21/sample.html for full list.
    switch (sTag) {
        case 'div':
        case 'ul':
        case 'h1':
        case 'h2':
        case 'h3':
        case 'h4':
        case 'h5':
        case 'h6':      return 'block';
        //
        case 'li':      return 'list-item';
        //
        case 'table':   return 'table';
        //
        case 'td':
        case 'th':      return 'table-cell';
    }
    // Fallback:
    return 'block';
} // getDefaultDisplayByTag(...)
//
function computeDisplay(o) {
    var oFunction = window.getComputedStyle;
    if (oFunction) {
        var oStyle = window.getComputedStyle(o)
        if ((oStyle) && (oStyle.getPropertyValue)) {
            return oStyle.getPropertyValue('display');
        }
    }
    if (window.currentStyle) {
        return window.currentStyle.display;
    }
    return null; // <-- This is going to be a bad day...
} // computeStyle(...)
//
// This will most probably work:
function ShowHideObject_WillProbablyWork(o, bDisplay, bMaybeRecursive) {
    if ((o == null) || (o == undefined) || (o == document) || (o.tagName == undefined)) return;
    //
    if (bDisplay == null) bDisplay = true
    if (!bDisplay) {
        o.style.display = 'none';
    }
    else {
        // First remove any directly set display:none;
        if ((o.style.display == 'none') || (o.style.display == '')) {
            o.style.display = null;
        }
        //
        var sDisplay = null;
        var sDisplayCurrent = computeDisplay(o);
        var oParent = o.parentNode;
        // Was this element hidden via css?
        if ((sDisplayCurrent == null) || (sDisplayCurrent == 'none')) {
            // We must determing a sensible display value:
            var sTag = o.tagName;
            sDisplay = getDefaultDisplayByTag(sTag);
        } // else: if ((sDisplayCurrent != null) && (sDisplayCurrent != 'none'))
        //
        // Make sure visibility is also on:
        if (sDisplay != null) o.style.display = sDisplay;
        o.style.visibility = true;
        //
        if (bMaybeRecursive) {
            // We should travel up the tree and make sure parent are also displayed:
            ShowHideObject_WillProbablyWork(oParent, true, true);
        }
    } // else: if (!bDisplay) ...
    //
} // ShowHideObject_WillProbablyWork(...)
//
// ... and finally:
function ShowHideId_WillProbablyWork(id, bDisplay, bMaybeRecursive)
    var o = document.getElementById(id);
    ShowHideObject_WillProbablyWork(o, bDisplay, bMaybeRecursive)
} // ShowHideId_WillProbablyWork(...)

Of course this could be shortened a bit; but that's how it looks in my source.

A: Here is one more solution for retrieving any property default value of any element. Idea is following:

*

*Get nodeName of specific element

*Append a fake element of the same node name to body

*Get any property value of the fake element.

*Remove fake element.

function getDefaultValue(element, property) {
    var elDefault = document.createElement(element.nodeName);
    document.body.appendChild(elDefault);
    propertyValue = window.getComputedStyle(elDefault,null).getPropertyValue(property);
    document.body.removeChild(elDefault);
  return propertyValue;
}
 function resetPropertyValue (element,propertyName) {
    var propertyDefaultValue = getDefaultValue(element, propertyName);
    if (element.style.setProperty) {
        element.style.setProperty (propertyName, propertyDefaultValue, null);
    }
    else {
        element.style.setAttribute (propertyName, propertyDefaultValue);
    }
}
#d {
  background: teal;
  display: inline;
}
<button onclick="resetPropertyValue(document.getElementById('d'), 'display')">Try it</button>

test

A: You can use custom attributes
function hide(id){
    var elem = document.getElementById(id);
    //Store prev value
    elem.setAttribute('custom-attr', elem.style.display);
    elem.style.display = "none";
}

function show(id){
    var elem = document.getElementById(id);
    //Set prev value
    elem.style.display = elem.getAttribute('custom-attr');
}

A: Filling in an empty value removes the inline override, so the original value is active again.
function show(id){
    document.getElementById(id).style.display = "";
}

A: Since what you want is the default value for the element and not what's in the style sheet, you simply want to set the value to auto.
document.getElementById(id).style.display="auto"

This tells the browser to calculate what the normal display for this type of element is and to use that.


text:
Q: What does '*' do as a parameter in discord.py? I want to know what does asterisk do as a parameter in ban_user function?. In which situations do we use it? What's its advantage against *args?
import discord
from discord.ext import commands

intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True,presences=True)

client = commands.Bot(command_prefix="!dc ", intents=intents)

@client.command(aliases=["ban"])
@commands.has_role("admin")

async def ban_user(ctx, member: discord.Member, *, reason=None):
    await member.ban(reason=reason)

client.run(Token)

A: It makes it so all content/provided args after member count as the reason. basically just specify's that all following words are also part of the reason argument.


text:
Q: Where to place nee file location? HTML I changed the location of a file called finds.html
to html/finds.html. Where do I add this in my page in order for the new location of the page to be recognized.  I thought in the area: Finds is this correct?

<!DOCTYPE html>

       <title>Finds</title>
        <meta charset="UTF-8">
       <link rel="shortcut icon" href="path to icon/favicon.ico"/>
<link href='https://fonts.googleapis.com/css?family=Noto+Sans' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Courgette' rel='stylesheet' type='text/css'>
       <link href='styles.css? version=1' rel='stylesheet'></link>
       <link rel="stylesheet"type="text/css" href="/css/finds.css">

<link rel="stylesheet" type="text/css" href="engine1/style.css">

One Bug Design

Designed to create&#153

Home

Portfolio

Finds

Contact

            <main
               <div id="content"

  <svg height="60" width="320"
  xmlns="http://www.w3.org/2000/svg">
  <rect class="shape" height="60" width="320"/>

FINDS

  </svg>

Warning!!!(The following pictures were taken with an actual camera.)

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11

A: Try

Finds

to go back one directory, or use full path to resource.

A: Can't you just change all the finds.html to html/finds.html?


text:
Q: Ember-cli nested model array using {{each}} helper re-renders whole list when adding to Ember data store I have a route that loads a dashboard
// routes/dashboard/index.js
...
  model: function(params) {
    return this.store.find('dashboard', params.dashboard_id);
  }
...

The dashboard model contains a hasMany relationship to the widget model
// models/dashboard.js
...
DS.Model.extend({
  widgets: hasMany('widget', {async: true})
...

The widget model contains a belongsTo relationship to the dashboard model
// models/widget.js
...
DS.Model.extend({
  dashboard: belongsTo('dashboard', {async: true})
...

The dashboard.index template renders the widgets using the {{each}} helper
// templates/dashboard/index.js
...
{{#each model.widgets as |widget|}}
  {{widget config="widget"}}
{{/each}}
...

The user can add a widget to their dashboard
// routes/dashboard/index.js
...
actions: {
  addWidget: function() {
    this.store.createRecord('widget', {
      dashboard: this.modelFor('dashboard.index')
      ...
    });
  }
}

Although this works, when the new widget is created, ALL widgets are re-rendered.
Some things of note:
- I have not implemented a View or Controller.
- If I change the implementation to return just a collection of widgets, causing ember-cli to create an ArrayController rather than an ObjectController, the each loop does not re-render (excellent). However, dashboards have more than one child array that needs to be rendered, and so I cannot take this approach.
- Despite efforts to implement the object controller and create my own array controllers, I cannot get the same functionality here.
Any suggestions of how I can add widgets without all widgets re-rendering?


text:
Q: AF-XDP: Is there a bug regarding small packets? Is there a known (or maybe unknown) bug regarding the size of packets in the AF-XDP socket framework (+ libbpf)?
I am experiencing a strange packet loss for my application:

*

*IPv4/UDP/RTP packet stream with all packets being the same size (1442 bytes): no packet loss

*IPv4/UDP/RTP packet stream where pretty much all packets are the same size (1492 bytes) except a special "marker" packet (only 357 bytes but they are also IPv4/UDP-packets): all marker packets get lost

I added a bpf_printk statement in my XDP-Kernelprogram:
const int len = bpf_ntohs(iph->tot_len);
if(len < 400) {
    bpf_printk("FOUND PACKET LEN < 400: %d.\n", len);
}

This output is never observed via sudo cat /sys/kernel/debug/tracing/trace_pipe. So these small RTP-marker packets aren't even received by my kernel filter - no wonder why I don't receive them in userspace.
ethtool -S <if> shows me this number: rx_256_to_511_bytes_phy. This number is increasing in a similar rate as marker-packets should come in (about 30/s). So this means that my NIC does receive the packets but my XDP-program doesn't - why?
Any idea what could be the cause of this problem?

A: First, bpf_printk() doesn't always work for me. You may want to take a look at this snippet (kernel-space code):
// Nicer way to call bpf_trace_printk()
#define bpf_custom_printk(fmt, ...)                     \
        ({                                              \
            char ____fmt[] = fmt;                       \
            bpf_trace_printk(____fmt, sizeof(____fmt),  \
                    ##__VA_ARGS__);                     \
        })

// print:
bpf_custom_printk("This year is %d\n", 2020);
// output: sudo cat /sys/kernel/debug/tracing/trace_pipe

Second: May be the packet entered the other NIC queue. You may want to use vanilla code from xdp-tutorial and add the kernel tracing from the above snippet to print size of packet, then compile and run the example program with -q 1 for queue number 1 for example.
A way to get size of packet:
void *data_end = (void *)(long)ctx->data_end;
void *data = (void *)(long)ctx->data;
size_t size_pkt = data - data_end;
bpf_custom_printk("Packet size %d\n", size_pkt);


text:
Q: Syncronizing object to avoid a null pointer exception on Muiti Thread enviroment I'm having a null pointer exception in my app. The null pointer is happening even after checking if the object isn't null..
My class is accessed by different threads. So, I believe the class-member object is being set to null after the if statement. So, when I actually try to access it, it might be null already leading to the NPE (null pointer exception).
Below is my code:
private MyCustomListener listener;

public void setListener(@Nullable final MyCustomListener listener) {
    mMyCustomListener = listener;
}

public void onEvent() {
    if (mMyCustomListener != null) {
        .... // Some code
        listener.execute(); // Null Pointer Exception at this line
    }
}

What I have tried:
private MyCustomListener listener;

private static final Object mListenerSync = new Object();

public void setListener(@Nullable final MyCustomListener listener) {
    synchronized(mListenerSync) {
        mMyCustomListener = listener;
    }
}

public void onEvent() {
    synchronized(mListenerSync) {
        if (mMyCustomListener != null) {
            .... // Some small code
            listener.execute(); // Null Pointer Exception
        }
    }
}

Basically, I have two threads. One that set/unset the listener to receive onEvent() notifications. The second thread is responsible to produce onEvent() calls. I would like that the listener from the first thread stop being invoked as soon as I set the listener to null.
So, I would like to request your support to confirm following points.

*

*Will my code be tread-safe now? Or at least I'm avoiding the NPE.

*mListenerSync object must be static?
I'm testing my code and I didn't observed any side-effect such as a dead-lock.. However, I'm not sure if this code will fix my issue given it is hard to reproduce.

A: If you're sure that the reason is other threads setting the listener to null, you can rectify it easily with a local variable and no additional synchronization. Make the variable transient if you're actually changing the listener to ensure visibility. Although I have a feeling this isn't the reason for your errors
private transient MyCustomListener listener;

public void onEvent() {
    MyCustomListener listener = myCustomListener;
    if (listener != null) {
        .... // Some code
        listener.execute();
    }
}


text:
Q: HBase scans are slow Problem
I am trying to build a secondary index with Phoenix. Index creation takes several hours. It seems to be due to slow HBase scans, as I noticed the following performance :

*

*I might need 2 hours to scan the table, whereas other developers reported a few minutes for larger tables (100 millions rows).

*HBase shell is able to count rows at an approx. rate of 10.000 per second, which means 3800s (>1 hour!) to count all rows of this table.

Both with HBase shell and a Java scanner.
NB : The GET(by rowkey) operation is achieved with good performances (approx 0.5s).

Context

*

*38 millions rows / 1000 columns / single column family / 96Go with GZ compression.

*Cluster has 6 nodes (126Go RAM, 24 cores) with 5 region servers.

*Hortonworks Data Platform 2.2.0

Troubleshooting
Based on the HBase book (http://hbase.apache.org/book.html#performance), here is what I already checked :
1) Hardware

*

*IO(disk)

*

*NMon says disk are never busy more than 80%, and most frequently between 0 and 20%

*Top says HBase JVM's are not swapping (checked 2 of 5 RS)

*IO(network) : each node active interface stand on the same switch (all second passive interface are plugged on a different switch)

2) JVM

*

*GC pauses OK (few milliseconds pause every minute or so)

*Heap looks OK (not peaking too long near the limit)

*CPU is suprisingly LOW : never more than 10%

*Threads :

*

*Active threads (10 "RpServe.reader=N" + a few other) show no contention

*Lot of parked thread doing nothing (60 "DefaultRpcServer.handler=n", approx 15 other)

*Huge list of IPC Client without any thread status

3) Data

*

*was bulk loaded using Hive + completebulkload.

*Number of region :

*

*13 regions meaning we have 2 to 3 large regions for each RS, which is what is expected.

*Scan performance remains unchanged after forcing a major compaction.

*Region size is rather homogeneous : 4,5Go (+/-0.5) for 11 regions, 2,5Go for 2 regions

4) HBase configuration

*

*Most configuration remained unchanged.

*

*HBase env only indicates ports for JMX console

*HBase-site has few settings for Phoenix

*Some of the params that looked OK to me

*

*hbase.hregion.memstore.block.multiplier

*hbase.hregion.memstore.flush.size : 134217728 bytes (134Go)

*Xmn ratio of Xmx : .2 Xmn max value : 512 Mb Xms : 6144m

*hbase.regionserver.global.memstore.lowerLimit : 0.38

*hbase.hstore.compactionTreshold : 3

*hfile.block.cache.size : 0.4 (Block cache size AS % of heap)

*Maximum HStoreFile (hbase.hregion.max.filesize) : 10 go (10737418240)

*Client scanner cache : 100 rows zookeeper timeout : 30s

*Client max keyvalue size : 10mo

*hbase.regionserver.global.memstore.lowerLimit : 0.38

*hbase.regionserver.global.memstore.upperLimit : 0.40

*hstore blocking storefiles : 10

*hbase.hregion.memstore.mslab.enabled :

*enabled hbase.hregion.majorcompaction.jitter : 0.5

*Tried following configuration changes without any impact on performance

*

*hbase-env.sh : tried to increase HBASE_HEAPSIZE=6144 (since it default at 1000)

*hbase-site.xml :

*

*hbase.ipc.server.callqueue.read.ratio : 0.9

*hbase.ipc.server.callqueue.scan.ratio : 0.9

5) Log say nothing usefull
cat hbase-hbase-master-cox.log | grep "2015-05-11.*ERROR"
cat hbase-hbase-regionserver-*.log | grep "2015-05-11.*ERROR"
print nothing
Printing WARNs shows non related errors
2015-05-11 17:11:10,544 WARN  [B.DefaultRpcServer.handler=8,queue=2,port=60020] shortcircuit.ShortCircuitCache: ShortCircuitCache(0x2aca5fca): could not load 1074749724_BP-2077371184-184.10.17.65-1423758745093 due to InvalidToken exception.
2015-05-11 17:09:12,848 WARN  [regionserver60020-smallCompactions-1430754386533] hbase.HBaseConfiguration: Config option "hbase.regionserver.lease.period" is deprecated. Instead, use "hbase.client.scanner.timeout.period"

A: Got it : the key is to separate "hot" content from "cold" content into separate column families. Column families are used to store columns in separate HFiles, so we can use one column family for indexed (or frequently read) columns, and one other column family (thus file) for all other columns.
First step : see that smaller column family is faster to scan
We simply discard cold content to build a single smaller column family (1655 columns -> 7 columns).
Performances on medium size table scans :

*

*[37.876.602 rows, 1655 columns] scan 1000 rows took 39.4750

*[76.611.463 rows,    7 columns] scan 1000 rows took  1.8620

Remarks :

*

*total number of rows can be ignored as we scan the first 1000 rows

*there is an overhead with large rows as scanning from Hbase shell prints content in console

Second step : generate multi-family HTable
We do a bulk load by generating HFiles from Hive. Although the doc says we can't generate one multi family table, one can generate HFiles separately :
create table mytable_f1 (UUID string, source_col1, source_col2)
...
TBLPROPERTIES('hfile.family.path' = 'tmp/mytable/**f1**');

create table mytable_f1 (UUID string, source_col3, source_col4)
...
TBLPROPERTIES('hfile.family.path' = 'tmp/mytable/f2');

And then simply call import command as usual :
hadoop jar [hbase-server-jar] completebulkload /tmp/mytable mytable

A: *

*TurnOff blockcache at time of scan (it is churning ur heap memory)

*Figure out whats the size of ur record , if its > 1 MB , please increase hbase.scanner.timeout period scan.setCacheBlocks(false);

*scan.setCaching(x) x * record size what is getting fetched in one short , make sure it is close to 1 MB .

*some necessary check : make sure regions for the Tabled being scanned are equally distributed across regions .
(If u have done bulk load run a Major compaction Once )