text:
Q: from php to python - dealing without braces i am a PHP developer by... well that's just what i picked up from a need to develop web services. since than i've found a need to start using python for various projects. one of the first things that has pissed me off is the obsession "properly" indenting code. now i understand its purpose. however, what i have found is that not using { } in my code blocks tends to cause me some periods of wtf.
because of this, i find myself doing stuff like
if a is not None:
  for x in a:
      print x
  # endfor
# endif

this seems to help me keep my code in order and visually i can see whats in scope to the loop and control statement.
so what are some other people doing out there that come from the land of { and ; ? or am i the only maniac with this issue?

A: You just need to adapt to the awesomeness of python. If you're a long time braces users, it will take some time, but eventually you'll love it.
Also, a blank line sometimes goes a long way to improve readability
if a is not None:
    for o in objects
        for attribute in o
            do_something_with_the_attribute(attribute)
            do_something_with_the_attribute(attribute)
            ...
            still_using_the_attribute(attribute)

        do_something_with_the_object(o)
        other_things_using_object(o)
        c = 2+2
        if o.something != c:
            print 5

    do_something_with_a(a)

A: Python deliberately makes this difficult.
Why?  To stop you making too deeply nested a logic pile.
If you stick to 80 characters width, and 4 spaces indentation, then as soon as it begins to be even slightly annoying or confusing, it's python's way of saying, "Dude! Split this monster up into smaller functions before it grows teeth and gnaws you arm off!".
One rule of thumb is that any function, or method, should be able to fit almost completely on screen at once (Including docstring).  If it's longer than that, you should split it up.
Don't be religious about it, but if you stick to this, it really does lead to very clean, clear code bases.

A: 1 )
do not do
from __future__ import braces
python will troll you with the following if you do
>>> from __future__ import braces
SyntaxError: not a chance

basically python is telling you no because python is not coded for php and javascript like syntax
its coded to tell you no
to python coders/devs its considered an inside joke but its cruel to tell someone to do that when they are asking for help
2)
(if your using python 2.7.5 or older than your fine)
for python 3.x your code is broken as it will return a syntax error
>>> a = "hsfjsdhfjdhfdhfdhf"
>>> if a is not None:
        for x in a:
                print x

SyntaxError: invalid syntax

you forgot ()
it should look like this
>>> a = "hsfjsdhfjdhfdhfdhf"
>>> if a is not None:
        for x in a:
                print(x)

h
s
f
j
s
d
h
f
j
d
h
f
d
h
f
d
h
f

also {} is a dict in python and since python has strict syntax rules you wont be able to wrap code in it only strings in the following formats
{"lol":"omg"}
{"lol":"omg","wow":"omg"}
{"lol":{"wow":"omg","pfft":"lolwut"}}
{"lol":["lol","omg","pfft","lolwut"]}
{"lol":[["lol","omg"],["pfft","lolwut"]]}

and numerous other ways
also you can infinetly place a dict inside a dict as long as a key exists the value can be a dict, list, tuple, or string
example:
{"lol":{"wow":{"omg":{"pfft":"lolwut"}}}}

only thing is
it gets harder to split that if you dont know what to do
3)
the one thing i recommend you do is get a nice big book on python and start reading
that's the best way to learn python
especially if you want your projects to be good
or if you want to learn online
start with this
http://learnpythonthehardway.org/
and then move onto this
Datastructures and Algorithms (below is the link)
http://interactivepython.org/courselib/static/pythonds/index.html
or you can do both it doesnt really matter which order you do it in so long as you learn something


text:
Q: Azure web app with access to multiple key vaults I'm wondering if an Azure web application can have access to multiple key vaults? This is because one of our web applications has multiple database connection strings and each of the databases has columns encrypted with always encrypted and the column encryption keys will be stored in their own key vaults per database. If this is possible, how does the web application know which key vault to access to get the column encryption key for the respective database it's connecting to?
Currently the web application has access to one key vault and all of the databases are encrypted with the same column encryption key which is in this key vault. But I want to split this out so each database has it's own key vault and respective column encryption key for better security. The web application obtains access to the key vault via Azure Active Directory with the client id and secret mechanism. I've played around with adding the Azure Active Directory application to the multiple key vaults using the key vault access policy but not sure if this is correct/will work.
The code I'm using to wire up the column encryption key with the web application (which appears to be key vault agnostic):
    public static void InitializeAzureKeyVaultProvider()
    {
        var clientId = ConfigurationManager.AppSettings["AuthClientId"];
        var clientSecret = ConfigurationManager.AppSettings["AuthClientSecret"];
        _clientCredential = new ClientCredential(clientId, clientSecret);

        SqlColumnEncryptionAzureKeyVaultProvider azureKeyVaultProvider =
            new SqlColumnEncryptionAzureKeyVaultProvider(GetToken);

        Dictionary<string, SqlColumnEncryptionKeyStoreProvider> providers =
            new Dictionary<string, SqlColumnEncryptionKeyStoreProvider>
            {
                {SqlColumnEncryptionAzureKeyVaultProvider.ProviderName, azureKeyVaultProvider}
            };

        SqlConnection.RegisterColumnEncryptionKeyStoreProviders(providers);
    }

    private static async Task<string> GetToken(string authority, string resource, string scope)
    {
        var authContext = new AuthenticationContext(authority);
        var result = await authContext.AcquireTokenAsync(resource, _clientCredential);

        if (result == null)
        {
            throw new InvalidOperationException("Failed to obtain the access token");
        }

        return result.AccessToken;
    }

Thoughts?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does anyone know how to install the Python P5 Package on Windows? Every time I try to install the package using pip it gives me this error
ERROR: Command errored out with exit status 1: 'c:\users\jtcap\desktop\projects\python\stuff\venv\scripts\python.exe' 'c:\users\jtcap\desktop\projects\python\stuff\v
env\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\jtcap\AppData\Local\Temp\pip-build-env-9r4nif3r\overlay' --no-warn-script-location
 --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- wheel 'setuptools>=30.3.0' setuptools_scm setuptools_scm_git_archive 'Cython>=0.29.2' 'numpy;
python_version=='"'"'2.7'"'"'' 'numpy==1.13.3; python_version=='"'"'3.5'"'"'' 'numpy==1.13.3; python_version=='"'"'3.6'"'"'' 'numpy==1.14.5; python_version>='"'"'3.7
'"'"'' Check the logs for full command output.
"""

Anyone know how to fix this?

A: Use the command pip install p5 if you have installed pip version 2 or pip3 install p5 if the pip and python versions are above 3


text:
Q: How can I get a list of all users in groups linked to the admin?
For example, I have 3 groups with following ids: 1, 2, 3;
 id | name     |
 ---------------
  1  |  group1 |
  2  |  group2 |
  3  |  group3 |

Also, I have users in those groups: 2 in group 1, 3 in group 2 and 1 in group 3;
 id | user | groupid |
 ---------------------
  1  |  user1 | 1
  2  |  user2 | 1
  3  |  user3 | 2
  4  |  user4 | 2
  5  |  user5 | 2
  6  |  user6 | 3

And of course I have the table admgroups
id | groupid | admid |
----------------------
1  |  1      | 3     |
2  |  2      | 4     |
3  |  3      | 3     |
4  |  2      | 5     |

All I want to get - a list which should include all users from groups, that are linked to admin, for example, with id = 3. So the result should be like:
var list = {"user1", "user2", "user6"}

A: You can do it using select likes the following. First, find the groupids related to the specified admin. Then, select users which have the selected groupid:
var admin_id = 3;
var admin_groups = admgroups.Where(x=> x.admid == admin_id).Select(x=> x.groupid).ToList();
var result = users.Select(x=> admin_groups.Contains(x.groupid)).ToList();

A: Just put those lines in your code:
var list = (from cl in (from adm in admgroups
                join gr in groups
                    on adm.groupid equals gr.Id
                where adm.admid==3
                select new {gr.Id})
                join client in users
                on cl.Id equals client.groupid
                        select new {client.user}).ToList();


text:
Q: Forefront Identity Manager location
I have to delete a filter on the UserProfile-AD connection.
I can not delete it from interface (from central admin).
I know it is possible to do it from the Forefront Identity Manager Client.
But I can not locate it on the server.
I am using SharePoint Server 2013.
I already checked in the folder:
C:\Program Files\Microsoft Office Servers\15.0\

A: Location of the FIM Client(MIISClient.exe) is
C:\Program Files\Microsoft Office Servers\15.0\Synchronization Service\UIShell

You should use the client from the server where Profile Synchronization is configured.


text:
Q: How to select scanner lightsource through WIA in C# I am writing a GUI to control and automate a scanner. However, I can't seem to find the control to select the light source in the scanner to make it scan either reflective or transmissive. Would this be an item.property index? I tried looking through them but didn't find anything useful.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms630202(v=vs.85).aspx
Please let me know if you know of a solution.


text:
Q: Where are the Spark logs on EMR? I'm not able to locate error logs or message's from println calls in Scala while running jobs on Spark in EMR.
Where can I access these?
I'm submitting the Spark job, written in Scala to EMR using script-runner.jar with arguments --deploy-mode set to cluster and --master set to yarn.  It runs the job fine.
However I do not see my println statements in the Amazon EMR UI where it lists "stderr, stdoutetc.  Furthermore if my job errors I don't see why it had an error.  All I see is this in thestderr`:
15/05/27 20:24:44 INFO yarn.Client: Application report from ResourceManager:
 application identifier: application_1432754139536_0002
 appId: 2
 clientToAMToken: null
 appDiagnostics:
 appMasterHost: ip-10-185-87-217.ec2.internal
 appQueue: default
 appMasterRpcPort: 0
 appStartTime: 1432758272973
 yarnAppState: FINISHED
 distributedFinalState: FAILED
 appTrackingUrl: http://10.150.67.62:9046/proxy/application_1432754139536_0002/A
 appUser: hadoop

`

A: If you SSH into the master node of your cluster then you should be able to find the stdout, stderr, syslog and controller logs under:
/mnt/var/log/hadoop/steps/<stepname>

A: I also spent a lot of time figuring this out. Found logs in the following location:
EMR UI Console -> Summary -> Log URI -> Containers -> application_xxx_xxx -> container_yyy_yy_yy -> stdout.gz.

A: With the deploy mode of cluster on yarn the Spark driver and hence the user code executed will be within the Application Master container. It sounds like you had EMR debugging enabled on the cluster so logs should have also pushed to S3. In the S3 location look at task-attempts/<applicationid>/<firstcontainer>/*.

A: The event logs, the ones required for the spark-history-server can be found at :
hdfs:///var/log/spark/apps

A: If you submit your job with emr-bootstrap you can specify the log directory as an s3 bucket with --log-uri


text:
Q: UrlRewriteFilter equivalent for mod_rewrite I want to do Url rewrite in Tomcat using UrlRewriteFilter
This is the rule would like in mod_rewrite apache
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule (.*) index.php/$1 [L]

I'm confused in how to check the request filename if it's not a file or not a folder in UrlRewriteFilter
Can anybody help me?

A: This worked for me
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 4.0//EN"
        "http://www.tuckey.org/res/dtds/urlrewrite4.0.dtd">
<urlrewrite>
    <rule>
        <note>
            Fitler for checking if file exists.
        </note>
        <condition type="request-filename" operator="notfile" next="and" />
        <condition type="request-filename" operator="notdir" />
        <from>(.*)</from>
        <to type="redirect" last="true">index.php/$1</to>
    </rule>
</urlrewrite>

A: Actually, you don't have to worry about that. Apache's mod_rerwite module take care of that for you. Try it .. If you try to access a folder or a file within the server, it will open it, othewhise it will apply the RewriteRule you have in there.

A: You can't. Well, you can if you're using version UrlRewriteFilter 3.2 and you will write your own custom class-rule to check for it; but that's not really what UrlRewriteFilter was designed for.
This definitely belongs in Apache's mod_rewrite, especially considering that you have index.php in your example. Why would that request even be forwarded to / served by Tomcat?


text:
Q: Python : Mapping values to other values without gap I have the following question. Is there somekind of method with numpy or scipy , which I can use to get an given unsorted array like this
a = np.array([0,0,1,1,4,4,4,4,5,1891,7]) #could be any number here

to something where the numbers are interpolated/mapped , there is no gap between the values and they are in the same order like before?:
[0,0,1,1,2,2,2,2,3,5,4]

EDIT
Is it furthermore possible to swap/shuffle the numbers after the mapping, so that
[0,0,1,1,2,2,2,2,3,5,4]

become something like:
[0,0,3,3,5,5,5,5,4,1,2]

A: Edit: I'm not sure what the etiquette is here (should this be a separate answer?), but this is actually directly obtainable from np.unique.
>>> u, indices = np.unique(a, return_inverse=True)
>>> indices
array([0, 0, 1, 1, 2, 2, 2, 2, 3, 5, 4])

Original answer: This isn't too hard to do in plain python by building a dictionary of what index each value of the array would map to:
x = np.sort(np.unique(a))
index_dict = {j: i for i, j in enumerate(x)}
[index_dict[i] for i in a]

A: Seems you need to rank (dense) your array, in which case use scipy.stats.rankdata:
from scipy.stats import rankdata
rankdata(a, 'dense')-1
# array([ 0.,  0.,  1.,  1.,  2.,  2.,  2.,  2.,  3.,  5.,  4.])


text:
Q: Odoo using Traefik proxy instead of Nginx I have successfully used Traefik for several containerized applications and I am happy with the native SSL support using LetsEncrypt (Thank you very much Traefik team). However, specifically, to run Odoo (Open-source ERP/CRM), I am getting an exception in the back-end and also in the browser via javascript logs:
Exception: bus.Bus unavailable + the call stack not important here. Apparently, the root cause of this exception is that Traefik is not proxying the requests coming to the URL /longpolling when the parameter workers > 1 in the odoo.conf file.
The Odoo server exposes two different ports:

*

*8069: normal requests for the webapp

*7082: used by the chat service under the /longpolling
I made a GitHub Repository explaining how to reproduce this "bug" (I don't know if it's a bug or if I don't know how to use it properly).
As a reference, I also added one nginx.conf file not using SSL (just to make it simple).
Here is my docker-compose.yml used to run Odoo + Traefik:
version: "2.3"
networks:
  web:
    external: true

services:
  traefik:
    image: "traefik:v2.4"
    container_name: "traefik"
    env_file: .env
    environment:
      - UID=2000
      - GID=2000
    ports:
      - "80:80"
      - "443:443"
    command:
      - --api.insecure=true
      - --api.dashboard=true
      - --api.debug=true
      - --log=true
      - --log.level=INFO
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --providers.file.filename=/dynamic.yml
      - --providers.docker.network=web
      - --entrypoints.http.address=:80
      - --entrypoints.https.address=:443
      - --certificatesresolvers.le.acme.httpchallenge=true
      - --certificatesresolvers.le.acme.httpchallenge.entrypoint=http
      - --certificatesresolvers.le.acme.email=${LETS_ENCRYPT_CONTACT_EMAIL}
      - --certificatesresolvers.le.acme.storage=/letsencrypt/acme.json
    networks:
      - web
    volumes:
      - "${BASE_VOLUME_DIR}/traefik/conf/letsencrypt:/letsencrypt"
      - "${BASE_VOLUME_DIR}/traefik/conf/dynamic.yml:/dynamic.yml"
      - "/var/run/docker.sock:/var/run/docker.sock:ro"
    labels:
      - traefik.enable=true
      - traefik.http.routers.traefik-http.rule=Host(`${TRAEFIK_HOSTNAME}`)
      - traefik.http.routers.traefik-http.entrypoints=http
      - traefik.http.routers.traefik-http.service=traefik
      - traefik.http.routers.traefik-http.middlewares=redirect@file
      - traefik.http.routers.traefik-https.rule=Host(`${TRAEFIK_HOSTNAME}`)
      - traefik.http.routers.traefik-https.entrypoints=https
      - traefik.http.routers.traefik-https.tls=true
      - traefik.http.routers.traefik-https.tls.options=default
      - traefik.http.routers.traefik-https.service=traefik
      - traefik.http.routers.traefik-https.tls.certresolver=le
      - traefik.http.services.traefik.loadbalancer.server.port=8080
      - traefik.http.routers.traefik-https.middlewares=gzip
      - traefik.http.middlewares.gzip.compress=true

  odoo:
    image: registry.wisecoding.io/docker/odoo:11.0
    container_name: odoo
    networks:
      - web
    env_file: .env
    ports:
      - "8069:8069"
      - "8072:8072"
    volumes:
      - "${BASE_VOLUME_DIR}/odoo/extra-addons:/opt/odoo/extra-addons"
      - "${BASE_VOLUME_DIR}/odoo/data:/opt/odoo/data"
      - "${BASE_VOLUME_DIR}/odoo/logs:/opt/odoo/logs"
      - "${BASE_VOLUME_DIR}/odoo/conf:/opt/odoo/conf"
    ulimits:
      nofile:
        soft: 65536
        hard: 65536
    labels:
      - traefik.enable=true
      - traefik.http.routers.odoo-http.rule=Host(`${ODOO_HOSTNAME}`)
      - traefik.http.routers.odoo-http.entrypoints=http
      - traefik.http.routers.odoo-http.service=odoo-http
      - traefik.http.services.odoo-http.loadbalancer.server.port=8069
      - traefik.http.routers.odoo-http.middlewares=redirect@file
      - traefik.http.routers.odoo-https.rule=Host(`${ODOO_HOSTNAME}`)
      - traefik.http.routers.odoo-https.entrypoints=https
      - traefik.http.routers.odoo-https.service=odoo-https
      - traefik.http.routers.odoo-https.tls.certresolver=le
      - traefik.http.routers.odoo-https.middlewares=gzip
      - traefik.http.services.odoo-https.loadbalancer.server.port=8069

       #====> On the next line was my mistake. It was typo as pointed out by @Veikko
      - traefik.http.routers.odoo-im-https.rule=Host(`${ODOO_HOSTNAME}`) && (PathPrefix(`/longpooling`))
      - traefik.http.routers.odoo-im-https.entrypoints=https
      - traefik.http.routers.odoo-im-https.service=odoo-im-https
      - traefik.http.routers.odoo-im-https.tls.certresolver=le
      - traefik.http.routers.odoo-im-https.middlewares=gzip,sslheader
      - traefik.http.services.odoo-im-https.loadbalancer.server.port=8072

      # middlewares
      - traefik.http.middlewares.gzip.compress=true
      - traefik.http.middlewares.sslheader.headers.customrequestheaders.X-Forwarded-Proto=https

The closest solution that I found was on this question on the Traefik forum, suggesting to include the line below (which I tried, but still did not work):
traefik.http.middlewares.sslheader.headers.customrequestheaders.X-Forwarded-Proto = https
I may have missed something, but I could not figure it out.
Thoughts?

A: Correct Odoo url path is /longpolling. Check that your Traefik and Odoo configurations use longpolling, not longpooling, e.g. the Odoo container labels for Traefik ...PathPrefix('/longpooling')" ->  ...PathPrefix('/longpolling')".


text:
Q: Invoking javac.exe within Vim I had previously asked a question about using Vim to develop Java, but I ended up realizing JDK works very well and that Ant is wayyy too much complicated for a starter like me. Things got a little bit clearer, and now I have a question again.
When I work with a file such as 'filename.java', I need to be able to use 'javac.exe', which is in the Java Development Kit (JDK), on 'filename.java' (a typical project I could be working on). Normally, to do this outside Vim, I could do
:shell in Vim to access a shell outside Vim
C:\Program Files...\javac C:\home-directory-of-filename.java\filename.java
Which is pretty long, because I must access the javac directory and then write the whole 'filename.java' directory.
Is there anyway to ask Vim to call javac and use it directly on the file that I am working on? I would be pleased if anyone could help. I tried to write a couple of things in my _vimrc file, unsuccessfully. By the way, I am a windows vista user.

A: You can perform an action against the file open in the current buffer using %. So, if you want to execute javac.exe against your current buffer, you could type:
:!javac %

To make it easier on the fingers, you could create a mapping in your .vimrc like so:
map <LocalLeader>jc :!javac %<CR>

Now simply type \jc (or whatever your local leader is) in your buffer and presto, you've run javac against that file.

A: Thanks to Drew Olson, I found my answer. But it was not a system path problem, I simply needed to type correctly the path to javac in the mapping. What I have added in my _vimrc was this line :
map jc :!"C:\Program Files\path-leading-to-javac.exe\javac.exe" %
The path written between "s is read correctly by Vim. I don't know if it is written correctly for master-geeks, but I don't care, because it works for me and I know barely nothing right now. =D
P.S. : For geeks who think noobs know everything, please try to be user-friendly. Popping a website with no indications is not user-friendly. It is only a tip, not an offense. I still appreciate the help.

A: G'day,
Why not do something to map a function key to call the javac on the file you are currently editing? Maybe something like:
map <silent> <F9> :w<CR>:!C:\Program Files...\javac %<CR>

This will then call javac on the file you are currently editing.
HTH
cheers,

A: To eliminate the need for full path to javac, just add the directory to your SYSTEM PATH Enviornment variable. It is possible to also add the directory that contains your .java files to the PATH variable as well - which would eliminate the need to use full path.

A: If you use Ant for your build manager, you can set vim up to use Ant when you issue the :make command from within vim.
More details here: http://everything101.sourceforge.net/docs/papers/java_and_vim.html


text:
Q: QTimer::singleShot only calling lambda when interval is 0 Note: My original post had an important omission: I left out that I had already instantiated the main QApplication instance at the beginning of main. Creating two QApplication instances is what caused the problem. Using the same QApplication instance instead of creating two fixed the issue.
My intention is to run a QApplication before the main application to iterate the available Bluetooth devices, to find a specific one. If the specific one is not found in a certain time limit, the QApplication is terminated. The first stored lambda (startDiscovery) is called as soon as QApplication::exec() is called, but the second stored lambda (cancelDiscovery) is never called! The relevant section is below:
#include <QtBluetooth/QBluetoothDeviceInfo>
#include <QtBluetooth/QBluetoothDeviceDiscoveryAgent>
#include <QtBluetooth/QBluetoothLocalDevice>
#include <QTimer>
#include <QString>
#include <QApplication>

#include <memory>
#define TARGET_BLUETOOTH_DEVICE_NAME "MyBluetoothDevice"
#define BLUETOOTH_DISCOVERY_TIMEOUT 5000 //5 second timeout

int main(int argc, char *argv[])
{
    std::shared_ptr<QApplication> mainApplication{std::make_shared<QApplication>(argc, argv)};
    //Error checking for no adapters and powered off devices
    //omitted for sake of brevity
    auto bluetoothAdapters = QBluetoothLocalDevice::allDevices();
    std::shared_ptr<QBluetoothLocalDevice> localDevice{std::make_shared<QBluetoothLocalDevice>(bluetoothAdapters.at(0).address())};

    std::shared_ptr<QBluetoothDeviceDiscoveryAgent> discoveryAgent{std::make_shared<QBluetoothDeviceDiscoveryAgent>(localDevice.get())};
    std::shared_ptr<QBluetoothDeviceInfo> targetDeviceInfo{nullptr};

    std::shared_ptr<QApplication> findBluetooth{std::make_shared<QApplication>(argc, argv)};
    auto setTargetDeviceInfo = [=](QBluetoothDeviceInfo info) {
        if (info.name() == TARGET_BLUETOOTH_DEVICE_NAME) {
            targetDeviceInfo = std::make_shared<QBluetoothDeviceInfo>(info);
            discoveryAgent->stop();
            findBluetooth->exit(0);
        }
    };

    auto cancelDiscovery = [=]() {
        discoveryAgent->stop();
        findBluetooth->exit(1);
    };

    auto startDiscovery = [=]() {
        discoveryAgent->start();
    };

    QObject::connect(discoveryAgent.get(), &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, setTargetDeviceInfo);
    QTimer::singleShot(0, startDiscovery); //startDiscovery get called fine
    QTimer::singleShot(BLUETOOTH_DISCOVERY_TIMEOUT, cancelDiscovery); //cancelDiscovery never gets called!

    findBluetooth->exec();

    //Now check if targetDeviceInfo is nullptr and run the real application etc...
    mainApplication->exec();

}

A: Answer: discoveryAgent->start(); is basically blocking your main thread. That is why, event which gets posted by  QTimer::singleShot(BLUETOOTH_DISCOVERY_TIMEOUT, cancelDiscovery); never gets processed - application executing discoveryAgent->start() and have not opportunity to look into event loop.

A: My original post had an important omission: I left out that I had already instantiated the main QApplication instance at the beginning of main. Creating two QApplication instances is what caused the problem. Using the same QApplication instance instead of creating two fixed the issue.


text:
Q: python IDLE stack viewer hangs with bigger data I am trying to debug a script using IDLE (python 2.7 under Bodhi Linux).
When debugger encounters a big list containing thousands of lists, and I try to open stack-viewer, it hangs.
Is this a known issue or do I need to do something to address this?
Thanks.


text:
Q: weka java code kmeans clustering I write a java code for malware detection using datamining techniques (kmeans clustering). I use the jnetpcap library for sniffing packets to analyse it, then in the method nextpacket I write the kmeans clustering algorithm for the first packet.
The algorithm works well as it creates objects from class Instances with the specific attributes which will cluster based upon them, but on the next packet this code can't be run again as it throws an exception.
The code I'm using is this:
for(int dim = 0; dim < numDimensions; dim++)
{
    Attribute current = new Attribute("Attribute" + dim , dim);

    if(dim == 0)
    {
        for(int obj = 0; obj < numInstances; obj++)
        {
            // instances.add(new SparseInstance(numDimensions));
            instances.add(new DenseInstance(numDimensions) );
        }
    }

    for(int obj = 0; obj < numInstances; obj++)
    {
        instances.get(obj).setValue(current, (Double)data[dim+1][obj]);
    }

    atts.add(current);
}

Instances newDataset = new Instances("Dataset" , atts, instances.size());       //this is the line that throws the exception

for(Instance inst : instances)
    newDataset.add(inst);
SimpleKMeans kMeans = new SimpleKMeans();
kMeans.setNumClusters(2);
// kMeans.setMaxIterations(4);
kMeans.buildClusterer(newDataset);
//   int clusterNumbers;
// clusterNumbers=kMeans.numberOfClusters();
for (int j=0;j<numInstances;j++)
{
    int classif=kMeans.clusterInstance(newDataset.get(j));
    //  double []distr=kMeans.distributionForInstance(newDataset.firstInstance());
    System.out.println(classif);
    //   System.out.println(distr[0]);
    //  System.out.println(distr[1]);
    ArrayList<Double> temp5=flowFeatures.get((JFlowKey)data[0][j]);
    if (classif==0)
    {
        // instances0.add(newDataset.get(j));
         instance0FlowFeatures.put((JFlowKey)data[0][j], temp5);
    }
    else if(classif==1)
    {
        //instances1.add(newDataset.get(j));
        instance1FlowFeatures.put((JFlowKey)data[0][j], temp5);
    }
}

And the exception I'm seeing is:
java.lang.IllegalArgumentException: Attribute names are not unique! Causes: 'Attribute0' 'Attribute1' 'Attribute2' 'Attribute3' 'Attribute4' 'Attribute5' 'Attribute6' 'Attribute7' 'Attribute0' 'Attribute1' 'Attribute2' 'Attribute3' 'Attribute4' 'Attribute5' 'Attribute6' 'Attribute7'

Could anyone please help me, please?

A: Think attributes like table's columns and has to be created once.
Here is the code for single dimensional data.
In this example my imaginary table has one column as "attr1" and table has
3 records(instances) in it, keeping very simple to understand the structure.
        Attribute attr1 = new Attribute("attr1");
        ArrayList<Attribute> attrList = new ArrayList<Attribute>();
        attrList.add(attr1);

        Instances dataset = new Instances("test", attrList, 0);

        double[] val1 = new double[] { 1.2};
        double[] val2 = new double[] { 2.2};
        double[] val3 = new double[] { 1.4};

        Instance instance0 = new DenseInstance(1.0, val1);
        instance0.setDataset(dataset);

        Instance instance1 = new DenseInstance(1.0, val2);
        instance1.setDataset(dataset);

        Instance instance2 = new DenseInstance(1.0, val3);
        instance2.setDataset(dataset);

        dataset.add(instance0);
        dataset.add(instance1);
        dataset.add(instance2);

        SimpleKMeans kmeans = new SimpleKMeans();
        try {
            kmeans.setPreserveInstancesOrder(true);
            kmeans.setNumClusters(2);
            kmeans.setSeed(2);
            kmeans.setDontReplaceMissingValues(true);
            kmeans.buildClusterer(dataset);
            kmeans.setMaxIterations(10);
            Instances instances = kmeans.getClusterCentroids();
            int assignments[] = kmeans.getAssignments();
            int x=0;
            for(int assignment : assignments) {
                System.out.println("data :" + dataset.get(x) + "instance idx: " + x + " centroid value: " + instances.get(assignment));
                x++;
            }
         }


text:
Q: How to force pdfminorversion globally? I have a problem with opening PDF files in Acrobat Reader. It comes up with error 131.
I have solved this issue thanks to How to overcome Acrobat Reader error 131 with a pdfLaTeX doc? The solution to include \pdfminorversion=4 works for me, but it's inconvenient to remember about it in every document.
So I have two questions, not being a tex superuser:

*

*how to force this setting globally?

*how to overcome this error in another way?

I believe it's somehow related to different images formats I use, but I am not sure yet.
On the other hand, should I really care about v1.5? I don't use neither forms nor multimedia, I don't need any file certification.

A: TeX Live
pdftexconfig.tex contains these settings. You can locate it via kpsewhich:
kpsewhich pdftexconfig.tex

Then you can put a copy in the local or home texmf tree. After putting it in the local texmf tree, you need to recreate the file name database:
texhash

In the file you can change the settings:
\pdfminorversion=4
\pdfobjcompresslevel=0

Finally the formats need to be recreated:
fmtutil --all

or those that are using pdftexconfig.tex:
fmtutil --byengine pdftex
fmtutil --byengine luatex

MiKTeX (updated with Ulrike Fischer's comment)
MiKTeX uses pdftexconfig.tex for the format generation. It can be found via
`kpsewhich pdftexconfig.tex`.

Example:
...\AppData\Roaming\MiKTeX\2.9\tex\generic\config\pdftexconfig.tex

This file is a generated file, example:
%%% DO NOT EDIT THIS FILE! It will be overwritten.
%%% Run 'initexmf --edit-config-file pdftex' to edit configuration settings
%%% for pdfTeX.
\pdfcompresslevel=9
\pdfdecimaldigits=3
\pdfhorigin=1 true in
\pdfoutput=1
\pdfpageheight=297 true mm
\pdfpagewidth=210 true mm
\pdfminorversion=5
\pdfpkresolution=600
\pdfvorigin=1 true in

Thus initexmf --edit-config-file pdftex opens an editor (notepad) for the file pdftex.cfg, the default contains:
%% pdfTeX configuration file. Run 'mthelp pdftexcfg' for parameter help.

The command mthelp pdftexcfg opens the manual page for pdftex.cfg.
For example, add the line
pdf_minorversion 4

The creation of a format file (see below) will trigger the writing of pdftexconfig.tex from pdftex.cfg and it will contain the following line
\pdfminorversion=4

appended at the end after the default settings.
All formats (memory dump files) can be regenerated by
initexmf --dump

Or the dump files that are using pdftexconfig.tex can be selected manually:
initexmf --dump=pdftex
initexmf --dump=pdflatex
initexmf --dump=luatex
initexmf --dump=lualatex

Perhaps you need to try admin mode: Add --admin to the command line calls.
This more "official" procedure has one drawback, \pdfobjcompresslevel seems not to be supported by pdftex.cfg.

For the latter case the older precedure based on the comments of Speravir might work1:
A local texmf tree (root tree) is needed: Create a local texmf tree in MiKTeX
Then the file pdftexconfig from the MiKTeX distribution tree is copied to the new
local tree (the starting points of the paths ... need to be adjusted, texmf.new is the local texmf tree):
copy ...\miktex-2.9\tex\generic\config\pdftexconfig.tex  ...\texmf.new\tex\generic\config\pdftexconfig.tex

The file name database needs to be updated:
initexmf --update-fndb

If the file is not found in the right location:
kpsewhich pdftexconfig.tex

then admin mode might be needed (see below).
The file can be edited to change the value of \pdfobjcompresslevel, for example (see description for TeX Live above).
At last the format files need to be regenerated (see above).
1It did not work for my single user installation of MiKTeX, because the user configuration directory is used before the local texmf tree and the modified pdftexconfig.tex is not used.


text:
Q: Spring Data JPA project, how to limit the amount of nested objects? @OneToMany I'm working on a small Spring REST API project. I have two classes that represent 2 tables in my database. I have a @OneToMany mapping in the object that I want to retrive data from. Right now I retrive ALL the nested objects, but what I want is to be able to limit the amount of nested objects by its int datestamp variable (which is an epoch declared as "utcs" in my class). I was naively thinking that the CrudRepoitory could help me with that but now I understand I was wrong. What I was hoping to be able to do in my repository was something like this:
@Repository
public interface TypeRepository extends CrudRepository<Type, Integer> {
    List<Type> findByDataUtcsGreaterThan(int utcs);
}

This is the JSON structure I want and how it looks right now. But how do I limit the amount of Data objects?
[
    {
        "typeKey": "Queue",
        "uomId": 1,
        "data": [
            {
                "value": 11,
                "utcs": 1605840300
            },
            {
                "value": 15,
                "utcs": 1605840360
            },
            {
                "value": 22,
                "utcs": 1605840420
            }
        ]
    },
    {
        "typeKey": "Unroutable",
        "uomId": 1,
        "data": [
            {
                "value": 196,
                "utcs": 1605840300
            },
            {
                "value": 196,
                "utcs": 1605840360
            },
            {
                "value": 196,
                "utcs": 1605840420
            }
        ]
    }
]

The (Type) object class with the nested object   @OneToMany
@Entity
@Table(name = "SYSTEMSTATSTYPE")
public class Type {
    @Id
    @Column(name = "ID")
    private int id;
    @Column(name = "TYPEKEY")
    private String typeKey;
    @Column(name = "UOMID")
    private int uomId;

    @OneToMany(mappedBy = "type", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private List<Data> data = new ArrayList<>();

    public Type() {
        super();
    }

    public Type(String typeKey, int uomId) {
        this.typeKey = typeKey;
        this.uomId = uomId;
    }

    // Getters and setters
}

The (Data) object class   @ManyToOne
@Entity
@Table(name = "SYSTEMSTATSDATA")
public class Data {
    @Id
    @Column(name = "ID")
    private int id;
    @Column(name = "VALUE")
    private int value;
    @Column(name = "UTCS")
    private int utcs;

    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "TYPEID")
    private Type type;

    public Data() {
        super();
    }

    public Data(int value, int utcs, Type type) {
        super();
        this.value = value;
        this.utcs = utcs;
        this.type = type;
    }
    // Getters and setters
}

A: I don't think there is a possibility directly with the annotation, and using EAGER fetching is in most cases not a good idea anyway. I think you have to build the logic yourself with a custom query, either fetching only the 2 Data objects (something as described here https://www.baeldung.com/jpa-limit-query-results), or a join getting you Type and Data all together right away.

A: That's not directly possible. You could do dedicated select queries for each Type object or maybe use something like Blaze-Persistence Entity Views which has native support for limiting collection elements.
I created the library to allow easy mapping between JPA models and custom interface or abstract class defined models, something like Spring Data Projections on steroids. The idea is that you define your target structure(domain model) the way you like and map attributes(getters) via JPQL expressions to the entity model.
A DTO model for your use case could look like the following with Blaze-Persistence Entity-Views:
@EntityView(Type.class)
public interface TypeDto {
    @IdMapping
    Integer getId();
    String getTypeKey();
    int getUomId();
    @Limit(limit = "5", order = "utcs DESC")
    Set<DataDto> getData();

    @EntityView(Data.class)
    interface DataDto {
        @IdMapping
        Integer getId();
        int getValue();
        int getUtcs();
    }
}

Querying is a matter of applying the entity view to a query, the simplest being just a query by id.
TypeDto a = entityViewManager.find(entityManager, TypeDto.class, id);
The Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
@Repository
public interface TypeRepository extends CrudRepository<Type, Integer> {
    List<TypeDto> findByDataUtcsGreaterThan(int utcs);
}


text:
Q: Scanner.nextLine() return null I had written this code :
class PerfectPair {
    public static void main(String args[]) throws IOException{
        Scanner scan = new Scanner(System.in);
        int test=scan.nextInt();
        StringBuffer b=null;
        String a=null;
        while(test!=0){
            a=scan.nextLine();
            b=new StringBuffer(scan.nextLine());
            System.out.println(a);
            String reverse=b.reverse().toString();
            if((a.length()!=b.length()) || !(reverse.equals(a))){
                System.out.println("No");
            }
            else
            {
                if((a.length()==b.length()) && (reverse.equals(a))) System.out.println("Yes");
            }

            --test;
        }
    }
}

Input which is entered:
1
aa
ab

but the value of variable a is null ..WHY?? Please explain .Also please correct the code so that it reads full input.

A: That's because you are entered 1 followed by an enter . So your nextLine method call just reads return key while nextInt just reads integer value ignoring the return key. To avoid this issue:
Just after reading input, you call something like:
int test=scan.nextInt();
scan.nextLine();//to read the return key.

If you want to avoid that as well, then i would suggest, you read the whole line and then convert it to integer. Some thing like:
int test=Integer.parseInt(scan.nexLine());

A: when you use
int test=scan.nextInt();

the carriage return that you push after entering the Integer does not get read off the input stream, so what you can do is
int test=scan.nextInt();
scan.nextLine();


text:
Q: Get the value of CURLOPT_HTTPHEADER from cURL I have the method below that is to get the response from webserver using cURL.
function login (string $_login, string $_password) : string {

    $url = "https://acweb.net.br/api/orcamentos/login";

    $fields = [
        "login"    => $_login,
        "password" => $_password
    ];

    $headers = [
        "Try" => "Trying"
    ];

    $ch = curl_init();

    curl_setopt( $ch, CURLOPT_URL, $url);
    curl_setopt( $ch, CURLOPT_POST, true);
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    return curl_exec( $ch );

}

It works fine!
i can get the value of $_POST with
print_r ($_POST)

But i can't get the value of CURLOPT_HTTPHEADER.
EDIT:
I did try so:
print_r ($_SERVER)

but it wasn't there.
How can i get the value of CURLOPT_HTTPHEADER?
all HTTP_headers in $_SERVER:
[HTTP_HOST] => ctemcasb.com.br
[HTTP_CONNECTION] => keep-alive
[HTTP_UPGRADE_INSECURE_REQUESTS] => 1
[HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36
[HTTP_SEC_FETCH_USER] => ?1
[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
[HTTP_SEC_FETCH_SITE] => none
[HTTP_SEC_FETCH_MODE] => navigate
[HTTP_ACCEPT_ENCODING] => gzip, deflate, br
[HTTP_ACCEPT_LANGUAGE] => pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7
[HTTP_COOKIE] => PHPSESSID=j4cqqdc83fia68nk0gsglqk1bv

HTTP_TRY, not exists.
And now?
I did this in the server:
print_r($_SERVER)

and
print_r ($_SERVER["HTTP_TRY]);

A: The headers shouldn't be an associative array, it should be an indexed array of strings.
$headers = [
    'Try: Trying',
    'Content-Type: text/html',
    ...
];

Then you should be able to access the header with: $_SERVER['HTTP_TRY'] since custom headers are prefixed with HTTP_


text:
Q: What is the different between Handler, Runnable, and Threads? What is the difference between Handler, Runnable, and Threads?
While I was working with android, and I need something to run in the background. I use Threads to run it. Usually I would write a class that extends Thread and implement the run method.
I have also saw some examples that implments runnable and pass into runnable into Threads.
However I am still confused. Can someone give me a clear explanation?

*

*What is the point of Runnable if one can write the background code in the Thread's run method?

*How is Handler used inside thread and why do we need to use it.

*Android has another thing call runOnUiThread, How do we use that? I know that it is used for updating the UI.

A: Handler, Runnable, and Threads actually work together, I dont think you should compare them.

Handler

allows send messages between two threads in a safe manner, that means that sending thread puts message into destination thread queue, and this destination queue will process this message in its appropriate time.

Runnable

this is an interface that you implement, in implementation you put logic you want to execute on some thread. You can actually use Runnable also in non thread related places. Lots of Java apis actually use Runnable, not only Thread's. You can post Runnable using handler, or you can use it with executors. Runnables are nice because you can implement them in a form of anonymous implementation.

UniThread

you meant UI Thread? Most user interfaces implements its workings in single thread, all UI elements: windows/widgets communicate using messages (just like in Handler). Ie. user presses button, this initiates a message with information that button was pressed, it is send to UI thread and finally delivered to your listener.
In Android it is forbidden (results in exception) to modify UI elements from non UI thread, this makes sense - if you would modify it from other thread this could happen while UI thread is doing some changes to the same widget - resulting in Undefined Behaviour.

A: Why use Runnable over Thread?

*

*Runnable separates code that needs to run asynchronously, from how the code is run. This keeps your code flexible.  For instance, asynchronous code in a runnable can run on a threadpool, or a dedicated thread.
A Thread has state your runnable probably doesn't need access to. Having access to more state than necessary is poor design.
Threads occupy a lot of memory.  Creating a new thread for every small actions takes processing time to allocate and deallocate this memory.
What is runOnUiThread actually doing?

*

*Android's runOnUiThread queues a Runnable to execute on the UI thread.  This is important because you should never update UI from multiple threads.  runOnUiThread uses a Handler.
Be aware if the UI thread's queue is full, or the items needing execution are lengthy, it may be some time before your queued Runnable actually runs.
What is a Handler?

*

*A handler allows you to post runnables to execute on a specific thread.  Behind the scenes, runOnUi Thread queues your Runnable up with Android's Ui Handler so your runnable can execute safely on the UI thread.

A: 1. Why runnable ?
Runnable is just an interface you need to instantiate a thread to contain it. Whereas thread already contains the ability to spawn a thread.If you extend Thread you can't extend anything else (Java doesn't support multiple inheritance). You can have multiple interfaces on a class, therefore you could have Runnable.
Also, When you extends Thread class, each of your thread creates unique object and associate with it. When you implements Runnable, it shares the same object to multiple threads.
2. Why to Use handler and what is it ?
Handler is written in Java (internally use a Thread), so everything you can do with Handler, you can achieve using a Thread too.
So why should you use Handler? Reason is as below

*

*Handler allows you to send and process Message and Runnable objects
associated with a thread's MessageQueue. To put it in simple terms,
handler makes your job easy.

*Android has two main rules for handling threads:

*Do not block the UI thread

*Do not access the Android UI toolkit from outside the UI thread

To bind by the 2 rules stated above, In android we have 3 built-in methods that can handle the situation when one of your Activity classes are run on or called from a different thread.
We can then schedule the UI updates to be run on the UI thread with these three methods below. The Activity or View then works as a handler (more on handlers below) and schedules your runnable to the UI thread:

*

*Activity.runOnUiThread(Runnable)

*

*View.post(Runnable)

*View.postDelayed(Runnable, long) //(long = time to scheduling)

3. What is UI Thread ?
UI thread is the main thread in which the UI elements like View and Activity are rendered. Any time consuming operations should not happen in the UI Thread. The application default runs in UI Thread. You need not do anything special to use the UI Thread.

A:
I use Threads to run it. Usually I would write a class that extends Thread and implement the run method.
1.What is the point of Runnable if one can write the background code in the Thread's run method?

Using Runnable and creating a Thread from Runnable is general practice.
From oracle tutorial on concurrency regarding Runnable Vs Thread usage :
Runnable object, is more general, because the Runnable object can subclass a class other than Thread.

2.How is Handler used inside thread and why do we need to use it.

It's a vast topic to explain. In simpler terms from official documentation site:

*

*Handler  allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue.

*When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

*There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own

*When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods as before, but from your new thread. The given Runnable or Message will then be scheduled in the Handler's message queue and processed when appropriate.
This picture from blog.mindorks.com article by Anishar Ali explains concepts clearly.

3.Android has another thing call runOnUiThread, How do we use that? I know that it is used for updating the UI.

You can find more details by looking into implementation of runOnUiThread
/**
     * Runs the specified action on the UI thread. If the current thread is the UI
     * thread, then the action is executed immediately. If the current thread is
     * not the UI thread, the action is posted to the event queue of the UI thread.
     *
     * @param action the action to run on the UI thread
     */
    public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

Refer to below post for example code of Handler usage.
Android: Toast in a thread

A: Runnable Interface is parent of Thread Class and run() is method of Runnable Interface
So normally we should prefer Runnable interface over extending thread class because  we don't want to change behavior of the class and we can also  extend another class .It also help in achieving loose coupling as well as we have a benefit of changing the User Interface from any other class.
We Can  change Ui in 4 ways
1.By using Handler example
public class MainActivity extends AppCompatActivity {
private Handler mainHandler=new Handler();
class ExampleRunnable implements Runnable {
        int seconds;

        public ExampleRunnable(int seconds) {
            this.seconds = seconds;
        }

        @Override
        public void run() {
            for (int i = 0; i < seconds; i++) {
 mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                        button.setText("50% process completed");
                        }
                    });

2.By Using runOnUIThread()  we have to attach runOnUIThread with post it can be easily understood with example
class ExampleRunnable implements Runnable {
        int seconds;

 public ExampleRunnable(int seconds) {
        this.seconds = seconds;
    }

    @Override
    public void run() {runOnUIThread.post(new Runnable() {
                    @Override
                    public void run() {
                        button.setText(" Runnable");
                    }
                });
            }

3.By using any View we can call by any view here i have called with switch
public class MainActivity extends AppCompatActivity {
 private Switch aSwitch;
@Override
    protected void onCreate(Bundle savedInstanceState) {
 aSwitch=findViewById(R.id.switch1);
class ExampleRunnable implements Runnable {
            int seconds;

     public ExampleRunnable(int seconds) {
            this.seconds = seconds;
        }

        @Override
        public void run() { aSwitch.post(new Runnable() {
                        @Override
                        public void run() {
                            button.setText(" Runnable");
                        }
                    });
                }

4.By making Handler in another Thread  we have to define Looper because by default it attach us to our thread looper
Handler threadHandler=new Handler(Looper.getMainLooper());
threadHandler.post(new Runnable()
{
                            @Override
                            public void run() {
                                button.setText(" Runnable");
                            }
                        });
                    }

This are 4 ways of implementing so I think from it you may now something about runnable thread and runOnUIThread() and Handler is written by other person beautifully.

A:
What is the point of Runnable if one can write the background code in
  the Thread's run method?

Runnable is an interface which used for creating a new thread class similar to the thread class created by extending java.lang.Thread class. Only difference is, Runnable interface allows the class to extend other class (if required) to override/inherit functionality of some class. Extending java.lang.Thread class will revoke this capability.
Also, Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.
Read more: http://javarevisited.blogspot.com/2012/01/difference-thread-vs-runnable-interface.html#ixzz2qgjDYJhT


text:
Q: Google Sheets: Trigger script IF value Can someone please help me with this script?
function HistoryTrigger() {
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 if (sheet.getName() == "Status") {
   var activeCell = sheet.getRange("G11");
     if (activeCell.getValue() ="OK") {
        recordHistory();

     }
   }
 }

function recordHistory() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Historie");
  var source = sheet.getRange("A2:B2");
  var values = source.getValues();
  values[0][0] = new Date();
  sheet.appendRow(values[0]);
};

I want the trigger to start when Status!G11="OK", then start recordHistory().

A: try:
if (activeCell.getValue() =="OK") {
double == is proper syntax for if statements.
You may run this functoin with onEdit:
function onEdit(e) {
  if (e.range.getSheet().getName() === 'Status') { HistoryTrigger(); }
}

It'll check each time user change something. It will run when G11 is OK on sheet 'Status'.
To combine all together, I suggest passing e into HistoryTrigger:
function onEdit(e) {
      HistoryTrigger(e);
    }

function HistoryTrigger(e) {

 var ss = e.range.getSheet();
 if (ss.getName() === 'Status') {
   var activeCell = ss.getRange("G11");
     if (activeCell.getValue() == "OK") {
        recordHistory();

     }
   }
 }

function recordHistory() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Historie");
  var source = sheet.getRange("A2:B2");
  var values = source.getValues();
  values[0][0] = new Date();
  sheet.appendRow(values[0]);
};


text:
Q: Decompress logged GZIP binary data In an effort to verify my app was sending back and forth with my server correctly, I had run
tcpdump -w ~/capture.txt -s 0 port 80

on a server with proxy sitting in between to capture all requests.  This worked great except that my browser and server are configured to use gzip when sending data.  I now have a capture.txt file with a bunch of binary data.  What is the simplest way that I can decode this data to verify that my api calls are working correctly?
I had tried copying the binary payload of the requests into a separate file and then gunzipping them but this wasn't working... I just want the simplest way to see the plain text version of what is being sent back and forth.

A: Unfortunately, I don't think there's any commands to gunzip just the zipped bits of a file. I think you'll have to figure out a way to get tcpdump to pipe output that is compressed through gunzip before putting it in the file.
On a side note, why don't you use something like curl http://server/api > apilog.txt ? Or is the client a mobile device?

A:
I now have a capture.txt file with a bunch of binary data.

Or, more correctly, you have a pcap file, with the misleading suffix .txt ("misleading" because it's not a text file - the output of tcpdump's -w is never a text file!), which, by definition, is a bunch of binary data.

This worked great except that my browser and server are configured to use gzip when sending data.

Try loading the pcap file in Wireshark; it has code to un-gzip gzipped payloads.


text:
Q: How to draw a (colored) square at the (upper right) corner of the page? I think I could draw a square with the \rule command, but I can't place it at the corner of the page. How can I change the absolute position of my square?

A: I found my own answer now:
\usepackage{eso-pic}
\AddToShipoutPictureBG*{%
   \AtPageUpperLeft{%
      \hspace{\paperwidth}%
      \raisebox{-\height}{%
         \makebox[0pt][r]{{\color{red}\rule{40pt}{40pt}}}
      }
   }
}

Thanks to @werner


text:
Q: What is the best practice to protect some fields in a entity for being edited? I started playing around with JHipster and created my first JDL-Entities. I learned that an Entity can be "readonly", but is there a way to secure a field like "creationDate" is not changed by anyone?
I added a [readonly]="true" to the input-tag in edit-view, but I want to secure the api behind as well.
There are any suggestions or best practices to do it a clean way?

A: You could use a DTO so that you select which fields of your entity you want to expose in service layer.
https://www.jhipster.tech/using-dtos/
JHipster uses MapStruct to generate DTOs but you can also do it manually.


text:
Q: Converting string to an arithmetic operator I have some string that I want to convert in to operators, for which I used
Scanner in=new Scanner(System.in);
string foo=in.nextLine();
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
System.out.println(engine.eval(foo));

I ran and it worked for +,-,/,mod and * but didn't work for any other thing like ^ or !. Does anybody know any way to convert any string to arithmetic.


text:
Q: How to allow a generic type parameter for a C# method to accept a null argument? private static Matcher<T> EqualTo<T>(T item)
{
    return new IsEqual<T>(item);
}

How do I modify the above method definition such that the following are valid/allowed.
EqualTo("abc");
EqualTo(4);
EqualTo(null); // doesn't compile. EqualTo<string>(null) does

Trying to port some Java code where null seems to be acceptable value for a T parameter.

Update
Thanks: for all the answers - especially Eamon and Jason. I didn't want the method calls to bother with type-inference. The following overload fixed it.
    private static Matcher<object> EqualTo(object item)
    {
        return EqualTo<object>(item);
    }

Actually the above question was a part of a larger puzzle. The end goal was for the following to work.
        this.AssertThat(null, EqualTo(null));
        this.AssertThat(null, Not(EqualTo("hi")));
        this.AssertThat("hi", Not(EqualTo(null)));

Applied the same fix.. RFC. (Ignore the ugly extension method part - that's another problem. Wanted to have these methods in all test-fixtures without inheritance.)
public static void AssertThat<T>(this object testFixture, object actual, Matcher<T> matcher, string message = "")
{
  AssertThat(anyObject, (T)actual, matcher, message);
}

public static void AssertThat<T, TSuper>(this object testFixture, T actual, Matcher<TSuper> matcher, string message = "") where T : TSuper
{
  ... check and assert

A: Not possible without explicitly specifying a T or doing a cast. Generics are compile time constructs and as such if the compiler can't figure out the type at compile time, then it won't compile (as you're seeing).

A: Since you can't do exactly what you are wanting to do, how about defining an EqualTo(object) overloaded method? That should allow your required syntax.

A: You may work around this limitation by using the following syntax:
EqualTo("abc");
EqualTo(4);
EqualTo(default(object));
//equivalently:
EqualTo((object)null);

default(T) is the value a field of type T has if not set.  For reference types, it's null, for value types it's essentially memory filled with zero bytes (...which may mean different things for different types, but generally means some version of zero).
I try to avoid the null  everywhere in my code nowadays.  It hampers type inference elsewhere too, such as with the var declared field and in a ternary operator.  For example,  myArray==null ? default(int?) : myArray.Length is OK, but myArray==null ? null : myArray.Length won't compile.

A: Consider the following method:
public bool IsNullString<T>(T item) {
    return typeof(T) == typeof(string) && item == null;
}

Yes, this is a pathetically stupid method and using generics is pointless here, but you'll see the point in a moment.
Now consider
bool first = IsNullString<string>(null);
bool second = IsNullString<Foo>(null);

bool third = IsNullString(null);

In the first and second, the compiler can clearly distinguish the type of T (no inference is needed). In the third, how the compiler infer what T is? In particular, it can't distinguish between T == string and T == Foo, or any other type for that matter. Therefore, the compiler has to give you a compile-time error.
If you want to get around this, you either need to cast null
EqualTo((object)null);

or explicitly state the type
EqualTo<object>(null)

or define an overload
private static Matcher<object> EqualTo(object item) {
    return new IsEqual<object>(item);
}

A: Maybe implementing a non-generic EqualTo, which takes an Object as the argument type, would solve the issue of rewriting those code lines.


text:
Q: Convert Varchar columns to Datetime I am tasked to calculate the difference in months and fiscal years from a NUMBERS column and a SHIP_DATES column. I have trouble converting date or time from character string in the NUMBERS columns (NUMBER_MONTH), and (NUMBER_FY) before the calculations.
Could someone please look? Basically, the issue I have is I cant take SHIP_DATE_MONTH minus NUMBER_MONTH and SHIP_DATE_FY minus NUMBER_FY.

*

*Column NUMBERS is varchar. It is formatted as SSSYYMMFFFFFF, where

*

*SSS is the store station,

*YY is the fiscal year,

*MM is the month, and

*FFFFFF is the frequency

*Column SHIP_DATES is datetime.

*Column ID is int.
Here is my code:
CREATE TABLE #TEMP
(
  NUMBERS    VARCHAR (20),
  SHIP_DATES DATETIME,
  ID         INT
)

INSERT INTO #TEMP VALUES ( 'ABC1006000046' , '6/5/2010'  , '123' )
INSERT INTO #TEMP VALUES ( 'ABC1006000046' , '7/15/2013' , '123' )
INSERT INTO #TEMP VALUES ( 'CDS0809000059' , '9/8/2008'  , '124' )
INSERT INTO #TEMP VALUES ( 'CDS0809000059' , '1/31/2013' , '124' )

SELECT SUBSTRING(NUMBERS, 6, 2)     AS NUMBER_MONTH,
       SUBSTRING(NUMBERS, 4, 2)     AS NUMBER_FY,
       DATEPART (MONTH, SHIP_DATES) AS SHIP_DATE_MONTH,
       DATEPART (YEAR, SHIP_DATES)  AS SHIP_DATE_FY,
       ID
INTO #TEMP1
FROM #TEMP

--calculate the difference in month and fiscal year
SELECT DATEDIFF( YEAR  , NUMBER_FY    , SHIP_DATE_FY    ) AS DIFF_YEAR  ,
       DATEDIFF( MONTH , NUMBER_MONTH , SHIP_DATE_MONTH ) AS DIFF_MONTH ,
       ID
FROM #TEMP1

and this is the error message I receive:
Conversion failed when converting date and/or time from character string.
Please note, here is a converting to datetime approach, but i have not figured out how to make it work yet:
CONVERT(VARCHAR , SHIP_DATES , 101 ) AS 'MM/DD/YYYY'

A: When you call DATEDIFF the 2nd and 3rd arguments are of type DateTime where you pass strings for the 2nd argument and integers for the 3rd argument.
I think (if i understand what you are trying to do) you should convert the strings to numbers, get rid of the DATEDIFF and do a regular minus operation.
Addition after comment:
to cast a nvarcahr to an int you can change your code like this:
SELECT
    CAST(SUBSTRING(NUMBERS, 6, 2) AS BIGINT)    AS NUMBER_MONTH,
    CAST(SUBSTRING(NUMBERS, 4, 2) AS BIGINT)    AS NUMBER_FY,
    DATEPART (MONTH, SHIP_DATES) AS SHIP_DATE_MONTH,
    DATEPART (YEAR, SHIP_DATES)  AS SHIP_DATE_FY,
        ID
INTO #TEMP1
FROM #TEMP

A: I would try something more along these lines:
CREATE TABLE #TEMP
    (NUMBERS VARCHAR (20), SHIP_DATES_A DATETIME, SHIP_DATES_B DATETIME, ID INT)

Then for testing:
INSERT INTO TEMP VALUES ('ABC1006000046', '6/5/2010','7/15/2013', '123')
INSERT INTO TEMP VALUES ('CDS0809000059', '9/8/2008','1/31/2013', '124')

Then this query:
select NUMBERS,SHIP_DATES_A,SHIP_DATES_B,ID,
    DATEDIFF(month,ship_dates_a,ship_dates_b)
from temp

A: Why not do this?
CREATE TABLE #TEMP
(
  NUMBERS    VARCHAR (20),
  SHIP_DATES DATETIME,
  ID         INT
)

INSERT INTO #TEMP VALUES ( 'ABC1006000046' , '6/5/2010'  , '123' )
INSERT INTO #TEMP VALUES ( 'ABC1006000046' , '7/15/2013' , '123' )
INSERT INTO #TEMP VALUES ( 'CDS0809000059' , '9/8/2008'  , '124' )
INSERT INTO #TEMP VALUES ( 'CDS0809000059' , '1/31/2013' , '124' )

SELECT  CAST('20' + SUBSTRING(NUMBERS, 6, 2) + '-' + SUBSTRING(NUMBERS, 4, 2) + '-01'     AS DATE) AS NumsDate,
SHIP_DATES
INTO #TEMP2
FROM #TEMP

SELECT
    DATEDIFF(M, NumsDate, SHIP_DATES) AS Diff_In_Months,
    DATEDIFF(YEAR, NumsDate, SHIP_DATES) AS Diff_In_Years
FROM
    #TEMP2


text:
Q: Java Is it possible to get the Variable name of a jButton? I can't come up with any other way of doing this. I'm trying to get the variable name of a java button which I've already declared so I can loop through a Database (Which has a screen field to access the correct product) and set the desired text to that jButton. I can do this by manually setting each jButtons text or setting a hard codded text through the Netbeans GUI. But I was looking to see if there's a more efficient way of doing this.
Code that can achieve this
    ArrayList<Products> myList = myProductsDataHandler.getAllProducts();
    myList.forEach((var i) ->
    {
        if (i.getScreen() == 0)
        {
            btnProduct1.setText(i.getProductName());
        }
        else if (i.getScreen() == 1)
        {
            btnProduct2.setText(i.getProductName());
        }
        else if (i.getScreen() == 2)
        {
            btnProduct3.setText(i.getProductName());
        }
        else if (i.getScreen() == 3)
        {
            btnProduct4.setText(i.getProductName());
        }
        else if (i.getScreen() == 4)
        {
            btnProduct5.setText(i.getProductName());
        }
        else if (i.getScreen() == 5)
        {
            btnProduct6.setText(i.getProductName());
        }
        else if (i.getScreen() == 6)
        {
            btnProduct7.setText(i.getProductName());
        }
        else if (i.getScreen() == 7)
        {
            btnProduct8.setText(i.getProductName());
        }
        else if (i.getScreen() == 8)
        {
            btnProduct9.setText(i.getProductName());
        }

Code I need help with
        int btnInt = 1;
        String btnStr = "btnProduct";
        btnCatagory1.setText(i.getCategory());
        Component[] components = pnlOrder.getComponents();
        for(Component component : components)
        {
            if(component instanceof JButton)
            {
                System.out.println(btnStr+btnInt);
                JButton button = (JButton) component;
                System.out.println(button.getName());
                if (button.getName().contains(btnStr+btnInt))
                {
                    btnProduct1.setText(i.getProductName());
                    btnInt++;
                }
            }
            }
        });

It's an Epos system and when the program is executed I want to get texts from the Database and set it to desired buttons. There are only 9 buttons. I have tried getName() but it returns null. Is there any other I can achieve this. Thanks

A: When you create your buttons you can also add each button to an ArrayList:
List<JButton> buttons = new ArrayList<JButton>();
buttons.add(btnProduct1);
buttons.add(btnProduct2);

Then when you want to update the text on the button you simply use:
JButton button = buttons.get( i.getScreen() );
button.setText( i.getProductName() );

A: You used setText() therefore should be using getText().
Had you used setName() you would use getName().
https://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/AbstractButton.html#getText()


text:
Q: How to submit a form data without reloading the page I tried submitting form data without reloading the page using a submit event check. Below is my piece of code:
$( "#my-form" ).submit(function( event ) {
            alert( "Handler for .submit() called." );
            //event.preventDefault();
            return false;
                });

Due to this page refresh has been stopped. But the action mapping to the form is not getting called. Is there any way that I can call the action and submit data without reloading page.

A: In the submit handler you have to make an ajax call that serializes the form data and sends it over. Adding event.preventDefault() and return false avoid the page refresh
See this Submit form via AJAX in jQuery


text:
Q: retrieve data from an existing database and display it in a TextView in android
*

*i have successfully build 2 tables in my SQLite for signup and
UploadBook for my app where i used the email as linked key between
the tables and i created one view from the both tables using the
linked key so now i want to retrieve the image,Bname,BId from the
view to display all the books in list view and then when user click
the button will load to another activity and display all the
information about the book using BId (book id) .
here my SQLite
  public class DBConnection extends SQLiteOpenHelper {
        public static final String DbName="RFAll.db";
        SQLiteDatabase db;

            public DBConnection(Context context){
                super(context,DbName,null,1);

            }
            @Override
            public void onCreate(SQLiteDatabase db) {
                db.execSQL("create table IF NOT EXISTS UploadBook(BId INTEGER  PRIMARY KEY AUTOINCREMENT,Bname TEXT,Bcategory TEXT,AuthorName TEXT,Bdecs TEXT, Brate REAL, country TEXT,  city TEXT,  address TEXT, phoneno INTEGER,  Email TEXT,  Bprice REAL, Brent REAL,  Bdeposit REAL,   Bimage BLOB ,FOREIGN KEY (Email) REFERENCES signup(Email))");

                db.execSQL("create table IF NOT EXISTS signup(ID INTEGER PRIMARY KEY AUTOINCREMENT,Name TEXT,Email TEXT,Password TEXT,REpassword TEXT)");
                db.execSQL("create VIEW IF NOT EXISTS show as select BId,Bname,Bcategory,AuthorName,Bdecs,Brate,country,city,address,phoneno,Bprice,Brent,Bdeposit,Bimage,ID,signup.Email from signup left join UploadBook on signup.Email=UploadBook.Email");
            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                db.execSQL("Drop table if EXISTS UploadBook");

                db.execSQL("DROP TABLE IF EXISTS signup");
                onCreate(db);

            }

            public void insertRow(String Name,String Email,String Password,String REpassword)
            {
                SQLiteDatabase db=this.getWritableDatabase();
                ContentValues contentValues= new ContentValues();

                contentValues.put("Name", Name);
                contentValues.put("Email", Email);
                contentValues.put("Password", Password);
                contentValues.put("REpassword", REpassword);

                db.insert("signup",null,contentValues);

            }
            public void InsertRowUpload(String Bname,String Bcategory,String AuthorName,String Bdecs,Float Brate,String country,String city,String address,Double Phoneno,String Email,Float Bprice,Float Brent ,Float Bdeposit,byte [] Bimage )
            {

                SQLiteDatabase db = this.getWritableDatabase();
                ContentValues contentValues = new ContentValues();

                contentValues.put("Bname", Bname);
                contentValues.put("Bcategory", Bcategory);
                contentValues.put("AuthorName", AuthorName);
                contentValues.put("Bdecs", Bdecs);
                contentValues.put("Brate", Brate);
                contentValues.put("country", country);
                contentValues.put("city", city);
                contentValues.put("address", address);
                contentValues.put("Phoneno", Phoneno);
                contentValues.put("Email", Email);
                contentValues.put("Bprice", Bprice);
                contentValues.put("Brent", Brent);
                contentValues.put("Bdeposit", Bdeposit);
                contentValues.put("Bimage", Bimage);

                db.insert("UploadBook",null,contentValues);

            }

            public void close()
            {
                db.close();
            }

            public boolean getUser(String email, String pass)
            {

                String selectQuery = "SELECT * FROM signup WHERE Email= '"+ email+"' AND Password = '"+ pass+"' ";

                SQLiteDatabase db = this.getReadableDatabase();
                Cursor cursor = db.rawQuery(selectQuery, null);
                // Move to first row
                cursor.moveToFirst();
                if (cursor.getCount() > 0)
                {

                    return true;
                }
                cursor.close();
                db.close();

                return false;
            }
            public boolean getEmail(String email)
            {

                String selectQuery = "SELECT * FROM signup WHERE  Email= '"+ email+"' ";

                SQLiteDatabase db = this.getReadableDatabase();
                Cursor cursor = db.rawQuery(selectQuery, null);
                // Move to first row
                cursor.moveToFirst();
               //if (cursor != null)
                if (cursor.getCount() > 1)
                {

                    return true;
                }
                cursor.close();
                db.close();

                return false;
            }
            public boolean getAdmin(String email,String pass)
            {

                String selectQuery = "SELECT * FROM signup WHERE ID=2 AND Email= '"+ email+"' AND Password = '"+ pass+"' ";

                SQLiteDatabase db = this.getReadableDatabase();
                Cursor cursor = db.rawQuery(selectQuery, null);
                // Move to first row
                cursor.moveToFirst();
                if (cursor.getCount() > 0)
                {

                    return true;
                }
                cursor.close();
                db.close();

                return false;
            }

        }

and here my listrow html

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:srcCompat="@mipmap/ic_launcher"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:text="TextView"
        android:layout_width="85dp"
        android:layout_height="wrap_content"
        android:id="@+id/txtcost"
        android:layout_marginBottom="21dp"
        android:layout_alignBottom="@+id/imageView"
        android:layout_alignLeft="@+id/txttitle"
        android:layout_alignStart="@+id/txttitle" />

    <TextView
        android:text="TextView"
        android:layout_width="85dp"
        android:layout_height="wrap_content"
        android:id="@+id/txttitle"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_above="@+id/txtcost"
        android:layout_toRightOf="@+id/imageView"
        android:layout_toEndOf="@+id/imageView" />

    <Button
        android:text="MORE"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/butget"
        android:layout_alignBottom="@+id/txtcost"
        android:layout_toRightOf="@+id/txtcost"
        android:layout_toEndOf="@+id/txtcost"
        android:layout_marginLeft="14dp"
        android:layout_marginStart="14dp" />

</RelativeLayout>

and here my listview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.karman.first.MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/ListView"
        android:layout_above="@+id/button"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

 </RelativeLayout>

A: The questioner is asking to implement the app functionality which is too broad. However, I can only provide suggested workflow:
You can write a function which retrieves required info of all the books using a select query
select Bid, Bname, Bimage from UploadBook

Store the results in objects of a Book class
public Book{
  public Book(int Bid, String Bname, String Bimage){
  }
}

Pass the results to your activity.
Use a listadapter to display these results in the ListView
Handle Button click event and initialize Book activity. Make a DB query to retrieve info of this particular book using Bid and display result same as done above.


text:
Q: ng hide/show based on list values I need to hide the "Current insurance cover" when coverAmt of all the covers in the list are zero or negative value. If any one coverAmt in the list is positive value then I need show the "Current insurance cover" only once.
I tried with something like this, but now no luck..!

        <h4 class="font-16 fontwt-400" ng-hide="cover.coverAmt <= 0">Current insurance cover

can anybody please help me on this..! thanks.

A: Firstly if you have the h4 Current insurance cover, within the ng-repeat. If you have multiple positive values, the header will appear multiple times
As for the calculation itself... Rather do that in your controller, then do something like:

             {{ cover.Something }}

Current insurance cover

Thus in the success event of the ajax request / promise you could do this:
  var total = 0;

  $http({    // or whatever request mechanism you're using
     url: someURL,
     method: "POST",
     data: "{}",
     headers: { 'Content-Type': 'application/json' }
  })
  .success(function (data) {
     angular.forEach(data.accSummary, function(value, key) {
         total += data.accSummary["coverAmt"]
     })
  })
  .finally(function() {
     $scope.isCurrent = total <= 0;
  })

Or you could create a function and then pass the whole collection through from the view.
Your calculation function could look something like this:
$scope.isCurrent = function(covers) {
     var total = 0;
     for(var i = 0; i < covers.length; i++){
         var cover = covers[i];
         total += cover.coverAmt;
     }
     return total <= 0;
  }

Then the usage would be usage:

Current insurance cover

A: Try using ```ng-if`` to control the visibility of the Current Insurance Cover. But on the init of the ng-repeat, run a call to loop through the array to test your case.
Below is a sample of what this would look like:
HTML:

Current insurance cover

JS:
$scope.visible = false;

$scope.checkCover = function() {
  angular.forEach(accSummary.response.covers, function(cover) {
    if(cover.coverAmt > 0) { $scope.visible = true; return true; }
  }
  return false;
}

A: You have to calculate this in your controller as below:
app.controller("cover", function($scope){
   $scope.covers = [{coverAmt: 10},{coverAmt: 0},{coverAmt: -1}];

   $scope.showHeading = function(){
   var flag = false;
   for(var i=0; i<$scope.covers.length; i++)
   {
      if($scope.covers[i].coverAmount > 0)
      {
         flag =  true;
         break;
       }
    }
    return flag;
 };
});

HTML will be

Current insurance cover


text:
Q: How to execute conditional script when on new customize.php (Theme Customize) screen The new "Customize" theme screen is a welcome addition in WordPress 3.4, however, I find it conflicts with my method of loading scripts loaded in the footer:
In functions.php
if(!is_admin())
{
/* GET PUBLIC FUNCTIONS
*************************************************************/
require_once(TEMPLATEPATH . '/functions_public.php');
}

In functions_public.php
/* Move scripts to the footer, speeding up page loading time as per http://yhoo.it/IAL94Z
*************************************************************************/
if ( isset($_GET['page']) && $_GET['page'] == 'customize.php') echo "in customize.php"; else echo "NOT in customize.php";

if(!get_option('my_scripts_head')){
    remove_action('wp_head', 'wp_print_scripts');
    remove_action('wp_head', 'wp_print_head_scripts', 9);
    remove_action('wp_head', 'wp_enqueue_scripts', 1);
    add_action('wp_footer', 'wp_print_scripts', 5);
    add_action('wp_footer', 'wp_enqueue_scripts', 5);
    add_action('wp_footer', 'wp_print_head_scripts', 5);
}

This code branch moves those scripts from wp_head to wp_footer. When this option (my_scripts_head) is enabled, the "Customize" screen shows my theme preview without the scripts that are loaded in the footer.
I find that when I disable this option, the "Customize" screen loads fine, including my scripts.
When themes are previewed in customize.php, does wp_footer not fire?

A: Okay, first, let's set things up properly, with a callback hooked into an appropriate action hook:
<?php
function wpse55227_enqueue_scripts() {
    // Enqueue code goes here
}
add_action( 'wp_head', 'wpse55227_enqueue_scripts' );
?>

We'll put all of our code in to this callback.
The next step is to add our if ( ! is_admin() ) conditional wrapper:
<?php
function wpse55227_enqueue_scripts() {
    if ( ! is_admin() ) {
        // Enqueue code goes here
    }
}
add_action( 'wp_head', 'wpse55227_enqueue_scripts' );
?>

Now, let's add in your original code:
<?php
function wpse55227_enqueue_scripts() {
    if ( ! is_admin() ) {
        if(!get_option('my_scripts_head')){
            remove_action('wp_head', 'wp_print_scripts');
            remove_action('wp_head', 'wp_print_head_scripts', 9);
            remove_action('wp_head', 'wp_enqueue_scripts', 1);
            add_action('wp_footer', 'wp_print_scripts', 5);
            add_action('wp_footer', 'wp_enqueue_scripts', 5);
            add_action('wp_footer', 'wp_print_head_scripts', 5);
        }
    }
}
add_action( 'wp_head', 'wpse55227_enqueue_scripts' );
?>

So, at this point, we should be back to where you were before. Now, let's account for the Customizer. The easiest way is to check for the $wp_customize global being set:
<?php
function wpse55227_enqueue_scripts() {
    // Globalize
    global $wp_customize;
    // If $wp_customize is set, return
    if ( isset( $wp_customize ) ) {
        return;
    }

    if ( ! is_admin() ) {
        if(!get_option('my_scripts_head')){
            remove_action('wp_head', 'wp_print_scripts');
            remove_action('wp_head', 'wp_print_head_scripts', 9);
            remove_action('wp_head', 'wp_enqueue_scripts', 1);
            add_action('wp_footer', 'wp_print_scripts', 5);
            add_action('wp_footer', 'wp_enqueue_scripts', 5);
            add_action('wp_footer', 'wp_print_head_scripts', 5);
        }
    }
}
add_action( 'wp_head', 'wpse55227_enqueue_scripts' );
?>

By the way: out of curiosity, why are you moving all of the script enqueueing to the footer? I would imagine that has a very high likelihood of breaking things, and/or causing unintended consequences.


text:
Q: Order of Riemann tensor indexes and the Ricci Identity I have seen the Ricci identity written variously as

*

*$R_{ijk}{}^l x^k = (\nabla_i\nabla_j- \nabla_j\nabla_i) x^l$

*$R_{ij}{}^l{}_k x^k = (\nabla_i\nabla_j- \nabla_j\nabla_i) x^l$

*$R^l{}_{kij} x^k = (\nabla_i\nabla_j- \nabla_j\nabla_i) x^l$

To my understanding 2. and 3. are equivalent but 1. has the opposite sign
due to the symmetries of the Riemann tensor.
Oddly I do not recall ever seeing the 4 possible variant.
Which is the correct form?


text:
Q: Norm of the dual of the Tensor product of Hilbert spaces Let $V$ and $W$ be Hilbert spaces, we can define inner product and induced norm on Tensor product of these spaces as:
Let $v_1,v_2 \in V$,and $w_1,w_2 \in W$. then $(v_1 \otimes w_1, v_2 \otimes w_2)_{V\otimes W} := (v_1,v_2)_{V}(w_1,w_2)_{W}$.
The dual space of $V \otimes W$ is $(V \otimes W)^{*}$, I also want to define an inner product on this space.How can I do that?
How about for the case $V= H^1_0(D)$ and $W=L^2(\Omega)$ where $D \subset \mathbb{R}$ and $\Omega$ is bounded closed subset of $\mathbb{R}$, and $T>0$. Indeed I need the norm of the dual space.
I want to creet Gelfand triple with $V \otimes W$ and it's dual $(V \otimes W)^{*}$,  I Can find a tensor product space like $H$ such that:
$$V \otimes W \subset H \subset (V \otimes W)^{*}$$
can I think about $H= L^2(D) \otimes L^2(\Omega)$ as a solution?
Thank you.

A: You have an inner product on $V\otimes W$, so it(s completion) is a Hilbert space; the dual of a Hilbert space is a Hilbert space, by the Riesz representation theorem, which tells you the inner product.


text:
Q: fopen / fopen_s and writing to files I'm using fopen in C to write the output to a text file. The function declaration is (where ARRAY_SIZE has been defined earlier):
void create_out_file(char file_name[],long double *z1){
  FILE *out;
  int i;

  if((out = fopen(file_name, "w+")) == NULL){
    fprintf(stderr, "***> Open error on output file %s", file_name);
    exit(-1);
  }

  for(i = 0; i < ARRAY_SIZE; i++)
    fprintf(out, "%.16Le\n", z1[i]);
  fclose(out);
}

My questions:

*

*On compilation with MVS2008 I get the warning: warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. I haven't see much information on fopen_s so that I can change my code. Any suggestions?

*Can one instruct fprintf to write numbers at a desired numerical precision to a file? If I'm using long double then I assume that my answers are good till 15 digits after the decimal point. Am I right?

A: *

*fopen_s and all the other _s functions are MS-specific "secure" variants of standard functions. If your code doesn't need to be cross-platform, you can just switch and make the compiler happy. Otherwise, just add the _CRT_SECURE_NO_WARNINGS pre-processor directive into your project settings and it'll stop warning you about it.

*Yeah, long double is easily good for 15 digits of precision; actually, even regular doubles are good enough for that much (but no more).

A: Moving from fopen to fopen_s disabled the ability to open file in notepad (read only) while file is opened and being writen.
Swithing back to fopen and I can read wile my program writes the file.

A: Other posters have pointed out that fopen is not really very unsafe.  If you don't want this warning, but you do want the other ones that warn of real vulnerabilities, don't
#define _CRT_SECURE_NO_WARNINGS.
Instead, the next time you get the fopen warning, click on the line that says "see declaration of 'fopen'".  This will take you to the line in stdio.h which is injecting the warning.  Delete the text _CRT_INSECURE_DEPRECATE(fopen_s) from that line, and you will no longer get the security warning when you use fopen, but it will remain for strcpy, strdup and those other possibly dangerous ones.

A: fopen_s is a variant of fopen which contains parameter validation and hands back an error code instead of a pointer in case something goes wrong during the open process. It's more secure than the base variant because it accounts for more edge conditions. The compiler is warning you to use it because fopen represents a potential exploitation vector in your application.
You can specify digits of precision to the printf family of functions by using the specifier %.xg, where x is the digits of precision you want in the output. A long double varies in precision from platform to platform, but you can generally bet on it being at least 16 digits of decimal precision.
Edit: While I'm not entirely on board with the others who are suggesting that fopen_s is a complete waste of time, it does represent a pretty low chance of exploitation and it isn't widely supported. Some of the other functions warned about under C4996 are much more serious vulnerabilities, however, and using _CRT_SECURE_NO_WARNINGS is the equivalent of turning off the alarm for both "you left your bedroom door unlocked" and "you left a nuclear bomb in the kitchen".
As long as you aren't restricted to using "pure C" for your project (e.g. for a school assignment or an embedded microcontroller), you would do well to exploit the fact that almost all modern C compilers are also C++ compilers and use the C++ iostream variants of all of these I/O functions in order to get both improved security and compatibility at the same time.

A: I ran into a similar problem working with Visual Studio 2012 but where my problem expanded was I'm building a program that I want to use the bells and whistles of Visual Studio for testing and eventually be able to compile and run the same application on my Linux server (I'm making a bot)
so this is what I came up with after some Google-ing and thought I'd post it in case it may help anyone else.
FILE *fp_config;
const char *configfile ;
configfile = "bot.conf";
#ifdef WIN32
    errno_t err;
    if( (err  = fopen_s( &fp_config, configfile, "r" )) !=0 ) {
#else
    if ((fp_config = fopen(configfile, "r")) == NULL) {
#endif
        fprintf(stderr, "Cannot open config file %s!\n", configfile);
    }

this will appease Visual Studio and it will not complain and it will also allow the same code to compile on gcc or any other standards compliant c/c++ compiler

A: Just define _CRT_SECURE_NO_WARNINGS before you include any file to get rid of this warnings, and stop believe to what MS says about fopen


text:
Q: Modal para varias imagenes Tengo una vista en MVC, a la que le llegan cinco imagenes. Para mostrarlas en el inicio, lo hago de esta manera:
@for (int i = 1; i <= 5; i++)
                {
                    switch (i)
                    {
                        case 1:
                            if (Model.Imagenes.Imagen1 != null)
                            {

                                    ×

                            }
                            break;
                        case 2:
                            if (Model.Imagenes.Imagen2 != null)
                            {

                            }
                            break;
                        case 3:
                            if (Model.Imagenes.Imagen3 != null)
                            {

                            }
                            break;
                        case 4:
                            if (Model.Imagenes.Imagen4 != null)
                            {

                            }
                            break;
                        case 5:
                            if (Model.Imagenes.Imagen5 != null)
                            {

                            }
                            break;

                        default:
                            break;
                    }
                }

Lo que quisiera, es que al hacerle clic, se agranden con JS, pero soy nuevo en frontend y me esta costando, logre que se agrande una cuando le hago clic, pero las otras no se agrandan cuando les hago clic a cada una de ellas. Alguien me podria mostrar como hacer un script para que esto pueda hacerse?.
Gracias.

A: Este trozo de código solo lo pones al case 1: tienes que agregarlo en todos los "case" para que te funcione en las 5 imágenes:

                                ×


text:
Q: What is the default path for local Prezi files? I recently had to reinstall Windows 10 on my PC.
It appears that I had not saved all of my Prezi files to the cloud. I still have the old disc image and would like to find the location of the local Prezi files so that I could transfer them to my current environment.
I am running Prezi for Windows 6.16.2.0.
Where might that be?

A: The default location that local prezis will be saved is:
C:\Users\<username>\Documents\Prezi\Content\<uniqueID>
UniqueID will be something like
On OSX they will be saved under"
/Users/<username>/Library/Application Support/com.prezi.desktop/<uniqueID>/content
Where uniqueID will be something like 0000000002b4abd4.


text:
Q: Spring profile properties inheritance with single properties file I have one application.yml file containing multiple spring profiles.
I want to inherit properties from one profile to another.
In this example I want to inherit properties of prod profile into prod1 without writing common properties again in prod1 profile.
  server:
    port: 8080

  spring:
    datasource:
      driver-class-name: com.mysql.cj.jdbc.Driver
    application:
      name: TestApp

    URL: "https://localhost:8181/Services/IDEA-Client-Partners"
  ---
  spring:
    profiles: dev
  ---
  spring:
    profiles: prod

  URL: https://www.ideaedu.org/Services/IDEA-Client-Partners

  ---
  spring:
    profiles: prod1

A: properties do already inherit if multiple profiles are activate. E.g. if you activate prod, and prod1 all default < prod < prod1 properties will activate with default, getting overwritten by anything in prod, and prod getting overwritten by anything in prod1.
Given your example,
 server:
    port: 8080

  spring:
    datasource:
      driver-class-name: com.mysql.cj.jdbc.Driver
    application:
      name: TestApp

    URL: "https://localhost:8181/Services/IDEA-Client-Partners"
  ---
  spring:
    profiles: dev
  ---
  spring:
    profiles: prod

  URL: https://www.ideaedu.org/Services/IDEA-Client-Partners
  prodProperty: test
  ---
  spring:
    profiles: prod1

  URL: https://localhost/

And activating all profiles, -Dspring.profiles.active=prod,prod1
the following properties will be set,

*

*port = 8080

*diver-class-name= com.mysql.cj.jdbc.Driver

*name = TestApp

*prodProperty = test

*URL = https://localhost/
In case of conflicting properties e.g. URL in this example, the last property read wins i.e. when prod and prod1 are active the last property read will in, prod1's definition in this case.


text:
Q: How do upload an Image to django from angularjs client using django rest framework? I can't figure out how I should post an Image from angularjs.
I'm a newbie in django and django-rest-framework.
Thanks in advance.
models.py
class UserImages(models.Model):
   owner = models.ForeignKey('auth.User', related_name='UserImages')
   user=models.ForeignKey(Profile)

   # highlighted = models.TextField(default=None,blank=True,null=True)
   likes=JSONField(null=True,blank=True)
   image=models.ImageField()
   pub_date=models.DateTimeField(default=now)
   def __str__(self):
      return str(self.owner)

serializers.py
class ImageSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='user.username')
image_url = serializers.SerializerMethodField('gett_image_url')
class Meta:
    model=UserImages
    fields=('id','owner','image','likes','image','image_url','owner')
def gett_image_url(self,obj):
    return obj.image.url

views.py(what I've tried)
class Profile_List(APIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly)
parser_classes = (FileUploadParser,)
def get(self, request, format=None):
    profiles=Profile.objects.all()
    serializer=ProfileSerializer(profiles, many=True)
    return Response(serializer.data)
def post(self, request, format=None):
    req=request.data
    image = req['display_image']
    req['user']=self.request.user.id
    #self.request.user.
    serializer=ProfileSerializer(data=req)
    if serializer.is_valid():
        serializer.save(owner=self.request.user)
        return Response(serializer.data,status=status.HTTP_201_CREATED)
    return Response(serializer.errors,status=status.HTTP_403_FORBIDDEN)

I can't figure out how i should design the view, I read something about FileUploadParser but its going way over my head a code snippet of the view would be nice.
Thank you.