Q: Run GitHub Actions workflows Jobs on 2 runners parallelly at a time I'm using GitHub actions to copy the artifact to the runner/VM, here I added my VM as a self-hosted runner and ran the workflow directly on the runner. I'm downloading the artifact from artifactory and copying it to the deployment location, Now, I Need to do the same thing on another runner/VM as I have an identical deployment VM for the application.
To achieve this, I have copied the same job and changed the 'runs-on' value with a different runner name which is my second VM. below is my workflow code snippet.
My question is, Instead of 2 jobs, how can we run using a single job for all VMs related to dev? let's say, Assume that I have 4 VMs for the Dev environment and 3 VMs for QA, and 5 VMs for Production
can someone help with this or do we need to continue with the same approach as whatever I'm doing right now?
I have tried matrix but looking to see if there is any other solution
name: Deployment_workflow

on:
  workflow_dispatch:
    inputs:
      dev:
        type: boolean
        required: false
        default: false
      qa:
        type: boolean
        required: false
        default: false
jobs:
    dev_deploy_1:
      if: github.event.inputs.dev =='true'
      runs-on: dev-vm-1
      steps:
        - name: Download the artifact from artifactory
          run: |
            cd /tmp
            curl -u ${ARTIFACTORY_USER}:${ARTIFACTORY_ENCRYPT} -T dep-deploy-1.war "$(ARTIFACTORY_URL)/artifactory/general-artifacts/dep-deploy-1.war"
        - name: copy the file from /tmp to deployment location
          run: |
            cp /tmp/dep-deploy-1.war /var/lib/app_deploy_dir

    dev_deploy_2:
      if: github.event.inputs.dev =='true'
      runs-on: dev-vm-2
      steps:
        - name: Download the artifact from artifactory
          run: |
            cd /tmp
            curl -u ${ARTIFACTORY_USER}:${ARTIFACTORY_ENCRYPT} -T dep-deploy-2.war "$(ARTIFACTORY_URL)/artifactory/general-artifacts/dep-deploy-2.war"
        - name: copy the file from /tmp to deployment location
          run: |
            cp /tmp/dep-deploy-1.bar /var/lib/app_deploy_dir


Q: Read a PEM file with Flutter API encrypt import 'package:encrypt/encrypt.dart';
import 'package:encrypt/encrypt_io.dart';
import 'dart:io';
import 'package:pointycastle/asymmetric/api.dart';
import 'dart:async';
import 'package:flutter/services.dart' show rootBundle;

class Encrypt {
  Future<String> loadPrivateKey() async {
    return await rootBundle.loadString('assets/private_key.pem');
  }

  Future<String> loadPublicKey() async {
    return await rootBundle.loadString('assets/public_key.pem');
  }

  encryptString() async {
    print(loadPublicKey().toString());
    final publicKey =
        await parseKeyFromFile<RSAPublicKey>('${loadPublicKey()}');
    final privateKey =
        await parseKeyFromFile<RSAPrivateKey>('${loadPrivateKey()}');

    final plainText = 'James Bond';
    final encrypter =
        Encrypter(RSA(publicKey: publicKey, privateKey: privateKey));

    final encrypted = encrypter.encrypt(plainText);
    final decrypted = encrypter.decrypt(encrypted);

    print(decrypted);
    print(encrypted.base64);
  }
}

ERROR:
Performing hot reload...
Syncing files to device AOSP on IA Emulator...
Reloaded 8 of 707 libraries in 1,021ms.
I/flutter ( 7395): Instance of 'Future'
E/flutter ( 7395): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Cannot open file, path = 'Instance of 'Future'' (OS Error: No such file or directory, errno = 2)
I did add assets in yaml file as:
flutter:
  assets:
    - assets/

A: parseKeyFromFile is a convenience function that reads a file and parses the contents. You don't have a file, you have an asset that you are already doing the work of reading into a string. Having read the file, it just parses it - and that's what you need.
This should work:
final publicPem = await rootBundle.loadString('assets/public_key.pem');
final publicKey = RSAKeyParser().parse(publicPem) as RSAPublicKey;

and similar for the private key.


Q: Using Vagrant to manage AWS instances For some time I am managing EC2 (Windows Boxes), RDS and S3 on AWS.
I do know manual steps that must be made in order to set up lets say a normal box (DB, Storage and Server. I heard about Vagrand, but everywhere I looked it mainly talks about Linux boxes on AWS.
My main question is: Is Vagrand a tool that will save me time for deyploment (windows), or should I not use it at all (in Windows scenario).

A: Vagrant plays nicely with AWS (via vagrant-aws plugin).
Vagrant seems to play nicely with Windows as well since version 1.6 and the introduction of WinRM support (ssh alternative for Windows).
However AWS plugin doesn't support WinRM communicator yet. So you'll need to pre-bake your Windows AMIs with SSH service pre installed, if you want vagrant to provision it.
Update (29/03/2016): Thanks to Rafael Goodman for pointing to vagrant-aws-winrm plugin as a possible workaround.


Q: A proof involving linear ordering concept

"Let $(P, <)$ and $(Q, \prec)$ be linearly ordered sets, and let $h$ be a one-to-one function with domain $P$ and range $Q$ such that $h(p_1)\prec h(p_2)$ whenever $p_1<p_2$. Then $h$ is an isomorphism between $(P,<)$ and $(Q,\prec )$.
Proof. We have to verify that if $p_1, p_2 \in P$ are such that $h(p_1)\prec h(p_2)$, then $p_1<p_2$. But if $p_1$ is not less than $p_2$, then, because < is a linear ordering of $P$, either $p_1=p_2$ or $p_2<p_1$. If $p_1=p_2$, then $h(p_1)=h(p_2)$, and if $p_2<p_1$, then $h(p_2)\prec h(p_1)$, by the assumption. Either case contradicts $h(p_1)\prec h(p_2)$."

Since $<$ is a linear ordering, for all $p_1, p_2\in P$, either $p_1<p_2$ or $p_2<p_1$.
Why is $p_1=p_2$ treated as a separate case?

A: The author is using linear ordering to mean what I would call a strict linear order(ing). A binary relation $<$ on a set $A$ is a strict linear order if it is transitive and has the trichotomy property: for any $a,b\in A$, exactly one of $a<b$, $a=b$, and $b<a$ holds. The usual notions $<$ and $>$ in $\Bbb R$ are strict linear orders, while $\le$ and $\ge$ are what I would call simply linear orders.
Thus, the case $p_1=p_2$ really is a separate case.


Q: Have you told him?/Did you tell him? A: I already know what's going to happen.
B: You do? (to C) Have you told him?/Did you tell him?
C: No, I haven't said a word.
Are "have you told him?" and "Did you tell him?" equally natural here?

A: Yes. They're equally natural. Have you told him treats the telling as an act which continues to have relevance to now, did you tell him treats it as a completed act. Both forms are available in most cases.


Q: Entity Framework - Challenging setup includes multiple primary keys, and multiple associations to foreign table I'm trying to map a couple of legacy tables using Entity Framework. The classes look like this...
public class Customer
{
    [Key, Required]
    public string Code { get; set; }

    public string Domain { get; set; }

    public virtual Address BillToAddress { get; set; }

    public virtual ICollection<Address> ShipToAddresses { get; set; }
}

public class Address
{
    [Column(Order = 0), Key, Required]
    public string Code { get; set; }

    [Column(Order = 1), Key, Required]
    public string Domain { get; set; }

    public string Type { get; set; }

    public string CustomerReferenceCode { get; set; }
}

Each Customer has one "BillToAddress" that corresponds with an Address whose CustomerReferenceCode contains the Customer's Code and where the Type field contains the text "Customer"
Each Customer has zero or more "ShipToAddresses" that correspond to Addresses whose CustomerReferenceCode contains the Customer's Code and whose where the Type fields contain the text "Ship-To"
I'm able to reference the BillToAddress by adding
[Key, Required]
[ForeignKey("BillToAddress"), Column(Order = 1)]
public string Code { get; set; }

[ForeignKey("BillToAddress"), Column(Order = 2)]
public string Domain { get; set; }

But I've not been able to figure out how to reference the collection of ShipToAddresses for the customer.

A: See this example (note it is separate classes): Fluent NHibernate automap inheritance with subclass relationship
One easy approach might be:
public class Customer
{
[Key, Required]
public string Code { get; set; }

public string Domain { get; set; }

public virtual ICollection<Address> Addresses{ get; set; }

public virtual Address BillToAddress { get { Addresses.Where(n=>n.Type = Address.BillingAddress)).Single(); }

public virtual ICollection<Address> ShipToAddresses { get { Addresses.Where(n=>n.Type = Address.ShipToAddress)); }
}

One additional comment - this is not implicitly forcing your one Billing address business logic as the example you start with does, so you either need to enforce that elsewhere with the above approach. Also, creating two classes and using TPH as described in the example I link to is the approach I would likely take anyway - which would meet your described goal above directly. Also, in between the two, this may work, using the discriminator in the getter of each property directly.


Q: Is it an axiom of set theory that $|\mathbb N| = \omega$? $\omega$ is the first infinite cardinal. $|\mathbb N| = \omega$. is this an axiom of set theory? or it has a proof based on preceding axioms?
thanks.

A: It's not an axiom, because no axiom of $\sf ZFC$ is talking about $\Bbb N$.
But regardless of set theory, we know that $\Bbb N$ is the unique second-order model of Peano axioms; or the unique (non-empty) well-ordered set which has no maximal element, and every proper initial segment is finite.
This is why we can prove, from the axioms of $\sf ZF$, that $\omega$ satisfy the second-order version of Peano axioms: all the arithmetic (cardinal or ordinal) and the second-order induction axiom, stating that every inductive subset is equal to the entire set of natural numbers.
Now, we can prove that every two models of second-order Peano are isomorphic. Therefore we can prove that if $A$ is a model of second-order Peano, then $A$ has a bijection with $\omega$. So if we know that every set "worthy of being called $\Bbb N$" is equipotent with $\omega$, it means that $\sf ZF$ proves that the natural numbers have the same cardinality as $\omega$.

A: Well, it's common to define $\mathbb N := \omega$ and since $|\omega | = \omega$, i.e. there is a bijection $f \colon \omega \to \omega$ (the identity), the result follows.


Q: Python Regex Capturing Multiple Matches in separate observations I am trying to create variables location; contract items; contract code; federal aid using regex on the following text:
    PAGE    1

                BID OPENING DATE    07/25/18    FROM 0.2 MILES WEST OF ICE HOUSE        07/26/18 CONTRACT NUMBER    03-2F1304   ROAD TO 0.015 MILES WEST OF CONTRACT CODE 'A '

            LOCATION    03-ED-50-39.5/48.7  DIVISION HIGHWAY ROAD   44 CONTRACT ITEMS

        INSTALL SANDTRAPS AND PULLOUTS  FEDERAL AID ACNH-P050-(146)E

PAGE    1

                    BID OPENING DATE    07/25/18    IN EL DORADO COUNTY AT VARIOUS          07/26/18 CONTRACT NUMBER     03-2H6804  LOCATIONS ALONG ROUTES 49 AND 193   CONTRACT CODE 'C ' LOCATION 03-ED-0999-VAR          13 CONTRACT ITEMS

        TREE REMOVAL    FEDERAL AID NONE

PAGE    1

                BID OPENING DATE    07/25/18    IN LOS ANGELES, INGLEWOOD AND       07/26/18 CONTRACT NUMBER    07-296304   CULVER CITY, FROM I-105 TO PORT CONTRACT CODE 'B '

            LOCATION    07-LA-405-R21.5/26.3    ROAD UNDERCROSSING  55 CONTRACT ITEMS

        ROADWAY SAFETY IMPROVEMENT  FEDERAL AID ACIM-405-3(056)E

This text is from one word file; I'll be looping my code on multiple doc files. In the text above are three location; contract items; contract code; federal aid pairs. But when I use regex to create variables, only the first instance of each pair is included.
The code I have right now is:
# imports
import os
import pandas as pd
import re
import docx2txt
import textract
import antiword

all_bod = []
all_cn = []
all_location = []
all_fedaid = []
all_contractcode = []
all_contractitems = []
all_file = []

text = '    PAGE    1

            BID OPENING DATE    07/25/18    FROM 0.2 MILES WEST OF ICE HOUSE        07/26/18 CONTRACT NUMBER    03-2F1304   ROAD TO 0.015 MILES WEST OF CONTRACT CODE 'A '

        LOCATION    03-ED-50-39.5/48.7  DIVISION HIGHWAY ROAD   44 CONTRACT ITEMS

    INSTALL SANDTRAPS AND PULLOUTS  FEDERAL AID ACNH-P050-(146)E

PAGE    1

                BID OPENING DATE    07/25/18    IN EL DORADO COUNTY AT VARIOUS          07/26/18 CONTRACT NUMBER     03-2H6804  LOCATIONS ALONG ROUTES 49 AND 193   CONTRACT CODE 'C ' LOCATION 03-ED-0999-VAR          13 CONTRACT ITEMS

    TREE REMOVAL    FEDERAL AID NONE

    PAGE    1

            BID OPENING DATE    07/25/18    IN LOS ANGELES, INGLEWOOD AND       07/26/18 CONTRACT NUMBER    07-296304   CULVER CITY, FROM I-105 TO PORT CONTRACT CODE 'B '

        LOCATION    07-LA-405-R21.5/26.3    ROAD UNDERCROSSING  55 CONTRACT ITEMS

    ROADWAY SAFETY IMPROVEMENT  FEDERAL AID ACIM-405-3(056)E'

bod1 = re.search('BID OPENING DATE \s+ (\d+\/\d+\/\d+)', text)
bod2 = re.search('BID OPENING DATE\n\n(\d+\/\d+\/\d+)', text)

if not(bod1 is None):
    bod = bod1.group(1)
elif not(bod2 is None):
    bod = bod2.group(1)
else:
    bod = 'NA'

all_bod.append(bod)

# creating contract number
cn1 = re.search('CONTRACT NUMBER\n+(.*)', text)
cn2 = re.search('CONTRACT NUMBER\s+(.........)', text)

if not(cn1 is None):
   cn = cn1.group(1)
elif not(cn2 is None):
   cn = cn2.group(1)
else:
   cn = 'NA'

all_cn.append(cn)

# location

location1 = re.search('LOCATION \s+\S+', text)
location2 = re.search('LOCATION \n+\S+', text)

if not(location1 is None):
    location = location1.group(0)
elif not(location2 is None):
    location = location2.group(0)
else:
    location = 'NA'

all_location.append(location)

# federal aid

fedaid = re.search('FEDERAL AID\s+\S+', text)
fedaid = fedaid.group(0)

all_fedaid.append(fedaid)

# contract code

contractcode = re.search('CONTRACT CODE\s+\S+', text)
contractcode = contractcode.group(0)

all_contractcode.append(contractcode)

# contract items

contractitems = re.search('\d+ CONTRACT ITEMS', text)
contractitems = contractitems.group(0)

all_contractitems.append(contractitems)

This code parses the only first instance of these variables in the text.

contract-number
location
contract-items
contract-code
federal-aid

03-2F1304
03-ED-50-39.5/48.7
44
A
ACNH-P050-(146)E

But, I am trying to figure out a way to get all possible instances in different observations.

contract-number
location
contract-items
contract-code
federal-aid

03-2F1304
03-ED-50-39.5/48.7
44
A
ACNH-P050-(146)E

03-2H6804
03-ED-0999-VAR
13
C
NONE

07-296304
07-LA-405-R21.5/26.3
55
B
ACIM-405-3(056)E

The all_variables in the code are for looping over multiple word files - we can ignore that if we want :).
Any leads would be super helpful. Thanks so much!

A: import re
data = []
df = pd.DataFrame()

regex_contract_number =r"(?:CONTRACT NUMBER\s+(?P<contract_number>\S+?)\s)"
regex_location = r"(?:LOCATION\s+(?P<location>\S+))"
regex_contract_items = r"(?:(?P<contract_items>\d+)\sCONTRACT ITEMS)"
regex_federal_aid =r"(?:FEDERAL AID\s+(?P<federal_aid>\S+?)\s)"
regex_contract_code =r"(?:CONTRACT CODE\s+\'(?P<contract_code>\S+?)\s)"
regexes = [regex_contract_number,regex_location,regex_contract_items,regex_federal_aid,regex_contract_code]

for regex in regexes:
    for match in re.finditer(regex, text):
        data.append(match.groupdict())
    df = pd.concat([df, pd.DataFrame(data)], axis=1)
    data = []

df


Q: OpenLayers.js which files to use? As i red from the readme file, openlayers.js has multiple choices for including files and themes.
What i would like is to use the lightest solution of openlayers.js files.
I included the openlayers.light.js in my app, and it creates maps but do not show them, check this:

do i forgot to include some other file?
my structure structure is this:
/vendor
   /js
     openlayers.light.js
     /img
     /theme

how to show maps layers?
Also does the openlayers.light.js will work on mobile devices (once fixed this problem :P )? or i'll need to include openlayers.mobile.js too?
This is the code not working with openlayers.light.js but working with openlayers.js (740kb) :
var _element = "#map";
 var map = new OpenLayers.Map (_element, {
    controls: [
    new OpenLayers.Control.Navigation({
      dragPanOptions: {
        enableKinetic: true
      }
    }),
    new OpenLayers.Control.Zoom()
    ],
    projection: new OpenLayers.Projection("EPSG:900913"),
    displayProjection: new OpenLayers.Projection("EPSG:4326")
  });

  var lonLat = new OpenLayers.LonLat(_lon, _lat).transform (
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
// map.getProjectionObject() doesn't work for unknown reason
);
  var markers = new OpenLayers.Layer.Markers( "Markers" );
  map.addLayer(markers);

  var size = new OpenLayers.Size(21,25);
  var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
  var icon = new OpenLayers.Icon(_img_map_marker, size, offset);
  markers.addMarker(new OpenLayers.Marker(lonLat, icon.clone()));

  var mapnik = new OpenLayers.Layer.OSM("Test");
  map.addLayer(mapnik);

  map.setCenter (lonLat,3);

PS: my openlayers map js init method is ok, it works using the huge openlayers.js (740KB), but not working with openlayers.light.js as i showed above
html

css
img{max-width:none;}
#map{
width:300px;
height:300px;
}

A: if you want to use mobile properties with openlayers as panning or zooming with hand you have to use openlayers.mobile.js.
you can use openlayers.light.js with mobile devices but not mobile functions.
i think your structure should be :
myProject
   /js
      openlayers.light.js
   /img
   /theme

and i have tried openlayers.light.js in http://jsfiddle.net/aragon/ZecJj/ and there is no problem with it.
My code:
var map = new OpenLayers.Map({
    div: "map",
    minResolution: "auto",
    maxResolution: "auto",
});

var osm = new OpenLayers.Layer.OSM();
var toMercator = OpenLayers.Projection.transforms['EPSG:4326']['EPSG:3857'];
var center = toMercator({x:-0.05,y:51.5});
map.addLayers([osm]);

map.setCenter(new OpenLayers.LonLat(center.x,center.y), 13);

and try to read Deploying (Shipping OpenLayers in your Application).

OpenLayers comes with pre-configured examples out of the box: simply
  download a release of OpenLayers, and you get a full set of easy to
  use examples. However, these examples are designed to be used for
  development. When you’re ready to deploy your application, you want a
  highly optimized OpenLayers distribution, to limit bandwidth and
  loading time.

you can change src file with this link and can see it still works.

to

i hope it helps you...


Q: Need to sort complex objects, like dominoe Here is a situation. For example I have a structure like this (code is simplified):
class Dominoe
{
    ctor Dominoe(left, right)

    string LeftSide;
    string RightSide;
}

And I have data, somewhat like this:
Dominoe("2", "3"), Dominoe("1", "2"), Dominoe("4", "5"), Dominoe("3", "4")

I know that there won't be any gaps in dominoes, nor repeats.
I need to order this collection, so every RightSide would be connected to appropriate LeftSide. Like so:
Dominoe("1", "2"), Dominoe("2", "3"), Dominoe("3", "4"), Dominoe("4", "5")

Values - not numbers. Just need a clue.
Right now I've done this task in 2 steps. Primary - i'm looking for the entry point. The dominoe which have LeftSide not presented in any other Dominoe RightSide. After that i switch it with 0 index item. Secondly - i'm looking for next dominoe which have LeftSide same as RightSide of my entry dominoe and so on in cycle.
I'm doing this in C#, but this really doesn't matter.
The problem is - i don't think it's best algorithm. Any ideas will be great. Thx.
EDITED !
Was my bad to talk about numbers.
Let's change Dominoe for trevel cards.
So it'll be like:
TravelCard ("Dublin", "New York"), TravelCard ("Moscow", "Dublin"), TravelCard ("New York", "Habana")

A: Unless you have huge amount of your cards your solution will work. Otherwise you can consider 2 dictionaries to make searches constants and keep O(N) complexity:
namespace ConsoleApplication
{
    public class Dominoe
    {
        public Dominoe(int left, int right)
        {
            LeftSide = left;
            RightSide = right;
        }

        public int LeftSide;
        public int RightSide;
    }

    class Program
    {
        static void Main(string[] args)
        {
            var input = new List<Dominoe>()
            {
                new Dominoe(2, 3),
                new Dominoe(1, 2),
                new Dominoe(4, 5),
                new Dominoe(3, 4)
            };

            var dicLeft = new Dictionary<int, Dominoe>();
            var dicRigth = new Dictionary<int, Dominoe>();

            foreach (var item in input)
            {
                dicLeft.Add(item.LeftSide, item);
                dicRigth.Add(item.RightSide, item);
            }

            Dominoe first = null;

            foreach(var item in input)
            {
                if (!dicRigth.ContainsKey(item.LeftSide))
                {
                    first = item;
                    break;
                }
            }

            Console.WriteLine(string.Format("{0} - {1}", first.LeftSide, first.RightSide));

            for(int i = 0; i < input.Count - 1; i++)
            {
                first = dicLeft[first.RightSide];
                Console.WriteLine(string.Format("{0} - {1}", first.LeftSide, first.RightSide));
            }

            Console.ReadLine();
        }
    }
}


Q: How to cache a small piece of information in Django I have a website that delivers a list of questions to users. This set of questions is the same for all users. I have these questions stored in a text file. The content of this file will not change while the server is running.
I cannot use a static page to display these questions because I have some logic to decide when to show which question.
I would like to cache these questions in memory (instead of reading the file off the hard drive every time a user connects). I am using Django 1.7.
I did read about caching from Django's website, I think the suggested methods (like memcached and database) are too heavy for my need. What would be a good solution for my situation? use a global variable?
Thanks!

A: There are so many caching back-ends you can use as listed in https://docs.djangoproject.com/en/1.7/topics/cache/
I haven't tried the file system or local memory caching myself, I always needed memcached, but looks like they're available, and the rest is a piece of cake!
from django.core import cache

cache_key = 'questions'
questions = cache.cache.get(cache_key) # to get
if questions:
  # use questions you fetched from cache
else:
  questions = { 'question1': 'How are you?'} #Something serializable that has your questions
  cache.cache.set(cache_key, questions)


Q: XAMPP 7.0.0 php session causing whole page not to load Before upgrading to XAMPP 7, everything used to work fine.
Then after the update, everything except php sessions is working.
Any page with session_start() does not load in the browser and nothing is logged into php.log file concerning the error.
I've looked everywhere for such, and I found one here on Stackoverflow that had a similar problem, but the issue had been using MySQL.
Now, at the very basic level, this won't load:
<?php
   session_start();
?>

I've tried changing the session.save_path in php.ini file without any success. Any help?


Q: Automatically sync 2 writable git repositories I am working in a small office, where we are using git with a central repository at a windows share, where we can PUSH to and PULL from.
To be able to work from home, travel etc, we want to have a possibility to reach a central repo from "the outside world". Our internet connection is very, very slow, so it is no possibility to have just one central repository "inside" or "outside".
My simple attempt was the following:

*

*Make a central repository at the internal WIN network share: git init --bare

*Make one "outside" (e.g. github or an external WIN share or anything else)

*At the internal repo call git remote add EXTERNALREPO <pathToIt>

*and make a batch running every x minutes/hours, saying git fetch --tags EXTERNALREPO, git push --tags EXTERNALREPO
When working "inside", clone/push/pull the internal repo, when on the road, use the external repo for that.
Question: Is this the way to go, is there a better way, or am I completely wrong?
Related:

*

*Two-way git mirror –
I do not think that wee need locking as we are not so many people.

*Safe master-master setup with git? (writable git mirror)

*How to keep 2 git repositories in sync automatically – As far as I know, a push lasts as long as it take to run all the hooks, AND since using a windows share, the CLIENT has to run it, so it wouldn't be a solution.

Update 1: I now came up with a slightly adjusted configuration.

*

*INTERNAL repo on an internal Windows Share: git init --bare

*EXTERNAL repo on an external Windows Share: git init --bare

*Both repos:
git config receive.denyNonFastForwards 1
git config receive.denyDeletes 1
git remote add {INTERNAL|EXTERNAL} file:///...

*Every x seconds/minutes/hours, call git push --all {INTERNAL|EXTERNAL} and git push --tags {INTERNAL|EXTERNAL}, at first at the internal, then at the external repository.

A: *

*"repository at a windows share" is The Bad&Ugly Idea (tm)

*Use post-* hook in INTERNAL for pushing to EXTERNAL as it happens

*Pseudo-CVCS in DVCS is ugly (everybody can bring local travel-repo to workplace and sync from it)


Q: Google Cloud Shell - How to resolve CERTIFICATE_VERIFY_FAILED error? I have simple dataflow pipeline and trying to execute from cloud shell,
Code:
from __future__ import print_function
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
with beam.Pipeline(options=PipelineOptions()) as p:
    lines = p | 'Read' >> beam.io.ReadFromText('test.csv')
    lines | 'Write' >> beam.io.WriteToText('gs://bucket/output_20193003', file_name_suffix='.csv')
    result = p.run()
    result.wait_until_finish()

Command used to execute:
python -m simple_pipeline --runner DataflowRunner --project myproject --staging_location gs://bucket/staging --temp_location gs://bucket/temp

Observations:
When executed from Cloud shell I encounter below error,
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/portability/fn_api_runner.py", line 859, in run_stages
    pcoll_buffers, safe_coders).process_bundle.metrics
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/portability/fn_api_runner.py", line 970, in run_stage
    self._progress_frequency).process_bundle(data_input, data_output)
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/portability/fn_api_runner.py", line 1174, in process_bundle
    result_future = self._controller.control_handler.push(process_bundle)
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/portability/fn_api_runner.py", line 1054, in push
    response = self.worker.do_instruction(request)
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/worker/sdk_worker.py", line 208, in do_instruction
    request.instruction_id)
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/worker/sdk_worker.py", line 230, in process_bundle
    processor.process_bundle(instruction_id)
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/runners/worker/bundle_processor.py", line 301, in process_bundle
    op.finish()
  File "apache_beam/runners/worker/operations.py", line 398, in apache_beam.runners.worker.operations.DoOperation.finish
  File "apache_beam/runners/worker/operations.py", line 399, in apache_beam.runners.worker.operations.DoOperation.finish
  File "apache_beam/runners/worker/operations.py", line 400, in apache_beam.runners.worker.operations.DoOperation.finish
  File "apache_beam/runners/common.py", line 598, in apache_beam.runners.common.DoFnRunner.finish
  File "apache_beam/runners/common.py", line 589, in apache_beam.runners.common.DoFnRunner._invoke_bundle_method
  File "apache_beam/runners/common.py", line 618, in apache_beam.runners.common.DoFnRunner._reraise_augmented
  File "apache_beam/runners/common.py", line 587, in apache_beam.runners.common.DoFnRunner._invoke_bundle_method
  File "apache_beam/runners/common.py", line 299, in apache_beam.runners.common.DoFnInvoker.invoke_finish_bundle
  File "apache_beam/runners/common.py", line 302, in apache_beam.runners.common.DoFnInvoker.invoke_finish_bundle
  File "apache_beam/runners/common.py", line 693, in apache_beam.runners.common._OutputProcessor.finish_bundle_outputs
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/io/iobase.py", line 1005, in finish_bundle
    yield WindowedValue(self.writer.close(), window.MAX_TIMESTAMP,
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/io/filebasedsink.py", line 388, in close
    self.sink.close(self.temp_handle)
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/io/filebasedsink.py", line 148, in close
    file_handle.close()
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/io/filesystemio.py", line 201, in close
    self._uploader.finish()
  File "/home/user/beam-env/local/lib/python2.7/site-packages/apache_beam/io/gcp/gcsio.py", line 553, in finish
    raise self._upload_thread.last_error  # pylint: disable=raising-bad-type
RuntimeError: SSLHandshakeError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661) [while running 'Write/Write/WriteImpl/WriteBundles']

Note: I see this error only from Cloud Shell and the same code and commands works fine when executed from local machine - Using SDK or PyCharm IDE.
What is the problem with my cloud shell? How to fix it? Please suggest.

A: Or try this in cloud shell?
virtualenv --python=/usr/bin/python2 run_pipeline
. ./run_pipeline/bin/activate
pip install apache-beam[gcp]
python -m simple_pipeline --runner DataflowRunner --project myproject --staging_location gs://bucket/staging --temp_location gs://bucket/temp

A: I am able to launch dataflow jobs after upgrading to latest version.
pip install apache-beam[gcp]


Q: PHP duplicating query results? For some reason,when I run this query through PHP, it returns 8 rows, when in reality i only have 2 rows in my database, and when i run it through phpmyadmin it returns 2 obviously.
 $sql = "SELECT url FROM bookmarks,users WHERE bookmarks.user_id = {$session->user_id}";
 $resultado = $db->query($sql);

 echo mysql_num_rows($resultado);

I'm breaking my head!

A: your query produces cartesian product because you have not supplied the relationship between the two tables: bookmarks and users,
SELECT url
FROM   bookmarks
       INNER JOIN users
          ON bookmarks.COLNAME = users.COLNAME
WHERE  bookmarks.user_id = '$session->user_id'

where COLNAME is the column that defines how the table are related with each other, or how the tables should be linked.
To further gain more knowledge about joins, kindly visit the link below:

*

*Visual Representation of SQL Joins
As a sidenote, the query is vulnerable with SQL Injection if the value(s)  of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

*

*How to prevent SQL injection in PHP?

A: As JW pointed out, you are producing a Cartesian Product -- you aren't joining bookmarks against users.  That's why you're duplicating rows.
With that said, you don't need to join users at all in your above query:
"SELECT url FROM bookmarks WHERE bookmarks.user_id = {$session->user_id}"

Good luck.


Q: Intemittent Cannot create ActiveX component Everything was working fine, and then our code starts throwing:
Cannot create ActiveX component when we try to create a com object.
We reboot the server a couple of times and it goes away
Then after a while it comes back
This is driving us nuts.  Any help appreciated.

A: I apologize that the question was vague.  However we had no clue what was causing the problem so what facts would have been relevant?
At any rate it turns out we have two web apps running under IIS, both are trying to create ActiveX components.  As soon as we turn one of the web apps off the problem goes away.
After we verified this behavior, we tried calling some simple ActiveX components (like excel).  Lo and behold exactly the same behavior as long as there are more than two web apps running.
Our solution for now is to host the second web app elsewhere.


Q: Alternative to Cookie Session for different applications within same domain I have 2 different ASP.NET applications on the same domain, different app pools on IIS. Application 1 opens Application 2 using window.open(url). At this stage the cookie is shared among both applications.
Application 2 runs the following code after login:
Context.Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
Context.Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);

The purpose of this code is to prevent Session Fixation vulnerability whereby an attacker could steal the session id pre-login, and use it post-login to authenticate themselves as a legitimate user.
However, this also changes the session id on Application 1, effectively login the user out of the application.
How can I prevent this from happening? and what other approaches could I follow?

A: You could try use JSON web tokens instead
https://www.red-gate.com/simple-talk/dotnet/net-development/jwt-authentication-microservices-net/
https://jwt.io/


Q: Crash with UITabBarController Sometimes I have strange crash when I switch from one tab to another:
0   libobjc.A.dylib                     0x3857e636 objc_msgSend + 22
1   UIKit                               0x3024ca89 -[UIResponder(Internal) _canBecomeFirstResponder] + 21
2   UIKit                               0x3024c7a3 -[UIResponder becomeFirstResponder] + 207
3   UIKit                               0x3024caff -[UIView(Hierarchy) becomeFirstResponder] + 107
4   UIKit                               0x302c946b -[UITextField becomeFirstResponder] + 47
5   UIKit                               0x302ca345 -[UIView(Hierarchy) deferredBecomeFirstResponder] + 57
6   UIKit                               0x301cd441 __45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke + 165
7   Foundation                          0x2e304d33 -[NSISEngine withBehaviors:performModifications:] + 211
8   UIKit                               0x301cd291 -[UIView(Hierarchy) _postMovedFromSuperview:] + 297
9   UIKit                               0x301da01d -[UIView(Internal) _addSubview:positioned:relativeTo:] + 1413
10  UIKit                               0x301d9a93 -[UIView(Hierarchy) addSubview:] + 31
11  UIKit                               0x302bb563 -[UITransitionView transition:fromView:toView:removeFromView:] + 979
12  UIKit                               0x302fb783 -[UITransitionView transition:fromView:toView:] + 31
13  UIKit                               0x302fb759 -[UITransitionView transition:toView:] + 105
14  UIKit                               0x302fa87b -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:] + 1107
15  UIKit                               0x302fa41f -[UITabBarController transitionFromViewController:toViewController:] + 39
16  UIKit                               0x302fa2f7 -[UITabBarController _setSelectedViewController:] + 259
17  UIKit                               0x303c45c9 -[UITabBarController _tabBarItemClicked:] + 273
18  UIKit                               0x302036c7 -[UIApplication sendAction:to:from:forEvent:] + 91
19  UIKit                               0x30203663 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 39
20  UIKit                               0x303c447f -[UITabBar _sendAction:withEvent:] + 371
21  UIKit                               0x302036c7 -[UIApplication sendAction:to:from:forEvent:] + 91
22  UIKit                               0x30203663 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 39
23  UIKit                               0x30203633 -[UIControl sendAction:to:forEvent:] + 47
24  UIKit                               0x301eed7b -[UIControl _sendActionsForEvents:withEvent:] + 375
25  UIKit                               0x303c41a7 -[UITabBar(Static) _buttonUp:] + 119
26  UIKit                               0x302036c7 -[UIApplication sendAction:to:from:forEvent:] + 91
27  UIKit                               0x30203663 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 39
28  UIKit                               0x30203633 -[UIControl sendAction:to:forEvent:] + 47
29  UIKit                               0x301eed7b -[UIControl _sendActionsForEvents:withEvent:] + 375
30  UIKit                               0x3020307b -[UIControl touchesEnded:withEvent:] + 595
31  UIKit                               0x30202d4d -[UIWindow _sendTouchesForEvent:] + 529
32  UIKit                               0x301fdca7 -[UIWindow sendEvent:] + 759
33  UIKit                               0x301d2e75 -[UIApplication sendEvent:] + 197
34  UIKit                               0x301d1541 _UIApplicationHandleEventQueue + 7121

Maybe for someone this will look familiar and he could help to understand root of problem.

A: I got the same crash log.And my reason is  the view controller is released but the UITextField.delegate is not setting nil. So you can set UITextField.delegate = nil in dealloc of the view controller.


Q: Asking the user about the radius of the circle and will solve the area and the circumference I am making a class similar code to this but I don't know how I will make it into a input function.
How would I ask the user to input a radius of a circle?
class Circle:
    def __init__(self, r):
        self.radius = r
    def area(self):
        return 3.14 * (self.radius ** 2)
    def perimeter(self):
        return 2*3.14*self.radius
obj = Circle(3)
print("Area of circle:",obj.area())
print("Perimeter of circle:",obj.perimeter())

A: You just have to replace the argument to an input function to take input from the user. So the code will be changed from
obj = Circle(3)

to
obj = Circle(int(input("Please Enter Radius:")))

The int() before the input function is to convert the input from string to an integer.
To know more about taking input from user, please check out here.

A: class Circle:
    def __init__(self, r):
        self.radius = r
    def area(self):
        return 3.14 * (self.radius ** 2)
    def perimeter(self):
        return 2*3.14*self.radius
obj = Circle(int(input("Enter Radius:")))
#obj = Circle()
print("Area of circle:",obj.area())
print("Perimeter of circle:",obj.perimeter())


Q: Where to place a data array in zf2 I want to create the following static data array in my zf2 project so that routing and others methods can be done based on department codes, and then view helpers and form select elements in different modules look up the department titles for the user interface.
    $deptList = array(
        '01'  => 'Human Resources',
        '02'  => 'Sales',
        '03'  => 'Marketing',
        '04'  => 'Accounting',
           // ...
    );

In the zf2 directory structure, where should I put this?  Does it need it's own class?
Also, it might be convenient to record this data in a database table instead of hard-coding it.  But I question whether this would affect performance.

A: As there is no registry singleton like in ZF1 creating a service and injecting it where needed is appropriate. You can then place it according to your autoloader configuration in the filesystem.  As well inside that class you could do anything you like to build the array, e.g. using a database for it.
Nevertheless you can as well use your config for it if it is static information - e.g. like this:
Module.php
class Module
{
    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }
}

module.config.php
return [
    'deptList' => [
        '01' => 'Human Resources',
        '02' => 'Sales',
        '03' => 'Marketing',
        '04' => 'Accounting',
        // ...
    ],
];

MyController.php
class MyController extends \Zend\Mvc\Controller\AbstractActionController
{

    public function myAction()
    {
        $config   = $this->getServiceLocator()->get('config');
        $deptList = $config['deptList'];
    }

}


Q: Facebook API Send Message : How to send link I send messages with facebook application, the messages are texts
I want to send link in the message.
This is my code :
$message_to_reply = 'hello';

$ch = curl_init($url);
$jsonData = '{
    "recipient":{
        "id":"' . $sender . '"
    },
    "message":{
        "text":"' . $message_to_reply . '"
    }
}';

$jsonDataEncoded = $jsonData;

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

But it doesnt work.


Q: Animating Text/Graphics in ArcMap ArcScene includes the capacity to animate 3D text added to the scene, through the use of Graphics Layers. I'm able to use this to make text fade in and out as visibility of layers is changed, however I'd like to achieve something similar in ArcMap.
I've got a clunky work around which involves creating new point layers with transparent symbology, labeling them to suit the different layers, and fading those in with the relevant layer. I can't apply the labels to the layers I'm displaying as they are all raster. Is there a more straight forward way to achieve this?
I could do this in ArcScene with a view point set perpendicular to the plane of the data, but I'd rather use ArcMap because it is more stable with the amount of raster data I'm using.

A: As commented by @MichaelMiles-Stimson:

Have a read of
  http://resources.arcgis.com/en/help/arcobjects-net/conceptualhelp/index.html#/How_dynamic_display_works/0001000003wt000000/
  for the fundamentals of IDynamicDisplay then create a dynamic glyph
  using IDynamicGlyphFactory. See sample Dynamic Logo
  http://resources.arcgis.com/en/help/arcobjects-net/conceptualhelp/index.html#/d/00010000006z000000.htm


Q: qTranslate plugin switching language in the same page I have a serious problem with a qTranslate buttons.
Right now the web structure is: http://www.site.com/news/?lang=en
When I stay in the home page and I try to change the language, the botton opens the first post (maybe because I'm using permalink):
<?php if(qtrans_getLanguage()=='it'): ?>

<a href="<?php echo qtrans_convertURL(get_permalink(), 'en'); ?>" >eng

ita

<?php endif; ?>
<?php if(qtrans_getLanguage()=='en'): ?>

eng

<a href="<?php echo qtrans_convertURL(get_permalink(), 'it'); ?>" >ita

<?php endif; ?>

How to solve this without open the last post or come back at the home page, but only switching language in the same page?

A: I'm using qTranslate on my project and I do not do any of that stuff you do in your code above and have no problem switching between languages.
All I do is call qts_language_menu() function that creates language menu, nothing else. This will create necessary links which ables you to switch between languages but stay on the same page.

A: You don't need to use get_permalink()
you can just pass an empty string as url and the language as 2nd param
and the function will do rest !
just like:
$my_translated_content_url = qtrans_convertURL("", "en");

infact if you see at the function definition:
function qtrans_convertURL($url='', $lang='', $forceadmin = false) {
  global $q_config;

  // invalid language
  if($url=='') $url = esc_url($q_config['url_info']['url']); // <-You don't need the url
  if($lang=='') $lang = $q_config['language'];
      [... the function continue...]

A: The links are stored in the $qTranslate_slug object. I made a function to make it easy to get the link for the current page in the desired language:
function getUrlInTargetLanguage($targetLang){
    global $qtranslate_slug;
    return $qtranslate_slug->get_current_url($targetLang);
}

So for example, if you wanted to get the english link, you should write:
getUrlInTargetLanguage("en");

A: May be this late but following good functions to easy call check current language or auto generate any language URL for qTranslate:
// check language
function check_lang() {
    return qtranxf_getLanguage();
}

// Generate language convert URL
function get_lan_url($lang){
    echo qtranxf_convertURL('', $lang);
}

// generate inline translate short code
add_shortcode( 'translate_now', 'get_translate' );
function get_translate( $atts, $content = null ) {
    extract( shortcode_atts(
            array(
                'ar' => '',
                'en' => '',
                'es' => '',
                'fr' => '',
            ), $atts )
    );
    if ( check_lang() == 'ar' ) {
        echo $atts['ar'];
    }
    if ( check_lang() == 'en' ) {
        echo $atts['en'];
    }
    if ( check_lang() == 'es' ) {
        echo $atts['ar'];
    }
    if ( check_lang() == 'fr' ) {
        echo $atts['ar'];
    }
}

function translate_now($ar,$en,$es,$fr){
    $content = '[translate_now ar="'.$ar.'" en="'.$en.'" es="'.$es.'" fr="'.$fr.'"]';
    echo do_shortcode($content);
}

So now you can check current language using check_lang() function for example:
<?php if(check_lang() == 'ar'): echo 'مرحبا'; endif;?>
<?php if(check_lang() == 'en'): echo 'Hello'; endif;?>
<?php if(check_lang() == 'es'): echo 'Hola'; endif;?>
<?php if(check_lang() == 'fr'): echo 'Bonjour'; endif;?>

Also you can use function translate_now()to translate inline by passing values:
<?php
translate_now(
    'مرحبا', // ar
    'Hello', //en
    'Hola', //es
    'Bonjour' //fr
);
?>

Also to generate any langauge convert URL use function get_lan_url() passing requested language:
<a href="<?php get_lan_url('ar');?>">العربية
<a href="<?php get_lan_url('en');?>">English
<a href="<?php get_lan_url('es');?>">España
<a href="<?php get_lan_url('fr');?>">Français


Q: Can anyone explain ![]/[] == true statement in js? console.log(true == []); // -> false
console.log(true == ![]); // -> false

Why they are always false?

A: true == [] is false simply because true is not equal to [].
![] evaluates to false, so true == ![] is false.
Also, true == !![] is true.


Q: code/website to generate stacked bar graph in jsp hi all
can any one provide me the code/website name from where i can get jsp source code to generate stacked bar graph and other graphs.it will be good if code is in jsp .
Thanks
Yugal

A: Here's one on RoseIndia's site that shows how to create area chart in JSP  http://www.roseindia.net/chartgraphs/areachart-jsppage.shtml
Now, just replace the charting code with the one for making bar charts and you are done: http://www.geodaq.com/jfreechart-sample/bar_chart_code.jsp


Q: How to cast GETDATE() to be only time ignore day,month and year I have a table for store takt-time. It's compound with "day_shift(1)" and "night_shift(0)" like below.

If I put current time(by using GETDATE() function ).
I need to know this current time is "day(1)" or "night(0)". my query like this.
SELECT [day_shift_flag]
FROM  [company_working_time]
WHERE   GETDATE() BETWEEN [start_time] AND[end_time]

But it can't found because a date received from GETDATE() isn't '1900-01-01'
How to compare a only time and ignore day,month,year.
What should I do?

A: You can cast a DateTime as a Time data type. For example:
SELECT
    [day_shift_flag]
FROM  [company_working_time]
WHERE
CAST(GETDATE() AS TIME) BETWEEN CAST([start_time] AS TIME) AND CAST([end_time] AS TIME)

A: By Following Way You can Ignore the  day,month,year
       SELECT [day_shift_flag]
        FROM  [company_working_time]
        WHERE   DatePart(HH,GETDATE()) BETWEEN DatePart(HH,[start_time]) AND DatePart(HH,[end_time])


Q: Proof of irrationality of $\zeta(3)$ I'm reading this article of Henri Cohen about Apery's proof of the irrationality of $\zeta(3)$ but I don't really get the details of "THEOREME 1".
My first doubt is about the relation $a_n \sim A \alpha^n n^{-3/2}$.
I know that if $a_n$ fulfilled the relation $a_n-34a_{n-1}+1=0$ then as its characteristic polynomial is $x^2-34x+1$ and as $\alpha$ is one of its roots, if we denote by $\bar{\alpha}$ the second root, then we would have $a_n=A_1\alpha^n+A_2\bar{\alpha}^n$.
Then, as $0<\bar{\alpha}<1$ we have that $a_n/\alpha^n \longrightarrow A_1$.
However, the relation for $a_n$ is
$$a_n-(34-51n^{1}+27n^{-2}-5n^{-3})+(n-1)^3n^{-3}a_{n-2}=0$$
and I don't know how can we rigurously take care of the extra terms.
Furthermore, how does one get the extra $n^{-3/2}$ term?
Secondly, why does that relation implies that $\zeta(3)-a_n/b_n = O(\alpha^{-2n})?$
After that, it stays that it can be shown that from the prime number theorem we have that $\log d_n \sim n$ where $d_n=\text{lcm}(1,2, \cdots, n)$.
I've managed to prove that
$$\dfrac{\log d_n}{n} \leq \pi(n) \dfrac{\log n}{n} $$
but I'm not able to prove that $\log d_n/n$ converges to $1$.
Lastly, I don't know how from this last result it is true that for any $\varepsilon >0$ we get
$$\zeta(3)-\dfrac{p_n}{q_n}=O(q_n^{-r-\varepsilon})$$
I'm not really good at asymptotic behaivour and big-O notation so I would really appreciate if someone could answer with rigurous and detailed explanations.
Thank you very much.


Q: MVC3 - How to insert a ValidationMessageFor with a line break  at the end? I'm validating about 10 input fileds in a form. The ValidationMessageFor-tags should be at the top of the page, so I'm writing every one like:
@Html.ValidationMessageFor(model => model.Customer.ADDRESS.NAME)
@Html.ValidationMessageFor(model => model.Customer.ADDRESS.CITY)

and so on.
My Models look like this:
[Required(ErrorMessage = Constants.ErrorMsgNameMissing)]
public string NAME { get; set; }
[Required(ErrorMessage = Constants.ErrorMsgCityMissing)]
public string CITY { get; set; }

The constants are Strings.
Now, if more than one ValidationMessageFor is shown, they are all in one line.
How can I insert a line break like
 at the end of every message?
This is NOT the right way:
@Html.ValidationMessageFor(model => model.Customer.ADDRESS.NAME)

@Html.ValidationMessageFor(model => model.Customer.ADDRESS.CITY)

since the
 is shown even if there is no error...;)
Thanks in advance.
PS: Displaying them as a list would also be great.

A: I think what you're actually looking for is:
@Html.ValidationSummary()

A: I would go with @Html.ValidationSummary() if possible

A: Check out Custom ValidationSummary template Asp.net MVC 3.  I think it would be best for your situation if you had complete control over how the validation is rendered.  You could easily write an extension method for ValidationMessageFor.

A: Actually, at the top should be:
@Html.ValidationSummary(/*...*/)

The field validations should be with their respective fields.
However, if you absolutely insist on putting @Html.ValidationMessageFor(/*...*/) at the top then adjust their layout behavior in your CSS and forget about the
's

A: I'm not sure if there's a built in way, but you could easily make another Extension method:
public static MvcHtmlString ValidationMessageLineFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) {
    return helper.ValidationMessageFor(expression) + "
";
}

Something like that?


Q: Eigenvalues of Angular momentum $L^2$ and $L_z$ for a complex function I was given the following function:
$$\Psi(t=0)=\frac{1}{\sqrt{2}}\left[(Y_{1,1})+i(Y_{1,-1})\right],$$
where $Y_{lm}$ refers to the standard spherical harmonic function. I am trying to come up with the expectation values for $L^2$, $L_z$ and $L_x$, but I am running into trouble.
$$\langle L^2\rangle=\left(\frac{1}{\sqrt{2}}\right)^2\hbar l(l+1)+\left(i\frac{1}{\sqrt{2}}\right)^2\hbar l(l+1)=0$$
$$\langle L_z\rangle=\left(\frac{1}{\sqrt{2}}\right)^2\hbar m+\left(i\frac{1}{\sqrt{2}}\right)^2\hbar (-m)=\hbar m$$
I am not sure how to compute $L_x$, but the above result already looks impossible, in light of:
$$L^2=L_x^2+L_y^2+L_z^2.$$
I would like to know where the mistake in my reasoning is. Thank you!

A: Representing the states  as $|l,m\rangle $, We know that
$$L^2|l,m\rangle =l(l+1)\hbar^2|l,m\rangle $$
$$L_z|l,m\rangle=m\hbar |l,m\rangle $$
The state given by
$$|\psi\rangle =\frac{1}{\sqrt{2}}(|1,1\rangle +i|1,-1\rangle) $$
Now, it's easy to find
$$\langle L^2\rangle =\langle \psi|L^2|\psi\rangle, \ \ \ \ \ \langle L_z\rangle =\langle \psi|L_z|\psi\rangle  $$
For $L_x$, We can use
$$L_\pm =L_x\pm iL_y\rightarrow L_x=\frac{L_++L_-}{2}$$
Further, We know
$$L_\pm |l,m\rangle =\hbar\sqrt{l(l+1)-m(m\pm 1)}|l,m\pm 1\rangle $$
Further, Note the orthonormality relation:-
$$\langle l',m'|l,m\rangle =\delta_{l,l'}\delta_{m,m'}$$
This should suffice!!

A: When calculating expectation values of diagonal operators
(like $L^2$ and $L_z$), you need to
take the absolute square $|c|^2$ or $(c^*c)$ of the coefficients
of $|\Psi\rangle$, not their square $(c)^2$.
Then you get the correct values
$$\begin{align}
\langle L^2\rangle
 &=\langle\Psi|L^2|\Psi\rangle \\
 &=\left|\frac{1}{\sqrt{2}}\right|^2\hbar^2 l(l+1)+\left|i\frac{1}{\sqrt{2}}\right|^2\hbar^2 l(l+1) \\
 &=\frac{1}{2}\hbar^2 l(l+1) + \frac{1}{2}\hbar^2 l(l+1) \\
 &=\hbar^2 l(l+1)
\end{align}$$
and
$$\begin{align}
\langle L_z\rangle
 &=\langle\Psi|L_z|\Psi\rangle \\
 &=\left|\frac{1}{\sqrt{2}}\right|^2\hbar m+\left|i\frac{1}{\sqrt{2}}\right|^2\hbar (-m) \\
 &=\frac{1}{2}\hbar m - \frac{1}{2}\hbar m \\
 &= 0
\end{align}$$
And likewise for calculating $\langle L_x\rangle$ and
$\langle L_y\rangle$ be aware, that $\langle\Psi|$ will involve
the complex conjugates.


Q: return extra columns based on group and count results Source data:
+-----+-------------+--------+---------+
| ID  | CandidateID | Rating |  Name   |
+-----+-------------+--------+---------+
| 777 |         119 |      5 | Fred    |
| 777 |         120 |      5 | Tony    |
| 777 |         121 |      3 | Ben     |
| 888 |         131 |      4 | Joe     |
| 888 |         132 |      4 | Matt    |
| 888 |         133 |      1 | Russell |
+-----+-------------+--------+---------+

I need to find duplicates (where ID and Rating are the same), but also somehow keep a reference to them (CandidateID) to present their names in the resulting table.
Desired output (only shows rows where ID AND Rating are the same):
+-----+-------------+--------+------+
| ID  | CandidateID | Rating | Name |
+-----+-------------+--------+------+
| 777 |         119 |      5 | Fred |
| 777 |         120 |      5 | Tony |
| 888 |         131 |      4 | Joe  |
| 888 |         132 |      4 | Matt |
+-----+-------------+--------+------+

My initial approach was to GROUP by ID and Rating, producing COUNT, then do HAVING COUNT(*) >= 2, and then listing all rows where ID from that result is present. Sadly, that also returns non-duplicate rows. Is there a better solution?

A: One simple way uses exists:
select t.*
from t
where exists (select 1
              from t t2
              where t2.id = t.id and t2.rating = t.rating and
                    t2.candidateid <> t.candidateid
             );

A: You can use analytics function for this as well
SELECT ID,CANDIDATEID,RATING,NAME
FROM T
QUALIFY COUNT(*)OVER(PARTITION BY ID,RATING)>=2

based on your database, you can change syntax for count(*) over. This syntax works in teradata.


Q: Howto merge two arrays with values from array2 that are in 1? I have an array with allowed values and an array with given values.
Howto merge two arrays with values from array2 that are in 1?
allowed_values => ["one", "two", "three"]
given_values => ["", "one", "five", "three", "seven"]

...

expected_values => ["one", "three"]

A: You want the array intersection, and you can obtain it via the & operator:

Set Intersection—Returns a new array containing elements common to the two arrays, with no duplicates.

[ 1, 1, 3, 5 ] & [ 1, 2, 3 ]   #=> [ 1, 3 ]


Q: s3fs "could not determine how to establish security credentials" I'm trying to use s3fs to mount an S3 bucket on to a standard AWS Amazon Linux AMI (with all the necessary dependencies installed). However when following this tutorial when I run: s3fs mybucketname -o allow_other myfolder or variations thereof, I get a response of:

s3fs: could not determine how to establish security credentials

I've tried:

*

*creating passwd-s3fs in the etc folder, with the format: accessID:secretAccessKey

*creating .passwd-s3fs in the home folder

*setting AWS_ACCESS_KEY_ID & AWS_SECRET_ACCESS_KEY environment
variables

*Opening up permissions on passwd-s3fs as far as possible (it's become more secure since this question)

*Giving the IAM user associated with this Access Key Administrator Access

*Successfully connecting via a local client with the same Access & Secret Access Key details

*Generally double checking everything for typos etc

I've a feeling I'm doing something dumb AWS side (I'm totally new to AWS), is there something specific I need to apply to the S3 bucket Permissions, Policy etc? This is driving me mad, help much appreciated!

A: I found the best way to resolve this was to use the -o iam_role option to pass the name of the instance role in, plus if you're not in the us-east-1 region, you may also need to specify the url and endpoint options.
E.g.
s3fs mybucketname -o allow_other myfolder -o iam_role=$iam_role_name -o endpoint=${aws_region} -o url=https://s3-${aws_region}

(This is the command I used to mount an S3 bucket to an ECS container host instance, so an EC2 instance deployed as part of a cluster)

A: Although this question is old, I also had the problem so I figure I would post the solution that worked for me in case another person has the same issue.
sudo apt purge s3fs -y
sudo apt update -y && sudo apt upgrade -y
sudo apt install s3fs -y

In the current users home directory, create a txt file with the name .passwd-s3fs with your IAM credentials as such:
key:secret
i.e

kjewndkjsn8387:emkwlmskld8/knsdknjnsjnsdk

# 1. use a text editor to add your key:secret & save the file
vim ~/.passwd-s3fs
# set permissions of .passwd-s3fs to 0400
sudo chmod 0400 ~/.passwd-s3fs
# mount drive s3fs /the_remote_path as /local_path
# i.e
s3fs my_bucket:/the_remote_path /local_path

A: This topic might be old but i ran into the same issue. The answer of Aslan and many other pages are "correct" but still did not work for me. I first did deinstall, update and upgrade like Aslan suggested, but I had to take care NOT to use any sudo commands. I strictly used:
nano ~/.passwd-s3fs

Like Aslan said, entered only
AccesskeyID:SecretAccessKey
i.e.

kjewndkjsn8387:emkwlmskld8/knsdknjnsjnsdk

Then
chmod 0400 ~/.passwd-s3fs
s3fs bucket-name target-name

Took me like 2 hours to figure this out....hope i can help anyone to shorten this time.


Q: ERROR: could not get unknown property 'plugin' for root project I am trying to build LineageOS' trebuchet launcher. After updating protobuf plugin I managed to get rid of some errors. But after several tries I can not handle this error:

Could not get unknown property 'plugin' for root project
'android_packages_apps_Trebuchet-lineage-16.0' of type
org.gradle.api.Project.

This is my first time editing code from Github. Please help.
buildscript {

    repositories {
        mavenCentral()
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.2'
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.13'
    }
}
apply plugin 'com.android.application'
apply plugin 'com.google.protobuf' version '0.8.13'

final String SUPPORT_LIBS_VERSION = '28.0.0'

android {

    defaultConfig {
        compileSdkVersion 28
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        debug {
            minifyEnabled false
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

There is a lot more code after this, didn't seem important so didn't add. Let me know if it's needed

A: It should be:
apply plugin: 'com.android.application'

with a colon.


Q: What is the precise definition of 'uniformly differentiable'? Since I'm not familiar with manifold concept, let's restrict ourselves to functions with real domain.
Let $A\subset \mathbb{R}$ and $f:A\rightarrow \mathbb{R}^k$.
What is '$f$ is uniformly differentiable on $A$' referring to?

A: Let $f:[a,b] \to \mathbb{R}$.  Differentiability means that the limit
$$
\lim_{h \to 0} \frac{f(x+h) - f(x)}{h}
$$ (with the obvious modifications for $x = a,b$) exists, in which case we denote the limit as $f'(x)$.  This definition can be rephrased as saying that there is a function $f':[a,b] \to \mathbb{R}$ which satisfies
$$
\lim_{h \to 0} \left |\frac{f(x+h) - f(x) - hf'(x)}{h} \right| = 0.
$$
The uniformity here means that we can approximate uniformly in $x$.
More precisely, given an $\epsilon > 0$ we may find a $\delta > 0$ so that whenever $0 < |h| < \delta$, then
$$
\left|\frac{f(x+h) - f(x) - hf'(x)}{h}\right| < \epsilon.
$$
It's easy to show that a differentible function is uniformly differentiable if and only if it's differentiable with a continuous derivative.  I believe this is what Rudin has you prove.
Outside of Rudin's book, I don't know if I've ever heard the term "uniformly differentiable" used exactly, and a quick Google search seems to suggest that the term is primarily connected with that problem.

A: As a matter of fact, the most well-known concepts of differentiability are always pointwise, like (where $f^{-1}(\mathbb R)$ is the domain of  $f$)
$$\forall \varepsilon>0, \exists \delta>0, \forall x \in f^{-1}(\mathbb R): 0<|x-x_0|\le \delta \to \left|\frac{f(x)-f(x_0)}{x-x_0}-L\right| \le \varepsilon$$
or the Cauchy-convergence form
$$\forall x_0,\forall \varepsilon>0, \exists \delta>0, \forall x_1,x_2 : \left.\begin{aligned}0<|x_1-x_0|\le \delta\\ 0<|x_2-x_0|\le \delta\end{aligned}\right\}\to \left|\frac{f(x_2)-f(x_1)}{x_2-x_1}-g(x_0)\right| \le \varepsilon$$
However, just like the concept of pointwise continuity ($\forall x_0 \forall \varepsilon \exists \delta \forall x$) is different from uniform continuity ($\forall \varepsilon \exists \delta \forall x_0 \forall x$), the not-generally-used concept "uniform differentiability" can be defined by erasing $x_0$, as
$$\begin{aligned}
\forall \varepsilon>0, \exists \delta > 0, \forall x_1, x_2 \in f^{-1}(\mathbb R), \\
(0<x_2-x_1\le\delta) \to \forall \xi\in (x_1, x_2)&: \\
\qquad \qquad\left|\frac{f(x_2)-f(x_1)}{x_2-x_1}-g(\xi)\right| &\le \varepsilon
\end{aligned}$$
where I do not use the term $g(x_2)$, but any representers $g(\xi)$ instead, like what Riemann integral uses, to keep the symmetry of the formula.
A page of a Chinese textbook The Straightforward Calculus about uniform differentiability
In fact, it is really compatible with the Lagrange mean value theorem associated with the differentiable-preserving property of close subintervals, which can be written as
$$\forall [u,v] \subset f^{-1}(\mathbb R), \exists \xi \in [u,v]:\frac{f(v)-f(u)}{v-u}=g(\xi)$$
where a quantifier $\forall \xi$ is changed into $\exists \xi$.


Q: Crash Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE), Xamarin Forms I'm using Xamarin Forms framework for android and iOS mobile platform, on iOS devices it work's well but in Android when going on a specific page app shut down.
I got this error : Explicit concurrent copying GC freed 7041(512KB) AllocSpace objects
Using breakpoint I noticed crash arrived executing this
var content = JsonConvert.SerializeObject(
                            newStorageUsers,
                            Formatting.None,
                            new JsonSerializerSettings()
                            {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            });

I show you entire demo code
Page in which I got error
private readonly IStorageUserService _storageService
public MyPage(User user)
{
   InitializeComponent();
   ...
   _storageService = new StorageUserServiceImpl();
   _storageService.StoreUser(user);
   ...
}

Service Interface
public interface IStorageUserService
{
    void StoreUser(User user);
}

Service Implementation
public class StorageUserServiceImpl : IStorageUserService
{
    private string _usersPathFile = Path.Combine(App.GetPackagePath(), "users.txt");
    public StorageUserServiceImpl()
    {
        if (!File.Exists(_usersPathFile))
        {
            _createUsersFile();
        }
    }

    private void _createUsersFile()
    {
        var file = File.Create(_usersPathFile);
        file.Close();
    }

    public void StoreUser(User user)
    {
        var currentStorage = GetStorageUsers();
        List<StorageUser> newStorageUsers = new List<StorageUser>() { };
        if (currentStorage != "" && currentStorage != "[]")
        {
            newStorageUsers = JsonConvert.DeserializeObject<List<StorageUser>>(currentStorage);
        }
        var storageUser = new StorageUser()
        {
            Infos = user,
            CreationDate = Helper.DateFormatter.NowDateTime()
            ...
        };
        newStorageUsers.Add(storageUser);

        var content = JsonConvert.SerializeObject(
                            newStorageUsers,
                            Formatting.None,
                            new JsonSerializerSettings()
                            {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            });

        _store(newStorageUsers, content);
    }

    private void _store(List<StorageUser> newStorageUser, string content)
    {
        // breakpoint can't be triggered there because app shut down with logs
        File.WriteAllText(_usersPathFile, content);
    }
 }

This service is used on several pages but I got this bug in only one page
After this message on logs :

Explicit concurrent copying GC freed 7041(512KB) AllocSpace objects, 2(264KB) LOS objects, 49% free, 4343KB/8687KB, paused 187us total 28.412ms

I got

Pending exception java.lang.StackOverflowError: stack size 8192KB ...

JNI DETECTED ERROR IN APPLICATION: JNI IsInstanceOf called with pending exception java.lang.StackOverflowError: stack size 8192KB ...

Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 8815 (om.myapp.app), pid 8815

I've no more details of what happened, how can I fix this please?


Q: Using udev to block wireless devices on Debian How to defend against Badusb devices that act as wireless non-Bluetooth devices on Debian?
I've read that the best way to block a device on Linux will be to block it using udev.
So how do I blacklist all wireless devices (non-Bluetooth that use USB adaptor) using udev?


Q: csv file extension hidden while downloading I have written a nodeJS + express server backend which creates reports and then uses fs.createWriteStream to write data separated by "," like below:
let writeStream = fs.createWriteStream(someFilename);
writeStream.write("header1, header2, header3");
writeStream.write("\n1, 2, 3");
writeStream.write("\n1, 2, 3");
writeStream.end();

Then I send the name of the file on server as a response to this request - so that user can do a post to request this file from server - like an "export to excel" functionality.
All this is working fine - but when the user downloads the csv file - in windows - it always hides the extension of the csv file. It downloads as a generic common file - when I open it in an explorer window - it doesn't have an extension - so I have to manually rename it and then open it. In mac it works perfectly.
I have unchecked the "hide extension for known file types" checkbox in Folder options.
How do I fix this - make the browser respect the extension of the file or download it with the extension - ONLY on Windows.


Q: do a sum when clicking on the datagridview checkbox private void grid_games_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    int total = 0;
    for (int i = 0; i <= grid_games.RowCount - 1; i++)
    {
        Boolean chek = Convert.ToBoolean(grid_games.Rows[i].Cells[0].Value);
        if (chek)
        {
            total += 1;
        }
    }
    total *= 50;
    txt_total.Text = total.ToString();
}

I need to do a sum for each row selected from the datagridview selection box. each line is worth 50. it is working, but it has a delay, so when I click on 2 check, it only shows me 50... and the same delay occurs when I uncheck a box. how can i instantly get the total by clicking on that checkbox?

A: The CheckBox column of the DataGridView control is implemented by the DataGridViewCheckBoxCell class, and this class has a delay function, that is, when the user selects a CheckBox in the DataGridView, it will delay updating it to the data source for a period of time.
You just need to add an event about CurrentCellDirtyStateChanged to get the state immediately
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (this.dataGridView1.IsCurrentCellDirty)
            {
                this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

Best used with CellValueChanged:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int total = 0;
            for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
            {
                Boolean chek = Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value);
                if (chek)
                {
                    total += 1;
        }
    }
            total *= 50;
            textBox1.Text = total.ToString();
        }


Q: $f''(e^{x})$ and it's definition I'm working through "The Calculus Tutoring Book" by Carol and Robert Ash (0-7803-1044-6).  In chapter 3.3, when discussing derivatives of basic functions, they show and define the $D_{x}e^{x}$ and subsequently define $e$.  Page 67 for those that have the book.
In any event, they define a "base", eventually, they land at $(1)$: $$D_{x}b^x = \lim_{\Delta x\to 0} b^x\lbrack \frac{b^{\Delta x}-1}{\Delta x} \rbrack$$  I have no problem here.  And I understand why they effectively ignore the constant $b^x$ when you factor it out $(2)$:
$$\frac{b^{\Delta x}-1}{\Delta x}$$ to $(3)$
$$D_{x}b^x=mb^x$$
And go on to state that the latter must be the slope of a line centered at $(0, 1)$
Then from the former, they land on the fact the $(4)$ $$D_{x}e^x = e^x$$
I don't see the path from $(2)$ to $(3)$ and subsequently $(4)$.

A: What they are doing, which is fairly sloppy the way it is phrased and justified, is the following.

*

*They assume that limits as $\Delta x\to0$ of expressions of the form $(2)$ exist, and that they are numbers $m(b)$ (depending on $b$)

*They argue "by picture" that, as $b$ moves between $1$ and $100$, the numbers $m(b)$ range from close to zero to very big

*They assume that $m(b)$ depends continually on $b$

*They assume that a continuous function satisfies the Intermediate Value Theorem

*They put together all the above to conclude that there exists a number $e$ such that $m(e)=1$.

*It follows, by $(1)$, that $(e^x)'=e^x$.
Comment: the notation you are using for derivatives is highly unusual, and it will be confusing for   anybody who sees is. One often writes $f'(x)$ for the derivative of the function $f$ at the point $x$. When you write $f'(e^x)$, what we all read is "the derivative of the function $f$, evaluated at the point $e^x$", which is not what you meant.

A: I don't have the book but what they are doing in general is showing that $\frac{d}{dx} \ b^x = ln(b)\cdot b^x\cdot 1$ ..........where the $1$ is the derivative of the exponent x (chain rule)
This is a general rule so for example $\frac{d}{dx}\ 5^{3x}= ln(5)\cdot 5^{3x}\cdot 3$
When applying this rule to $e^x$ we get $\frac{d}{dx} \ e^x = ln(e)\cdot e^x\cdot 1 = e^x$


Q: UIWebView stuck at the second time I am working on an iOS app that user can pick an email from inbox list, and view it on the next page (there's a UIWebView to serve the content).
Here's what I am observing: The first time I pick the email and it shows up on the second page pretty fast. However, if I navigate back and choose to view the email again, it takes a very long time to get webViewDidFinishLoad: called on the second page.
I saw the following message in console:
void SendDelegateMessage(NSInvocation *):
delegate (webView:didFinishLoadForFrame:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode

As soon as this message is printed, the content is rendered on WebView.
What I don't understand is, this always happen at the second time of using webview to show HTML content. There's no local cache for files/resources, and there's no network issues.
Please point me where I should look at for this issue. Thanks!
---- Update ----
During my random attempts, I found removing this line:
self.webView.delegate = self;
will make the issue gone. This makes me feel even more confusing. Why making self to be the delegate could cause such issue?
---- Update 2 ----
I found the culprit is a flatten html method I called after webview loaded the html. If I remove the NSHTMLTextDocumentType it's all good, but I don't understand why:
+ (NSString *) stripHtmlSchema: (NSString *)htmlString
{
    NSString *flatString = [[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
                                                            options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                      NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
                                                 documentAttributes:nil
                                                              error:nil] string];
    return flatString;
}

---- Final Update ----
Figured out the issue. [NSAttributedString alloc] initWithData was taking too long to execute, so blocked everything.

A: Figured out the issue. [NSAttributedString alloc] initWithData was taking too long to execute, so blocked everything.


Q: Swing layout issue on migration to java 8 My swing application in java 5 which had a display like

After migrating to java 8, zoomed up and displays only a part of it like

I saw this and tried setting J2D_D3D as environment variable and also tried passing it as a vm parameter. But didn't solved the issue. Any idea what this could be?

A: For reference, here's an example the doesn't have the problem. It uses a GridLayout(0, 1) with congruent gaps and border. Resize the enclosing frame to see the effect. Experiment with Box(BoxLayout.Y_AXIS) as an alternative.
I suspect the original code (mis-)uses some combination of setXxxSize() or setBounds(), which will display the effect shown if the chosen Look & Feel has different geometry specified by the buttons' UI delegate.

import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see https://stackoverflow.com/a/31078625/230513 */
public class Buttons {

    private void display() {
        JFrame f = new JFrame("Buttons");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel p = new JPanel(new GridLayout(0, 1, 10, 10));
        p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        for (int i = 0; i < 3; i++) {
            p.add(new JButton("Button " + (i + 1)));
        }
        f.add(p);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Buttons()::display);
    }
}


Q: Missing name in confusion matrix? In a confusion matrix, what's the name of the percentage of cases I predict as positive out of the total population?
I am in the position of having to use this metric for my project, but I can't find a standard name for it.
If you also see the confusion matrix here (https://en.wikipedia.org/wiki/Sensitivity_and_specificity), the closest definition would be 'prevalence', but in my case I need to use the predicted positives not the actual positives.
Thanks
Gian

A: I don't think there's a standard term for this; you might find one that's been used before, but I doubt it would be well-known enough to use without defining anyway. If you're referring to it enough to need a succinct phrase, I'd say something like "positive prediction rate" or "predicted prevalence."


Q: Error Generando Codigo QR Aleatorio con Async Await Saludos.
Estoy intentando generar codigos QR con nodejs de forma aleatoria pero siempre obtengo como resultado el mismo codigo qr base64.
aChtwo5eF7
Task One:  data:image/gif;base64,R0lGODdhCgAKAIAAAAAAAP///ywAAAAACgAKAAACD4yPqcvtAGGKElV1JzCgAAA7
vHXhJoldQJ
Task One:  data:image/gif;base64,R0lGODdhCgAKAIAAAAAAAP///ywAAAAACgAKAAACD4yPqcvtAGGKElV1JzCgAAA7
qKTwoy7gxd
Task One:  data:image/gif;base64,R0lGODdhCgAKAIAAAAAAAP///ywAAAAACgAKAAACD4yPqcvtAGGKElV1JzCgAAA7
KGlNhLIMTF
Task One:  data:image/gif;base64,R0lGODdhCgAKAIAAAAAAAP///ywAAAAACgAKAAACD4yPqcvtAGGKElV1JzCgAAA7
bmCiNnDwvp
Task One:  data:image/gif;base64,R0lGODdhCgAKAIAAAAAAAP///ywAAAAACgAKAAACD4yPqcvtAGGKElV1JzCgAAA7
olh67ej1xV
Task One:  data:image/gif;base64,R0lGODdhCgAKAIAAAAAAAP///ywAAAAACgAKAAACD4yPqcvtAGGKElV1JzCgAAA7
pUA0VghGpr
Task One:  data:image/gif;base64,R0lGODdhCgAKAIAAAAAAAP///ywAAAAACgAKAAACD4yPqcvtAGGKElV1JzCgAAA7
q0aRptpb0b
Task One:  data:image/gif;base64,R0lGODdhCgAKAIAAAAAAAP///ywAAAAACgAKAAACD4yPqcvtAGGKElV1JzCgAAA7
vI4sQ9uNi2
Task One:  data:image/gif;base64,R0lGODdhCgAKAIAAAAAAAP///ywAAAAACgAKAAACD4yPqcvtAGGKElV1JzCgAAA7

Como se muestra en la imagen, el primer dato es un codigo aleatorio de 10 digitos y el segundo se trata de un codigo QR Base64 para generar una imagen basado en la informacion proporcionada.
Quisiera de su colaboracion para que me orienten cual puede ser el problema que estoy presanto...
A continuacion les indico el codigo utilizado.
index.js
const {taskOne, taskTwo }   =   require('./task.js');

async function main()
{
    try {
        for (let index = 1; index < 10; index++) {
            const   valueOne    =   await taskOne(index);
            console.log("Task One: ", valueOne);
            delete valueOne;
        }
    } catch (e) {
        console.log(e);
    }
}

main();

Task.js
const util      =   require('util');
const sleep     =   util.promisify(setTimeout);
const base64    =   require('yaqrcode');
const QRCode    =   require('qrcode');

module.exports  =   {
    async taskOne(x)
    {
        try {
            // throw new Error('some problem');
            await sleep(1000);
            const random    =  await generateRandomString(10);
            console.log(random);
            const qr    =  await qrCodeFun(random);
            return qr;

        } catch (e) {
            console.log(e);
        }
    },
}

async function qrCodeFun(x)
{
    return base64(x, { size: 10});
}

async function generateRandomString(myLength) {
    const chars =
      "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";
    const randomArray = Array.from(
      { length: myLength },
      (v, k) => chars[Math.floor(Math.random() * chars.length)]
    );

    const randomString = randomArray.join("");
    return randomString;
  };

Gracias de antemano por su colaboracion.


Q: VBA - Check if recordset has been deleted before updating DB I'm experimenting with VBA and i made the following thingy.
Dim rs1 As Recordset
Set rs1 = CurrentDb.OpenRecordset("TBL_Registratie")

With rs1
.AddNew
!leerling_Id = Me.leerling_Id
datum = DateValue(!datum_tijd)
tijd = TimeValue(!datum_tijd)
weekDag = Weekday(datum, vbMonday)

Select Case weekDag
    Case 1, 2, 4
        Select Case tijd
            Case "07:00:00" To "08:00:00"
                !score = !score + 1
            Case "16:00" To "16:30"
                !score = !score + 1
            Case "16:31" To "17:00"
                !score = !score + 2
            Case "17:01" To "22:00"
                !score = !score + 3
            Case Else
                Me.txt_resultaat.Caption = "Het is geen opvang"
                Me.txt_resultaat.Visible = True
                ( rs1.close ? )
        End Select

other cases
 .Update
 .Close

QUESTION: How can i check if my last record in there recordset has a score added or not? if not, i want to delete it and close Else Update & Close

A: A much easier way: Calculate the score before adding the record, save all needed data in variables instead of recordset fields.
Then only if score > 0 do the rs1.AddNew etc.


Q: How to change back.color of WindowsForm using a picture box on a mouseClick event? I have a simple windows form and I have added a picturebox that I want to act as a dark mode on/off switch for my application. I have created an event for mouse click, but it only works one way:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WeatherApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // The below two lines are used to move my WindowsForm window
        private bool mouseDown;
        private Point lastlocation;

        public void picDarkMode_MouseClick(object sender, MouseEventArgs e)
        {
            //var frmForm1 = new Form1();
            //frmForm1.BackColor = Color.Black;
            //var darkTheme = this.BackColor = System.Drawing.Color.DarkGray;

            this.BackColor = System.Drawing.Color.DarkGray;

            if (System.Drawing.Color.DarkGray == System.Drawing.Color.DarkGray)
            {
                this.BackColor = System.Drawing.Color.LightYellow;
            }
            else
            {
                this.BackColor = System.Drawing.Color.DarkGray;
            }

            //this.BackColor = System.Drawing.Color.LightYellow;
        }

I tried to play with if statements, but cannot understand why it is not working...

A: You are making two mistakes. You are setting the backcolor to DarkGray before the if statement, so it will always give the same result, and you are comparing DarkGray to DarkGray instead of the forms backcolor to DarkGray. So...
Get rid of this line:
this.BackColor = System.Drawing.Color.DarkGray;

And change this:
if (System.Drawing.Color.DarkGray == System.Drawing.Color.DarkGray)

To this:
if (this.BackColor == System.Drawing.Color.DarkGray)

This is the whole click event:
public void picDarkMode_MouseClick(object sender, MouseEventArgs e)
{
    if (this.BackColor == System.Drawing.Color.DarkGray)
    {
        this.BackColor = System.Drawing.Color.LightYellow;
    }
    else
    {
        this.BackColor = System.Drawing.Color.DarkGray;
    }
}


Q: Simple approach to check and store which states that has changed from initial value This component checks if the fields have been changed from the initial value and display the number of changed fields. There's a useEffect for each field. It would be better with something more DRY, but haven't figured out how.
Is there a way to do this faster and better?
States
    const [unsavedChanges, setUnsavedChanges] = useState<Array<string>>([]);
    const [customField1, setCustomField1] = useState<string | null | undefined>(
        Data.field1
    );
    const [customField2, setCustomField2] = useState<string | null | undefined>(
        Data.field2
    );

Set unsavedChanges state
//Field 1
    useEffect(() => {
        if (
            (customField1 === Data.field1 ||
                customField1 === null) &&
            unsavedChanges?.includes('customfield1')
        ) {
            let filtered = unsavedChanges.filter(
                (item) => item !== 'customfield1'
            );
            setUnsavedChanges(filtered);
        } else if (
            customField1 === Data.field1 ||
            unsavedChanges?.includes('customfield1')
        ) {
            return;
        } else {
            setUnsavedChanges([...unsavedChanges, 'customfield1']);
        }
    }, [customField1]);

//Field 2
    useEffect(() => {
        if (
            (customField2 === Data.field2 ||
                customField2 === null) &&
            unsavedChanges?.includes('customfield2')
        ) {
            let filtered = unsavedChanges.filter(
                (item) => item !== 'customfield2'
            );
            setUnsavedChanges(filtered);
        } else if (
            customField2 === Data.field2 ||
            unsavedChanges?.includes('customfield2')
        ) {
            return;
        } else {
            setUnsavedChanges([...unsavedChanges, 'customfield2']);
        }
    }, [customField2]);

Return
        <>
            <Input value={customField1} onChange={setCustomField1(e.target.value}/>
            <Input value={customField2} onChange={setCustomField2(e.target.value}/>

{unsavedChanges.length} # of unsaved changes.

            <Button disabled={unsavedChanges.length > 0 ? false : true} label='Submit'/>
        </>

A: i created an example of how to make it simple (in my opinion).
I merged the three states into one. this way i can get each one in more dynamic way. then i created on change handler that handles the changes and doing the all if statements (with less code).
each input is firing the change handler on change. and it sets the state according to the if statements.
this way we can create as many inputs as we want, we just need to pass the right arguments to the change handler and it will take care of the rest for us (and to make sure to include one more key value pair to the state)
this is the dummy data for Data:
 const Data = { field1: "abc", field2: "efg" };

the state:
  const [generalState, setGeneralState] = useState({
     unsavedChanges: [],
     customField1: "",
     customField2: ""
  });

the handler:
const changeTheState = (type, value, field, customField) => {
    //setting the values to the state. so we can fetch the values for the inputs and for later use
    setGeneralState((prev) => ({ ...prev, [type]: value }));

    // i narrowed down the if statements. now its only two.
    if (
      value === Data[field] &&
      generalState.unsavedChanges?.includes(customField)
    ) {
      return setGeneralState((prev) => {
        let filtered = prev.unsavedChanges.filter(
          (item) => item !== customField
        );
        return { ...prev, unsavedChanges: filtered };
      });
    }

    if (!generalState.unsavedChanges?.includes(customField)) {
      setGeneralState((prev) => ({
        ...prev,
        unsavedChanges: [...prev.unsavedChanges, customField]
      }));
    }
  };

and the jsx:

      <input
        value={generalState.customField1}
        onChange={(e) => {
          changeTheState(
            "customField1",
            e.target.value,
            "field1",
            "customField1"
          );
        }}
      />
      <input
        value={generalState.customField2}
        onChange={(e) => {
          changeTheState(
            "customField2",
            e.target.value,
            "field2",
            "customField2"
          );
        }}
      />

{generalState.unsavedChanges.length} # of unsaved changes.

      <button disabled={generalState.unsavedChanges.length > 0 ? false : true}>
        Submit
      </button>

here is the example : codesandbox example
One more thing you can do , is to create a reusable component for the input. create array of objects to represent each input. loop through the array and generate as many inputs you want.
if you need extra explaination let me know.


Q: Delphi XE2 Rounding with DecimalRounding_JH1 Because of a documented rounding issue in Delphi XE2, we are using a special rounding unit available on the Embarcadero site named DecimalRounding_JH1 to achieve true bankers rounding.  A link to the unit can be found here:
DecimalRounding_JH1
Using this unit's DecimalRound function with numbers containing a large number of decimal place we
This is the rounding routine from the DecimalRounding_JH1 unit.  In our example we call this DecimalRound function with the following parameters (166426800, 12, MaxRelErrDbl, drHalfEven) where maxRelErrDbl = 2.2204460493e-16 * 1.234375 * 2
Function DecimalRound(Value: extended; NDFD: integer; MaxRelErr: double;
                         Ctrl: tDecimalRoundingCtrl = drHalfEven): extended;
{ The DecimalRounding function is for doing the best possible job of rounding
  floating binary point numbers to the specified (NDFD) number of decimal
  fraction digits.  MaxRelErr is the maximum relative error that will allowed
  when determining when to apply the rounding rule.  }
var i64, j64: Int64; k: integer; m, ScaledVal, ScaledErr: extended;
begin

  If IsNaN(Value) or (Ctrl = drNone)
    then begin Result := Value; EXIT end;

  Assert(MaxRelErr > 0,
      'MaxRelErr param in call to DecimalRound() must be greater than zero.');

{ Compute 10^NDFD and scale the Value and MaxError: }
  m := 1; For k := 1 to abs(NDFD) do m := m*10;
  If NDFD >= 0
    then begin
      ScaledVal := Value * m;
      ScaledErr := abs(MaxRelErr*Value) * m;
      end
    else begin
      ScaledVal := Value / m;
      ScaledErr := abs(MaxRelErr*Value) / m;
      end;

{ Do the diferent basic types separately: }
  Case Ctrl of
    drHalfEven: begin
      **i64 := round((ScaledVal - ScaledErr));**

The last line is where we get a floating point error.
Any thoughts on why this error is occurring?

A: If you get an exception, that means you cannot represent your value as an double within specified error range.
In other words, the maxRelErrDbl is too small.
Try with maxRelErrDbl = 0,0000000001 or something to test if I am right.


Q: Add timestamp to sdterr? I've a application launched by bash script. I redirected stderr and stdout to different files:
./app >> /home/user/logs/debug.log 2>>/home/user/logs/debug.err &

And I need to add a timestamp for stderr lines.
How I can do it?

A: check this out
./app >> /home/user/logs/debug.log 2> >( while read line; do echo "$(date): ${line}"; done > /home/user/logs/debug.err )


Q: AJAX: download new content every X seconds using jQuery I have page with posts. Initially posts was added by server-side code.
I need every 60 seconds download and show new posts from server.
Server can return 0 to N posts. Page returned by server have this format for two posts (most recent on top):

...

...

There is my code:

...

...

...

Can you please recommend me any good jQuery timer plugin?
I see at JS console every 10s:
null "lastPostID"

Where I have an error?

Update:
If I use:

Output is OK:
3 "divs with class *post*" jQuery_div_update.html:37
100 lastPostID jQuery_div_update.html:40
20 lastPostID jQuery_div_update.html:40
1 lastPostID

But with jQuery:

Output is bad:
null "lastPostID"

Why?

A: If you want to poll some external resource (with an AJAX call, for example) you can follow the "Recursive setTimeout pattern" (from https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval).  Example:
(function loop(){
  setTimeout(function(){

    // logic here

    // recurse
    loop();

  }, 1000);
})();

A: use setInterval() instead of setTimeout()
something like:
setInterval(function(){
    $.ajax({
      url: "test.html",
      context: document.body
    }).done(function() {
      //do something
    });
},1000*60);

http://www.w3schools.com/jsref/met_win_setinterval.asp
https://api.jquery.com/jQuery.ajax/


Q: perf get time elasped with field separator option I have a program which parses the output of the linux command perf. It requires the use of option -x, (the field separator option. I want to extract elapsed time (not task-time or cpu-clock) using perf. However when I use the -x option, the elapsed time is not present in the output and I cannot find a corresponding perf event. Here are the sample outputs
perf stat ls
============
 Performance counter stats for 'ls':

          0.934889 task-clock (msec)         #    0.740 CPUs utilized
                 6 context-switches          #    0.006 M/sec
                 0 cpu-migrations            #    0.000 K/sec
               261 page-faults               #    0.279 M/sec
         1,937,910 cycles                    #    2.073 GHz
   <not supported> stalled-cycles-frontend
   <not supported> stalled-cycles-backend
         1,616,944 instructions              #    0.83  insns per cycle
           317,016 branches                  #  339.095 M/sec
            12,439 branch-misses             #    3.92% of all branches

       0.001262625 seconds time elapsed //here we have it

Now with field separator option
perf stat -x, ls
================
2.359807,task-clock
6,context-switches
0,cpu-migrations
261,page-faults
1863028,cycles
<not supported>,stalled-cycles-frontend
<not supported>,stalled-cycles-backend
1670644,instructions
325047,branches
12251,branch-misses

Any help is appreciated

A: # perf stat ls 2>&1 >/dev/null | tail -n 2 | sed 's/ \+//' | sed 's/ /,/'

0.002272536,seconds time elapsed

A: Starting with kernel 5.2-rc1, a new event called duration_time is exposed by perf statto solve exactly this problem. The value of this event is exactly equal to the time elapsed value, but the unit is nanoseconds instead of seconds.


Q: passing bash a value with leading hyphen I have a bash command that requires a string value after "-v". When this string value has a leading "-", bash tries to interpret it as a new option of the bash command rather than the value I'm trying to give for -v. Is there a way I can escape this leading hyphen? I tried
-v -- -myValue but then it tells me "option '-v' needs a parameter."
The command is calling a ruby file. I think this is the meaningful part of the ruby code for the purposes of this question:
opts = Trollop::options do
  opt :method, "Encrypt or Decrypt", :short => "m", :type => :string, :default => "decrypt"
  opt :value, "Value to Decrypt or Encrypt", :short  => "v", :type => :string, :default => ""
end

A: There's two conventional ways to specify arguments, but these are not enforced at the shell level, they're just tradition:
-v xxxx
--value=xxxx

Now it's sometimes possible to do:
-vxxxx

If you have a value with a dash and it's not being interpreted correctly, do this:
--value=-value

A: cmd -v '-string value with leading dash'

edit
$ cat ~/tmp/test.sh
 #!/bin/bash
 str=
 while getopts "v:" opt; do
 case "$opt" in
    v) str=$OPTARG;;
 esac
 done
 shift $(( OPTIND -1 ))

 echo "option was '$str'"

simple test file, my bash is GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
results:
chris@druidstudio:~⟫ ~/tmp/test.sh -v string
  option was 'string'
chris@druidstudio:~⟫ ~/tmp/test.sh -v -string
  option was '-string'
chris@druidstudio:~⟫ ~/tmp/test.sh -v '-string'
  option was '-string'

so, maybe, the bash script handling your options is not written correctly, or you have an early version of bash. As I answered in another of these silly questions earlier, clairvoyance is not one of my skills.  So, be a good chap and possibly give us, the people you are asking for help from, the pertinent information (as you state, your script is failing at the bash level, not at the ruby level, so why bother to post a ruby script?)


Q: How to find if specific changeset within the parents in mercurial I am a git background and just moved to a project where is uses mercurial, the projects is branched with heads model.
Before pushing things to our testing server, I want to make sure that production head is one of my parents list. is there is a command for that?

A: actually I found a way to do so using "revsets" of mercurial.
in order to list all ancestors for specific changeset, we can use the command
hg log -r "ancestors(84e5bc6fd673)"

now in order to find specific changeset in these parents, we can use the matching function like below
hg log -r "ancestors(84e5bc6fd673) and id(hh6cjb9c48se)"

so if hh6cjb9c48se is part of 84e5bc6fd673 parents it will be printed to the terminal.


Q: Cannot build OpenCL program on Windows I have written a simple "do-nothing" OpenCL application (in C++ but using the C API) on Linux to get some data about OpenCL speed. It compiles fine and runs without error. I don't have a graphics card that supports OpenCL, but I need to test it on a GPU. I'm trying to build the application on my friend's Windows 7 64bit  computer using the OpenCL implementation provided with NVIDIA'S CUDA Toolkit.
When I try to link to the OpenCL.lib file in CUDA\x64 I get undefined references for each OpenCL call within the program (using the standard C API). The same thing happens when I link to the OpenCL.dll in the system32 directory. If I link to the win32 library that came with the CUDA Toolkit, I don't get errors, but OpenCL cannot acquire a platform. All the undefined references I get when linking have an @20 or @46 or some random number on the end of the symbol name. I'm not familiar enough with Windows development to know how to fix this problem. What could be my problem?
I apoligize for any newbie-ness. Thanks for any answers!

A: I believe you'll want to use the library that doesn't give link errors.
The other errors you're getting are because you're linking mismatched code together.
Then focus on trying to determine what your platform identifier should be.
I think you were close but gave up too soon