text:
Q: Clearing caches on plugin uninstall When a plugin is uninstalled, it should remove all related data from the site (or network, if on multisite). If a plugin adds tables to the database, for example, it should remove those tables from the database.
My question concerns a case like this where the plugin is actually _doing_it_right() and caching some of the queries that it makes on those database tables, using the wp_cache_*() functions.
I'm thinking that when the plugin is uninstalled it should probably clear those caches. My reasoning is that sometimes the user might reinstall the plugin after uninstalling (for example if they were just testing it out and want to erase the test data and start fresh). If the caches aren't cleared on uninstall, the plugin might retrieve that ghost data from the caches after it was re-installed, causing very strange behavior.
Of course, this is mostly a concern for those sites that would have persistent caching of some sort. (And it would be exacerbated on those  with a pretty big large amount of storage, since the stale data would likely be retained longer.)
For any site with a persistent caching back-end enabled though, having a bunch of stale data sitting in there from an uninstalled plugin is not ideal.
The downside of trying to clear those caches is that there is no way to clear a whole cache group. The plugin would have to loop through all of the IDs of the objects in the database table and clear the cache for each one. So there is resource-usage trade-off between clearing the cache and leaving it.
My question is, has anybody else considered whether plugin caches should be cleared on uninstall, and when the trade-off is worth it? Is this a known best practice?

A: There are different approaches to this, depending on specific requirements.
For example in your case you seem more worried about plugin picking up ghost data than that data being left behind. Such case might be easier handled by generating unique key prefix to use and just flushing that on uninstall. No prefix = no data access.
I would say the general case is to ignore the issue and to use appropriate timeout values for transients. If data is only relevant for specific amount of time then using appropriate timeout handles it implicitly just fine.
Options can (should) be stored as single set, so clearing those out is easy and fast.

A: Yes, they should be, especially since cache might contain sensitive information the user might wish to be removed with the plugin.
Best thing is to design your system in a way in which it is easy to delete all persistent information - for example place all your cache files under one directory.
As for your example, cache in theory should not be part of an object (it is not a description of it in any way), therefor your problem is with the design of your objects which leads to your problems with clearing the cache. If your only option is a cache in the DB (and it sounds to me like a symptom of early optimization) then use a different table for it.
Update
Your assumption that wp_cache_* APIs use a persistent storage is false. It is actually an underlining assumption of core code that they are nor persistent and whatever is driving the cache does a "garbage collection" from time to time (core rarely delete anything from the cache). Caching systems that do not do garbage collection are either very specific or buggy as if you don't do it you are going at some point to run out of RAM/disk space.
In addition the cache implementation might not support a delete (unlikely, but strange things do happen from time to time) therefor you will not be able to clear the data in any case.
In essence. on one hand those are 3rd party tools that you might not have enough control to be sure that you delete anything, on the other most of them in practice are smart enough to auto delete your data given some sensible enough time (less then a day) making the issue of cleaning it up a "nice to have" but totally not essential.
And yes, people do use redis for cache, but IMO it is a mistake. redis is a nosql DB, not a RAM/distributed cache although it probably can be configured to be used like one.


text:
Q: Is there any difference in saving same value in different integer types? The main integer fields in Django are the following,

Integer Field
An integer. Values from -2147483648 to 2147483647 are safe in all databases supported by Django. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise.

SmallIntegerField
Like an IntegerField, but only allows values under a certain (database-dependent) point. Values from -32768 to 32767 are
  safe in all databases supported by Django.

BigIntegerField
A 64 bit integer, much like an IntegerField except that it is guaranteed to fit numbers from -9223372036854775808 to 9223372036854775807. The default form widget for this field is a TextInput.

If I have a number, 33432 (some number that fits in all of the fields), If I choose to store the same number in all of the below fields, will there be an excess use of memory with both the database or at the runtime?
number0 = models.SmallIntegerField()
number1 = models.IntegerField()
number2 = models.BigIntegerField()

My database is PostgreSQL.

A: Most operations are fastest for plain integer, but the difference is very small and typically the least of your concerns when optimizing performance.
Storage size is more relevant, but the difference between various integer types is still very small and often hardly relevant, sometimes lost to padding and alignment. There are other data types that can waste much more space.
smallint (int2) occupies 2 bytes on disk and in RAM.
integer (int, int4) occupies 4 bytes on disk and in RAM.
bigint (int8) occupies 8 bytes on disk and in RAM.
Details for numeric types in Postgres in the manual.
There are various other factors for actual storage size. You have to consider page and tuple overhead, alignment and padding, possible NULL values, indexing ...
Details:

*

*Measure the size of a PostgreSQL table row

*Calculating and saving space in PostgreSQL
There is some potential for optimizing, but typically not much. Best concentrate on choosing an appropriate data type for your data and don't worry about minor differences in storage and performance, unless you know exactly what you are doing.

A: Yes, the memory storage and runtime memory allocated for your numeric data will be directly proportional to the byte size of the numeric structure you choose.
There are some compression methods such as changing integers and decimals to the variable-length format instead of their native fixed-length format for SQL server. However, they introduce higher CPU usage as mentioned here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails3, JQuery and RJS (UJS)  I am trying to get ajax callbacks working on a href using remote.  I have the rails.js and
 JQuery1.6 installed.
Here is the attempt to catch the callback:
$('#choo').bind('ajax:success', function(){
    alert("Success!");

});

Here is my div and AJAX link
<%= link_to "Choose", {:action => "choose", :id => 538}, :remote => true, :id => "choo" %>

When I click the link the ajax fires hits the server and returns the response but the callback is not working...
I have followed everything in this guide but with little by the way of success.  In other words "!ajax:success" :-).
Any ideas what I am doing wrong?
EDIT++++++++++++++++++++==
I updated to 3.1 and it worked.
Cheers,
s

A: Try to "live"
$('#choo').live('ajax:success', function(){
  alert("Success!");
});

or this:
$('a[data-remote],input[data-remote]').live('ajax:success', function() {
  alert('success');
});


text:
Q: What image format is easy to turn into on or off pixels? I have a hobby project that includes me driving a LCD by my serial port.
I'd like to display an image with 128x128 pixels, but I'm not sure what image format to use.  I'm limited to either "off" or "on" as a state of each pixel. What image format do you recommend?
In case it matters, I'm planning on using one of the .NET frameworks with this

A: I recommend using a Bitmap.
The .GetPixel and .SetPixel methods both use System.Drawing.Color values, an so are quite easy to work with.


text:
Q: Is Minecraft VR cross play with other platforms? I have recently started playing Minecraft VR on the Oculus rift. Can I play multiplayer with players on PC, Xbone and Switch?

A: Minecraft VR can crossplay with all Bedrock Edition devices, as it is part of Windows 10 edition.

A: From Oculus site:
Plus, with this launch, you and your friends can explore Minecraft—simultaneously, cross platform—on Rift, Gear VR, iOS, Android, and Windows 10 devices.
Notice that Xbox and Switch are not listed to crossplay


text:
Q: How to extract field value from nested SOQL query inside APEX If case is updated I would like to send email to all contacts for the account associated with that case.
I am getting list of contacts in map and then looping through the map keyset and then looping through list to send email. I would like to avoid "For" loop for list to make it efficient
map<case, list<string>> m = new map<case, list<string>>();
list<string> conList= new list<string>();
for(account a :[select Id, Name, (select Id, AccountId, email from Contacts), (select Id, CaseNumber, AccountId, Account.Name, subject from Cases), Type from Account]){
    for(case cs:a.Cases){
        \\Here below I would like to have a list of all emails related to Case for that account
        conList.addall(a.Contacts);
        m.put(cs,conList);
    }
    conList = new List<string>();
}

A: This sort of query is likely to run into governor limits as you are querying every Account and then every Contact and Case related to those Accounts. So if this is code that will remain in use it will break when the data volumes rise so requires significant rethinking.
Assuming this is once-off code in an org with only a few thousand rows in total, and looking at this ERD, I suggest you query the Case. In that query you can also retrieve the Cases parent Contact and that Contact's parent Account as you can go 5 levels up the parent hierarchy. This approach avoids any nasty code to try to relate the Case to the right Contact.


text:
Q: Visual Studio 2017 not showing GUI icons I recently installed the newest version of Visual Studio, and when I ran it, I came to this screen. So far, I tried to rollback, which just corrupted the Visual Studio install, and which to fix was to re-install the new version, which seems to be the culprit. I have also tried to copy the image library cache file from the profile of the admin account that was used to install VS 2017 into the profile of the development account. This also, did not solve my problem. I did try and update my NVIDIA driver. This did not solve my issue. Can someone offer me an alternative course of action?

A: Have you tried to completely uninstall and re-install? Sounds like your 'update' didn't work out right.


text:
Q: Usando Docker y Laravel tengo este error con MySQL: "SQLSTATE[HY000] [2002] No such file or directory" Tengo una app en laravel 5.2 que se conecta a mi base de datos mysql local, sin problemas. Pero, al colocar la app dentro de un contenedor docker, no logra conectarse a la base de datos y obtengo este error:
SQLSTATE[HY000] [2002] No such file or directory

Si cambio la constante DB_HOST en el archivo .env a 127.0.0.1 en vez de localhost, entonces obtengo este otro:
SQLSTATE[HY000] [2002] Connection refused

Lei que el problema podia deberse a no tener una ruta por defecto para el socket en el php.ini
$ ls -l /var/run/mysqld/mysqld.sock
$ srwxrwxrwx 1 mysql mysql 0 nov 27 08:31 /var/run/mysqld/mysqld.sock

Asi que lo agregue solo en el caso del pdo:
; Default socket name for local MySQL connects.  If empty, uses the built-in
; MySQL defaults.
; http://php.net/pdo_mysql.default-socket
pdo_mysql.default_socket=/var/run/mysqld/mysqld.sock

Parte de mi archivo .env
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=developer
DB_PASSWORD=123456

Mi database.php
'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => false,
        'engine' => null,
    ],

Utilice docker-compose para montar el contenedor, pues planeo crear otros microservicios mas adelante:
version: "3.3"
services:
   api_test:
      build: .
      ports:
         - "8181:8181"
      env_file:
         - ./.env
      environment:
         - PORT:8181

Mi Dockerfile:
FROM php:7.1.5-apache

RUN apt-get update -y && apt-get install -y openssl zip unzip git
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN docker-php-ext-install pdo pdo_mysql mbstring
WORKDIR /api_test
COPY . /api_test
RUN composer install
RUN a2enmod rewrite
CMD php artisan serve --host=0.0.0.0 --port=8181
EXPOSE 8181

Uso:

*

*Debian 9.6, kernel 4.9.0-8-amd64

*Apache/2.4.25

*PHP 7.0.30-0+deb9u1

*MariaDB 10.1.37 database server
Alguna sugerencia?

A: Encontré la solución.
O una solución que me sirve.
Las encontré aquí y aquí
El problema era el acceso remoto en mi base de datos mysql local. La red de mi contenedor era distinta a la de mi localhost. Y no tenia configurado mi mysql para recibir conexiones externas.
En el my.cnf
[mysqld]
bind-address = 0.0.0.0

Y con los permisos
mysql> grant all privileges on *.* to 'developer'@'%' identified by '123456';
mysql> flush privileges;

EDITADO
Olvidé agregar que cambiar mi DB_HOST por mi IP local (de la IP asignada por mi enrutador) a mi archivo .env también fue necesario.


text:
Q: How to download file from kinvey in android Trying to download publicly accessible file from kinvey to android app
tried following code,
FileOutputStream fos = new FileOutputStream(videoName);
        FileMetaData meta = new FileMetaData(videoName);
        meta.setId(videoName);
        kinveyClient.file().downloadWithTTL(meta.getId(), 1200000, fos, new DownloaderProgressListener() {
            @Override
            public void progressChanged(MediaHttpDownloader downloader) throws IOException {
                Log.i("", "progress updated: " + downloader.getDownloadState());
                final String state = new String(downloader.getDownloadState().toString());

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //tProgress.setText((tProgress.getText() == null) ? state : tProgress.getText() + "\n" + state)
                    }
                });
            }

            @Override
            public void onSuccess(Void result) {
            }

            @Override
            public void onFailure(Throwable error) {
            }
        });

getting event success but data is not being received. any idea how this will work??
getting error like this :
failure com.kinvey.java.core.KinveyJsonResponseException: InsufficientCredentials
                                                          The credentials used to authenticate this request are not authorized to run this operation. Please retry your request with appropriate credentials

A: According to the documentation, this is how you are supposed to use the value you get from getDownloadState() . In order to get the progress of your download, you need to first check the downloadState is equal to DOWNLOAD_IN_PROGRESS value, and then use the download.getProgress() method to get the progress, then you can use this to update the value on your progress slider, (you shouldn't be converting these values to string using the toString() method like you've done above.
public void progressChanged(MediaHttpDownloader downloader) throws IOException {
  switch (downloader.getDownloadState()) {
    case DOWNLOAD_IN_PROGRESS:
      //Download in progress
      //Download percentage:  + downloader.getProgress()
      break;
    case DOWNLOAD_COMPLETE:
      //Download Completed!
      break;
  }
}

Code taken from documentation here

A: Nayana,
You might be getting this error because user does not have permission to access that file. You can try following to solve your issue:

*

*If you make the file publicly readable, all authenticated users will be able to access that particular file.

*You can make the file accessible by adding read/write permissions for
few users in ACL.

Also check the documentation for Access Control List:
http://devcenter.kinvey.com/rest/guides/security#entityanduserpermissions
Thanks,
Pranav
Kinvey Support


text:
Q: Unexpected C behaviour I'm trying to understand why my program won't to compile,
int myfunction(int x)
{
   return x;
}

int main(){
  int x = 10;
  int result=0;
  result=myfunction(x) * myfunction(++x);
  printf("Result is = %d", result);
}

After execution i get : warnings being treated as errors
In function 'int main()': operation on 'x' may be undefined.
Someone has an idea ?

A: myfunction(x) * myfunction(++x) is undefined because the order of evaluation of the two arguments to operator * is unspecified. So either the first or second call can be executed first, meaning that theoretically x or ++x can be evaluated first, which can lead to different results. Theoretically. In practice, the standard just passes responsibility to you not to do this.

A: You are using undefined behavior.
There's no guarantee that the expression myfunction(x) * myfunction(++x) is evaluated in any particular order, and since it has side-effects its behavior is undefined.

A: Your code used "Undefined behaviour".
The C and C++ standards does not state (or define) in which order x and ++x myfunction(x) and myfunction(++x) should be evaluated. Do you expect the result to be 121 or 110 (or soemthing else entirely) - since both of those values are perfectly valid results, would you be equally happy having both results, or do you think one is "more accurate" than the other?
The compiler is warning you that you can't expect this code to produce whichever you prefer of the possible results (which may include something you think "isn't possible"), and a different compiler (or different settings/version for your current compiler) may result in a different value.

A: The ++ operator has a side effect that makes the statement undefined.
You can do like this :
    result = myfunction(x) * myfunction(x + 1);

    ++i; /* or i++ in this case, doesnt matter */

    printf("Result is = %d", result)


text:
Q: Showing that whether a construction is the maximum /minimum or not 16 friends decided to form clubs. Each club will have 4 members, and any two clubs may have at most two member in common. What is the greatest/least possible number of clubs they can form.

Got 7 clubs (not sure if it is the maximum)
I made it so every club contains members $A$ and $B$. Then there are 14 members left, so 7 clubs. How to show whether this is the maximum or not ? And minimum i think is 4 by letting exactly 4 diff members in each of the four club , all conditions are satisfied but i dont know how to show its the minimum

A: You can solve the problem via integer linear programming as follows.  Let $n=16$.
For each $4$-subset $C \subset\{1,\dots,n\}$, let binary decision variable $x_C$ indicate whether $C$ is selected.  The problem is to maximize $\sum_C x_C$ subject to linear (conflict) constraints
$$x_C + x_D \le 1 \quad \text{if $|C \cap D|>2$}.$$
You can also interpret this as finding a maximum independent set in a graph with one node per $4$-subset and an edge between each pair of subsets whose intersection has cardinality greater than two.
The maximum for general $n$ is given in https://oeis.org/A001843.


text:
Q: How to download entire directory from azure file share Not able to download entire directory from azure file share in python
I have  used all basic stuffs available in google
share = ShareClient.from_connection_string(connection_string, "filshare")
my_file = share.get_file_client("dir1/sub_idr1")
# print(dir(my_file))
stream_1 = my_file.download_file()

A: I tried in my environment and got below results:
Initially I tried with python,

*

*Unfortunately, ShareServiceClient Class which Interacts with A client to interact with the File Share Service at the account level. does not yet support Download operation in the Azure Python SDK.

*ShareClient Class which only interacts with specific file Share in the account does not support Download Directory or file share option Python SDK..

*But there's one class ShareFileClient Class which supports downloading of individual files inside a directory but not entire directory, you can use this class to download the files from directory with Python SDK.
Also you check Azure Portal > Select your Storage account > File Share and Directory > There's no option in Portal too to download the directory, but there's an option to download specific file.
As workaround, if you need to download directory from file-share, you can use Az copy tool command to download the directory in your local machine.
I tried to download the Directory with Az-copy command and was able to download to it successfully!
Command:
azcopy copy 'https://mystorageaccount.file.core.windows.net/myfileshare/myFileShareDirectory?sv=2018-03-28&ss=bjqt&srs=sco&sp=rjklhjup&se=2019-05-10T04:37:48Z&st=2019-05-09T20:37:48Z&spr=https&sig=/SOVEFfsKDqRry4bk3xxxxxxxx' 'C:\myDirectory' --recursive --preserve-smb-permissions=true --preserve-smb-info=true

Console:

Local environment:


text:
Q: Is there any way to kill (stop) a TFS 2017 team build from code? I have a TFS2017 build and the first step is to check if a required folder exists on the c:\ drive. That folder is a pre-requisite for the build to finish properly so if the folder doesn't exist I want to display an error message and kill the build. I've tried returning -1 but that doesn't stop the build from continuing. Is there any way to kill a running build programmatically?
Here's my current PS script that checks for the folder. I've substituted xxxx for my actual folder names (to protect the innocent ;-):
param([string]$DirSuffix="x")
<#
This script is called by the xxxx build to make sure that the GVB folder
exists on c:\ before the build is run. It should be called by passing in the
directory suffix (e.g. \xxxx 2.3.1). I can't figure out how to
kill the build
if the folder doesn't exist so I'm just going to write multiple errors to
the console and hope that the builder see them and cancels the build.
#>

[string] $WholeDirectory='C:\XXXX' + $DirSuffix
if (-NOT [IO.Directory]::Exists($WholeDirectory))
{
  Write-Host Directory $WholeDirectory does not exist - please make sure that the xxxx build has run first!!!
  Write-Host "##vso[task.logissue type=error;] Directory $WholeDirectory does not exist - please make sure that the xxxx build has run
  return -1
}

A: If you have multiple agents and you want to run the build only on the agent that required folder is exists, you can add this folder to the "Capabilities"
(Click here to photo),
and in the build definition you need to specify on the "Demands" that it's required (Click here to photo).

A: Instead of using return -1, you should use Logging Commands and exit code to fail a build task, then fail the entire build.
 Write-Error "Some error"
 exit 1

Add a powershell task to catch if the folder doesn't exist and judge if you have to fail the task or not.
More details about how to fail a vNext build please refer this question: How to fail the build from a PowerShell task in TFS 2015
Also remember to check the Fail on Standard Error  option in your powershell task and also select the condition Only when all previous tasks have succeeded to Run this task for the build task which next to powershell in your build pipeline. This will kill the build process.


text:
Q: Cocos2d with GameCenter, OpenGLError I get this error in a particular situation and i dont know how to solve it.
After i invite someone to play with me, i touch the 'uninvite' button then i hit cancell and it calls this method:
    // The user has cancelled matchmaking
- (void)matchmakerViewControllerWasCancelled:(GKMatchmakerViewController *)viewController {
    [self.presentingViewController dismissModalViewControllerAnimated:YES];
    NSLog(@"User cancelled the invitation.");
}

And after that happens i get this error:
OpenGL error 0x0506 in -[EAGLView swapBuffers]
Over and over again.
If i dont invite someone and just hit cancel, it calls that method again but it gets back to the game screen correctly. Have anyone seen something like this before? Do i have to stop the invitation before i dismiss the view or something?

A: I had similar issue and fixed it. It was hard to find a solution.
I had to change my init method in AppDelegate like this:
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
    CC_DIRECTOR_INIT();
    // Obtain the shared director in order to...
    CCDirector *director = [CCDirector sharedDirector];
    // Sets landscape mode
    [director setDeviceOrientation:kCCDeviceOrientationLandscapeLeft];

    if( ! [director enableRetinaDisplay:YES] )
        CCLOG(@"Retina Display Not supported");
    [[CCDirector sharedDirector] runWithScene: [MainMenuLayer scene]];
    [[CCDirector sharedDirector] setDisplayFPS:NO];
    [self authenticateLocalPlayer];
}

Dismiss:
-(void)achievementViewControllerDidFinish:(GKAchievementViewController *)viewController{
     [tempController dismissModalViewControllerAnimated:YES];
        [tempController.view removeFromSuperview];
     [[CCDirector sharedDirector] resume];
}

A: Not sure if this will help but maybe pause the CCDirector before displaying the Game Center UI and resume it when all the Game Center actions are done.


text:
Q: Tasking on Windows and the -gnatP switch What's the deal with the -gnatP (enable polling for asynch tasking operations) switch?
I'm working on a fairly large game project using GNAT, and the documentation claims that this switch is needed for Windows NT to allow various asynch tasking operations.  Since my project uses quite a lot of tasking, I've been trying to determine if I actually need this switch or not.
What I can't determine is if "Windows NT" in this context refers specifically to Windows NT, or to NT-based systems.  My searches on this topic have turned up blank.
This is concerning issue for me, since the inclusion of the polling code has a serious impact on the runtime performance of my project.  Everything appears to work correctly without it, but I haven't had time to test extensively, and I'm still afraid that something I'm not aware of will bite me in the end.
So to sum up:  Is -gnatP still needed for tasking on Windows systems?  If so, is there a way that I can invoke the poller manually so that I can at least have some measure of control over it?

A: AdaCore and GNAT make an overt effort to "do the right thing" with Ada on a particular platform.
My reading of the GNAT Pro User's Guide about -gnatP is that it's needed only if you need the ability in your program for "asynchronous abort and asynchronous transfer of control". An "asynchronous abort" I take to be an "abort task" statement, while "asynchonous transfer of control" is what it is.
If your program is not employing either of these features, then there is no need for -gnatP.
I've personally never used ATC, and used task abortion only until I figured out a better way to achieve what I was trying to do.
If your code is running fine without the switch so far, then I'm guessing that you're not using either of those features. And if you continue to avoid them, you should be fine.


text:
Q: interchanging double summation with the upper limit of one summation being other's index Let's say I have an infinite series $\sum_{n=1}^{\infty}\sum_{k=1}^{n}a_{nk}$ which converge. Now I want to interchange the order of summation to sum $n$ first, so the series become $\sum_{k=1}^{\infty}\sum_{n=k}^{\infty}a_{nk}$. I would like to ask, can we do that without assuming the series absolute converge? If we use limit notation, the first series is $\lim_{N\rightarrow\infty}\sum_{n=1}^{N}\sum_{k=1}^{n}a_{nk}$, if we change the order of summation, it becomes $\lim_{N\rightarrow\infty}\sum_{k=1}^{N}\sum_{n=k}^{N}a_{nk}$, there are no interchange of limit so it seems possible.

A: Let $a_{n,k}:=\frac 1{k^2}-\frac 1{(k-1)^2}$ for $k\geq 2$ and $a_{n,1}:=1$ for all $n$.
We have
$$
\sum_{n=1}^{+\infty}\sum_{k=1}^n a_{n,k} = \sum_{n=1}^{+\infty}\frac 1{n^2}=\frac{\pi^2}6.
$$
On the other hand
$$
\sum_{k=1}^{+\infty}\sum_{n=k}^{+\infty} a_{n,k}
$$
diverges, as already the inner sum diverges.


text:
Q: Can't update (deploy) page to Firebase host I looked for a while for similiar quest, but those solutions didn't work for me.
firebase deploy command doesn't change version on the web's url.
Even though there  is an update seen in the console there in no change seen in web.
I don't know if it's important but I run those commands from cmd

A: The page is updated, but your browser shows you the old version of the page. To fix this do a hard cache reset. Open the website in Chrome and press ctrl + shift + r.


text:
Q: python Mysql SELECT data not refreshed Non-commercial, non-professional user, seeking advice for hobbyist project.
I'm trying to pull data from one Pi, and scroll it on a second Pi.
However, terminal is showing repeats of the data initially loaded, not fresh data that I can see in the database.
(For info...The database is updated automatically every ten minutes. For tests like this, I am running a manual update script to force new readings into the database.)
#!/usr/bin/env python

import signal
import time
import scrollphathd
from scrollphathd.fonts import font5x7
import mysql.connector
from mysql.connector import Error
con = mysql.connector.connect(host='192.168.###############')

str_len = 0
scroll_x = 0
timer = 2 # number of mins for display loop

### Create cursorS for each database element:
### Keep in buffer with =True
while True:
    curT = con.cursor(buffered=True)
    curY = con.cursor(buffered=True)
    curL = con.cursor(buffered=True)

### Use each cursor to read required data from database:
    curT.execute('SELECT Temp FROM readings ORDER BY Added DESC LIMIT 1')
    curY.execute('SELECT Yaxis FROM readings ORDER BY Added DESC LIMIT 1')
    curL.execute('SELECT Lux FROM readings ORDER BY Added DESC LIMIT 1')

### Get rid of trailing comma from each SELECT result:
    resultT = [row[0] for row in curT.fetchall()]
    resultY = [row[0] for row in curY.fetchall()]
    resultL = [row[0] for row in curL.fetchall()]

### Not essential, but let's show the
### result of each SELECT query in the terminal:
    print resultT
    print resultY
    print resultL

    # set loop time in seconds
    start = time.time()
    end = start + ( timer + 60 )

### Set strings for display on Scroll PhatHD from SELECT results:
    while time.time() < end:
            temperature = resultT[0]
            yaxis = resultY[0]
            lux = resultL[0]

### Dim down Scroll Phat HD, and clear its buffer:
            scrollphathd.set_brightness(0.1)
            scrollphathd.clear()

### Uncomment/comment the below line to rotate Scroll PhatHD by 180/upside down
            scrollphathd.rotate(degrees=180)

### Uncomment line below to test all data on Scroll PhatHD in one go.
### str_len = scrollphathd.write_string(" :-) %.1fC Y%i L%i "%(temperature, yaxis, lux), brightness=0.5)

### Check light levels and door angle (Yaxis) and report appripriately. Always show the temperature:
            if lux <= 100 and yaxis >=3500 :
                str_len = scrollphathd.write_string("Garage: light off & door closed.  %.1fC Y%i "%(temperature, yaxis), x=0, y=0, font=font5x7)
            elif lux <= 100 and yaxis <500:
                str_len = scrollphathd.write_string("Garage: Light off & door open.  %.1fC "%(temperature), x=0, y=0, font=font5x7)
            elif lux > 100 and yaxis <500:
                str_len = scrollphathd.write_string("Garage: Light on & door open.  %.1fC "%(temperature), x=0, y=0, font=font5x7)
            elif lux > 100 and yaxis >=3500:
                str_len = scrollphathd.write_string("Garage: Light on & door closed.  %.1fC "%(temperature), x=0, y=0, font=font5x7)
            elif yaxis >500 and yaxis <3499:
                str_len = scrollphathd.write_string("Garage door ajar %.1fC  "%(temperature), x=0, y=0, font=font5x7)

            scrollphathd.scroll_to(scroll_x, 0)
            scrollphathd.show()
            time.sleep(0.01)
            scroll_x += 1
            if scroll_x >= str_len:
                scroll_x = 0

What do I need to change to make the display show fresh data from the database, and not repeated show old stale data?
Thank you.
EDIT:
I do wonder if it's in the cursor buffer, and if that needs flushing somehow between each SELECT loop?

A: I ran into this same problem with MySQL from different notebooks running Python. I was seeing obvious cases where my queries from one notebook was not seeing data being posted by the other ones.
This is a very simple solution, but I find it works well.
Just setup a fresh connection, then process the SQL, and at the end close the connection. Code in Python looks like:
import mysql.connector

def do_SQL_Stuff(rds_Dict):

   #Get RDS connection
   cnx_GDAX = mysql.connector.connect(
      host = rds_Dict['host'],
      user = rds_Dict['user'],
      password = rds_Dict['password'],
      database = rds_Dict['database'])

   #Do SQL stuff

   #Close RDS connection
   cnx_GDAX.close()

   return r_Stuff

This works well for my coding and totally removed this issue.

A: InnoDB problem with REPEATABLE READ, but a very simple solution I've come up is just by putting con.commit() in the end of your loop (before performing next SELECT). The commit method will clear the previous snapshot so the query will return the current real record. Cheers :)


text:
Q: XSLT 1.0 store nodeset in variable I would like to store a node set in my variable. I have something like this:
<xsl:variable name="kontrahenci">
    <xsl:for-each select="RAKS_R3/EXPORT/KONTAKTY/WIERSZ">
        <xsl:element name="WIERSZ">
            <xsl:attribute name="ID">
                <xsl:value-of select="@ID"/>
            </xsl:attribute>
            <!--<xsl:attribute name="KONTO_AKWIZYTORA">
                <xsl:value-of select="DANE_DODATKOWE/WIERSZ[1]/@KONTO_AKWIZYTORA"/>
            </xsl:attribute>-->
        </xsl:element>
    </xsl:for-each>
</xsl:variable>

And my XML file:
<?xml version="1.0" encoding="UTF-8"?>
<RAKS_R3>
   <EXPORT ID="1" DATA_EKSPORTU="2015-09-08" EKSPORTUJACY="ADMIN" WERSJA="24">
      <RAPORTY_KASOWE>
         <WIERSZ ID="2" ID_KASY="0" WALUTA_DOMYSLNA="PLN" NUMER="RK\0001\00" DATA_WYSTAWIENIA="2015-09-08" DATA_POCZATKU="2015-09-08" DATA_KONCA="2015-09-08" WALUTA="PLN" ID_WZORCA_RAPORTU="203" ID_PIERWSZEGO_DOKUMENTU="1" ID_OSTATNIEGO_DOKUMENTU="1" SALDO_OTWARCIA="0" SALDO_ZAMKNIECIA="50" NUMER_SERYJNY="1" NAZWA_WZORCA="RK" ZAREJESTROWAL="ADMIN" ZMODYFIKOWAL="ADMIN" DATA_REJESTRACJI="2015-09-08 15:57:07" DATA_MODYFIKACJI="2015-09-08 15:57:07" NUMER_ANALITYKI_KASY="" NAZWA_KASY="Kasa" KOD_WZORCA="RK">
            <DOKUMENTY_KASOWE>
               <WIERSZ ID="2" ID_WZORCA_DOKUMENTU="201" ID_KASY="0" ID_KONTAKTU="5" NUMER="KP\0001\00" TYP_DOKUMENTU="G" DATA_WYSTAWIENIA="2015-09-08" KWOTA="50" WALUTA="PLN" ROZLICZONY="False" WAZNY="True" KOD_KIERUNKU="I" ID_WNIOSKU_O_ZALICZKE="" ID_RAPORTU_KASOWEGO="2" OPIS="" ID_METODY_PLATNOSCI="0" NUMER_SERYJNY="1" ID_WALUTY="0" DOKUMENT_ZEWNETRZNY="False" KWOTA_PLN="50" ID_ROZRACHUNKU="29" ZAREJESTROWAL="ADMIN" ZMODYFIKOWAL="ADMIN" DATA_REJESTRACJI="2015-09-08 15:57:01" DATA_MODYFIKACJI="2015-09-08 15:57:01" KONTAKT_NAZWA_SKROCONA="n" KONTAKT_NAZWA_PELNA="n" KONTAKT_MIEJSCOWOSC="" KONTAKT_KOD_POCZTOWY="" KONTAKT_ULICA="" KONTAKT_NUMER_BUDYNKU="" KONTAKT_NUMER_LOKALU="" KONTAKT_NIP="" NAZWA_SERII_NUMERACYJNEJ="KP" ZNACZNIKI="" NUMER_DOKUMENTU_HANDLOWEGO="" />
            </DOKUMENTY_KASOWE>
         </WIERSZ>
      </RAPORTY_KASOWE>
      <ROZRACHUNKI>
         <WIERSZ ID="29" TYP_ROZR="Z" ID_KONTAKTU="5" KOD_WAL="PLN" DATA_OPER="2015-09-08" DATA_PLAT="" KWOTA="50" KWOTA_WAL="0" OPIS="KP\0001\00" KONTAKT_NAZWA_SKROCONA="n" KONTAKT_NIP="" />
      </ROZRACHUNKI>
      <KONTAKTY>
         <WIERSZ ID="5" ID_GRUPY="" NAZWA_GRUPY="" NAZWA_SKROCONA="n" NAZWA_PELNA="n" AKWIZYTOR="True" DOSTAWCA="False" ODBIORCA="False" KOD_KRESKOWY="" NIP="" TYP_KONTAKTU="0" ID_ADRESU_DOMYSLNEGO="4" ULICA="" NUMER_BUDYNKU="" NUMER_LOKALU="" KOD_POCZTOWY="" MIEJSCOWOSC="" WOJEWODZTWO="" KRAJ="Polska" KOD_KRAJU_UE="PL" UWAGI="" NEW_ID="" SPRZ_DETAL="0" KOD_WALUTY="PLN" POWIAT="" GMINA="" KOD_GMINY_WG_GUS="" POCZTA="" GLN="">
            <ADRESY>
               <WIERSZ NEW_ID="" ID="4" ULICA="" NUMER_DOMU="" NUMER_LOKALU="" KOD_POCZTOWY="" MIEJSCOWOSC="" WOJEWODZTWO="" KRAJ="Polska" NAZWA_TYPU="Adres firmowy" POWIAT="" GMINA="" KOD_GMINY_WG_GUS="" POCZTA="" GLN="" />
            </ADRESY>
            <DANE_DODATKOWE>
               <WIERSZ ID="5" KONTO_AKWIZYTORA="00001" KONTO_DOSTAWCY="" KONTO_ODBIORCY="" KONTO_PRACOWNIKA="" ID_TYPU_FIRMY="" NAZWA_TYPU_FIRMY="" REGON="" NUMER_REJESTRU_SADOWEGO="" PESEL="" NUMER_DOWODU_OS="" DATA_WYDANIA_DOWODU_OS="" ORGAN_WYDAJACY_DOWOD_OS="" PLATNIK_VAT="False" ROLNIK_INDYWIDUALNY="False" MAKS_WARTOSC_DLUGU_WOBEC_DOSTAWCY="0" MAKS_ILOSC_DOKUMENTOW_SPRZED_W_KREDYCIE="0" MAKS_ILOSC_DOKUMENTOW_SPRZED_W_KREDYCIE_PRZETERM="0" ID_AKWIZYTORA="" PROWIZJA="0" MAKS_WARTOSC_KREDYTU_DLA_KLIENTA="0" MAKS_WARTOSC_KREDYTU_DLA_KLIENTA_PRZETERM="0" ID_SPOSOBU_ZAPLATY="" ID_SPOSOBU_ZAPLATY_DOST="" SPOSOB_LICZENIA_DOST="0" ID_RODZAJU_CENY="" ID_RABATU="" ID_WALUTY="" KOD_WALUTY="" NAZWA_WALUTY="" MNOZNIK="" ID_PLATNIKA="" BLOKADA="False" BLOKADA_POWOD="" KREDYT="0" DLUG="0" NEW_FIRM_ID="" NEW_SM_ID="" ID_NAGLOWKA="5" NEW_WORKER_ID="" MASS_PAYMENT_NR="" NASZ_NUMER_U_KONTRAHENTA="" IMIE_PIERWSZE="" IMIE_DRUGIE="" NAZWISKO="" NAZWISKO_RODOWE="" NAZWA_WYSWIETLANA="" PLEC="" DATA_URODZENIA="" JEZYK="" NARODOWOSC="" OBYWATELSTWO="" HOBBY="" WSPOLMALZONEK="" URODZINY_WSPOLMALZONKA="" ROCZNICA_SLUBU="" ZLECENIOWY="" ETATOWY="" ARCHIWALNY="0" DATA_ROZP_ROZLICZEN="" TYP_DOK_TOZSAMOSCI="" IMIE_OJCA="" IMIE_MATKI="" MIEJSCE_URODZENIA="" TYTUL_NAUKOWY="" US_NAZWA="" US_ULICA="" US_DOM="" US_KOD_POCZTOWY="" US_MIEJSCOWOSC="" NR_AKTU_MALZENSTWA="" WSPOLNE_GOSPODARSTWO="" WYNAGRODZENIE_PRZELEWEM="" KOD_ODDZIALU_NFZ="" DOK_TOZS_WYDANY_PRZEZ="" DOK_TOZS_WAZNY_OD="" DOK_TOZS_WAZNY_DO="" IDENTYFIKATOR_PODATKOWY="" IDENTYFIKATOR_PLATNIKA="" ID_ADRESU_DO_DEKLARACJI="" KRAJ_DO_DEKLARACJI="" IDENT_DO_DEKLARACJI="" RODZAJ_IDENT_DO_DEKLARACJI="" NIEREZYDENT="" />
            </DANE_DODATKOWE>
         </WIERSZ>
      </KONTAKTY>
   </EXPORT>
</RAKS_R3>

It's not working the variable is empty, is there any possibility to store a node set in variable in XSLT 1.0?

A: In XSLT-1.0, you need to use an extension, especially the node-set extension
You will need to add the following declarations on the root of your stylesheet:
            xmlns:exsl="http://exslt.org/common"
            extension-element-prefixes="exsl">

and then you can use your variable as a node like this (for example):
<xsl:value-of select="exsl:node-set($kontrahenci)/some/xpath" />

or like this:
<xsl:for-each select="exsl:node-set($kontrahenci)/some/xpath">

You might be also interested in the list of processors implementing exslt.


text:
Q: Ticking noise from guitar pedal attempt I am working on a tremolo guitar pedal circuit. A tremolo pedal basically attenuates the guitar signal using a pattern. Most tremolos use a combination of LEDs and LDRs to do this, but since I do not have any LDRs at the moment I chose to design one using a digital potentiometer.

For simplicity I have not included the digital side of the circuit. This only consists of an Arduino Nano, connected to the digital potentiometer using SPI.
I have breadboarded the circuit and it works, except it makes a ticking sound. It is very noticeable on the high gain setting on my amplifier. At first I thought it was an issue with the Arduino, but after removing both the Arduino and the digipot -- and replacing the digipot with a resistor -- the issue persists. I have no idea what is going on. Could it be an oscillation of some sort? Should the schematic work and lies the error in my breadboarded implementation?
Thanks in advance!

A: C7 is back to front. Its positive side is at +2.5 V and its negative at +4.5 V. Also the TL074 really needs a supply of at least 10 V (see data sheet). The common mode voltage of the op-amp needs to be at least 4 V above the negative rail too. This is not the case in the second stage.
An LM324 might work better although its audio qualities are poor (crossover distortion) but you could try it for starters.

A: Your +9V/2 voltage reference is probably the cause of the oscillations.
R3 and R4 are quite big resistors which means that only a small current is 'creating' the voltage reference.
As R10 and R11 are small (at least relatively speaking in comparison with R3 and R4) they allow currents to pass that will overwhelm the small current thus your voltage reference will fluctuate according to the signals that are present.
As the voltage reference is used in several places in your schematic you have created a feedback loop.
Easiest way to fix it is by decreasing the resistance of R3 & R4 and increasing the resistance of R10 & R11 using your spare op-amp as buffer as
Steve Hubbard has suggested.


text:
Q: A question on spotting the error.What are the following errors in this python3 script? #!/usr/bin/env python3
# trimAll.py
#Initialize variable to contain the directory of un-trimmed fastq files
fastqPath="/scratch/AiptasiaMiSeq/fastq/"
#Initialize variable to contain the suffix for the left reads
leftSuffix=".R1.fastq"
rightSuffix=".R2.fastq"
pairedOutPath="Paired/"
unpairedOutPath="Unpaired/"
#Loop through all the left-read fastq files in $fastqPath
for leftInFile in $fastqPath*$leftSuffix
do
    #Remove the path from the filename and assign to pathRemoved
    pathRemoved="${leftInFile/$fastqPath/}"
    #Remove the left-read suffix from $pathRemoved and assign to suffixRemoved
    sampleName="${pathRemoved/$leftSuffix/}"
    nice -n19 java -jar /usr/local/programs/Trimmomatic-0.36/trimmomatic-0.36.jar PE \
    -threads 1 -phred33 \
    $fastqPath$sampleName$leftSuffix \
    $fastqPath$sampleName$rightSuffix \
    $pairedOutPath$sampleName$leftSuffix \
    $unpairedOutPath$sampleName$leftsuffix \
    $pairedOutPath$sampleName$rightSuffix \
    $unpairedOutPath$sampleName$rightSuffix
    HEADCROP:0 \
    ILLUMINACLIP:/usr/local/programs/Trimmomatic-0.36/adapters/TruSeq3-PE.fa:2:30:10
    LEADING:20 TRAILING:20 SLIDINGWINDOW:4:30 MINLEN:36
done

Basically, the code is a Python Script and I am trying to find an error.What is the error in this piece of code?

A: Trimmomatic in 'PE' mode expects forward ("left") and reverse ("right") reads; this for loop is only looking at left reads ('$fastqPath*$leftSuffix') so it will fail. If you replace for leftInFile in $fastqPath*$leftSuffix with for leftInFile in $fastqPath*.fastq it should work as expected. Also, this looks to be a shell script, not a python script, so change your shebang to #!/bin/bash. Also, your trimming parameters are fairly strict (e.g. see https://www.frontiersin.org/articles/10.3389/fgene.2014.00013/full) - you may want to consider easing them off a bit, depending on your application.


text:
Q: How do I manually insert an item in a VB.net Combobox? I've created a Combobox and the list selections are being populated by a DataTable. I can populate it with no problems, but I need to add a default item for the list before the results from the DataTable appears.
The list should contain:
All Rooms and Facilities
Class Room
Laboratory
PE Facility
THE Facility
Drawing Room
Library

But I'm always getting:

I've been using this link as my resources:
https://msdn.microsoft.com/en-us/library/aa983551.aspx
And here's my code:
cboByRoomType.Items.Insert(0, "All Rooms and Facilities")
With cboByRoomType
    .DataSource = tempDTRoomType
    .DisplayMember = "Description"
    .ValueMember = "Room Type ID"
    .SelectedIndex = 0
End With

Also, I already tried to add the default item using the Items in the Properties Window, still no good.

A: Try replacing your first row with this (which probably has a more compact form):
    tempDTRoomType.Rows.InsertAt(tempDTRoomType.NewRow(), 0)
    tempDTRoomType.Rows(0).Item("Description") = "All Rooms and Facilities"
    tempDTRoomType.Rows(0).Item("Room Type ID") = 0


text:
Q: CSS responsive images I've been trying to adjust these styles.
On this page: http://69.195.124.215/~vtiffcom/about-vtiff/.
I have a div for my logo and one for the subhead. The logo is the icon. The subhead is the text "Vermont International Film Festival"
When the browser resizes, the subhead falls under the logo, then begins resize according to browser width. I'd like to resize, then fall under the logo.
I know the second step will come from style applied to the media query, but how do I get it to resize until the first media query.
I've tried most combinations of width/max-width/height:auto, but I can't get the subhead to resize prior to falling underneath the logo.
Thanks--

A: Remove the float: left; and float: right; from the 2 elements. Add display: inline-block; to id=container2 and give it a percentage width: 60%; or so.. that should get you covered. Enjoy :)

A: See my Fiddle: http://jsfiddle.net/Whre/acsa9/
What I did there is applying a width (in percent) to the image's parent elements instead of max-width.
Your approach of img { max-width:100%; } was absolutely correct apart from that.


text:
Q: Calculating aged tickets open at a given point in time Background:
We have a ticketing system and each ticket has fields such as open date, close date, category, type, etc. Each ticket is represented by one row in my data with a key to identify the ticket.
An individual record might look like:
Number, Type, Category, Opened, Closed
TICKET100, Database, Software, 2/1/2020 11:30 AM, 4/22/2020 4:40 PM

Goal:
My goal is to create a function that takes an input dataframe (pandas), some type of input age parameter, and a list of attributes/dimensions. The function would then return a dataframe of how many tickets were open past a certain age based on that age parameter, by each of the attributes/dimensions, by date.
Example of input:
ticket_age(input_dataframe, age=5, dimensions=['Type','Category'])

Example snippet of desired output:
Date, Type, Category, Count
3/1/2020, Database, Software, 1
3/2/2020, Database, Software, 1
...
4/22/2020, Database, Software, 0

An important note about the output... if the intersection of the date and the dimensions doesn't have any tickets that satisfy the condition, it should create a row with a count of 0.
Where I'm stuck:
I have no idea how to accept the dimensions of a list of unknown size and iterate through all of them.
What have I tried? I've been successful in generating the ticket counts that meet the age criteria when I hard code the loops through dimensions.
How I calculate type_list, first_date, and total_days:
    #Create function to find the minimum date
def date_minimum(input_dataframe, date_to_check):
    return input_dataframe[date_to_check].min().date()

#Create function to find the maximum date
def date_maximum(input_dataframe,date_to_check):
    return input_dataframe[date_to_check].max().date()

    #setup min and max dates
    min_date=date_minimum(df_aged_input,'Opened')
    max_date=date_maximum(df_aged_input,'Closed')
    #Get the first relevant date for the dataframe loop
    first_date=min_date+datetime.timedelta(days=aged_window)

    # Generate a list of unique assignment groups
    type_list=df_aged_input['Type'].unique().tolist()

My loop
aged_output_list=[]
for type_iterate in range(len(type_list)):
    #filter by the type
    aged_type=type_list[type_iterate]
    df_aged_input=df_tkt_relevant[df_tkt_relevant['Type']==aged_type].copy()
    for date_iterate in range(totalDays.days):
        #generate the aged date iterator
        aged_date=first_date+datetime.timedelta(days=date_iterate)
        #Count the number of records in the data frame that match the input conditions
        aged_frame=df_aged_input[(~(df_aged_input['Closed'].dt.date<aged_date))&(df_aged_input['Opened'].dt.date<(aged_date-datetime.timedelta(days=aged_window+1)))].copy()
        aged_frame['aged_Date']=aged_date-datetime.timedelta(days=1)
        aged_count=aged_frame.shape[0]
        #Write the date from iterative date and the aged count to a new data source
        aged_output_list.append([aged_date,aged_type or 'Error: Missing Type',aged_count])

What do I do next? Is there another library that does all of this for me?

A: IIUC
import pandas as pd
from pandas.tseries.offsets import DateOffset
from io import StringIO
import numpy as np

# sample data
s = """Number,Type,Category,Opened,Closed
TICKET100,Database,Software,2/1/2020 11:30 AM,2/22/2020 4:40 PM
TICKET101,Database,Software,2/10/2020 11:30 AM,2/23/2020 4:40 PM
TICKET102,Database,Software,2/11/2020 11:30 AM,2/22/2020 4:40 PM
TICKET103,something,else,2/10/2020 11:30 AM,2/23/2020 4:40 PM
TICKET104,something,else,2/12/2020 11:30 AM,2/22/2020 4:40 PM"""
df = pd.read_csv(StringIO(s))

# convert to datetime
df['Opened'] = pd.to_datetime(df['Opened'])
df['Closed'] = pd.to_datetime(df['Closed'])

# create a function
def myFunc(df, age, dimensions):
    # zip the date offset for open and close together
    z = zip(df['Opened'].dt.date + DateOffset(age), df['Closed'].dt.date - DateOffset(age))
    # create a daterange for each record in the dataframe
    df['date_range'] = [pd.date_range(o, c, freq='D') for o,c in z]
    # groupby your dimensions columns
    g = df.groupby(dimensions)
    # list comprehension for each group and create the date range
    idxs = [pd.date_range(df['Opened'].min(), df['Closed'].max(), freq='D',
                          normalize=True) for _,df in g]
    # sum all the true values where the datetime index create above
    # is in the date_range column
    l = [[sum(df[1]['date_range'].apply(lambda x: idx.isin(x))),
          idx, [df[0]]*len(idx)] for idx,df  in zip(idxs, g)]
    # transpose and hstack the list
    arr = np.transpose(np.hstack(l))
    # return pandas dataframe
    return pd.DataFrame(arr, columns=['count', 'date', 'dimensions'])

out = myFunc(df, 5, ['Type', 'Category'])

    count       date             dimensions
0       0 2020-02-01  (Database, Software)
1       0 2020-02-02  (Database, Software)
2       0 2020-02-03  (Database, Software)
3       0 2020-02-04  (Database, Software)
4       0 2020-02-05  (Database, Software)
5       1 2020-02-06  (Database, Software)
6       1 2020-02-07  (Database, Software)
7       1 2020-02-08  (Database, Software)
8       1 2020-02-09  (Database, Software)
9       1 2020-02-10  (Database, Software)
10      1 2020-02-11  (Database, Software)
11      1 2020-02-12  (Database, Software)
12      1 2020-02-13  (Database, Software)
13      1 2020-02-14  (Database, Software)
14      2 2020-02-15  (Database, Software)
15      3 2020-02-16  (Database, Software)
16      3 2020-02-17  (Database, Software)
17      1 2020-02-18  (Database, Software)
18      0 2020-02-19  (Database, Software)
19      0 2020-02-20  (Database, Software)
20      0 2020-02-21  (Database, Software)
21      0 2020-02-22  (Database, Software)
22      0 2020-02-23  (Database, Software)
23      0 2020-02-10     (something, else)
24      0 2020-02-11     (something, else)
25      0 2020-02-12     (something, else)
26      0 2020-02-13     (something, else)
27      0 2020-02-14     (something, else)
28      1 2020-02-15     (something, else)
29      1 2020-02-16     (something, else)
30      2 2020-02-17     (something, else)
31      1 2020-02-18     (something, else)
32      0 2020-02-19     (something, else)
33      0 2020-02-20     (something, else)
34      0 2020-02-21     (something, else)
35      0 2020-02-22     (something, else)
36      0 2020-02-23     (something, else)


text:
Q: Best way to design this code? I have a log function which takes a parameter, which prints out the name of some HW
logEvent("LOG THIS HW select = %s", NAME[selection]);

To determine what to print I have:
const char* NAME[] =
{
"A"
"B"
}

This was in the header but then I got multiple implementations problems, I want this to be accessed by many files.  How can I put this kind of data in a header?

A: Adjust logEvent so selection is passed as a parameter. You can then keep the string table local to that function.

A: You put a declaration in the header:
extern const char* NAME[];

and put the definition in one cpp file:
const char* NAME[] = {"A", "B"};


text: Q: Ubuntu 16.06 mysql 5.6 file privileges I have mysql 5.6 installed on Ubuntu 16.06.  I get an error on LOAD DATA  INFILE saying (Errcode: 13 - Permission denied). I have tried to set secure_file_priv, in a config file but I don't even know if it is taking and it is not fixing the error.  Any ideas?  Thanks!


text:
Q: Braided monoidal categories I know that it has been shown that $E_2$ algebra objects in Categories are simply braided monoidal categories.
In particular, Lurie says that an $E_2$-monoidal structure on the infinity-category $N(C)$ (the nerve of a category C) is a braided monoidal structure on C.
Is there a generalization (not sure if this is the right word) of this where instead of having braiding isomorphisms we have: $b_{V,W}:V\otimes W\to W\otimes V$ is a quasi-isomorphism?
Obviously, we need some dg-structure, so we would be talking about an $E_2$-monoidal structure on the dg-nerve of a dg-category.
What would the implications be for the composition $b_{W,V}\circ b_{V,W}$ when compared to the identity quasi-isomorphism $\mathrm{id}:V\otimes W\to V\otimes W$?
I am interested in possible new knot invariants.
Any thoughts or improvements on how I am asking the question are highly appreciated.


text:
Q: How to generate password protected excel report using JasperReports? I am trying to generate a simple password protected excel report.
Java code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JExcelApiExporterParameter;

public class Report {

    public static void main(String[] args) {
        try {
            JasperReport jasperReport;
            JasperPrint jasperPrint;

            Connection connection = establishConnection();
            HashMap jasperParameter = new HashMap();

            jasperReport = JasperCompileManager.compileReport("D:\\Jasper\\report1.jrxml");
            jasperPrint = JasperFillManager.fillReport(jasperReport, jasperParameter, connection);

            JExcelApiExporter exporter = new JExcelApiExporter();
            exporter.setParameter(JExcelApiExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JExcelApiExporterParameter.OUTPUT_FILE_NAME, "D:\\Jasper\\simple_report.xls");
            exporter.setParameter(JExcelApiExporterParameter.PASSWORD, "sam");

            exporter.exportReport();
        } catch (JRException e) {
            e.printStackTrace();
        }
    }

    public static Connection establishConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String mySQL = "jdbc:mysql://localhost:3306/test";
            connection = DriverManager.getConnection(mySQL, "root", "Infy123+");
            connection.setAutoCommit(false);
        } catch (SQLException | ClassNotFoundException exception) {
            exception.printStackTrace();
        }
        return connection;
    }
}

report1.jrxml:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports     http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report1" language="groovy"     pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20"     topMargin="20" bottomMargin="20" uuid="ac32c69e-bb80-4dc5-9139-f9b085ffa739">
    <queryString language="SQL">
        <![CDATA[SELECT * FROM test.item]]>
    </queryString>
    <field name="ITEM_NAME" class="java.lang.String">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <field name="ITEM_DESCIPTION" class="java.lang.String">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <field name="ITEM_AMOUNT" class="java.lang.Integer">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="36" splitType="Stretch"/>
    </title>
    <pageHeader>
        <band height="35" splitType="Stretch"/>
    </pageHeader>
    <columnHeader>
        <band height="41" splitType="Stretch">
            <staticText>
                <reportElement x="13" y="11" width="100" height="20"     uuid="97ab8c4f-ec9e-47a1-807e-37e2adbf9d36"/>
                <text><![CDATA[ITEM NAME]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="43" splitType="Stretch">
            <textField>
                <reportElement x="13" y="11" width="100" height="20"     uuid="0fe760df-5c76-499f-8f79-3308680e9a37"/>
                    <textFieldExpression><![CDATA[$F{ITEM_NAME}]]>        </textFieldExpression>
                </textField>
        </band>
    </detail>
    <columnFooter>
        <band height="45" splitType="Stretch"/>
    </columnFooter>
    <pageFooter>
        <band height="54" splitType="Stretch"/>
    </pageFooter>
    <summary>
        <band height="42" splitType="Stretch"/>
    </summary>
</jasperReport>

The file is getting generated but is not password protected.
I am using JasperReports-5.5.0 and iReport 5.5.0.
How to resolve this issue?

A: You can disable the editing of the Excel report using the inbuilt POI api provided in the JasperReport. However, excel can still be opened.
The password protected is applicable only for the Excel editing option.
I would also be interested to know if there's a way to password protect excel document itself.. Could not find anything in Apache POI.


text:
Q: Using model callback with Simulink Coder I am using Matlab 2012a and the Simulink Coder (aka Real-Time Workshop). I want to compile the model using Simulink Coder but preserve the functionality of model callbacks.

Consider the following simple example. I have a Simulink model, callBackTest, which reads in a constant and outputs to a since. input1 is defined in myValues.m and loaded into the model workspace using the PreLoadFcn model callback. The PreLoadFcn callback is executed when the model is first opened. By using the PreLoadFcn callback, input1 will automatically be defined every time the model is opened.

Suppose myValues.m is originally coded as input1=1. When you run the simulation, yout will be an array of 1s. Also if I compile the model using the Simulink coder, the output will also be an array of 1s. However if I modify myValues.m so that input1 = 2 and do not recompile, the realtime output is still 1. This is wrong, so how can I read variables from a file into the model workspace with a compiled model?

A: This does not answer your question about Model callbacks, but it might be helpful anyway.
If the "Inline Parameters" option is checked in:
Preferences -> Optimization -> Signals and Parameters
there is no way to change values in an already compiled model because they are hardcoded. Once you have this option turned off and you have recompiled, you could for example connect with external mode and run your myValues.m script and the values will be updated (unless you have marked them as non-tuneable).

A: You cannot generate code for model callbacks. If you do not want to regenerate code every time you change your input you can try using "From File" block which can read data from a .mat file. When you want to change your data you can then run your MATLAB code and save the output data into the same .mat file. There are some restrictions on what kind of data is supported for code generation from this block. Check out the doc for that block for details.
If your data is not too big you can also edit the generated source to modify the data. Data from Constant block is usually in-lined in the generated source code. After editing you can compile the generated code to produce new binary.
Another approach is to write your custom C S-Function where you can read from your own data sources. You need to write a TLC file to support code generation for this S-Function.
You need to recompile your model if these does not work for you. Documentation at http://www.mathworks.com/help/simulink/ug/importing-signal-data-in-simulink.html lists different ways of importing signal data into Simulink.


text:
Q: Sass calc decleration dropped Chrome I am writing a simple grid layout using Sass. I am trying to use calc() to determine the width in relative units %. To test the styles, I am using a simple HTML file.
Problem: Inspecting the results with dev tools on Chrome, it shows that the width declaration with the calc() call is dropped as Invalid property value. Here is the code:
src.html
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="X-UA Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width initial-scale=1.0">
        <link rel="stylesheet" type="text/css" href="./../css/12grid_rwd.css">

src.scss
$context-width: 1200;
// Grid >> 12 Columns
.grid {
    &_1 { width: calc(calc(80/#{$context-width})*100); }
}

generated css:
.grid_1 {
  width: calc(calc(80/1200)*100); }

A: calc() call's can't be nested, it expects expression to calculate, it is the reason why your property is dropped by browser.
Moreover since your expression contains plain math - it can be calculated by Sass itself. Moreover from your expression it looks like you want resulted value to be percent from container's width, in this case you can use percentage() function from Sass:
$context-width: 1200;
$column-width: 80;
// Grid >> 12 Columns
.grid {
  @for $n from 1 through 12 {
    &_#{$n} {
      width: percentage($column-width * $n/$context-width);
    }
  }
}

You can play with this example at Sassmeister.

A: Following the suggestions from @Flying, I was able to implement the logic I wanted. The code is much simpler to understand and debug.
Goal: To have a 1280 pixels grid system with 20px margin on container and 20px padding on the grids. Note that these margin and padding properties are for left and right only (10px each side). Starting with a first grid, class grid_1, at 80px, grid_2 will be 80*2 + 20*(2-1) where 80 is the fixed column width, 2 is the grid number, 20 is the paddingand so on. The scss code is as follows:
src.scss
$context-width: 1200;
$column-width: 80;
$fixed-gutter: 20;

// Grid >> 12 Columns

@mixin width-calc($n) {
  @if $n == 1{
    width: percentage(($column-width * $n)/$context-width);
  }
  @else {
    $c: $column-width * $n + ($fixed-gutter * ($n - 1));
    width: percentage(($c)/$context-width);
  }
}

.grid {
  @for $n from 1 through 12 {
    &_#{$n} {
      @include width-calc($n);
    }
  }
}

The generated css:
.grid_1 {
  width: 6.66667%;
}
.grid_2 {
  width: 15%;
}
.grid_3 {
  width: 23.33333%;
}
.grid_4 {
  width: 31.66667%;
}
.grid_5 {
  width: 40%;
}
.grid_6 {
  width: 48.33333%;
}
.grid_7 {
  width: 56.66667%;
}
.grid_8 {
  width: 65%;
}
.grid_9 {
  width: 73.33333%;
}
.grid_10 {
  width: 81.66667%;
}
.grid_11 {
  width: 90%;
}
.grid_12 {
  width: 98.33333%;
}


text:
Q: Omitting y-axis ticks (and labels) in base R The Question:
Imagine I am making a simple plot: plot(1:5,1:5,ylab = "y-axis"). Here, the y-axis (well actually both axis) are not only nicely labeled, but they both have tick marks with labels. How would I go about making a plot with neither tick marks nor tick mark labels?
What I've tried
The first thing I've tried was removing the margins to the left of the graph, while this effectively worked, it was a bit hacky and didn't get at what my actual problem was. I then continued to dive into the par specifications. Setting par(tck = 0) removes y-axis tick marks, but does so by removing all tick marks on the graph - this isn't ideal. I also tried par(ann = FALSE), and par(cex.lab = 0.001, cex.axis = 0.001) which also did not work.
I'm pretty sure the answer to my question is burried somewhere in the par specifications but for now, unfortunately, I will have to stick with removing the left margins to 'cut off' these undesirable labels.


text:
Q: jQuery, Sortabtable: I want to drag at the center, but height is wrong? I have the following draggable list items structure:

1

2

3

4

5

the jQuery:
dad_list.sortable({
    connectWith: 'ul.dad-list',
    containment: '#containment',
    items: 'li.dad-item',
    cursorAt: {
        top: Math.round($(this).outerHeight() / 2)
    },
    stop: function(event, ui) {
        serializedads();
    }
});

this all is OK, but it looks .outerHeight() is 0, the dragged item stucks to the top. I need the height / 2 position.

A: Try
cursorAt: function(ui){
    top: Math.round($(ui.item).outerHeight() / 2)
}


text:
Q: Calculating an SLA and considering statistical confidence When calculating a Service Level Agreement (SLA) one might consider the %age of successful transactions with the system. E.g. if 99 out of 100 transactions fail, the 99.9% SLA was not met.
However, this introduces a lot of 'noise' where some clients only have two transactions and one can fail - meaning only a 50% SLA was achieved.
How could we factor in statistical methods here to create a more concrete rule. For example, something like: 'where 99.9% of transactions succeed with a statistical confidence of 80%'.
Forgive the poor nomenclature but the idea would be that there would need to be statistically significant number of failures, with 80% certainty that the service was below 99.9%.
Be great to hear some approaches on how we might model this statistically.

A: $\DeclareMathOperator{\Beta}{Beta}$How about some sort of Bayesian analysis of the probability of failure?
The first step is to pick your prior distribution for the probability of success $s$. That is, before you see the results of any transactions, how probable do you think it is that $s$ is equal to a given value? Because we're looking at the results of independent trials, we should probably use a prior from the Beta family, because it makes it easy to update your beliefs. (If your prior for $f$ is a $\Beta(a, b)$ and you observe that a request succeeds or fails, your posterior belief about $f$ after you update on this evidence is a $\Beta(a+1, b)$ or $\Beta(a, b+1)$ distribution, respectively.) I'll talk more about picking the prior later, but suppose for now that it's a $Beta(a, b)$ for some $a$ and $b$.
Suppose your client makes $N$ requests and observes $F$ failures. Then your posterior distribution for $s$ is $\Beta(a+F, b+N-F)$. Then you can compute your subjective probability that $s < 0.99$ (or whatever your SLA is) using the CDF of the Beta distribution: $$p(s < 0.99) = \frac{B(0.99; a+N-F, b+F)}{B(a+N-F, b+F)}$$ where $B$ is the beta function (see Wiki on the link for details).
So how to choose a prior? A relatively uncontroversial choice would be the uniform prior $a = b = 1$, but this would make things quite tough for you, since you start out with 99% confidence that you will fail to make the SLA! In fact it would be pretty much impossible for you to overcome this with less than 100 trials (even if you succeeded in all 100 of them, you would still have 36% credence that you were failing your SLA). There are a couple other options:

*

*You could pool the results from similar clients as @fg nu commented.

*You could use the results from previous iterations of service. If you wanted to be fancy, you could weight them by time, so a success from 1 day ago counted as a full success, but a success from a year ago only counted as 1/2 success for your prior. If you make the weights decay exponentially, then this puts a limit on the amount that your prior can matter compared to the data you observe (although it's somewhat ad-hoc).

*You could pull something like $\Beta(101, 1)$ out of thin air. (This corresponds to saying that your client is as confident that you will uphold their SLA as they would be if they started from no preconceptions and then saw 100 successes in a row. They may or may not agree to this, but if their expectations are much lower than that, perhaps you need different clients!)
Of course, whether you could get your clients to understand this--let alone agree to it--is another matter entirely! Negotiating over priors is a notoriously tricky and subjective business, even for statisticians, let alone people who just want to buy software.


text:
Q: how can i put (keras/apply_affine_transform) to work ? (theta) I'm trying to rotate an image with keras affine tranformation (theta).
the output i'm reveiving is:
output here
import skimage.io as io
import matplotlib.pyplot as plt
import numpy as np

image = io.imread("dog.jpg")
plt.imshow(image)
plt.show()

import tensorflow as tf
transformed=tf.keras.preprocessing.image.apply_affine_transform(image, theta=45)
plt.imshow(transformed)
plt.show()

What can i do to rotate the image with affine transformation ?

A: Add row_axis=0, col_axis=1, channel_axis=2 to apply_affine_transform()'s arguments.
Your image's memory layout is "channels-last", but the function thinks it is "channels-first". It (incorrectly) thinks the image laid out as [C,H,W], rather than [H,W,C].


text:
Q: List of compiled regexes in Python I have a lot of substitution patterns which I need for text cleaning. I load the data from a database and compile the regular expressions before for performance reasons.
Unfortunately with my approach only the last assignment of the variable "text" seems to be valid, while the others appear to be overwritten:
# -*- coding: utf-8 -*-
import cx_Oracle
import re

connection = cx_Oracle.connect("SCHEMA", "passWORD", "TNS")
cursor = connection.cursor()
cursor.execute("""select column_1, column_2
from table""")

# Variables for matching
REPLACE_1 = re.compile(r'(sample_pattern_1)')
REPLACE_2 = re.compile(r'(sample_pattern_2)')
# ..
REPLACE_99 = re.compile(r'(sample_pattern_99)')
REPLACE_100 = re.compile(r'(sample_pattern_100)')

def extract_from_db():
    text = ''
    for row in cursor:
        # sidenote: each substitution text has the the name as the corresponding variable name, but as a string of course
        text = REPLACE_1.sub(r'REPLACE_1',str(row[0]))
        text = REPLACE_2.sub(r'REPLACE_2',str(row[0]))
        # ..
        text = REPLACE_99.sub(r'REPLACE_99',str(row[0]))
        text = REPLACE_100.sub(r'REPLACE_199',str(row[0]))
        print text

extract_from_db()

Does anyone know how to solve this in a working, elegant way? Or do I have to pound this through huge if/elif control structure?

A: You keep replacing the last result with a replacement on str(row[0]). Use text instead to accumulate substitutions:
text = REPLACE_1.sub(r'REPLACE_1', str(row[0]))
text = REPLACE_1.sub(r'REPLACE_1', text)
# ..
text = REPLACE_99.sub(r'REPLACE_99', text)
text = REPLACE_100.sub(r'REPLACE_199', text)

You'd be better of using an actual list instead:
REPLACEMENTS = [
    (re.compile(r'(sample_pattern_1)'), r'REPLACE_1'),
    (re.compile(r'(sample_pattern_2)'), r'REPLACE_2'),
    # ..
    (re.compile(r'(sample_pattern_99)'), r'REPLACE_99'),
    (re.compile(r'(sample_pattern_100)'), r'REPLACE_100'),
]

and use those in a loop:
text = str(row[0])
for pattern, replacement in REPLACEMENTS:
    text = pattern.sub(replacement, text)

or using functools.partial() to simplify the loop a bit further:
from functools import partial

REPLACEMENTS = [
    partial(re.compile(r'(sample_pattern_1)').sub, r'REPLACE_1'),
    partial(re.compile(r'(sample_pattern_2)').sub, r'REPLACE_2'),
    # ..
    partial(re.compile(r'(sample_pattern_99)').sub, r'REPLACE_99'),
    partial(re.compile(r'(sample_pattern_100)').sub, r'REPLACE_100'),
]

and the loop:
text = str(row[0])
for replacement in REPLACEMENTS:
    text = replacement(text)

or using the above list of patterns wrapped in partial() objects, and reduce():
text = reduce(lambda txt, repl: repl(txt), REPLACEMENTS, str(row[0])

A: Your approach is fine; however, on every line, you are applying the regex to the original string. You need to apply it to the result of the previous line, i.e.:
def extract_from_db():
    text = ''
    for row in cursor:
        # sidenote: each substitution text has the the name as the corresponding variable name, but as a string of course
        # This one stays the same - initialize from the row
        text = REPLACE_1.sub(r'REPLACE_1',str(row[0]))
        # For these, route text back into it
        text = REPLACE_2.sub(r'REPLACE_2',text)
        # ..
        text = REPLACE_99.sub(r'REPLACE_99',text)
        text = REPLACE_100.sub(r'REPLACE_100',text)
        print text

A: It looks like what you need is:
    text = REPLACE_1.sub(r'REPLACE_1',str(row[0]))
    text = REPLACE_2.sub(r'REPLACE_1',text)
    # ..
    text = REPLACE_99.sub(r'REPLACE_99',text)
    text = REPLACE_100.sub(r'REPLACE_199',text)

A: Might I suggest building a list of patterns and their replacement values, then iterating across it? Then you don't have to modify the function every time you want to update the patterns:
import cx_Oracle
import re

connection = cx_Oracle.connect("SCHEMA", "passWORD", "TNS")
cursor = connection.cursor()
cursor.execute("""select column_1, column_2
from table""")

REPLACEMENTS = [
    (re.compile(r'(sample_pattern_1)'), 'REPLACE_1'),
    (re.compile(r'(sample_pattern_2)'), 'REPLACE_2'),
# ..
    (re.compile(r'(sample_pattern_99)'), 'REPLACE_99'),
    (re.compile(r'(sample_pattern_100)'), 'REPLACE_100'),
]

def extract_from_db():
    for row in cursor:
        text = str(row[0])
        for pattern, replacement in REPLACEMENTS:
            text = pattern.sub(replacement, text)

        print text

extract_from_db()


text:
Q: Find specific varchar in Oracle Nested Table I'm new to PL-SQL, and struggling to find clear documentation of operations are nested tables.  Please correct any misused terminology etc.
I have a nested table type that I use as a parameters for a stored procedure.
CREATE OR REPLACE TYPE "STRARRAY" AS TABLE OF VARCHAR2 (255)

In my stored procedure, the table is initialized and populated.  Say I have a VARCHAR2 variable, and I want to know true or false if that varchar exists in the nested table.
I tried
strarray.exists('somevarchar')

but I get an ORA-6502
Is there an easier way to do that other than iterating?
FOR i IN strarray.FIRST..strarray.LAST
    LOOP
        IF strarray(i) = value THEN
            return 1;--found
        END IF;
    END LOOP;

A: For single value check I prefer the "member" operator.
zep@dev> declare
      2      enames     strarray;
      3      wordToFind varchar2(255) := 'King';
      4  begin
      5      select emp.last_name bulk collect
      6      into   enames
      7      from   employees emp;
      8      if wordToFind member of enames then
      9          dbms_output.put_line('Found King');
     10      end if;
     11  end;
     12  /

Found King

PL/SQL procedure successfully completed

zep@dev>

A: You can use the MULTISET INTERSECT operator to determine whether the string you're interested in exists in the collection.  For example
declare
  l_enames strarray;
  l_interesting_enames strarray := new strarray( 'KING' );
begin
  select ename
    bulk collect into l_enames
    from emp;
  if( l_interesting_enames = l_interesting_enames MULTISET INTERSECT l_enames )
  then
    dbms_output.put_line( 'Found King' );
  end if;
end;

will print out "Found King" if the string "KING" is an element of the l_enames collection.

A: You should pass an array index, not an array value to an exists in case you'd like to determine whether this element exists in collection. Nested tables are indexed by integers, so there's no way to reference them by strings.
However, you might want to look at  associative arrays instead of collections in case you wish to reference your array element by string index. This will look like this:
DECLARE
  TYPE assocArray IS TABLE OF VARCHAR2(100) INDEX BY VARCHAR2(100);
  myArray assocArray;
BEGIN

  myArray('foo') := 'bar';

  IF myArray.exists('baz') THEN
    dbms_output.put_line(myArray('baz'));

  ELSIF myArray.exists('foo') THEN
    dbms_output.put_line(myArray('foo'));

  END IF;

END;

Basically, if your array values are distinct, you can create paired arrays referencing each other, like,
arr('b') := 'a'; arr('a') := 'b';
This technique might help you to easily look up any element and its index.

A: When a nested table is declared as a schema-level type, as you have done, it can be used in any SQL query as a table.  So you can write a simple function like so:
CREATE OR REPLACE FUNCTION exists_in( str VARCHAR2, tab stararray)
  RETURN BOOLEAN
  AS
    c  INTEGER;
  BEGIN
    SELECT COUNT(*)
      INTO c
      FROM TABLE(CAST(tab AS strarray))
      WHERE column_value = str;
    RETURN (c > 0);
  END exists_in;


text:
Q: Rabbitmq message queues pile up untill system crash (all queues are "ready") I have a simple Raspberry pi + Django + Celery + Rabbitmq setup that I use to send and receive data from Xbee radios while users interact with the web app.
For the life of me I cant get Rabbitmq (or celery?) under control where after only a single day (sometimes a little longer) the whole system crashes due to some kind of memory leak.
What I am suspecting is that the queues are piling up and never being removed.
Heres a picture of what I see after only a few minutes of run time:

Seems that all of the queues are in the "ready" state.
What's strange is that it would appear that the workers do in fact receive the message and run the task.
The task is very small and shouldn't take longer than 1 second.
I have verified the tasks do execute to the last line and should be returning ok.
I'm no expert and have no clue what I'm actually looking at so I'm unsure if that is normal behavior and my issue lies elsewhere?
I have everything set to run as daemonized, however even when running in development modes I get same results.
I have spent the last four hours debugging with Google search and found it was taking me in circles and I was not finding clarity.
[CONFIGS AND CODE]
in /ect/default/celeryd I have set the following:
CELERY_APP="MyApp"
CELERYD_NODES="w1"

# Python interpreter from environment.
ENV_PYTHON="/home/pi/.virtualenvs/myappenv/bin/python"

# Where to chdir at start.
CELERYD_CHDIR="/home/pi/django_projects/MyApp"

# Virtual Environment Setup
ENV_MY="/home/pi/.virtualenvs/myappenv"
CELERYD="$ENV_MY/bin/celeryd"
CELERYD_MULTI="$ENV_PYTHON $CELERYD_CHDIR/manage.py celeryd_multi"
CELERYCTL="$ENV_MY/bin/celeryctl"

CELERYD_OPTS="--app=MyApp --concurrency=1 --loglevel=FATAL"

CELERYD_LOG_FILE="/var/log/celery/%n.log"
CELERYD_PID_FILE="/var/run/celery/%n.pid"

CELERYD_USER="celery"
CELERYD_GROUP="celery"

tasks.py
@celery.task
def sendStatus(modelContext, ignore_result=True, *args,  **kwargs):
    node = modelContext#EndNodes.objects.get(node_addr_lg=node_addr_lg)
    #check age of message and proceed to send status update if it is fresh, otherwise we'll skip it
    if not current_task.request.eta == None:
        now_date = datetime.now().replace(tzinfo=None) #the time now
        eta_date = dateutil.parser.parse(current_task.request.eta).replace(tzinfo=None)#the time this was supposed to run, remove timezone from message eta datetime
        delta_seconds = (now_date - eta_date).total_seconds()#seconds from when this task was supposed to run
        if delta_seconds >= node.status_timeout:#if the message was queued more than delta_seconds ago this message is too old to process
            return
    #now that we know the message is fresh we can proceed to process the contents and send status to xbee
    hostname = current_task.request.hostname #the name/key in the schedule that might have related xbee sessions

    app = Celery('app')#create a new instance of app (because documented methods didnt work)

    i = app.control.inspect()
    scheduled_tasks = i.scheduled()#the schedule of tasks in the queue

    for task in scheduled_tasks[hostname]:#iterate through each task
        xbee_session = ast.literal_eval(task['request']['kwargs'])#the request data in the message (converts unicode to dict)
        if xbee_session['xbee_addr'] == node.node_addr_lg:#get any session data for this device that we may have set from model's save override
            if xbee_session['type'] == 'STAT':#because we are responding with status update we look for status sessions
                app.control.revoke(task['request']['id'], terminate=True)#revoke this task because it is redundant and we are sending update now

    page_mode = chr(node.page_mode)#the paging mode to set on the remote device
    xbee_global.tx(dest_addr_long=bytearray.fromhex(node.node_addr_lg),
                   frame_id='A',
                   dest_addr='\xFF\xFE',
                   data=page_mode)

celery splash:
 -------------- celery@raspberrypi v3.1.23 (Cipater)
---- **** -----
--- * ***  * -- Linux-4.4.11-v7+-armv7l-with-debian-8.0
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app:         MyApp:0x762efe10
- ** ---------- .> transport:   amqp://guest:**@localhost:5672//
- ** ---------- .> results:     amqp://
- *** --- * --- .> concurrency: 1 (prefork)
-- ******* ----
--- ***** ----- [queues]
 -------------- .> celery           exchange=celery(direct) key=celery

[tasks]
  . MyApp.celery.debug_task
  . clone_app.tasks.nodeInterval
  . clone_app.tasks.nodePoll
  . clone_app.tasks.nodeState
  . clone_app.tasks.resetNetwork
  . clone_app.tasks.sendData
  . clone_app.tasks.sendStatus

[2016-10-11 03:41:12,863: WARNING/Worker-1] Got signal worker_process_init for task id None
[2016-10-11 03:41:12,913: WARNING/Worker-1] JUST OPENED
[2016-10-11 03:41:12,915: WARNING/Worker-1] /dev/ttyUSB0
[2016-10-11 03:41:12,948: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672//
[2016-10-11 03:41:13,101: INFO/MainProcess] mingle: searching for neighbors
[2016-10-11 03:41:14,206: INFO/MainProcess] mingle: all alone
[2016-10-11 03:41:14,341: WARNING/MainProcess] celery@raspberrypi ready.
[2016-10-11 03:41:16,223: WARNING/Worker-1] RAW DATA
[2016-10-11 03:41:16,225: WARNING/Worker-1] {'source_addr_long': '\x00\x13\xa2\x00@\x89\xe9\xd7', 'rf_data': '...^%:STAT:`', 'source_addr': '[*', 'id': 'rx', 'options': '\x01'}
[2016-10-11 03:41:16,458: INFO/MainProcess] Received task: clone_app.tasks.sendStatus[6e1a74ec-dca5-495f-a4fa-906a5c657b26] eta:[2016-10-11 03:41:17.307421+00:00]

I can provide additional details if required!!
And thank you for any help resolving this.

A: Wow, almost immedietly after posting my question I found this post and it has completely resolved my issue.
As I expected ignore_result=True was required, I just was not sure where it belonged.
Now I see no queues except maybe for the instant a worker is running a task. :)

Here's the change in tasks.py:
#From
@celery.task
def sendStatus(modelContext, ignore_result=True, *args,  **kwargs):
    #Some code here

#To
@celery.task(ignore_result=True)
def sendStatus(modelContext, *args,  **kwargs):
    #Some code here


text:
Q: Pushing back lambda to vector of functors produces infinite constructor calls I've got an interesting puzzle that I can't seem to completely solve. The following code is a snipped for my own function implementation. When I try to push_back a lambda into a vector of this function type, it should be converted to the function type. This seems to happen, but strangely the converting constructor is called an infinite amount of times. I tried to boil down the problem to the minimum example which I show below: It works when I either comment out the allocation of the lambda in the memory resource, the destructor or the operator() return value... But I can't find the commen denominator. I bet it's something stupid but I just can't find it.
Demo
#include <concepts>
#include <cstdio>
#include <memory_resource>

template <typename Fn, typename R, typename... Args>
concept invocable_r = std::is_invocable_r<R, Fn, Args...>::value;

template <typename R, typename... Args>
class function;

template <typename R, typename... Args>
class function<R(Args...)>
{
public:
    using allocator_type = std::pmr::polymorphic_allocator<std::byte>;
    auto get_allocator() {
        return allocator_;
    }

    template <invocable_r<R, Args...> Cb>
    function(Cb&& fn, allocator_type allocator = {})
        :   allocator_{ allocator }
    {
        printf("Converting constructor invoked!\n");
        // Comment this out
        mem_ptr_ = static_cast<void*>(allocator_.new_object<Cb>(std::forward<Cb>(fn)));
    }

    // Or this
    ~function() {}

    auto operator()(Args... args) {
        // or this
        return R{};
    }

private:
    allocator_type allocator_;
    void* mem_ptr_ = nullptr;
};

int main()
{
    using foo_t = function<int()>;
    std::vector<foo_t> myvec;
    myvec.push_back([]() -> int { printf("Hello World1!\n"); return 10; });
}

Yields:
Converting constructor invoked!
Converting constructor invoked!
Converting constructor invoked!
Converting constructor invoked!
Converting constructor invoked!
Converting constructor invoked!
Converting constructor invoked!
Converting constructor invoked!
Converting constructor invoked!
Converting constructor invoked!
Converting constructor invoked!
... (inifinte)

A: The problem was that an invisible templated method
function(Cb&& fn, allocator_type allocator = {})

was instantiated as requested by vector::push_back() with the following signature:
  template<>
  inline function<function<int ()> >(function<int ()> && fn, allocator_type allocator)

As can be seen in cppinsights. But why is instantiated? Well, vector::push_back has an overload for const T& and T&& whereas T is the actual value type of the vector. So in order to call those functions, an object of type T must first be instantiated before the call which is done using the converting constructor instantiated with the lambda parameter like this:
myvec.push_back(function<int ()>(__lambda_134_21{}, allocator_type{}));

The resulting r-value reference of type function<int()> is then supposed to be plugged into the push_back method and forwarded to allocator::construct() within the internals of std::vector eventually, but now arises an interesting situation: Afaik what happens is that because the default move constructor of function is implicitely deleted as ~function() is defined, it can't actually pass function as an rvalue-reference and has to use push_back's const T& overload.
Here's something I still don't quite understand though: An rvalue-reference could actually be bound to const T&, but somehow the compiler decides to "create a new function instance from scratch" using the converting constructor with the temporary function()-object as template parameter, hence we get the above mentioned template instantiation. This however produces the same scenario again: We still have an rvalue reference, and the compiler thinks it better converts it again, and again, and again...
So the fact that function<> is itself invokable actually makes it viable for overloads with its own template which is something I should prevent against. This is also why excluding operator()() will work, because now function<> is not invokable anymore. As for why the inifinite calls don't happen when I exclude the allocator call within the converting constructor is still a mistery to me. Could be related to optimizations, but honestly idk, maybe someone can shed some light on this.


text:
Q: Bounds on correlation to ensure covariance matrix is positive definite UPDATED: I am constructing a correlation matrix for an MA(1) process, which would look something like...
$$ C = \left( \begin{array}{cccccccccccccccccc}
1 & \rho & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
\rho & 1 & \rho & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & \rho & 1 & \rho & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & \rho & 1 & \rho & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & \rho & 1 & \rho & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & \rho & 1 & \rho & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & \rho & 1 & \rho & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & \rho & 1 & \rho & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & \rho & 1 & \rho & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \rho & 1 & \rho & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \rho & 1 & \rho & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \rho & 1 & \rho & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \rho & 1 & \rho & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \rho & 1 & \rho & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \rho & 1 & \rho & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \rho & 1 & \rho & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \rho & 1 & \rho\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \rho & 1\end{array} \right)$$
However, I'm using JAGS to fit the model and need to invert this matrix to sample from a multivariate normal distribution (after multiplying it by $\sigma^2$ of course).  $C$ must be positive definite for it to be valid and I recognize that $C$ is a tridiagonal Toeplitz matrix whose eigenvalues have a closed form solution:
$$
\lambda_k = 1 + 2\rho\cos\left(\frac{k\pi}{n+1}\right), \mbox{ for }k=1,\cdots,n
$$
where $n$ is the number of rows or columns (as the matrix is symmetric).  I can use the prior distribution on $\rho$ to ensure that $C$ is positive definite and the fact that I can calculate the eigenvalues for $C$ to determine the bounds of that prior, but I am stuck and need help.  Some values between $[-1,1]$ result in a matrix that is not positive definite.  I would also like to extend the method to a pentadiagonal matrix for an MA(2) process.

A: Regardless of whether the given covariance matrix correctly models the
covariance matrix of an AR(1) process (or an MA(1) process) or not,
the sum of all the entries
in a covariance matrix is the variance of the sum of the $n$ random variables.
Since this variance must be nonnegative, we get that in order for your
matrix to be a valid covariance matrix, it must be that
$$n + 2(n-1)\rho \geq 0 ~ \Rightarrow \rho \geq -\frac{n}{2(n-1)} \approx -\frac 12.$$
So it is certainly true that some choices of $\rho \in [-1,1]$ will not result
in valid covariance matrices.

In hindsight, the OP's problem has an even simpler solution.
Suppose that $Y_0, Y_1, Y_2, \cdots, Y_n$ are iid random variables
with variance $\sigma^2$, and define
$$X_i = aY_{i-1} + bY_i, ~ i = 1, 2, \cdots, n.$$
where $a^2+b^2 = 1$. It follows that
$\operatorname{var}(X_i) = \sigma^2$ for $1 \leq i \leq n$,
and more generally that
$$\operatorname{cov}(X_i,X_{i+k})
= \operatorname{cov}(aY_{i-1}+bY_i, aY_{i+k-1}+bY_{i+k})
 = \begin{cases}\sigma^2,& \text{if}~ k=0,\\
ab\sigma^2,& \text{if}~ k = \pm 1,\\
0,&\text{if}~ |k| > 1,
\end{cases}$$
that is, the covariance matrix of the $X_i$'s is what the OP wants.
So, subject to the constraint that $a^2+b^2 = 1$, what can we say about
$ab = \rho_{X_i,X_{i+1}}$, the correlation between adjacent $X_i$?
It is easy to deduce that
$ab \in \left[-\frac 12, \frac 12\right]$ which is what the OP
determined by experiment.

A: There are two problems here:

*

*The given matrix is not the covariance matrix of an AR(1) process.  If it were, there would be no problem since a covariance matrix is always positive definite.  The matrix you have given resembles the inverse of the AR(1) covariance matrix, but even this is not an exact match.

*You don't need to form the covariance matrix in order to specify an AR(1) process in JAGS.

In JAGS, you can specify an AR(1) model directly as:
for(i in 2:n) {
  x[i] ~ dnorm(theta*x[i-1],precision)
}


text:
Q: Making a struct before the unmarshal in golang Im new in golang and i have a question.
I have 5 structs where i use Json , but the JSON file can have more structs than the ones i have predetermined BUT... the structures of the JSON satisfies the structures in my programing ( lets say i have 5 structs "struct1" , 6 structs "struct 2" , 1 struct "struct 3", and so on...)
My question is , i want to make a function were i take the JSON FILE , read the structs of it and have as an output the number of structs of the JSON file.
I think i could use the map[string]interface{} but i dont understand it.
I hope i have explain myself
Thank u very much!

A: Without example JSON or structs, the exact question you are asking is a bit hard to decipher, specifically the "output the number of structs" bit in the question, as it could be interpreted several different ways. I will do my best to answer what I think are the most probable questions you are asking.
Interfaces
First off, some basic go knowledge that might be useful, but outside JSON marshaling itself. The interface{} type appears special, but is not a hardwired keyword as it first might appear. What the interface keyword does is describe the requirements that an object must have to fulfill that interface. Because interface{} has no requirements, and because everything is automatically interfaced in go, everything satisfies the interface{} type.
Because of this implementation of interfaces, map[string]interface{} is really map[string]. This allows for the JSON un/marshal to not care about what is on the value side of the map. This exactly lines up with the format of JSON, where you have a string key on one side, and a value that could be any of the JSON datatypes on the other.
How many different objects are in the base JSON object?
let us take an example json
{
  "debug": "on",
  "window": {
    "title": "Sample Konfabulator Widget",
    "name": "main_window",
    "width": 500,
    "height": 500
  },
  "image": {
    "src": "Images/Sun.png",
    "name": "sun1",
    "hOffset": 250,
    "vOffset": 250,
    "alignment": "center"
  },
  "text": {
    "data": "Click Here",
    "size": 36,
    "style": "bold",
    "name": "text1",
    "hOffset": 250,
    "vOffset": 100,
    "alignment": "center",
    "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
  }
}

The answer to the question in this circumstance would be four. debug, window, image, and text.
The process for determining the number would then be:

*

*Load the json into a byte array.

*Marshal into an interface{}

*Determine type (array vs object etc.) using type switch. see this A Tour of Go page

*

*If you know the type, you can skip this step

*Convert to desired type

*Get length, or perform any other operation as desired.

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    myJSON := `<see above>`

    var outStruct *interface{}
    json.Unmarshal([]byte(myJSON), &outStruct)
    outMap := (*outStruct).(map[string]interface{})
    fmt.Printf("Num Structs: %d", len(outMap))
}

Go Playground
How many json objects that I do not have structs for are present?
This answer has a very similar answer to the first one, and is really about manipulation of the output map and the struct
Taking almost the entire code from the first one to the second, let us assume that you have the following structs set up

type Image struct {
    Name string
    //etc
}
type Text struct {
    Name string
    //etc
}
type Window struct {
    Name string
    //etc
}

type Base struct {
    Image  Image
    Window Window
    Text   Text
}

In this case, in addition to the previous steps, you would have to
5. Marshal the json into a base object
6. Go through the map[string]interface{}, and for each key
7. Determine if the key is one of the objects in your base struct
total := 0
for k, _ := range outMap {
    if k != "image" && k != "text" && k != "window" && k != "other" {
        total++
    }
}
fmt.Printf("Total unknown structs: %d\n", total)

How many of my structs are empty?
This last question is also rather simple, and could be done by checking the map for a value given the input key, but for completion's sake, the example code marshals the JSON into a struct, and uses that.

*Marshal JSON into base

*For each of Window, Item, Text, Other in base, determine if empty.

total = 0

if (Image{}) == outBase.Image {
    total++
}
if (Window{}) == outBase.Window {
    total++
}
if (Text{}) == outBase.Text {
    total++
}
if (Other{}) == outBase.Other {
    total++
}

fmt.Printf("Total empty structs: %d\n", total)

Go Playground
See this go blog post for more information on golang JSON.