text:
Q: how to pass the dates to the x-axis in the base line high charts instead of the values This the base line Highcharts which is having the values on the x-axis and percent on the y-axis,
please share how to pass the dates to the x-axis instead of the values so that, this is my highcharts code.
<!DOCTYPE>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

This is the jsfiddle link : http://jsfiddle.net/wergeld/hj22wbe5/
i want to pass the dates to x-axis instead of the values..
like this 18-Jul-14', 19-Jul-14, 20-Jul-14....   so that the graph plot according to the dates and percent...
please help
thanks ...

A: Set your xAxis type to 'datetime'.
You can then either

*

*pass your dates as part of your data array

*use pointStart and pointInterval to handle the proper date alignment
Using categories for dates is both counterintuitive and loses all of the benefits of a datetime axis.
References:

*

*http://api.highcharts.com/highcharts#xAxis.type

*http://api.highcharts.com/highcharts#plotOptions.series.pointStart

*http://api.highcharts.com/highcharts#plotOptions.series.pointInterval

A: If you know the dates and they are fixed, for example consider below your dates' array:
dates: ['18-Jul-14', '19-Jul-14', '20-Jul-14', '18-Jul-14', '19-Jul-14', '20-Jul-14', '18-Jul-14', '19-Jul-14', '20-Jul-14', '18-Jul-14', '19-Jul-14', '20-Jul-14', '19-Jul-14', '20-Jul-14']

then you can use xAxis: categories to show these dates on xAxis like:
xAxis: {
    categories: ['18-Jul-14', '19-Jul-14', '20-Jul-14', '18-Jul-14', '19-Jul-14', '20-Jul-14', '18-Jul-14', '19-Jul-14', '20-Jul-14', '18-Jul-14', '19-Jul-14', '20-Jul-14', '19-Jul-14', '20-Jul-14'],
    labels:{rotation: 90, x:-20}
},

im giving further options such as labels' rotation of 90 degrees, its because there is not enough space for them to fit horizontally, they get mixed up that's why now they will be shown vertically like they should be.
See the DEMO here


text:
Q: linprog not provided in Octave although optim package installed I try to use Octave's optim package as a replacement (as far as possible) for Matlab. I installed both distros Octave MinGW and Octave MSVC.
pkg install parallel-2.2.0.tar.gz gives me the following error in case of using the MSVC version sh.exe: ./configure: /bin/sh: bad interpreter: No such file or directory.
So I tried the MinGW version. After installing all packages (general, struct, miscellaneous, parallel and optim) being required and typing help linprog I ended up with:
error: help: Octave does not currently provide linprog.  Linear programming problems
may be solved using `glpk'.  Try `help glpk' for more info.

Please read `http://www.octave.org/missing.html' to learn how you can
contribute missing functionality.

What needs to be done to use this function as documented here?
Update1
I tried version 3.8.1 as suggested by carandraug but the installation of parallel will abort with sclose.cc:37:24: fatal error: sys/socket.h: No such file or directory. I may add another update after fixing this. By the way I hope the Octave developer will choose an Eclipse IDE as the default Developer-GUI in the future so something that many, many people can contribute to without starting from scratch.
Update2
The above linked packages are newer than those being shipped with Octave 8.3.1 so I simply switched to the src folder and ran build_packages.

A: I just posted this answer on a separate question:
The problem is that you didn't load the optim package. When you type pkg list you can find which ones are loaded by an asterisk in front of their names. Load a package with pkg load optim.
Having to load a packages is that thing that many users coming from Matlab find strange but if you compare with other languages, such as Python, Perl, or C++, would you expect them to import, use, or #include every libraries available in the system by default? See Octave's FAQ for more details.
If you want a package to be loaded automatically by default, the recommended action is to add the line pkg load optim to your ~/.octaverc file.
Finally, you have just started with Octave, you should probably have installed Octave 3.8.1.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Import-SPWeb : The DateTime represented by the string is out of range? I am trying to import an exported sub site which exists in a separate site collection to another site collection that is hosted by different web application.
I'm running the import command like this:
Import-SPWeb http://sitename/destweb -Path ("D:\sourceweb.cmp") –NoLogFile

Then I get an error message:

Import-SPWeb : The DateTime represented by the string is out of
  rangeImport-SPWeb

In log file, I found it throws an exception at importing a particular document library:

[3/3/2016 10:21:22 AM] [Folder] [مجلد] Progress: Importing [3/3/2016
  10:21:22 AM] [Folder] [مجلد]   Verbose: Source URL: DocLib/Forms/مجلد
  [3/3/2016 10:21:22 AM] [Folder] [Docs] Progress: Importing [3/3/2016
  10:21:22 AM] [Folder] [Docs]   Verbose: Source URL: Docs [3/3/2016
  10:21:22 AM] [Folder] [Docs]   Error: The DateTime represented by the
  string is out of range.
  [3/3/2016 10:21:22 AM] [Folder] [Docs]   Debug:    at
  System.DateTime.Parse(String s, IFormatProvider provider)    at
  System.Convert.ToDateTime(String value, IFormatProvider provider)
  at System.Runtime.Serialization.SerializationInfo.GetDateTime(String
  name)    at
  Microsoft.SharePoint.Deployment.MetaInfoProperty..ctor(SerializationInfoHelper
  infoHelper)    at
  Microsoft.SharePoint.Deployment.DictionarySerializer.SetObjectData(Object
  obj, SerializationInfo info, StreamingContext context,
  ISurrogateSelector selector)    at
  Microsoft.SharePoint.Deployment.FolderSerializer.SetObjectData(Object
  obj, SerializationInfo info, StreamingContext context,
  ISurrogateSelector selector)    at
  Microsoft.SharePoint.Deployment.XmlFormatter.CallSetObjectData(Object
  obj, SerializationInfo objectData, ISerializationSurrogate surrogate,
  ISurrogateSelector selector) [3/3/2016 10:21:22 AM] FatalError: The
  DateTime represented by the string is out of range.

Note: I have the exported sub site as 3 files:
1- sourceweb.cmp
2- sourceweb1.cmp
3- sourceweb2.cmp
Any help would be much appreciated.
Thank you.

A: I also have same problem. After couple of hours of googling I have found this link
http://codecaching.blogspot.ru/2012/11/importing-cmp-and-string-was-not.html
There was a problem with wrong year in date 29 May 60354 05:36:10 -0000
In my case in have not found any wrong dates in my Manifest.xml files but I have found some max dates like 31 Dec 9999 23:59:59.
I think the import process parses the date(31 Dec 9999 23:59:59) and adds timezone to it and goes out of bounds.
I have replaced all 31 Dec 9999 23:59:59 to 31 Dec 2099 23:59:59 and problem has disappeared.

A: I used import-spweb and export sp web with the flag -NoFileCompression
Then it creates everything in a folder , you can then find the manifest file and remove the random dates with (notepad)  then import using the same flag and set the path to the folder , this resolved my issue a bit easier than trying to extract and convert multiple cmp / cab files.


text:
Q: reverse proxy serve file after it has been decrypted I need to put an *os.File into the request.Body but I don't know how to handle the closure of the file descriptor (and the elimination of the temporary file). I cannot use http.ServeFile to serve the file.
I have 3 softwares:
A) User interface ( that I cannot edit )
B) Backend which serves files
C) An http reverse proxy whose role is to sign the requests coming from  A going to B, to encrypt files going from A to B, and decrypto files going from B to A.
The software A is expected to receive the body of the decrypted file content. I know it would be easier just to decrypt the file in a directory using B and then have A open it, but unfortunately I cannot edit A which expects the file in the request body.
the work flow of the softwares is the following: software A sends a request to C which signs the request and forwards it to B, then C proceeds to decrypt the file and has to serve the decrypted content to A in a the request body.
type transportPageServeFile struct {
    http.RoundTripper
    // vault handles encryption and decryption of files
    vault *vault.Container
}

func (t *transportPageServeFile) RoundTrip(req *http.Request) (resp *http.Response, err error) {
    resp, err = t.RoundTripper.RoundTrip(req)
    if err != nil {
        return nil, errors.Wrap(err, "transportPageServeFile")
    }
    // create temporary destination dir for the decrypted file
    dstDir, err := utils.MkTmpDir()
    if err != nil {
        return nil, errors.Wrap(err, "transportPageServeFile")
    }
    defer os.RemoveAll(dstDir) // i'm deleting the directory where the temporary file is stored, deleting it before it even gets transmitted to software A
    fileName := req.Header.Get(api.FileNameHeader)
    decryptedFileDst := fmt.Sprintf("%s/%s", dstDir, fileName)
    // DecryptFileFromReader takes a reader and decrypts the file, saving it in the decided destination
    err = t.vault.DecryptFileFromReader(resp.Body, decryptedFileDst)
    if err != nil {
        return nil, errors.Wrap(err, "transportPageServeFile")
    }
    defer resp.Body.Close()
    // now open the saved decrypted file
    decryptedFile, err := os.Open(decryptedFileDst)
    if err != nil {
        return nil, errors.Wrap(err,"transportPageServeFile")
    }
    defer decryptedFile.Close() // close file before serving the content?
    resp.Body = decryptedFile
    return resp, nil
}
// pageServeFile is the handler of /serveFile
func (rpc *RPC) pageServeFile(c *gin.Context) {
    transport := &transportPageServeFile{RoundTripper:http.DefaultTransport, vault:rpc.vault}
    target, err := url.Parse(rpc.apiEndpoint)
    if err != nil {
        rpc.onError(c, errors.Wrapf(err, "pageServeFile"))
        return
    }
    proxy := httputil.NewSingleHostReverseProxy(target)
    proxy.Transport = transport
    proxy.ServeHTTP(c.Writer, c.Request)
}

How do I copy the file in the request body (using a reader) and when/how do I close the file descriptor once the response is forwarded?

A: The response body is an io.ReadCloser, so it is reasonable to assume that the reverse proxy calls Close. And indeed it does, as you can see by running the following program:
package main

import (
    "fmt"
    "io"
    "net/http"
    "net/http/httptest"
    "net/http/httputil"
    "net/url"
    "runtime/debug"
)

type dbg struct{ io.ReadCloser }

func (d dbg) Close() error {
    fmt.Println("Close() called:")
    debug.PrintStack()

    return d.ReadCloser.Close()
}

func main() {
    // srv simulates "software B"
    srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, world"))
    }))

    target, _ := url.Parse(srv.URL)
    p := httputil.NewSingleHostReverseProxy(target)

    // To modify the response, use the aptly named ModifyResponse field; no
    // need to implement a RoundTripper.
    p.ModifyResponse = func(res *http.Response) error {
        res.Body = dbg{res.Body}
        return nil
    }

    req := httptest.NewRequest("GET", "http://example.com/hello", nil)
    rec := httptest.NewRecorder()

    p.ServeHTTP(rec, req)
}

// Output:
// Close() called:
// goroutine 1 [running]:
// runtime/debug.Stack(0x10, 0x0, 0x0)
//         /usr/local/go/src/runtime/debug/stack.go:24 +0x9d
// runtime/debug.PrintStack()
//         /usr/local/go/src/runtime/debug/stack.go:16 +0x22
// main.dbg.Close(0x75b780, 0xc00013e140, 0xc000152000, 0x7f61fc523088)
//         /tmp/tmp.H9O7cizbkv/main.go:17 +0x7f
// net/http/httputil.(*ReverseProxy).ServeHTTP(0xc0000ac0f0, 0x75e460, 0xc000032440, 0xc00010a000)
//         /usr/local/go/src/net/http/httputil/reverseproxy.go:311 +0x8a6
// main.main()
//         /tmp/tmp.H9O7cizbkv/main.go:41 +0x152


text:
Q: CouchDB backups and cloning the database We're looking at CouchdDB for a CMS-ish application. What are some common patterns, best practices and workflow advice surrounding backing up our production database?
I'm particularly interested in the process of cloning the database for use in development and testing.
Is it sufficient to just copy the files on disk out from under a live running instance? Can you clone database data between two live running instances?
Advice and description of the techniques you use will be greatly appreciated.

A: I'd like to second Paul's suggestion: Just cp your database files from under the live server if you can take the I/O-load hit. If you run a replicated copy anyway, you can safely copy from that too, without impacting your master's performance.

A: CouchDB also works very nicely with filesystem snapshots offered by modern filesystems like ZFS. Since the database file always is in a consistent state you can take the snapshot of the file any time without weakening the integrity guarantees provided by CouchDB.
This results in nearly no I/O overhead. In case you have e.g. accidentally deleted a document from the database you can move the snapshot to another machine and extract the missing data there. You might even be able to replicate back to the production database, but I never have tried that.
But always make sure you use exactly the same couchdb revisions when moving around database files. The on-disk format is still evolving in incompatible ways.

A: Another thing to be aware of is that you can copy files out from under a live database. Given that you may have a possibly large database, you could just copy it OOB from your test/production machine to another machine.
Depending on the write load of the machines it may be advisable to trigger a replication after the copy to gather any writes that were in progress when the file was copied. But replication of a few records would still be quicker than replication the entire database.
For reference see: http://wiki.apache.org/couchdb/FilesystemBackups

A: CouchDB supports replication, so just replicate to another instance of CouchDB and backup from there, avoiding disturbing where you write changes to.
https://docs.couchdb.org/en/latest/maintenance/backups.html
You literally send a POST request to your CouchDB instance telling it where to replicate to, and it Works(tm)
EDIT: You can just cp out the .couch files in the data directory from under the running database as long as you can accept the I/O hit.

A: CouchDB replication is horrible. I generally do tar which is much better.

*

*Stop the CouchDB service on the source host

*tar.gz the data files.

*On my Ubuntu servers this is typically in /var/lib/couchdb (sometimes in a subdirectory based on the Couch version). If you aren't sure where these files are, you can find the path in your CouchDb config files, or often by doing a ps -A w to see the full command that started CouchDb. Make sure you get the subdirectories that start with . when you archive the files.

*Restart the couchdb service on the source host.

*scp the tar.gz file to the destination host and unpack them in a  temporary location there.

*chown the files to the user and group that owns the files already in the database directory on the destination. This is likely couchdb:couchdb. This is important, as messing up the file permissions is the only way I've managed to mess up this process so far.

*Stop CouchDB on the destination host.

*cp the files into the destination directory. Again on my hosts this has been /var/lib/couchdb.

*Double check the file permissions in their new home.

*Restart CouchDB on the destination host.

A: I do it via powershell and the PSCouchDB module with the command Export-CouchDBDatabase.
This exports an entire database to a json file, which you can re-import via the import command (see the link).
ex.
Export-CouchDBDatabase -Database test -Authorization "admin:password"

this export a json file in a current directory: test_05-28-2021_17_01_00.json


text:
Q: node.js, catching errors so script doesn't break? I have a node.js script and anytime an error happens node.js stops running with the error that happened.
What is the proper way of checking errors in node.js so it won't break the script and cause node.js to stop?

A: Catching uncaughtException is no longer recommended.
Using domains are preferred. Using either "uncaughtException" or Domain, restarting the process is highly recommended after handling the exception.
To auto-restart the process, NodeJS provides another library called Cluster which assists in managing the worker threads.

A: You can catch otherwise uncaught errors by setting the following:
process.on('uncaughtException', function (exception) {
   // handle or ignore error
  });

Of course, if you run your script in something like forever or node-supervisor, when your script "stops" it will start back up, which might solve your problem.


text:
Q: I2C communication problems unless test equipment is attached I have a RaspberryPi acting as a master for an Atmel ATTiny861A slave over I2C, continuously sending a command plus 3 bytes of data to light an RGB LED.  This works perfectly but only if the AVR programmer is attached (it shares the same pins I'm using for I2C) or if my Saleae Logic analyzer is connected to SDA and SCL.  If neither is connected, the Python code running on the RaspberryPi reports an "Input/output error" about every 50 to 100 commands and eventually the line will lock up; the target holds SDA low and won't let go.
My question is, what is special about the programmer or the probes that are allowing this to work?  What do I need to change to allow normal operation when they are not connected?
I don't know what conditions lead to the Python code giving the error (its hard to catch on the analyzer with the constant stream of data), but I'm assuming the target simply doesn't respond with an ACK when it should.
I am running about 5ft of ribbon cable from the RaspberryPi to the target (it cannot be closer).  The RPi I2C operates at 3.3 V so there is a level shifter/repeater that I connect to.  The output side Vcc is 5 V.  Additionally on the output of the TCA9509, I have 5k pullup resistors on the SDA and SCL lines.  The distance between the TCA9509 and the ATTiny861 is about 2 inches.
If its useful, this is the code running on the ATTiny861A:
https://github.com/garthwebb/dance-floor
It uses Donald Blake's USI TWI Slave driver code, modified to remove defines related to non-ATTiny861 devices.

A: Consider the I2C bus needing pull up resisters as most I2C drivers need to be of the open collector type.  For example, here 2 10K ohm resistors bring the I2C lines back high when not pulled low by an open collector output:

A: I'd suggest you could use a couple of changes to improve your I2C bus.

*

*Use lower value pull-up resistors. Your long cable is highly capacitive and will result in corruption of both signal and Gnd levels.
Use this document from TI to establish the best pull-up value at 100 kHz (the default speed in the Raspberry Pi). (Personally, I always terminate on both ends of long cables using twice the calculated pull-up value)
Your TCA9509 complicates the issue a little. It already has 1 mA pull-up current sources on your A side (the Rasberry Pi), so I would put 2.5 k-Ohm single value pull-ups only on the source end of the bus.

*Lower your I2c bus speed.  You can do this a couple of ways.
If you are using earlier copies of Raspian, then you need to use modprobe.
For example:  Sudo modprobe i2c_bcm2708 baudrate=50000
...this will set the bus speed to 50 kHz
If you are using the latest builds of Raspian, then it uses device tree and you have to add elements to configure the BCM2708 to the config.txt file.
For example add these lines to config.txt:
dtparam=i2c1=on             (this should already be there since I2C is enabled)
dtparam=i2c_arm_baudrate=50000
....this will drop the I2C to 50 kHz
Anything you need to know about configuration control via device tree is here.
The I2C will work down to 10 kHz without any problems, and can go up to 1 Mhz equally without problems....though you could not drive your long cable at these speeds.


text:
Q: CodeIgniter "if not specific page" condition I want to hide few elements of my master template "home" for a specific page only.
The full URL looks like this:
"sitesname.com/home/page/userpage".
Something like
<?php if ($this->router->fetch_class() != 'home' && $this->router->fetch_method() != 'page/userpage') : ?>

didn't work. Please help me settle the right condition.


text:
Q: SOAP client in Perl Im trying to "talk" to https://webapi.allegro.pl.webapisandbox.pl/service.php?wsdl using Perl and SOAP::Lite.
In PHP its as simple as this:
<?
$client = new SoapClient('https://webapi.allegro.pl.webapisandbox.pl/service.php?wsdl');
$results = $client->doQueryAllSysStatus(array(
    'countryId' => 1,
    'webapiKey' => 'XXXXXX'
));
header('Content-type: text/plain');
var_dump($results);
?>

But with Perl... its not ;).
I wrote this:
use SOAP::Lite;
my $soap = SOAP::Lite->new(proxy => 'https://webapi.allegro.pl.webapisandbox.pl/service.php?wsdl');
my $som = $soap->call('doQueryAllSysStatus', 1, 'XXXXXX');
# tried also this:
# my $som = $soap->call('doQueryAllSysStatus',
#     SOAP::Data->name('countryId')->value(1),
#     SOAP::Data->name('webapiKey')->value('XXXXXX')
# );
die $som->faultstring if ($som->fault);
print $som->result, "\n";

$som->result is empty.
Tried also:
use SOAP::Lite;
my $soap = SOAP::Lite->service('https://webapi.allegro.pl.webapisandbox.pl/service.php?wsdl');
my $r = $soap->doQueryAllSysStatus(1, 'xxxxxx');
print $r, "\n";

... and got Use of uninitialized value $r in print.
Any help would be appreciated...
UPDATE #1:
PHP code outputs this:
object(stdClass)#2 (1) {
  ["sysCountryStatus"]=>
  object(stdClass)#3 (1) {
    ["item"]=>
    object(stdClass)#4 (8) {
      ["countryId"]=>
      int(1)
      ["programVersion"]=>
      string(3) "1.0"
      ["catsVersion"]=>
      string(6) "1.4.94"
      ["apiVersion"]=>
      string(3) "1.0"
      ["attribVersion"]=>
      string(3) "1.0"
      ["formSellVersion"]=>
      string(7) "1.11.91"
      ["siteVersion"]=>
      string(3) "1.0"
      ["verKey"]=>
      int(1505223106)
    }
  }
}

A: I found a working solution, so for anybody curious here it is.
I gave up with SOAP::Lite and used XML::Compile::* modules with a little help from HTTP::Tiny.
The code:
use Data::Printer;
use HTTP::Tiny;
use XML::Compile::SOAP11;
use XML::Compile::WSDL11;
use XML::Compile::Transport::SOAPHTTP;

my $wsdlXml = HTTP::Tiny->new->get('https://....')->{content};
my $wsdl    = XML::Compile::WSDL11->new($wsdlXml);

my $response = $wsdl->compileCall('doQueryAllSysStatus')->(
    countryId => 1,
    webapiKey => 'xxxxxx'
);
p $response;

Which prints out:
\ {
    parameters   {
        sysCountryStatus   {
            item   [
                [0] {
                    apiVersion        1.0,
                    attribVersion     1.0,
                    catsVersion       "1.4.94",
                    countryId         1,
                    formSellVersion   "1.11.91",
                    programVersion    1.0,
                    siteVersion       1.0,
                    verKey            1505223106
                }
            ]
        }
    }
}

Yay! ;)

A: I don't have a web api key so I can't fully test but what about something like this?
#!/usr/bin/perl

use warnings;
use strict;
use SOAP::Lite;

my $soap = SOAP::Lite->new( proxy => 'https://webapi.allegro.pl.webapisandbox.pl/service.php?wsdl');

my $country = 1;
my $api = 'XXXXX';

my $r = $soap->doQueryAllSysStatus($country,$api);

print $r->result, "\n";

--- UPDATE ---
#!/usr/bin/perl

use warnings;
use strict;
use SOAP::Lite;
use Data::Dumper;

my $soap = SOAP::Lite->new( proxy => 'https://webapi.allegro.pl.webapisandbox.pl/service.php?wsdl');

my $country = 1;
my $api = 'XXXXX';

my @r = $soap->doQueryAllSysStatus($country,$api);

print Dumper(\@r);


text:
Q: AWS X Ray node js trails not showing I am using Lambda (Node 8.10) and working with AWS X Ray. I am calling an external ip address using promise.
When I call, other traces are shown but cannot get custom segment.
I am not using any frameworks just a pure node js.
const AWSXRay = require('aws-xray-sdk-core');

AWSXRay.enableManualMode();
AWSXRay.captureHTTPsGlobal(require('https'));

const https = AWSXRay.captureHTTPs(require('https'));

exports.handler = async (event, context, callback) => {
// other code

const response = await doSomething(event);
    return callback(error, response);
};

async doSomething(event) {
return new Promise((resolve, reject) => {
    const segment = new AWSXRay.Segment('custom_segment_here');

    AWSXRay.captureAsyncFunc('send', (subsegment) => {
        const options = {
                    hostname: host,
                    port: 443,
                    path: '/',
                    method: 'GET',
                    XRaySegment: subsegment,
                };

        const req = https.request(options, (res) => {
            code = res.statusCode;
            resolve(code);
        });

        req.on('error', (error) => {
                    subsegment.addError(error);
                    reject(error);
                });

                subsegment.close();
                req.end();
    }, segment);

}

}

A: In Lambda scenario, Lambda is responsible for creating Segments and AWS X-Ray SDKs only create Subsegments and then emits them. Based on your code snippet, you created a segment (const segment = new AWSXRay.Segment('custom_segment_here');) inside a lambda function which couldn't be emitted so that you cannot see it in our console. Hope my answer is clear. :)


text:
Q: AS3 print with button When I try to print my stage it results wrongly rotated. I tried to fix it, I googled 150 different solutions pages at least, without any luck. I am not the programmer I try to be. Anyway it should work but it doesn't. Can you help me please?
I tried to do that: when I click "print" button, I would like to save my page(sprit) as a pdf file but per default settings the page must be landscape oriented.
Furthermore, there is a drawing (I use someone's code which shared in web) in stage but I don't want save the whole scene (for example buttons). I want to save just the drawing. Thanks for your help.
İ used this (didn't work at all. even drawing didn't work.)
btnPrint.addEventListener(MouseEvent.CLICK, onPrintClick);
function onPrintClick(event:MouseEvent):void{
    var bd :BitmapData = new BitmapData(stage.width, stage.height, false);
    bd.draw(stage);
    var b:Bitmap = new Bitmap (bd);
    var s:Sprite = new Sprite();
    s.addChild(b);
    var myPrintjob:PrintJob = new PrintJob();
    myPrintjob.start();
    var printArea = new Rectangle( 23, 65, 650, 500 );
    myPrintJob.addPage( s, printArea );
    myPrintJob.send();
}

I tried also this approach (draw and print worked but orientation was wrong):
btnPrint.addEventListener(MouseEvent.CLICK, onPrintClick);
function onPrintClick(event:Event)void{
    var myPrintjob:PrintJob = newPrintJob;
    myPrintjob.start();
    myPrintjob.addPage(this)
    myPrintjob.send;
}

I also tried some code I don't remember. It was like oriented.landscape and rotation 90, or something like that. It didn't work too. Probably I didn't make it.

A: If you're publishing for AIR you can change page orientation using PrintJob.orientation.
You need to set that before calling start(). In your code example it would look something like this:
btnPrint.addEventListener(MouseEvent.CLICK, onPrintClick);
function onPrintClick(event:Event)void{
    var myPrintjob:PrintJob = new PrintJob();
    myPrintJob.orientation = PrintJobOrientation.LANDSCAPE;
    myPrintjob.start();
    myPrintjob.addPage(this)
    myPrintjob.send();
}

Unfortunately this property is not settable if building for Flash Player.

A: I used these codes and they did the job. Thanks for your efforts.
function onPrintClick(event:Event):void{
var bd :BitmapData = new BitmapData(stage.width, stage.height, false);
bd.draw(stage);
var b:Bitmap = new Bitmap (bd);
var s:Sprite = new Sprite();
s.addChild(b);
var pj:PrintJob = new PrintJob();
pj.start();
pj.orientation = PrintJobOrientation.LANDSCAPE;
var printArea = new Rectangle( Cw, Ch, 650, 500 );
pj.addPage(this);
pj.send();
}


text:
Q: Linear regression in the stationary case Let $(Y_t,X_{1,t},\dots X_{K,t})$, $t=1,2,\dots$, be a jointly stationary time series on the probability space $(\Omega,\mathcal A,P)$ and taking values in $\mathbb R^{K+1}$,  and assume each component to be square integrable at each $t$.
Question: Does there exists $\beta \in \mathbb R^K$ and square integrable scalar time series $\varepsilon_t$ such that
$$Y_t=X_t\beta +\varepsilon_t \quad  \text{and} \quad E[X_t \varepsilon_t]=0$$
for each $t$, where $X_t:=[X_{1,t},\dots X_{K,t}]$ is a $K \times 1$ row vector?
It seems to me that the following argument works:
Define $\beta=E[X'_t X_t]^+ E[X'_tY_t] \in \mathbb R^K$, where $A^+$ denotes the Moore-Penrose inverse of matrix $A$. Because of joint stationarity, we have that  $\beta$ does not depend on $t$. Moreover, from the Hilbert projection theorem in $\mathcal L^2 $ and the least-square properties of the Moore-Penrose inverse we have that
$$E[X'_tY_t]=E[X'_t X_t]\beta$$
for each $t$. Therefore if we define $\varepsilon_t:=Y_t-X_t\beta$ we get that $\varepsilon_t$ is square integrable and  $E[X_t\varepsilon_t]=0$ for each $t$.
Is this correct? Thanks a lot for your help.


text:
Q: How to intentionally overload almost any value resistor with a DC power supply? When attaching a resistor to my power supply (which is a Extech 80W 3-in-1 Switching DC Power Supply, capable of 36V 5A) and the amps are set to let's say 5A at 16V the voltage stays the same but the amps will shoot down to something like .11A, not even close to half an amp. I know this is because of Ohm's law but how can I exceed and force the resistor to take in what the power supply wants to put out? Of course it's the same situation on my weaker power supply as well. Do I have to toggle something on the PSU itself? I've seen at least 5 videos of others frying resistors, but they never show the readings on the PSU's display. I know it's possible with my own PSU, I'm just clueless as to how to configure it. I've tried it on a 4 band 120 ohm and a 5 band 1k resistor.
(I'm not a completely destructive mad man, I just have some useless components that no one wants. I want to stress test them out of curiosity instead of throwing them away.)

A: You can never "force" a current higher than 0.11A through a 120 ohm resistance while maintaining the voltage at 16V. You can either set the voltage or the current, not both. Your power supply is (within limits) a voltage supply, so it sets the voltage. If you want to increase the current, you need to either increase the voltage, or decrease the resistance.
When you set the "Amps" on your power supply, what you are really setting is the limit. This means that the power supply will supply up to 5A, but the actual current is determined by the voltage.
In order to "blow up" the resistor, you would have to exceed its power rating (by quite a bit). These are probably 1/4 watt resistors, so you would need to give them something like 5W if you want to see interesting things happen. For the 120 Ohm one, you would need 25V (P=I*V, V=I*R, P=(V^2)/R, V=sqrt(P*R)=sqrt(5*120)=24.5V).

A: When you set your power supply to 16 volts and 5 Amps, the supply will maintain 16 volts while delivering UP TO 5 Amps.  The actual current delivered will be determined by the resistance of the load.
If the supply delivered 0.11 amp at 16 volts, by Ohm's Law (V = I x R), the load resistance was about 145 Ohms, and the power dissipated in the load was about 1.76 watts.  A 1/4 Watt resistor would quickly go up in smoke, but a 5 watt resistor would just get fairly warm.
A 3.2 Ohm resistor would draw 5 Amps from your 16 volt supply.  If you connect a 1.6 Ohm resistor to your 16 volt 5 amp supply, the supply would reduce its voltage to about 8 volts, in order to limit the current to 5 amps.

A: To fry a resistor you need to put into it more power than its rating.
The power (W) dissipated in a resistor (R) with voltage (V) across it is...
W = V^2 / R
Note that the power supply current limit is nowhere in that equation.  The current limit setting on the power supply is just a max allowed value.  The logic is like this.
if V / R < current_limit then the supply will output I = V / R Amps.
otherwise the supply will output I = current_limit Amps (and the voltage will drop to make it so).
You can see from the power equation, that since we are dividing by R, lower values of resistance yield more power for the same Voltage.  For example...

(10V)^2 /  1K ohms = 0.1W (current is 10mA)
(10V)^2 /  100 ohms = 1.0W (current is 100mA)
(10V)^2 /  10 ohms = 10W (current is 1A)
(10V)^2 /  1 ohms = 100W (current is 10A)

So suppose you had a 1/4W resistor and you set the supply to 10V.  If you wanted to find the resistor value that would be at 1/4W you would write...

1/4W = (10V)^2 / R

And then solve for R...

R = (10V)^2 / (1/4W) = 400 ohms

To burn up the resistor you might want to set the wattage to 4X that, so make it 100 ohms instead of 400.


text:
Q: VirtualBox Windows 7 guest network driver not installed even after installing guest additions I installed VirtualBox on CentOS 6.0. Installed Windows 7 as a guest OS. Now it doesnt recognize the network card in the guest OS even after I installed guest additions. The network mode is NAT. Previously I tried bridged mode but that didn't work either. How do I resolve this?
vm info:
[root@sn ~]# VBoxManage showvminfo testvm
Name:            testvm
Groups:          /
Guest OS:        Windows 7 (64 bit)
UUID:            ef2de77b-67ba-42f9-b2f6-8a1a3a5c8adb
Config file:     /root/VirtualBox VMs/testvm/testvm.vbox
Snapshot folder: /root/VirtualBox VMs/testvm/Snapshots
Log folder:      /root/VirtualBox VMs/testvm/Logs
Hardware UUID:   ef2de77b-67ba-42f9-b2f6-8a1a3a5c8adb
Memory size:     1024MB
Page Fusion:     off
VRAM size:       8MB
CPU exec cap:    100%
HPET:            off
Chipset:         piix3
Firmware:        BIOS
Number of CPUs:  1
PAE:             on
Long Mode:       on
Synthetic CPU:   off
CPUID overrides: None
Boot menu mode:  message and menu
Boot Device (1): DVD
Boot Device (2): DVD
Boot Device (3): HardDisk
Boot Device (4): Not Assigned
ACPI:            on
IOAPIC:          on
Time offset:     0ms
RTC:             local time
Hardw. virt.ext: on
Nested Paging:   on
Large Pages:     off
VT-x VPID:       on
VT-x unr. exec.: on
State:           powered off (since 2014-06-25T00:44:24.000000000)
Monitor count:   1
3D Acceleration: off
2D Video Acceleration: off
Teleporter Enabled: off
Teleporter Port: 0
Teleporter Address:
Teleporter Password:
Tracing Enabled: off
Allow Tracing to Access VM: off
Tracing Configuration:
Autostart Enabled: off
Autostart Delay: 0
Default Frontend:
Storage Controller Name (0):            IDE Controller
Storage Controller Type (0):            PIIX4
Storage Controller Instance Number (0): 0
Storage Controller Max Port Count (0):  2
Storage Controller Port Count (0):      2
Storage Controller Bootable (0):        on
IDE Controller (0, 0): /root/VirtualBox VMs/testvm/testvm-disk03.vdi (UUID: ec572cb1-fc24-40da-a581-46f6eb4fe411)
IDE Controller (0, 1): /usr/share/virtualbox/VBoxGuestAdditions.iso (UUID: a30bd107-b2d9-48cc-b232-7bf2a4372389)
IDE Controller (1, 0): /tmp/win7.iso (UUID: a4e22aa8-fa5e-4dc6-8f41-e82377affeac)
NIC 1:           MAC: 080027CCF2B3, Attachment: NAT, Cable connected: on, Trace: off (file: none), Type: Am79C973, Reported speed: 0 Mbps, Boot priority: 0, Promisc Policy: allow-all, Bandwidth group: none
NIC 1 Settings:  MTU: 0, Socket (send: 64, receive: 64), TCP Window (send:64, receive: 64)
NIC 2:           disabled
NIC 3:           disabled
NIC 4:           disabled
NIC 5:           disabled
NIC 6:           disabled
NIC 7:           disabled
NIC 8:           disabled
Pointing Device: PS/2 Mouse
Keyboard Device: PS/2 Keyboard
UART 1:          disabled
UART 2:          disabled
LPT 1:           disabled
LPT 2:           disabled
Audio:           disabled
Clipboard Mode:  disabled
Drag'n'drop Mode: disabled
VRDE:            disabled
USB:             disabled
EHCI:            disabled

USB Device Filters:

<none>

Available remote USB devices:

<none>

Currently Attached USB Devices:

<none>

Bandwidth groups:  <none>

Shared folders:  <none>

VRDE Connection:    not active
Clients so far:     0

Video capturing:    not active
Capture screens:    0
Capture file:       /root/VirtualBox VMs/testvm/testvm.webm
Capture dimensions: 1024x768
Capture rate:       512 kbps
Capture FPS:        25

Guest:

Configured memory balloon size:      0 MB

A: I've spent 1 day, trying anything, manytimes unistall & install again (with reboot system). I have tried tens of methods, nothing can help me. Also I've tried to install drivers pack. I've tried to install different version (even beta)... Don't like Hyper-V, never had same problems with Hyper-V... nonsence...
Added (Fixed!):
Wow, finally I've fixed it, you know how?
Before I've tried to choose different ethernet NICs from the list in network configuration of machine in VirtualBox - nothing could help me.
I've just installed 6.0.12 version (the last was 6.0.14), and fixed it even without reboot. What I did: I downloaded Full pack of ethernet-drivers (you can find it in google drp dot su), but didn't run it! just unpack everything from folder "drivers", then update drivers in Drivers Manager, by choose second option: Others-Ethernet-controller(unknown device) and choose manual where to find for drivers... That's it. I've tried to do same in others version ov VirtualBox (it didn't help me, also don't install version 5.0 it will not work). Also before these manipulations I've changed NIC, to pcnet fast III & intel pro/1000 MT server. But if you only change it, it will not help...
Also don't forget to install new version of Extension pack for your version of VirtualBox. And don't use Portable version of VirtualBox, it will not work work correctly for now.


text:
Q: Share to Facebook in android (like twitter) As anyone who's tried to share to Facebook via Android knows, the Facebook team has decided to disregard the protocol for sharing and ignores the text provided in the share intent (see: Share Text on Facebook from Android App via ACTION_SEND)
However, it appears that the twitter app has figured out how to circumvent this. When you're looking at a tweet:

You can click the share icon below the tweet and it brings up the normal share dialog with a list of apps, including Facebook:

If you click on Facebook, you get this view:

Which looks perfect, and clearly twitter is sending more than just a link that other answers seem to propose. Furthermore, if you share to messaging:

You can see that the text is properly added and there are no issues. How did twitter get this to work?

A: If you're asking how you can include pre-fill text when sharing a link to Facebook from another app, this is actually directly against Facebook's policy -
"Ensure that all content in the user message parameter is entered by the user. Don't pre-fill. This includes posts, messages, comments, and captions." (https://developers.facebook.com/policy/)

A: what i did to over come the problem is little nasty but useful,
copy the text that want to be shared in clip board and
toast message "paste text",
Copying to clipboard
@SuppressLint("NewApi")
private void copyToClipBoard(String data)
{
    int sdk = android.os.Build.VERSION.SDK_INT;
    if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB)
    {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(data);
        Toast.makeText(context,"Paste text", Toast.LENGTH_SHORT).show();
    }
    else
    {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData.newPlainText(type,data);
        clipboard.setPrimaryClip(clip);
        Toast.makeText(context, "Paste text", Toast.LENGTH_SHORT).show();
    }

}

A: Just to close out this question, I believe the way it works for Twitter in the example is based on the meta data available in the url provided. This is a good starting point: https://developers.facebook.com/docs/sharing/best-practices#tags


text:
Q: excude a specidic category from showing in the "relative posts" I have a post slider on the homepage that shows a specific category (slider).
The thing is that I do not want this category to appear on other pages (except homepage) because I have  "relevant posts" at the bottom of every blog category post and it is mixing it up.
Any suggestions?


text:
Q: OS Closed my native thread? As far as I know the OS closes threads if it is low on memory.
1) Is is true for native threads that was started using pthread?
2) If so, how can I know if the OS closed a thread?
Thanks,
Nahum

A:
As far as I know the OS closes threads if it is low on memory

Not as far as I am aware. Android will terminate your entire process when it is low on memory, not individual threads.


text:
Q: LAMP server hosting multiple domains - how to ensure each domain's files and users locked to only that domain? I have a LAMP server (Ubuntu) running PHP. I want to host multiple domains on it.
My plan is to create different user for each domain because I want to make sure if one domain gets hacked, it wont affect other domains.
My worry is if one domain gets hacked, how do I prevent hacker from uploading a rogue PHP file that can grab data from my other domains? Is there a way to restrict all PHP files in a certain domain to only operate within that directory and not outside it?

A: There's several ways to do this. SELinux being one. Virtual servers being another. If you're really savvy, perhaps LXC containers.
But your provided question is far too broad to provide a detailed answer. I'd suggest doing some researching and then ask us specifics if you run into problems testing out potential solutions.


text:
Q: Why won't adding a nonce to my plaintext help defeat cryptanalysis? Disclaimer: I assume this is a dumb idea, I'm asking for an explanation as to why it's a dumb idea :)
Let's say I that before encrypting a file, I pick a random number x between 0 and a constant y. I then pad my plaintext with x random bytes before, and y-x bytes after, so that the filesize doesn't give away x. I add the actual value of x to my buffer before running my normal encryption routine.
This would mean that encrypting the same plaintext with the same key would rarely produce the same encrypted output, without adding much work to either encryption or decryption.
Intuitively, I feel like this should be quite handy in reducing weakness to cryptanalysis, but I've never read of its mention, so I'm guessing it doesn't. Can anybody explain to me why this would be so?

A: Actually it's not a bad idea and it is being used. Take a look at: http://en.wikipedia.org/wiki/Padding_%28cryptography%29 and especially at a couple of papers from this google scholar search:
http://scholar.google.de/scholar?hl=en&as_sdt=0,5&q=random+padding+cryptanalysis (a lot of them are freely available, just click the pdf link on the right).

A: I would say the correct answer here is "it depends." I know that's probably not what your looking for, but consider this.

*

*Is your encrypted data just a small bit of information (say a number between 0 and 2^32), If this piece of information is part of a large algorithm I can just bruteforce the whole algorithm and ignore your encrypted data altogether.

*What is "key" or secret to this ciphertext. You can pad all you want, but if you secret key is "7", then all the padding in the world wont help you. (This is analogous to small passwords + salt. Salt is not helping if your password space is simply 3 ASCII characters)

*What mode of encryption are you operating in? If you are in ECB mode, this padding can help immensely and is basically required. Other modes of operation (OFB, CTR, ...) will basically pad the data for you, such that the encryption of the same file over and over again will produce different ciphertext.
I would offer up the simple answer that from a cryptographic point of view it never hurts to pad the data...


text:
Q: Massive change in 'People Reached' overnight On Stack Overflow, your profile page provides a facility to determine the impact of your questions and answers.
Yesterday it was showing 7k and right now it is showing 19k, so in single day it increased by 12k. How is this possible?

A: You got an upvote yesterday on your answer to this question and as you can see, it got 12k views:

So yes indeed, you reached 11,778 people in a split of a second. :)
Technically speaking, the upvote just caused your answer to become eligible, as described here:

*

*Answers - Views of the parent question for answers that are:

*Non-deleted AND

*

*Score > 0 AND

*...

Worth to mention, that it goes both ways... if you will get a downvote on that answer, or other answers will  get enough upvotes, that 12k will be reduced again from your impact. Unlike badges, this is a "live" stat.


text:
Q: SQL query for table with multiple keys? I am sorry if this seems too easy but I was asked this question and I couldn't answer even after preparing SQL thoroughly :(. Can someone answer this?
There's a table - Seller id, product id, warehouse id, quantity of products at each warehouse for each product as per each seller.
We have to list the Product Ids with Seller Id who has highest number of products for that product and the total number of units he has for that product.
I think I got confused because there were 3 keys in the table.

A: It's not quite clear which DBMS you are using currently. The below should work if your DBMS support window functions.
You can find count of rows for each product and seller, rank each seller within each product using window function rank and then use filter to get only top ranked sellers in each product along with count of units.
select
    product_id,
    seller_id,
    no_of_products
from (
    select
        product_id,
        seller_id,
        count(*) no_of_products,
        rank() over (partition by product_id order by count(*) desc) rnk
    from your_table
    group by
        product_id,
        seller_id
) t where rnk = 1;

If window functions are not supported, you can use correlated query to achieve the same effect:
select
    product_id,
    seller_id,
    count(*) no_of_products
from your_table a
group by
    product_id,
    seller_id
having count(*) = (
    select max(cnt)
    from (
        select count(*) cnt
        from your_table b
        where b.product_id = a.product_id
        group by seller_id
    ) t
);

A: Don't know why having id columns would mess you up... group by the right columns, sum up the totals and just return the first row:
select *
from (
  select sellerid, productid, sum(quantity) as total_sold
  from theres_a_table
  group by sellerid, productid
) x
order by total_sold desc
fetch first 1 row only

A: If I do not think about optimization, straight forward answer is like this
select *
from
(
select seller_id, product_id, sum(product_qty) as seller_prod_qty
from your_table
group by seller_id, product_id
) spqo
inner join
(
 select product_id, max(seller_prod_qty) as max_prod_qty
 from
 (
  select seller_id, product_id, sum(product_qty) as seller_prod_qty
  from your_table
  group by seller_id, product_id
 ) spqi
 group by product_id
) pmaxq
on spqo.product_id = pmaxq.product_id
and spqo.seller_prod_qty = pmaxq.max_prod_qty

both spqi (inner) and sqpo (outer) give you seller, product, sum of quantity across warehouses. pmaxq gives you max of each product again across warehouses, and then final inner join picks up sum of quantities if seller has highest (max) of the product (could be multiple sellers with the same quantity). I think this is the answer you are looking for. However, I'm sure query can be improved, since what I'm posting is the "conceptual" one :)


text:
Q: How do I use a default setting from Root.plist? I have set up a default setting for my app using Root.plist, giving this a Boolean DefaultValue of YES (ticked checkbox).You can see a screengrab at http://www.infin8design.com/clients/stack/plist.png
However, when my app is first launched, the YES value is not picked up, and the setting is read as a NO (or 0). The user has to manually go into the settings app, turn the toggleswitch off, then turn it back on again for this setting to hold a YES(1) value.
I'm logging the value with appDidFinishLaunching like this.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSLog(@"%d",[defaults boolForKey:@"include_phrases"]);

SO... my question is... How do I pick up this initial default setting without the user having to set it manually?
Thanks in advance for any suggestions you can offer.
Mark

A: looks like you need to set the values that you want the key to take when the user switches the parameter on and off. Try adding the following to your plist:
TrueValue   String  YES
FalseValue  String  NO


text:
Q: Prove that $ \lim_{x \to 0} \frac{ \sqrt{x + \sqrt{ x + \sqrt{x}}} }{\sqrt[8]{x}}= 1$
Prove that $$ \lim_{x \to 0} \frac{ \sqrt{x + \sqrt{ x + \sqrt{x}}} }{\sqrt[8]{x}}= 1$$

Let $x=y^8$ with $t>0$. Then after we get
$$
\lim \frac{ \sqrt { t^8 + \sqrt{ t^8 + \sqrt{t^8}}}}{ t} = \lim \frac{ \sqrt{ t^8 + \sqrt{ t^8 + t^4}}}{ t}
$$
  and can't go further than that

A: We have that
$$ \frac{\sqrt{x + \sqrt{ x + \sqrt x}}}{\sqrt[8] x} = \frac{ \sqrt{x + \sqrt[4] x\sqrt{ \frac{x}{ \sqrt x}+1}}}{\sqrt[8] x} = \frac{\sqrt[8]x\sqrt{\frac{x}{\sqrt[4]x} + \sqrt{ \frac{x}{ \sqrt x}+1}}}{\sqrt[8] x} =$$
$$=\sqrt{\frac{x}{\sqrt[4]x} + \sqrt{ \frac{x}{ \sqrt x}+1}} \to \sqrt{0 + \sqrt{ 0+1}}=1$$
or in a similar way by your approach
$$\frac{ \sqrt{ t^8 + \sqrt{ t^8 + t^4}}}{ t}=\frac{ \sqrt{ t^8 + t^2\sqrt{ t^4 + 1}}}{ t}=\frac{ t\sqrt{ t^6 + \sqrt{ t^4 + 1}}}{ t}=\sqrt{ t^6 + \sqrt{ t^4 + 1}} \to 1$$

A: Numerator :
$((t^2)^4+t^2(1+t^4)^{1/2})^{1/2}=$
$t(t^6+(1+t^4)^{1/2})^{1/2}$;
1) $f(t):=(1+t^4)^{1/2};$
2) $g(t):=t^6;$
3)$ h(t):= (g(t)+f(t))^{1/2}:$
4) $\lim_{t \rightarrow 0} h(t)=$
$\lim_{t \rightarrow 0}(g(t)+f(t))^{1/2}$;
All functions $g, f, √$ are continuos.
Hence?


text:
Q: How to save fetched html content to database in apache nutch? I'm using 1.8 version of apache nutch. I want to save crawled HTML content to postgre database to do this, I modify FetcherThread.java class as below.
  case ProtocolStatus.SUCCESS: // got a page
  pstatus = output(fit.url, fit.datum, content, status,
  CrawlDatum.STATUS_FETCH_SUCCESS, fit.outlinkDepth);
  updateStatus(content.getContent().length);
  /*Added My code Here*/

But I want to use plug-in system instead of directly modifying FetcherThread class. To use plug-in system which extension points I need to use?

A: You could write a custom plugin and implement an extension of org.apache.nutch.indexer.IndexWriter to send the documents to
Postgres as part of the indexing step. You'll need to index the raw content which requires NUTCH-2032 - this is in Nutch 1.11 so you will need to upgrade your version of Nutch.
Alternatively you could write a custom MapReduce job which would take a segments as input, read the content and send it to your DB in the reduce step.


text:
Q: Updating row column with count value of query in same table I was wondering if somebody could help.
I have a products table and in the table a column called master_colours.
I have 3 columns in the table called stock_id, master and colour, the master column tells it which stock_id to link to like so...
stock_id, master, colour
12345, '', ''
aaa, '12345', 'red'
bbb, '12345', 'blue'
ccc, '12345', 'green'

In the master_colours column I want it to be updated to the value of how many colours the master product will have so in the example above it will be 3.
I have so far the following code which returns the error #1242 - Subquery returns more than 1 row.
UPDATE products AS main
SET main.master_colours = (SELECT master.stock_id FROM (
SELECT p.stock_id, COUNT(DISTINCT(m.colour))
FROM products AS p, products AS m
WHERE m.master = p.stock_id AND m.colour != ''
GROUP BY p.stock_id) AS master)

I understand why it is doing it because I have grouped by the stock_id but if I dont do this then it counts all colours in the table rather than the colours linked to that stock id.
The logical thing to me would be to do this...
UPDATE products AS main
SET main.master_colours = (SELECT master.stock_id FROM (
SELECT p.stock_id, COUNT(DISTINCT(m.colour))
FROM products AS p, products AS m
WHERE m.master = p.stock_id AND m.colour != '' AND p.stock_id = main.stock_id
GROUP BY p.stock_id) AS master)

but obviously this doesnt work because main.stock_id is outside the sub query.
Can anyone please point me in the right direction?
Thanks

A: Are you looking for something like this?
UPDATE products p JOIN
(
  SELECT master, COUNT(*) total
    FROM products
   GROUP BY master
) q ON p.stock_id = q.master
   SET p.master_colours = total;

That is assuming that you only have 1 level deep hierarchy
Outcome:

| STOCK_ID | MASTER | COLOUR | MASTER_COLOURS |
|----------|--------|--------|----------------|
|    12345 |        |        |              3 |
|      aaa |  12345 |    red |         (null) |
|      bbb |  12345 |   blue |         (null) |
|      ccc |  12345 |  green |         (null) |

Here is SQLFiddle demo


text:
Q: How to update configurable associated products programmatically? I'm trying to update configurable associated products. When I save my product I get this error:
Integrity constraint violation: 1062 Duplicate entry '183-137' for key 'UNQ_CATALOG_PRODUCT_SUPER_ATTRIBUTE_PRODUCT_ID_ATTRIBUTE_ID'
, query was: INSERT INTO `catalog_product_super_attribute` (`product_id`, `attribute_id`) VALUES (?,
 ?)<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">

How can I update the configurable associated products?

A: i use this code to insert and update configurable product in my custom extention.
where all data get in data variable
$pid is configurable product id.
$aid is attribute id.
before you use this code u set session variable is edit to 0 or 1. 0- if new product , 1- if edit existing product
$data = $this->getRequest ()->getPost();
            $pid=Mage::getSingleton('core/session')->getAttributeId();
            $aid=Mage::getSingleton('core/session')->getAttributeValue();
            Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
            $prd = Mage::getModel('catalog/product')->load($pid);
            try
            {
                $totalRow=count($data['product_id']);
                if($totalRow>0)
                {
                         $configurable = Mage::getModel('catalog/product')->load($pid);
                         if(!Mage::getSingleton('core/session')->getIsEdit(0))
                         {
                            $configurable->getTypeInstance()->setUsedProductAttributeIds(array($aid));
                         }
                         $configurable->save();
                         $productModel = Mage::getModel('catalog/product');
                         $configAttributeCode = $productModel->getResource()->getAttribute($aid)->getAttributeCode();
                         $simpleProducts = Mage::getResourceModel('catalog/product_collection')
                                ->addIdFilter($data['product_id'])
                                ->addAttributeToSelect($configAttributeCode);

                         $configurableProductsData = array();
                         $configurableAttributesData = $configurable->getTypeInstance()->getConfigurableAttributesAsArray();

                            for($l=0;$l<$totalRow;$l++)
                            {
                                $_product = Mage::getModel('catalog/product')->load($data['product_id'][$l]);
                                $_product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
                                $_product->getResource()->save($_product);
                                $productModel = Mage::getModel('catalog/product');
                                $attr = $productModel->getResource()->getAttribute($aid);
                                $att_label = $attr->getSource()->getOptionText($data['attribute_type'][$l]);
                                $productData = array(
                                        'label' => $att_label, //attribute label
                                        'attribute_id' => $aid, //attribute ID
                                        'value_index' => $data['attribute_type'][$l],
                                        'is_percent' => '0', //fixed/percent price for this option
                                        'pricing_value' => $data['product_price'][$l] //value for the pricing
                                );
                                $configurableProductsData[$_product->getId()] = $productData;
                                $configurableAttributesData[0]['values'][$l] = $productData;
                            }

                            $configurable->setConfigurableProductsData($configurableProductsData);
                            $configurable->setConfigurableAttributesData($configurableAttributesData);
                            Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
                            $configurable->setCanSaveConfigurableAttributes(true);
                            $configurable->setStatus(1);
                            $configurable->save();

                }
            }
            catch(Exception $e)
            {
                echo $e->getMessage();
            }


text:
Q: Extended Wpf Toolkit: TableView.Theme broken in version 2.4? Having installed "Extended Wpf Toolkit" (Community Edition) via NuGet in Visual Studio 2013 Professional in a certain project, an update attempt to the current version 2.4 is causing a System.Windows.Markup.XamlParseException at runtime with the same code that previously worked well in version 2.3 here.
As it turned out, that exception is being caused by an xcdg:TableView Theme property assignment, see also the repro sample pasted below.
And removing that assignment would cure the symptom.
Since I was unable to find anything on that issue in the web, the actual question probably is whether there is a way to apply DataGridControl / TableView Themes with "Extended WPF Toolkit" Community Edition version 2.4?
The following simplified version reproduces the issue for me in the MainWindow.xaml of a "test" project after having installed the current version 2.4 of Extended WPF Toolkit via NuGet and starting via F5 key:
<Window x:Class="testXceed24.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:xcdg="http://schemas.xceed.com/wpf/xaml/datagrid"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <xcdg:DataGridControl>
            <xcdg:DataGridControl.View>
                <xcdg:TableView Theme="ZuneNormalColorTheme"/>
            </xcdg:DataGridControl.View>
        </xcdg:DataGridControl>
    </Grid>
</Window>

FWIW, as a cross-check, downgrading the Extended.Wpf.Toolkit version via Package Manager Console apparently also cures the symptom here:
PM> Update-Package Extended.Wpf.Toolkit -Version 2.3.0

A: When that project was continued later, adding a project reference to "Presentationframework.Luna", with Properties -> "Copy Local = "True", turned out to cure the symptom in this particular case (after updating Extended.Wpf.Toolkit from Version 2.3.0 to 2.8.0)


text:
Q: Run single Grails unit/integration test will run all the tests on Intellij Sometimes, when I run a single Grails unit or integration test on Intellij (latest version), it will run all the tests in the console.
What I do is right click single unit test class or method in the code and select run.
Sometimes it happened but sometimes it is OK.
Anyone has idea how to fix or prevent this  happen?

A: This could be IntellijIdea issue. I'd suggest to use grails command prompt for testing. Just use:
grails test-app unit: YourTestClass

or
grails test-app integration: YourIntegrationTestClass

This works for me.


text:
Q: Proving inner product generated by matrix For a matrix A, how would I go about proving that the inner product defined by $$\langle\mathbf{u},\mathbf{v}\rangle=A\mathbf{u}\cdot A\mathbf{v}$$ is indeed an inner product? My math teacher assigned this as a problem, but we haven't talked about inner products yet and reading through my book is not that helpful. If anyone could help me understand the concept better, I would appreciate it!

A: An inner product is a mapping which assigns a real number to any pair of "vectors", $u$ and $v$ say, and the mapping also has to satisfy some axioms (specific properties). Technically if $V$ is your set of vectors and $\theta$ is an inner product map then $\theta : V\times V \rightarrow \mathbb{R}$. Historically people tend to write $<u,v>$ for $\theta ((u,v))$. It is possible to define many different inner products for a particular set of vectors $V$. What the inner product map "does" is give a particular way of assigning "how close two vectors are to each other". More generally it imposes a certain "geometry" on $V$.

A: It suffices to prove the three properties for vectors $\pmb{u},\pmb{v} \in V$ and $\alpha \in \mathbb{R}$.

*

*Symmetry: $\newcommand{\inp}[1]{\left\langle #1 \right\rangle}$
$\inp{\pmb{u}, \pmb{v}} = \inp{\pmb{v}, \pmb{u}}$ for real valued vectors.

*Linearity: $\inp{\alpha \pmb{u}, \pmb{v}} = \alpha \inp{\pmb{u}, \pmb{v}}$ for real valued vectors.

*Positive-definite: $\inp{\pmb{u}, \pmb{u}} \ge 0$ with equality if and only if $\pmb{u} = 0$, the zero function.
Let's show the three properties:

*

*$\newcommand{\inp}[1]{\left\langle #1 \right\rangle}$
$\inp{\pmb{u}, \pmb{v}} = \pmb{u}^T A^T A \pmb{v} = (\pmb{u}^T A^T A \pmb{v})^T = \pmb{v}^T A^T A \pmb{u} = \inp{\pmb{v}, \pmb{u}} $.

*$\inp{\alpha \pmb{u}, \pmb{v}} = (\alpha\pmb{u}^T A^T) A \pmb{v}  = \alpha\pmb{u}^T A^T A \pmb{v}  = \alpha \inp{ \pmb{u}, \pmb{v}}$

*$\inp{\pmb{u}, \pmb{u}}  = \pmb{u}^T A^T A \pmb{u} \geq 0$ and is $0$ only when $\pmb{u}=\pmb{0}$ or when $\pmb{A}$ is not full column rank (therefore $A^TA$ is positive semi-definite) and $\pmb{u}$ belongs to the column space of $A$. I think you should add this condition.


text:
Q: Zend Framework 2 Forms Array notation for drop down onchange event I am using Zend Framework 2 Forms using array notion for a select (drop down box). Code snippet from MenuForm.php is below:
 $options_for_select = $menuTable->GetParents();
    $this->add(array(
        'type' => 'Zend\Form\Element\Select',
        'name' => 'parent',
        'attributes' => array(
            'options' => $options_for_select,
        ),
        'options' => array(
            'label' => 'Select parent item',
            ),
        )
    );

When this drop down changes I would like to populate another drop down list on the form with a list of options that are related to the item selected in the parent drop down list.
How can I achieve this?
Thank you.


text:
Q: Docker build always got '/bin/sh: 1: go: Permission denied' on Ubuntu I am building my Docker image of miniflux below is the Dockerfile
ARG BASE_IMAGE_ARCH="amd64"

FROM ${BASE_IMAGE_ARCH}/golang:buster AS build

# blocking github workaround
ENV GO111MODULE=on
ENV GOPROXY=https://goproxy.cn,direct

ENV DEBIAN_FRONTEND noninteractive

RUN apt-get update -q && \
    apt-get install -y -qq build-essential devscripts dh-make dh-systemd && \
    mkdir -p /build/debian

ADD . /src

RUN ["chmod", "+x", "/src/packaging/debian/build.sh"]
RUN ["chmod", "+x", "/src/packaging/debian/miniflux.postinst"]

CMD ["/src/packaging/debian/build.sh"]

Here is the content in /src/packaging/debian/build.sh
#!/bin/sh

PKG_ARCH=`dpkg --print-architecture`
PKG_DATE=`date -R`
PKG_VERSION=`cd /src && git describe --tags --abbrev=0`

echo "PKG_VERSION=$PKG_VERSION"
echo "PKG_ARCH=$PKG_ARCH"
echo "PKG_DATE=$PKG_DATE"

cd /src && \
    make miniflux && \
    mkdir -p /build/debian && \
    cd /build && \
    cp /src/miniflux /build/ && \
    cp /src/miniflux.1 /build/ && \
    cp /src/LICENSE /build/ && \
    cp /src/packaging/miniflux.conf /build/ && \
    cp /src/packaging/systemd/miniflux.service /build/debian/ && \
    cp /src/packaging/debian/compat /build/debian/compat && \
    cp /src/packaging/debian/copyright /build/debian/copyright && \
    cp /src/packaging/debian/miniflux.manpages /build/debian/miniflux.manpages && \
    cp /src/packaging/debian/miniflux.postinst /build/debian/miniflux.postinst && \
    cp /src/packaging/debian/rules /build/debian/rules && \
    echo "miniflux ($PKG_VERSION) experimental; urgency=low" > /build/debian/changelog && \
    echo "  * Miniflux version $PKG_VERSION" >> /build/debian/changelog && \
    echo " -- Frédéric Guillot <f@miniflux.net>  $PKG_DATE" >> /build/debian/changelog && \
    sed "s/__PKG_ARCH__/${PKG_ARCH}/g" /src/packaging/debian/control > /build/debian/control && \
    dpkg-buildpackage -us -uc -b && \
    lintian --check --color always ../*.deb && \
    cp ../*.deb /pkg/

Here is Makefile content and output of
sudo make debian
Makefile:
APP          := miniflux
DOCKER_IMAGE := miniflux/miniflux
VERSION      := $(shell git describe --tags --abbrev=0)
COMMIT       := $(shell git rev-parse --short HEAD)
BUILD_DATE   := `date +%FT%T%z`
LD_FLAGS     := "-s -w -X 'miniflux.app/version.Version=$(VERSION)' -X 'miniflux.app/version.Commit=$(COMMIT)' -X 'miniflux.app/version.BuildDate=$(BUILD_DATE)'"
PKG_LIST     := $(shell go list ./... | grep -v /vendor/)
DB_URL       := postgres://postgres:postgres@localhost/miniflux_test?sslmode=disable
DEB_IMG_ARCH := amd64

export PGPASSWORD := postgres

.PHONY: \
    miniflux \
    linux-amd64 \
    linux-arm64 \
    linux-armv7 \
    linux-armv6 \
    linux-armv5 \
    linux-x86 \
    darwin-amd64 \
    darwin-arm64 \
    freebsd-amd64 \
    freebsd-x86 \
    openbsd-amd64 \
    openbsd-x86 \
    netbsd-x86 \
    netbsd-amd64 \
    windows-amd64 \
    windows-x86 \
    build \
    run \
    clean \
    test \
    lint \
    integration-test \
    clean-integration-test \
    docker-image \
    docker-image-distroless \
    docker-images \
    rpm \
    debian \
    debian-packages

miniflux:
    @ go build -buildmode=pie -ldflags=$(LD_FLAGS) -o $(APP) main.go

linux-amd64:
    @ GOOS=linux GOARCH=amd64 go build -ldflags=$(LD_FLAGS) -o $(APP)-linux-amd64 main.go

linux-arm64:
    @ GOOS=linux GOARCH=arm64 go build -ldflags=$(LD_FLAGS) -o $(APP)-linux-arm64 main.go

linux-armv7:
    @ GOOS=linux GOARCH=arm GOARM=7 go build -ldflags=$(LD_FLAGS) -o $(APP)-linux-armv7 main.go

linux-armv6:
    @ GOOS=linux GOARCH=arm GOARM=6 go build -ldflags=$(LD_FLAGS) -o $(APP)-linux-armv6 main.go

linux-armv5:
    @ GOOS=linux GOARCH=arm GOARM=5 go build -ldflags=$(LD_FLAGS) -o $(APP)-linux-armv5 main.go

darwin-amd64:
    @ GOOS=darwin GOARCH=amd64 go build -ldflags=$(LD_FLAGS) -o $(APP)-darwin-amd64 main.go

darwin-arm64:
    @ GOOS=darwin GOARCH=arm64 go build -ldflags=$(LD_FLAGS) -o $(APP)-darwin-arm64 main.go

freebsd-amd64:
    @ GOOS=freebsd GOARCH=amd64 go build -ldflags=$(LD_FLAGS) -o $(APP)-freebsd-amd64 main.go

openbsd-amd64:
    @ GOOS=openbsd GOARCH=amd64 go build -ldflags=$(LD_FLAGS) -o $(APP)-openbsd-amd64 main.go

windows-amd64:
    @ GOOS=windows GOARCH=amd64 go build -ldflags=$(LD_FLAGS) -o $(APP)-windows-amd64 main.go

build: linux-amd64 linux-arm64 linux-armv7 linux-armv6 linux-armv5 darwin-amd64 darwin-arm64 freebsd-amd64 openbsd-amd64 windows-amd64

# NOTE: unsupported targets
netbsd-amd64:
    @ GOOS=netbsd GOARCH=amd64 go build -ldflags=$(LD_FLAGS) -o $(APP)-netbsd-amd64 main.go

linux-x86:
    @ GOOS=linux GOARCH=386 go build -ldflags=$(LD_FLAGS) -o $(APP)-linux-x86 main.go

freebsd-x86:
    @ GOOS=freebsd GOARCH=386 go build -ldflags=$(LD_FLAGS) -o $(APP)-freebsd-x86 main.go

netbsd-x86:
    @ GOOS=netbsd GOARCH=386 go build -ldflags=$(LD_FLAGS) -o $(APP)-netbsd-x86 main.go

openbsd-x86:
    @ GOOS=openbsd GOARCH=386 go build -ldflags=$(LD_FLAGS) -o $(APP)-freebsd-x86 main.go

windows-x86:
    @ GOOS=windows GOARCH=386 go build -ldflags=$(LD_FLAGS) -o $(APP)-windows-x86 main.go

run:
    @ LOG_DATE_TIME=1 go run main.go -debug

clean:
    @ rm -f $(APP)-* $(APP) $(APP)*.rpm $(APP)*.deb

test:
    go test -cover -race -count=1 ./...

lint:
    golint -set_exit_status ${PKG_LIST}

integration-test:
    psql -U postgres -c 'drop database if exists miniflux_test;'
    psql -U postgres -c 'create database miniflux_test;'
    go build -o miniflux-test main.go

    DATABASE_URL=$(DB_URL) \
    ADMIN_USERNAME=admin \
    ADMIN_PASSWORD=test123 \
    CREATE_ADMIN=1 \
    RUN_MIGRATIONS=1 \
    DEBUG=1 \
    ./miniflux-test >/tmp/miniflux.log 2>&1 & echo "$$!" > "/tmp/miniflux.pid"

    while ! nc -z localhost 8080; do sleep 1; done
    go test -v -tags=integration -count=1 miniflux.app/tests

clean-integration-test:
    @ kill -9 `cat /tmp/miniflux.pid`
    @ rm -f /tmp/miniflux.pid /tmp/miniflux.log
    @ rm miniflux-test
    @ psql -U postgres -c 'drop database if exists miniflux_test;'

docker-image:
    docker build -t $(DOCKER_IMAGE):$(VERSION) -f packaging/docker/alpine/Dockerfile .

docker-image-distroless:
    docker build -t $(DOCKER_IMAGE):$(VERSION) -f packaging/docker/distroless/Dockerfile .

docker-images:
    docker buildx build \
        --platform linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6 \
        --file packaging/docker/alpine/Dockerfile \
        --tag $(DOCKER_IMAGE):$(VERSION) \
        --push .

rpm: clean
    @ docker build \
        -t miniflux-rpm-builder \
        -f packaging/rpm/Dockerfile \
        .
    @ docker run --rm \
        -v ${PWD}:/root/rpmbuild/RPMS/x86_64 miniflux-rpm-builder \
        rpmbuild -bb --define "_miniflux_version $(VERSION)" /root/rpmbuild/SPECS/miniflux.spec

debian:
    @ docker build \
        --build-arg BASE_IMAGE_ARCH=$(DEB_IMG_ARCH) \
        -t $(DEB_IMG_ARCH)/miniflux-deb-builder \
        -f packaging/debian/Dockerfile \
        --network=host \
        .
    @ docker run --rm \
        -v ${PWD}:/pkg $(DEB_IMG_ARCH)/miniflux-deb-builder

debian-packages: clean
    $(MAKE) debian DEB_IMG_ARCH=amd64
    $(MAKE) debian DEB_IMG_ARCH=arm64v8
    $(MAKE) debian DEB_IMG_ARCH=arm32v7

output of sudo make debian , it hang here for super long time , no response at at all (with VPN connected), then I disconnect VPN , build continues , but still has error (posted below)
sudo make debian
/bin/sh: 1: go: Permission denied
Sending build context to Docker daemon  34.76MB
Step 1/10 : ARG BASE_IMAGE_ARCH="amd64"
Step 2/10 : FROM ${BASE_IMAGE_ARCH}/golang:buster AS build
 ---> addc000ec7ea
Step 3/10 : ENV GO111MODULE=on
 ---> Using cache
 ---> 37bb9dc66b5b
Step 4/10 : ENV GOPROXY=https://goproxy.cn,direct
 ---> Using cache
 ---> de4310f89a71
Step 5/10 : ENV DEBIAN_FRONTEND noninteractive
 ---> Using cache
 ---> 66d006169476
Step 6/10 : RUN apt-get update -q &&     apt-get install -y -qq build-essential devscripts dh-make dh-systemd &&     mkdir -p /build/debian
 ---> Running in 1d212e6d1e38
Get:1 http://deb.debian.org/debian buster InRelease [122 kB]
Get:2 http://security.debian.org/debian-security buster/updates InRelease [65.4 kB]
Get:3 http://deb.debian.org/debian buster-updates InRelease [51.9 kB]
Get:4 http://security.debian.org/debian-security buster/updates/main amd64 Packages [328 kB]
Get:5 http://deb.debian.org/debian buster/main amd64 Packages [7911 kB]
Get:6 http://deb.debian.org/debian buster-updates/main amd64 Packages [8788 B]
Fetched 8486 kB in 1min 9s (124 kB/s)
Reading package lists...

Error messages from 'make debian':
make[1]: Leaving directory '/build'
   dh_systemd_start
   dh_perl
   dh_link
   dh_strip_nondeterminism
   dh_compress
   dh_fixperms
   dh_missing
   dh_strip
   dh_makeshlibs
   dh_shlibdeps
   dh_installdeb
   dh_gencontrol

   dh_md5sums
   dh_builddeb
dpkg-deb: building package 'miniflux' in '../miniflux_2.0.36_amd64.deb'.
 dpkg-genbuildinfo --build=binary
 dpkg-genchanges --build=binary >../miniflux_2.0.36_amd64.changes
dpkg-genchanges: info: binary-only upload (no source code included)
 dpkg-source --after-build .
dpkg-buildpackage: info: binary-only upload (no source included)
warning: the authors of lintian do not recommend running it with root privileges!
cp: cannot create regular file '/pkg/': Not a directory
Makefile:156: recipe for target 'debian' failed
make: *** [debian] Error 1

How can I grant my Docker container for the right permission to run my shell script ?


text:
Q: automatically create folders and hyperlinks I am trying to figure out a way to automatically do

*

*create a folder, with the name used = excel cell value in Column A.

*automatically create a hyperlink to this folder.

The process on my excel worksheet is as follows

*

*Enter Title in Column C (example: C1 value is NAME)

*Then cell A1 is auto-populated based on CONCATENATE of A1 and B1 (fixed content column) (example NAME_1)

At this point in time, I would like to achieve goals 1 & 2 above without having to run a macro every time, with the following deliverables:

*

*a new folder located on the same directory as where my workbook is located.

*a hyperlink is generated in Column G (in our example, it would be in G1).

So far I have gotten to the point of

*

*I can run a macro (either on a cell in Column A, or range within Column A) and this will generate the folders (and subfolders) indeed at the right location. This works :-)

*then, based on the fact that the name of my folder = cell value in the same row/column A - I just type =A(x) (in our example A1) and I have a macro that automatically converts this to a hyperlink to the right location   (combination of didcellchange -->convert to hyperlink). This also works.

I cannot take it to the next level  - what I really want to do is as soon as I enter a Title in Column C, automatically, the workbook detects the change/data entry to Column C and

*

*creates a folder based on the concatenate entry of COLUMN A

*creates a hyperlink to the folder.

OPTIONAL Nice-to-have(s) would be

*

*the macro actually giving an option to navigate to where the folders should be installed.

*hyperlink auto-updating correctly to the correct location (now pointing always to where the current workbook is located - Activeworkbook.path) / or if a link replies with Cannot find folder in specified location, a Browser window opens to update to the correct folder location

I have a suspicion that this might be too complicated to achieve.
If anybody can help with this, I would be extremely grateful - or if you indeed think that I am far too ambitious with this, let me know.
Any ideas?

A: Try this:

*

*Open the VBA editor

*Double click on Sheet(Sheet1) in the VBAProject Window (all the way to the left)
-or- choose Sheet(WhateverYourSheetNameIsJustSelectIt)

*Paste all of the following code in
Public blnFolderFound As Boolean
Option Explicit

Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Function gUsername() As String
Dim lngLen As Long
Dim strBuffer As String
Const dhcMaxUserName = 255
strBuffer = Space(dhcMaxUserName)
lngLen = dhcMaxUserName
   If CBool(GetUserName(strBuffer, lngLen)) Then gUsername = Left$(strBuffer, lngLen - 1)
End Function

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim endRow As Long
Dim rng As Range, c As Range
Dim currPath As String

endRow = Cells(ActiveSheet.Rows.Count, 3).End(xlUp).Row ''Find end row in column C

Set rng = Range(Cells(1, 3), Cells(endRow, 3)) ''check each used cell in column C
 For Each c In rng '' For each cell in range
   If c.Value <> vbNullString And c.Hyperlinks.Count = 0 Then  ''test to see if cell not empty and no hyperlink to speed loop up
 Cells(c.Row, 1).Value = Cells(c.Row, 3).Value & "_" & Cells(c.Row, 2).Value ''concatenate the two values

 ''Test to see if file exists and create on if it doesn't
  currPath = ThisWorkbook.Path
  If currPath = vbNullString Then currPath = "C:\Users\" & gUsername & "\Desktop" ''save folder to desktop if file isn't saved
    folderExists currPath, Cells(c.Row, 1).Value

   ''if the folder is found, move on to the next cell to check
   If blnFolderFound = True Then GoTo nextCellToCheck

   ''if the folder wasn't found and one was created in the folderExists function, add a hyperlink
    ActiveSheet.Hyperlinks.Add Anchor:=c, Address:=currPath & "\" & Cells(c.Row, 1).Value, TextToDisplay:=c.Value

    Else: End If
    nextCellToCheck:
    blnFolderFound = False
Next c

Set rng = Nothing

End Sub

Function folderExists(s_directory As String, s_folderName As String)
Dim obj_fso As Object, obj_dir As Object, obj_folder As Object

Set obj_fso = CreateObject("Scripting.FileSystemObject") '' create a filesystem object
Set obj_dir = obj_fso.GetFolder(s_directory) ''create a folder object

For Each obj_folder In obj_dir.SubFolders '' for each folder in the active workbook's folder
   If obj_fso.folderExists(s_directory & "\" & s_folderName) = True Then blnFolderFound = True: Exit For    ''see if the file exists
Next

If blnFolderFound = False Then obj_fso.CreateFolder (s_directory & "\" & s_folderName) ''if it doesn't exist create one

Set obj_fso = Nothing
Set obj_dir = Nothing

End Function

I added a condition to save to the user's desktop if the file has not been saved. Enter the value to concatenate in column b and then enter the other value in column c. You might have to modify this a little to fit your needs but it should get you pointed in the right direction.


text:
Q: Why Huffman's coding algorithm takes more bit than the original size? My given string is "Today_is_Monday". If I apply Huffman's coding algorithm to this string.
Without encoding, the total size of the string was (15*8) = 120 bits.
After encoding the size is (10*8 + 15 + 49) = 144 bits.
As I know Huffman's algorithm uses to reduce size. But why the encoded size is more than its original?
More details I have done are given below

Thank you.

A: Huffman encoding optimizes the message length, given the frequency table.  What you do with the frequency table is up to you.
Applications for very short messages often assume a static frequency table that both the transmitter and receiver know in advance, so it doesn't have to be transmitted.
Applications that need to send the frequency table often perform additional optimization.  It's possible to communicate the tree by transmitting just the lengths of each symbol in alphabetical order.  The lengths themselves can then be Huffman-encoded.

A: The text is too short and the probability distribution function looks uniform. If the frequencies of occurrence are (more or less) the same, the input string gets very close to random noise. It is impossible to compress random noise in a general way, compression will most likely be longer than the input sequence, because one also need to add some metadata, like an encoding table.
In contrast, consider encoding a string that is: aaaaaaaaaaaaaaa.
If one tries to encode a longer general English text, one would notice at some point, the encoded string size will start to get dramatically shorter than the original text. This is because the encoded sequence frequencies will start to make a much higher impact - the most frequent character will be encoded with the shortest possible code and because it is repeated a lot, its shorter size will dominate the size of the original character.

A: There is no reversible compression algorithm that is guaranteed to compress all possible inputs.  If there was, then you could repeatedly feed it its own output and eventually reduce any input file to 1 bit.  For any initial input file.
Hence, there must be some inputs that cannot be compressed by any particular algorithm.
As others have explained, you have found an input that Hoffman cannot compress.


text:
Q: Export of a realm from a running keycloak docker container fails I am running keycloak v8.0.0 using docker compose file. I am persisting the data into a MySQL database which I am running locally.
  version: '3'
  services:
   keycloak:
    image: jboss/keycloak:8.0.0
    ports:
      - "9999:8080"
    environment:
      KEYCLOAK_USER: admin
      KEYCLOAK_PASSWORD: <ADMIN_PASSWORD>
      DB_VENDOR: mysql
      DB_ADDR: <HOST>
      DB_PORT: <PORT>
      DB_USER: <USER>
      DB_PASSWORD: <PASSWORD>
      JDBC_PARAMS: "useSSL=false"
    volumes:
      - "./realms:/tmp"

I tried exporting a realm from the running docker container by using following command.
docker exec -it kc /opt/jboss/keycloak/bin/standalone.sh \
-Djboss.socket.binding.port-offset=100 -Dkeycloak.migration.action=export \
-Dkeycloak.migration.provider=singleFile \
-Dkeycloak.migration.realmName=my_realm\
-Dkeycloak.migration.usersExportStrategy=REALM_FILE \
-Dkeycloak.migration.file=/tmp/my_realm-realm.json

Below is the stack trace of the error i am getting when I run the above command. When I am running the above command keycloak is not able to connect to database server i.e. MySQL in this case. How to specify database connection configuration in this scenario?
16:30:04,000 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 65) MSC000001: Failed to start service jboss.deployment.unit."keycloak-server.war".undertow-deployment: org.jboss.msc.service.StartException in service jboss.deployment.unit."keycloak-server.war".undertow-deployment: java.lang.RuntimeException: RESTEASY003325: Failed to construct public org.keycloak.services.resources.KeycloakApplication()
        at org.wildfly.extension.undertow@18.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:81)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at org.jboss.threads@2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
        at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
        at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
        at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
        at java.base/java.lang.Thread.run(Thread.java:834)
        at org.jboss.threads@2.3.3.Final//org.jboss.threads.JBossThread.run(JBossThread.java:485)
Caused by: java.lang.RuntimeException: RESTEASY003325: Failed to construct public org.keycloak.services.resources.KeycloakApplication()
        at org.jboss.resteasy.resteasy-jaxrs@3.9.0.Final//org.jboss.resteasy.core.ConstructorInjectorImpl.construct(ConstructorInjectorImpl.java:164)
        at org.jboss.resteasy.resteasy-jaxrs@3.9.0.Final//org.jboss.resteasy.spi.ResteasyProviderFactory.createProviderInstance(ResteasyProviderFactory.java:2784)
        at org.jboss.resteasy.resteasy-jaxrs@3.9.0.Final//org.jboss.resteasy.spi.ResteasyDeployment.createApplication(ResteasyDeployment.java:364)
        at org.jboss.resteasy.resteasy-jaxrs@3.9.0.Final//org.jboss.resteasy.spi.ResteasyDeployment.startInternal(ResteasyDeployment.java:277)
        at org.jboss.resteasy.resteasy-jaxrs@3.9.0.Final//org.jboss.resteasy.spi.ResteasyDeployment.start(ResteasyDeployment.java:89)
        at org.jboss.resteasy.resteasy-jaxrs@3.9.0.Final//org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.init(ServletContainerDispatcher.java:119)
        at org.jboss.resteasy.resteasy-jaxrs@3.9.0.Final//org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.init(HttpServletDispatcher.java:36)
        at io.undertow.servlet@2.0.26.Final//io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:117)
        at org.wildfly.extension.undertow@18.0.0.Final//org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor.init(RunAsLifecycleInterceptor.java:78)
        at io.undertow.servlet@2.0.26.Final//io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:103)
        at io.undertow.servlet@2.0.26.Final//io.undertow.servlet.core.ManagedServlet$DefaultInstanceStrategy.start(ManagedServlet.java:305)
        at io.undertow.servlet@2.0.26.Final//io.undertow.servlet.core.ManagedServlet.createServlet(ManagedServlet.java:145)
        at io.undertow.servlet@2.0.26.Final//io.undertow.servlet.core.DeploymentManagerImpl$2.call(DeploymentManagerImpl.java:585)
        at io.undertow.servlet@2.0.26.Final//io.undertow.servlet.core.DeploymentManagerImpl$2.call(DeploymentManagerImpl.java:556)
        at io.undertow.servlet@2.0.26.Final//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
        at io.undertow.servlet@2.0.26.Final//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
        at org.wildfly.extension.undertow@18.0.0.Final//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
        at org.wildfly.extension.undertow@18.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
        at org.wildfly.extension.undertow@18.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
        at org.wildfly.extension.undertow@18.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
        at org.wildfly.extension.undertow@18.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
        at io.undertow.servlet@2.0.26.Final//io.undertow.servlet.core.DeploymentManagerImpl.start(DeploymentManagerImpl.java:598)
        at org.wildfly.extension.undertow@18.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:97)
        at org.wildfly.extension.undertow@18.0.0.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:78)
        ... 8 more
Caused by: java.lang.RuntimeException: Failed to connect to database
        at org.keycloak.keycloak-model-jpa@8.0.0//org.keycloak.connections.jpa.DefaultJpaConnectionProviderFactory.getConnection(DefaultJpaConnectionProviderFactory.java:372)
        at org.keycloak.keycloak-model-jpa@8.0.0//org.keycloak.connections.jpa.updater.liquibase.lock.LiquibaseDBLockProvider.lazyInit(LiquibaseDBLockProvider.java:65)
        at org.keycloak.keycloak-model-jpa@8.0.0//org.keycloak.connections.jpa.updater.liquibase.lock.LiquibaseDBLockProvider.lambda$waitForLock$2(LiquibaseDBLockProvider.java:96)
        at org.keycloak.keycloak-server-spi-private@8.0.0//org.keycloak.models.utils.KeycloakModelUtils.suspendJtaTransaction(KeycloakModelUtils.java:682)
        at org.keycloak.keycloak-model-jpa@8.0.0//org.keycloak.connections.jpa.updater.liquibase.lock.LiquibaseDBLockProvider.waitForLock(LiquibaseDBLockProvider.java:94)
        at org.keycloak.keycloak-services@8.0.0//org.keycloak.services.resources.KeycloakApplication$1.run(KeycloakApplication.java:178)
        at org.keycloak.keycloak-server-spi-private@8.0.0//org.keycloak.models.utils.KeycloakModelUtils.runJobInTransaction(KeycloakModelUtils.java:227)
        at org.keycloak.keycloak-services@8.0.0//org.keycloak.services.resources.KeycloakApplication.startup(KeycloakApplication.java:171)
        at org.keycloak.keycloak-services@8.0.0//org.keycloak.services.resources.KeycloakApplication.init(KeycloakApplication.java:162)
        at org.keycloak.keycloak-services@8.0.0//org.keycloak.services.resources.KeycloakApplication.<init>(KeycloakApplication.java:143)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
        at org.jboss.resteasy.resteasy-jaxrs@3.9.0.Final//org.jboss.resteasy.core.ConstructorInjectorImpl.construct(ConstructorInjectorImpl.java:152)
        ... 31 more
Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/KeycloakDS
        at org.jboss.ironjacamar.jdbcadapters@1.4.17.Final//org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:159)
        at org.jboss.as.connector@18.0.0.Final//org.jboss.as.connector.subsystems.datasources.WildFlyDataSource.getConnection(WildFlyDataSource.java:64)
        at org.keycloak.keycloak-model-jpa@8.0.0//org.keycloak.connections.jpa.DefaultJpaConnectionProviderFactory.getConnection(DefaultJpaConnectionProviderFactory.java:366)
        ... 45 more
Caused by: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/KeycloakDS
        at org.jboss.ironjacamar.impl@1.4.17.Final//org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:690)
        at org.jboss.ironjacamar.impl@1.4.17.Final//org.jboss.jca.core.connectionmanager.tx.TxConnectionManagerImpl.getManagedConnection(TxConnectionManagerImpl.java:440)
        at org.jboss.ironjacamar.impl@1.4.17.Final//org.jboss.jca.core.connectionmanager.AbstractConnectionManager.allocateConnection(AbstractConnectionManager.java:789)
        at org.jboss.ironjacamar.jdbcadapters@1.4.17.Final//org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:151)
        ... 47 more
Caused by: javax.resource.ResourceException: IJ031084: Unable to create connection
        at org.jboss.ironjacamar.jdbcadapters@1.4.17.Final//org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:345)
        at org.jboss.ironjacamar.jdbcadapters@1.4.17.Final//org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:352)
        at org.jboss.ironjacamar.jdbcadapters@1.4.17.Final//org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:287)
        at org.jboss.ironjacamar.impl@1.4.17.Final//org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.createConnectionEventListener(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:1328)
        at org.jboss.ironjacamar.impl@1.4.17.Final//org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.getConnection(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:499)
        at org.jboss.ironjacamar.impl@1.4.17.Final//org.jboss.jca.core.connectionmanager.pool.AbstractPool.getSimpleConnection(AbstractPool.java:632)
        at org.jboss.ironjacamar.impl@1.4.17.Final//org.jboss.jca.core.connectionmanager.pool.AbstractPool.getConnection(AbstractPool.java:604)
        at org.jboss.ironjacamar.impl@1.4.17.Final//org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:624)
        ... 50 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet successfully received from the server was 97 milliseconds ago.  The last packet sent successfully to the server was 91 milliseconds ago.
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:990)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.ExportControlled.transformSocketToSSLSocket(ExportControlled.java:201)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.MysqlIO.negotiateSSLConnection(MysqlIO.java:4912)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1663)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1224)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2190)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2221)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2016)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:776)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:386)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
        at org.jboss.ironjacamar.jdbcadapters@1.4.17.Final//org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:321)
        ... 57 more
Caused by: javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
        at java.base/sun.security.ssl.HandshakeContext.<init>(HandshakeContext.java:169)
        at java.base/sun.security.ssl.ClientHandshakeContext.<init>(ClientHandshakeContext.java:98)
        at java.base/sun.security.ssl.TransportContext.kickstart(TransportContext.java:216)
        at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:395)
        at com.mysql.jdbc@5.1.46//com.mysql.jdbc.ExportControlled.transformSocketToSSLSocket(ExportControlled.java:186)
        ... 73 more

A: The first solution did not work for me, so I had to investigate further. In my case, the reason was, that the DB_PORT environment variable was not added to the connection string, so keycloak tried to connect to the postgres DB under the dafault port 5432, as seen in this log:
11:29:10,185 ERROR [stderr] (ServerService Thread Pool -- 68) FINE: Connecting with URL: jdbc:postgresql://156149bb-0045-4086-b11a-1b55458b2a5f.blrv234f085n1l00bhrg.private.databases.appdomain.cloud/ibmclouddb?connectTimeout=30&ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory&loggerLevel=DEBUG
[...]
11:29:10,194 ERROR [stderr] (ServerService Thread Pool -- 68) FINE: Trying to establish a protocol version 3 connection to 156149bb-0045-4086-b11a-1b55458b2a5f.blrv234f085n1l00bhrg.private.databases.appdomain.cloud:5432

So I added the Port to the DB_ADDR variable and everything worked fine.

A: I got the same error today,and found is the JDBC_PARAMS format error;
so you can exec in the container,
docker exec -it kc bash

and modify the JDBC_PARAMS
# Append '?' in the beggining of the string if JDBC_PARAMS value isn't empty
export JDBC_PARAMS=$(echo ${JDBC_PARAMS} | sed '/^$/! s/^/?/')

Or redefine JDBC_PARAMS env
export JDBC_PARAMS='?connectTimeout=30&useSSL=false&allowPublicKeyRetrieval=true&characterEncoding=UTF-8'

the key is prefix ? char
then exec
/opt/jboss/keycloak/bin/standalone.sh \
-Djboss.socket.binding.port-offset=100 -Dkeycloak.migration.action=export \
-Dkeycloak.migration.provider=singleFile \
-Dkeycloak.migration.realmName=my_realm\
-Dkeycloak.migration.usersExportStrategy=REALM_FILE \
-Dkeycloak.migration.file=/tmp/my_realm-realm.json

everything is OK!