text:
Q: java websphere MQ My aim is  to put n number of messages in a for loop to a WebSphere MQ queue using WebSphere MQ java programming.
My java program will run as a standalone program.
If any exception in between , I need to rollback all the messages.
If no exception then I should commit all the messages .
The outside world should not see my messages in the queue until I complete fully.
How do I achieve this?
Updated with sample code as per reply from T.Rob:
Please check if sample code is fine ?
Does setting MQGMO_SYNCPOINT  is only related to my program's invocation ?
(because similar programs running parallely will also be putting  messages on the same queue and those messages should not gett affected by my program's SYNCPOINT.)
public void sendMsg() {
        MQQueue queue = null;
        MQQueueManager queueManager = null;
        MQMessage mqMessage = null;
        MQPutMessageOptions pmo = null;
        System.out.println("Entering..");
        try {
            MQEnvironment.hostname = "x.x.x.x";
            MQEnvironment.channel = "xxx.SVRCONN";
            MQEnvironment.port = 9999;

            queueManager = new MQQueueManager("XXXQMANAGER");
            int openOptions = MQConstants.MQOO_OUTPUT;
            queue = queueManager.accessQueue("XXX_QUEUENAME", openOptions, null, null, null);

            pmo = new MQPutMessageOptions();
            pmo.options = CMQC.MQGMO_SYNCPOINT;

            String input = "testing";
            System.out.println("sending messages....");
            for (int i = 0; i < 10; i++) {
                input = input + ": " + i;
                mqMessage = new MQMessage();
                mqMessage.writeString(input);
                System.out.println("Putting message: " + i);
                queue.put(mqMessage, pmo);

            }
            queueManager.commit();
            System.out.println("Exiting..");

        } catch (Exception e) {
            e.printStackTrace();
            try {
                System.out.println("rolling back messages");
                if (queueManager != null)
                    queueManager.backout();
            } catch (MQException e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                if (queue != null)
                    queue.close();
                if (queueManager != null)
                    queueManager.close();
            } catch (MQException e) {
                e.printStackTrace();
            }
        }
    }

A: WMQ supports both local and global (XA) units of work.  The local units of work are available simply by specifying the option.  Global XA transactions require a transaction manager, as mentioned by keithkreissl in another answer.
For what you described, a POJO doing messaging under syncpoint, specify MQC.MQGMO_SYNCPOINT in your MQGetMessageOptions.  When you are ready to commit, issue the MQQManager.commit() or MQQManager.backout() call.
Note that the response and doc provided by ggrandes refers to the JMS and not Java classes.  The Java classes use Java equivalents of the WMQ procedural API, can support many threads (doc) and even provide connection pooling (doc).  Please refer to the Java documentation rather than the JMS documentation for the correct behavior.  Also, I've linked to the WMQ V7.5 documentation which goes with the latest WMQ Java V7.5 client.  The later clients have a lot more local functionality (tracing, flexible install path, MQClient.ini, etc.) and work with back-level QMgrs.  It is highly recommended to be using the latest client and the download is free.

A: you only need to create a session with transaction enabled.
Session session;
// ...
boolean transacted = true;
session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
try {
    // ...do things...
    session.commit();
} catch (Exception e) {
    session.rollback();
}
// ...

WARN-NOTE: Sessions are not thread-safe ;-)

*

*Doc Websphere MQ/JMS

A: If you have access to a transaction manager and more importantly an XATransaction wired up to your MQ access, you can start a transaction at the beginning of your message processing put all the messages on the queue then commit the transaction.  Using the XATransactions it will not put any messages until the transaction commits.  If you don't have access to that, you can do a little more plumbing by placing your messages in a local data object, wrap your code in a try/catch if no exceptions iterate through the local data object sending the messages.  The issue with the later approach is that it will commit all your other processing but if a problem occurs in the sending of messages your other processing will not be rolled back.


text:
Q: How to use case in pivot I want to create a pivot of working hour by department and date.
I had a sql like
select department,sum(workinghours),date group by department,date.
then I write a pivot sql
select * from(
     select department,sum(workinghours) as hours,date group by department,date
        )as RC
    PIVOT
    (
        sum(hours) for date
    )as P

but this return lots of null value. so I update the pivot to
select * from(
         select department,sum(workinghours) as hours,date group by department,date
            )as RC
        PIVOT
        (
            (case when sum(hours) is null then 0 else sum(hours) end) for date
        )as P

then it has error.
I don't understand why, anyone can help?Thx.

A: You need to replace your null with some specific values in sum. As I have replaced 0 instead of null:
create table #t
(
Id int identity (1,1),
Department varchar (100),
WorkingHours int  ,
Date datetime
)

Insert into #t (Department,WorkingHours,Date)
Select '1','10',GETDATE ()-1

Insert into #t (Department,WorkingHours,Date)
Select '1','20',GETDATE ()-1
Insert into #t (Department,WorkingHours,Date)
Select '1',null,GETDATE ()

select * from #t

select * from(
         select department,sum(ISNULL(workinghours,0)) as hours,
         cast (Year(date) as varchar) date
         from #t
         group by department,date
            )as RC
        PIVOT
        (
            sum(hours ) for date  IN ([2018])
        )as P

A: Try below with case when inside sum :
select * from(
         select department,sum(workinghours) as hours,date group by department,date
            )as RC
        PIVOT
        (
            sum(case when hours is null then 0 else hours end) for date
        )as P

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get [] instead of {} in an array in javascript I am fairly new to js/nodejs and I am working on a little webscraper.
I have an array called const itemList = []; and a variable const id = url.split(substring)[1] which i use to get what i need from an url. Then I do itemList.push({id});
The Output looks like this
[
  { id: '330711' }, { id: '328921' },
  { id: '329362' }, { id: '328857' },
  { id: '321511' }, { id: '328897' },
  { id: '342074' }, { id: '341684' },
  { id: '341489' }, { id: '343365' },
  { id: '330711' }, { id: '340324' },
  { id: '342074' }, { id: '342923' },
  { id: '342863' }, { id: '344111' },
  { id: '343005' }, { id: '328857' },
  { id: '328897' }, { id: '328921' },
  { id: '343021' }, { id: '329362' },
  { id: '340047' }
]

But what I need is something like
[
  ['330711'],['328921'],
  ['329362'],['328857'],
  ['321511']
]

So basically, I need to get rid of the "id:" part and [] instead of {}. I don't know what to search for, so I am hoping someone cant get me on the right path here :)
Thanks in advance!

A: You can work with .map method of Array:
Array.prototype.map()

const data = [
  { id: '330711' }, { id: '328921' },
  { id: '329362' }, { id: '328857' },
  { id: '321511' }, { id: '328897' },
  { id: '342074' }, { id: '341684' },
  { id: '341489' }, { id: '343365' },
  { id: '330711' }, { id: '340324' },
  { id: '342074' }, { id: '342923' },
  { id: '342863' }, { id: '344111' },
  { id: '343005' }, { id: '328857' },
  { id: '328897' }, { id: '328921' },
  { id: '343021' }, { id: '329362' },
  { id: '340047' }
];

const mappedData = data.map(item => [item.id])

console.log(mappedData)

Good Luck...


text:
Q: iPad JavaScript Error not helpful I get the following error and iPad but not in desktop browsers:
JavaScript: Error
undefined
TypeError: 'undefined' is not a function

This is a larger js application, and this error message is totally unhelpful. Is there any way I can get the line number of the error or anymore information?
Update: This just got funky.
line : 0
page : undefined
desc : TypeError: 'undefined' is not a function
chr  : undefined

Did the user agent spoofing in FF and safari. No error.

A: If you bind an error handler to window.onerror, it should give you the line number, e.g.
window.onerror = function(msg,url,line) {
   alert('The error is on line '+line);
}

This question: Debug JavaScript errors on iPad seems to indicate you can enable debugging too.
If the script is loaded dynamically, though, it can be hard to get such info in any environment.

A: You could try registering a custom error handler to window.onerror
window.onerror = function (desc,page,line,chr)
{ alert('Line:'+line); }

desc = Error message
page = File/Page where the error occured
line = Well...
chr = Character position of the error in the line


text:
Q: SVN copy between repositories with history One of my teammates has asked if it is possible to export from one SVN to another, all while maintaining history.
To me, this seems like it would be a common request.
So: Is it possible to migrate between SVN repositories all while maintaining history?
It is important to note that we do not have svnadmin access on the Source, but we do have that on the Destination.
If this comes down to just checking out each revision from the source, and checking it in to the destination, we would be OK with that, as long as there was an automated process for that.
EDIT: I forgot to mention that the destination repo is on windows.

A: The way to typically achieve this is the svnadmin dump command.  If you don't have svnadmin access then I would ask the person that does if they can supply you with a dump.  This will make the process of importing much easier as well.
Are you on a shared repository currently?  This might make the person that owns the repository leary of giving you a dump, since it will be a copy of the entire repository, not just your piece of it.

A: I had a similar need (hence visited this page) and ended up writing my own program to do the work. Thought the tool may be useful to others who are still looking for a solution:

*

*The tool needs no admin access to the source repository.

*It supports add/delete/copy/move, preserves node property (e.g. svn:ignore, svn:external) and revision property (i.e., you get the correct author and date/time).

*Can also incrementally copy new revisions.

*Has both GUI and a command line utility.

If anybody is interested, check it out here

A: You can use git-svn (or perhaps another SCM system) to accomplish this task.
The steps would be:
1. Get a git svn clone of each repository:
    git svn clone <SVN-REPOSITORY-FROM> source-repo
    git svn clone <SVN-REPOSITORY-TO> dest-repo

 2. Create patches to be imported:
    cd source-repo/
    export commitFrom=`git log --pretty=%H | tail -1`
    git format-patch -o /tmp/mergepatchs ${commitFrom}..HEAD .

 3. Import the patches
    cd dest-repo/
    git am /tmp/mergepatchs/*.patch

Referenced: http://blog.neutrino.es/2012/git-copy-a-file-or-directory-from-another-repository-preserving-history/

A: [Edit: The original reply below is from pre SVN 1.7, and there this was the best way to solve the problem (although it is not the primary use case of svnsync). In SVN 1.7 client or later there is the svnrdump tool that does more directly what you are trying to achieve)]

use svnsync to synchronize the source to the destination (needs admin access to the destination repository or at least a way to add hooks, but no special access to the source repository). If the destination already has revisions, sync the source to a temporary repository, and then use svn-merge-repos.pl to merge the two local repositories.

A: If you need only a version control repo with full changeset, you can use bzr with bzr-svn plugin.
When you checkout a svn repo, everything will be syncronized.


text:
Q: Using a tangent line to approximate the value of an antiderivative given the graph of the derivative
I am wanting to solve part d. For c, I have the line's equation as $y=-3x+\cfrac{57}{5}$. I am not sure if this is the correct answer.
How can I find the zero indicated in part d if I do not know how to find the equation of the tangent line for x=4? Do I just use x=3?

A: For part c, use the equation of the tangent line at $(3,F(3))$:
$$y-F(3)=F'(3)(x-3)$$
$$
F'(x)=\left(\int_{1}^{x}f(t)\,dt\right)'=f(x)\implies
F'(3)=f(3)=-3
$$
The fact that $f(3)=-3$ follows from the graph.
The last piece of information that we need to find is the value of $F(3)$:
$$F(3)=\int_{1}^{3}f(t)\,dt$$
Again, we're going to use the graph. Notice that on the interval $[1,2]$ $f(t)=2$ and on the interval $[2,3]$ $f(t)=-5t+12$ (given the two points $(2,2)$ and $(3,-3)$, it's not difficult to find the equation of that line):
$$F(3)=\int_{1}^{3}f(t)\,dt=\int_{1}^{2}2\,dt+\int_{2}^{3}(-5t+12)\,dt=\\
2t\bigg|_{1}^{2}-\left[\frac{5t^2}{2}-12t\right]_{2}^{3}=
2\cdot(2-1)-\left[\frac{5\cdot 3^2}{2}-12\cdot 3-\left(\frac{5\cdot 2^2}{2}-12\cdot 2\right)\right]=2-\frac{1}{2}=\frac{3}{2}
$$
So, the equation of the tangent line to the curve $y=F(x)$ at $(3,F(3))$ is going to be:
$$y-\frac{3}{2}=-3(x-3)\implies y=-3x+\frac{21}{2}$$
It's generally assumed that locally a tangent line to a curve at a particular point very well approximates that curve at that point. This idea comes from the fact that near the point of tangency, the tangent line and the curve geometrically lie very close to each other and for approximation purposes we can assume that they're actually equal. So, near the point $x=3$, we can use the line equation that we came up with to find an approximate value for $F(x)=0$:
$$0=-3\cdot x+\frac{21}{2}\implies x=\frac{7}{2}$$
This means that if you take $x=\frac{7}{2}$ and plug it into $F(x)$, the value that you'll get is going to be very close to zero.

A: You are asked to approximate the zero using the equation you found; this means you can approximate the zero of $F$ by the zero of this linear equation. So all you need to do is solve
$$y=-3x+\frac{57}{5},$$
for $y=0$.


text:
Q: How to filter category with custom attribute Magento 2 I added a custom category attribute type yes/no like this:

In eav_attribute table:

the problem is when i filter follow this attribute it return empty array:
$model = $this->categoryFactory->create();
$categories = $model->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('show_category', 1)
->addIsActiveFilter();

Any help? Thank in advance

A:  Try this :-

namespace NameSpace\Module\Block;

    class FeaturedCategories extends \Magento\Framework\View\Element\Template
{

     protected $categoryCollectionFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        array $data = []
    ) {
        $this->categoryCollectionFactory = $categoryCollectionFactory;
        parent::__construct($context, $data);
    }

    public function getFeaturedCategories()
    {
        $collection = $this->categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*')
            ->addAttributeToFilter('show_category', '1');

        return $collection;
    }
}


text:
Q: How to first edit in local Wordpress editor on page and the add code? I started a local WordPress site using DesktopServer. (Atom for coding). And I want to start creating the new website by first creating a "page" in local WordPress and creating a basic layout, and then to find the file and edit it in my code editor.
BUT I can't find the file of the new page I created (don't even know what it would be named) in the folder where my local Wordpress installation is. How can I find it? Or if it does not sync like that, how can I syncronize it?
Any answears would be much appreciated!


text:
Q: Perform auth into another API? Laravel Passport I have developed an Laravel API which uses oauth 2.0 auth with Passport. Almost all the routes defined in api.php are protected with the middleare auth:api, as is explained in the docs (https://laravel.com/docs/9.x/passport) and everything is working fine.
However, for some reasons, I need to change the API where I make the request related to authentication. Namely, I need that all those protected routes be checked in another API that also has Passport.
Can I perform the middleware check to another API? I know that is possible to change the database in the Passport model but I haven't read anything about requesting to another API.
I also have thought creating a new middleware that makes a specific request to that API (for example, a request that verifies that token contained in headers is valid), but I'm not sure of how to do it and if the method Auth::user (this allows to get the information of logged user) will work.
Does anybody have any suggestion?


text:
Q: iOS Segue Issue, all method in the destination controller is called but doesn't show the view I use segue to perform the page jump from table cell in my.
I randomly got this issue in different places in my app. currently two places, the index table view and the setting table view (the setting one occurs first time this morning).
Methods in the destination controller are called according to the log."viewDidLoad","setup fetch result controller"..etc, but the app just stops there, doesn't response to any of my actions any more.
Any idea about that? Thanks in advance.


text:
Q: How do I return to mainline code from a signal handler in assembler? I've been writing a program in NASM for Linux. I'd like to be able to return to the normal code path out of a signal handler that I've established for SIGFPE. Stripped-down sample code is:
section .text

global _start
_start:                  ; --- Enter the program ---
   mov      ebx,8        ; Load the signal to handle (SIGFPE)
   mov      ecx,.handle  ; Load the handler address
   mov      eax,48       ; Load the syscall number for signal
   int      0x80         ; Establish the handler
   mov      ebx,0        ; Prepare a divisor for SIGFPE
   idiv     ebx          ; Divide edx:eax by 0
   mov      ebx,0        ; Set exit status 0 (shouldn't get here)
   jmp      .exit        ; Exit the program

.handle:                 ; --- Handle a divide exception ---
   mov      ebx,31       ; Set exit status 31 (instead of real handling)

.exit:                   ; --- Exit the program ---
   mov      eax,1        ; Load the syscall number for exit
   int      0x80         ; Exit back to the system

Magic numbers are for compactness of code here.
Before the idiv instruction, esp is 0xffffcc00. At entry to the signal handler, esp is 0xffffc52c. Quite a bit of stuff has been put on the stack! There's a welter of information out there about __NR_sigreturn. I've had no luck trying to use it. A ret instruction in the handler just puts me back at the idiv instruction, this time with no handler.
Any ideas about what I can do at the .handle label to get back safely into the mainline?
(I know that sigaction is available, but I'd like to understand what's going on in this situation.)

A: A simple ret will return so as to reattempt the faulting instruction. When using sigaction to register the signal handler with the flag SA_SIGINFO, the third argument is a pointer to a ucontext_t that contains the saved state, which may be altered.


text:
Q: Unable to create session from org.openqa.selenium.remote.NewSessionPayload, with phantomjs and nightwatch.js I am trying to execute my test over Phantom JS in nightwatchjs
 I am using Selenium server with nightwatchjs and cucumber
I took the following link as a reference-
https://github.com/nightwatchjs/nightwatch/wiki/Running-tests-in-PhantomJS
There are other answers as well but none is matching mine. this might be a configuration issue but I am not able to cut it. Can someone please help me out here.
error:
NFO Request: POST /wd/hub/session
 - data:  {"desiredCapabilities":{"browserName":"phantomjs","javascriptEnabled":true,"acceptSslCerts":true,"platform":"ANY","phantomjs.binary.path":"/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs","phantomjs.cli.args":["--ignore-ssl-errors=true"],"silent":false}}
 - headers:  {"Content-Type":"application/json; charset=utf-8","Content-Length":270}
ERROR Response 500 POST /wd/hub/session (482ms) { value:
   { message: 'Unable to create session from org.openqa.selenium.remote.NewSessionPayload@5c510db\nBuild info: version: \'3.12.0\', revision: \'7c6e0b3\', time: \'2018-05-08T15:15:08.936Z\'\nSystem info: host: \'Chirags-MacBook-Pro.local\', ip: \'fe80:0:0:0:142a:4efe:d208:27ae%en0\', os.name: \'Mac OS X\', os.arch: \'x86_64\', os.version: \'10.13.5\', java.version: \'1.8.0_171\'\nDriver info: driver.version: unknown',
     error: 'session not created' },
  status: 33 }
{ Error [ERR_UNHANDLED_ERROR]: Unhandled error. ([object Object])
    at ClientManager.emit (events.js:171:17)
    at Nightwatch.<anonymous> (/Users/prateik/Codebase/NightCuke/node_modules/nightwatch/lib/runner/clientmanager.js:68:10)
    at Object.onceWrapper (events.js:273:13)
    at Nightwatch.emit (events.js:182:13)
    at HttpRequest.<anonymous> (/Users/prateik/Codebase/NightCuke/node_modules/nightwatch/lib/index.js:501:10)
    at HttpRequest.emit (events.js:182:13)
    at IncomingMessage.<anonymous> (/Users/prateik/Codebase/NightCuke/node_modules/nightwatch/lib/http/request.js:172:16)
    at IncomingMessage.emit (events.js:187:15)
    at endReadableNT (_stream_readable.js:1086:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
  context:
   { message: 'Connection refused! Is selenium server started?\n',
     data: { value: [Object], status: 33 } } }

it says driver.version:unknown, can this be the issue?
all the components are at their latest versions
"cucumber": "^4.0.0",
"nightwatch": "^0.9.21",
"nightwatch-cucumber": "^9.1.2",
"phantomjs-prebuilt": "^2.1.16",
"selenium-server": "^3.12.0"

nightwatch.conf.js
    //Nightwatch Configuration

const seleniumServer = require('selenium-server')
const phantomjs = require('phantomjs-prebuilt')
const chromedriver = require('chromedriver')
const geckodriver = require('geckodriver')

require('nightwatch-cucumber')({
    cucumberArgs: [
        '--require-module', 'babel-core/register',
        '--format', 'node_modules/cucumber-pretty',
        '--require', 'hooks.js',
        '--require', 'features/step_definitions',
        '--format-options', '{"colorsEnabled":false}',

  '--format', 'json:reports/cucumber.json',
    'features'
],
nightwatchOutput: true
})

module.exports = {
    // src_folders:'features',
    output_folder: 'reports',
    custom_assertions_path: '',
    page_objects_path: 'page_objects/',
    live_output: true,
    disable_colors: false,

selenium: {
    start_process: true,
    server_path: seleniumServer.path,
    log_path: '/reports',
    host: '127.0.0.1',
    port: 4444,
    cli_args: {
        'webdriver.chrome.driver': chromedriver.path,
        'webdriver.gecko.driver' : geckodriver.path,
        "webdriver.edge.driver" : "",

    }
},
test_settings: {
    default: {
        launch_url: 'http://localhost',
        selenium_port: 4444,
        selenium_host: '127.0.0.1',
        desiredCapabilities: {
            browserName: 'chrome',
            javascriptEnabled: true,
            acceptSslCerts: true,
            silent:false
            //chromeOptions:['start-fullscreen']

        },

        selenium: {},
        screenshots: {
            enabled: true,
            on_failure: true,
            path: 'screenshots'
        }

    },
    phantomjs: {
        //launch_url: 'http://localhost/',
        selenium_port: 4444,
        selenium_host: '127.0.0.1',
        desiredCapabilities: {
            browserName: 'phantomjs',
            javascriptEnabled: true,
            acceptSslCerts: true,
            //platform: 'Mac OS X',
            "phantomjs.binary.path": phantomjs.path,
            "phantomjs.cli.args" : ['--ignore-ssl-errors=true']
        },

    },
    firefox: {
        desiredCapabilities: {
            browserName: 'firefox',
            javascriptEnabled: true,
            acceptSslCerts: true
        }
    }
}

}


text:
Q: How to cancel the windows shortcut key when I use emacs 24.3 in gui in windows? I download the emacs 24.3 in http://ftp.gnu.org/pub/gnu/emacs/windows/
In a gui mode, I found the following trouble. So I want to cancel the windows shortcut key
The 1st example is that I define the shortcut "C-F2" in linux and I also want to use it in windows.
The 2nd example "C-space" makes me to mark things but it is not working in windows. It is obvious that emacs are occupied by the windows shortcuts. How can I cancel the windows shortcut key when I use emacs in windows?

A: I suspect these are not taken by Windows itself, but by your IME. It may be possible to change the keys in the IME Settings.


text:
Q: how to query several MYSQL tables in one statement There are 30 tables(categories) all with the same structure storing news items with a siteID field to filter on a particular client.
The client select which tables(categories) they show by setting the field visible(tinyint) field to 1 or 0.
I have the following test MYSQL which works okay. I am using Applicationcraft.com so the syntax is different than standard MYSQL but you can see the query.
function _getAllData(cObj,p){
var result = [];
console.log('started');
selectObj=cObj.select().from('schoolNews').order('newsIDDESC').where('siteID=?',p.siteID);
result[0] = cObj.exec(selectObj);
selectObj=cObj.select().from('schoolDocs').order('newsIDASC').where('siteID=?',p.siteID);
result[1] = cObj.exec(selectObj);

return result;
}

So I have an array with the results of each table in result[0] & result[1].
So I created the following to :
function _getAllData(cObj,p){

var result = [];

console.log('started');

selectObj=cObj.select().from('schoolNews').order('newsIDDESC').where('siteID=?',p.siteID).where('visible=?',1);

result[0] = cObj.exec(selectObj);
selectObj=cObj.select().from('schoolDocs').order('newsIDASC').where('siteID=?',p.siteID).where('visible=?',1);

result[1] = cObj.exec(selectObj);
selectObj=Obj.select().from('schoolNews_copy').order('newsIDDESC').where('siteID=?',p.siteID).where('visible=?',1);

result[2] = cObj.exec(selectObj);
selectObj=cObj.select().from('schoolNews_copy').order('newsIDDESC').where('siteID=?',p.siteID).where('visible=?',1);

result[3] = cObj.exec(selectObj);
selectObj=cObj.select().from('schoolNews_copy').order('newsIDDESC').where('siteID=?',p.siteID;
result[4] = cObj.exec(selectObj).where('visible=?', 1);

upto result[30].
I have populated schoolNews_copy with 1000 records and run the query from my app.
I am getting a timed out error.
Is this because.

*

*query the same table causes the problem.

*This is the wrong approach all together.
If not what is the best approach.

Is there a way to query every table in a single statement and populate the results into an array named results.
So the result I need is an example array :
result[0] has data visible set to 1
result[1] has data visible set to 1
result[2] has data visible set to 0

A: I have now restructured the table as you said. And using joins can get all the info I need in one query.
SELECT * FROM categories INNER JOIN allNews on allNews.catID = categories.catID WHERE  categories.visible = 1 AND categories.siteID = '+p.siteID;
MrWarby.


text:
Q: T-SQL CLR: Can you CREATE AGGREGATE with optional parameter(s)? I'm hoping to be able to allow optional parameters to be specified, so I can overload the Accumulate() method, can it be done?
I'd like to overload to allow a delimiter to specified, I've seen others where it must force a delimiter to be specified but this behaviour doesn't suit.
CREATE AGGREGATE dbo.Concatenate (@input nvarchar(max), <OPTIONAL PARAMETER HERE>)
RETURNS nvarchar(max)

For reference, here is the aggregate class code that contains the Accumulate() method I'm looking to overload:
using System;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.IO;
using System.Text;

namespace CLR.Utilities {
    /// <summary>
    /// <list type="references">
    ///     <reference>
    ///         <name>How to: Create and Run a CLR SQL Server Aggregate</name>
    ///         <link>http://msdn.microsoft.com/en-us/library/91e6taax(v=vs.90).aspx</link>
    ///     </reference>
    ///     <reference>
    ///         <name>SqlUserDefinedAggregateAttribute</name>
    ///         <link>http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.server.sqluserdefinedaggregateattribute(v=vs.90).aspx</link>
    ///     </reference>
    ///     <reference>
    ///         <name>Invoking CLR User-Defined Aggregate Functions (Provides seed code for this function)</name>
    ///         <link>http://technet.microsoft.com/en-us/library/ms131056.aspx</link>
    ///     </reference>
    /// </list>
    /// </summary>
    [Serializable]
    [SqlUserDefinedAggregate(
        Format.UserDefined,                 //use clr serialization to serialize the intermediate result
        IsInvariantToNulls = true,          //optimizer property
        IsInvariantToDuplicates = false,    //optimizer property
        IsInvariantToOrder = false,         //optimizer property
        MaxByteSize = -1)                   //no maximum size in bytes of persisted value
    ]
    public class Concatenate : IBinarySerialize {
        /// <summary>
        /// The variable that holds the intermediate result of the concatenation
        /// </summary>
        private StringBuilder intermediateResult;

        /// <summary>
        /// Initialize the internal data structures
        /// </summary>
        public void Init() {
            this.intermediateResult = new StringBuilder();
        }

        /// <summary>
        /// Accumulate the next value, not if the value is null
        /// </summary>
        /// <param name="value"></param>
        public void Accumulate([SqlFacet(MaxSize = -1)] SqlString value) {
            if (value.IsNull) {
                return;
            }

            this.intermediateResult.Append(value.Value.Trim()).Append(',');
        }

        /// <summary>
        /// Merge the partially computed aggregate with this aggregate.
        /// </summary>
        /// <param name="other"></param>
        public void Merge(Concatenate other) {
            this.intermediateResult.Append(other.intermediateResult);
        }

        /// <summary>
        /// Called at the end of aggregation, to return the results of the aggregation.
        /// </summary>
        /// <returns></returns>
        [return: SqlFacet(MaxSize = -1)]
        public SqlString Terminate() {
            string output = string.Empty;
            //delete the trailing comma, if any
            if (this.intermediateResult != null
                && this.intermediateResult.Length > 0) {
                output = this.intermediateResult.ToString(0, this.intermediateResult.Length - 1).Trim();
            }

            return new SqlString(output);
        }

        public void Read(BinaryReader r) {
            intermediateResult = new StringBuilder(r.ReadString());
        }

        public void Write(BinaryWriter w) {
            w.Write(this.intermediateResult.ToString().Trim());
        }
    }
}

And here is the code for deployment that I'd like to modify also if optional parameters can be set:
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Concatenate]') AND type = N'AF')
DROP AGGREGATE [dbo].[Concatenate]
GO

IF  EXISTS (SELECT * FROM sys.assemblies asms WHERE asms.name = N'CLR.Utilities' and is_user_defined = 1)
DROP ASSEMBLY [CLR.Utilities]
GO

ALTER DATABASE [DatabaseName] SET TRUSTWORTHY ON
GO

CREATE ASSEMBLY [CLR.Utilities] FROM 'C:\Path\To\File\CLR.Utilities.dll' WITH PERMISSION_SET = UNSAFE
GO

CREATE AGGREGATE [dbo].[Concatenate] (@input nvarchar(max)) RETURNS nvarchar(max)
EXTERNAL NAME [CLR.Utilities].[CLR.Utilities.Concatenate]
GO

GRANT EXECUTE ON [dbo].[Concatenate] TO PUBLIC
GO

A: You could, however, make the parameter mandatory but optionally null. And, in your C# code test whether the value is null and act accordingly. Something like:
public void Accumulate([SqlFacet(MaxSize = -1)] SqlString value, SqlString delimiter) {
        string _delimiter;
        if (value.IsNull) {
            return;
        }

        if (delimiter.IsNull) {
            _delimiter = string.Empty;
        }
        else {
            _delimiter = Delimiter.Value;
        }

        this.intermediateResult.Append(value.Value.Trim()).Append(_delimiter);
    }

A: As far as I know, there's no way to make clr function or aggregate with optional parameters and that's sad.

A: There is a way, though it isn't nice.  You simple add the delimiter to the end of the column you're concatenating with a char(0) between them.  then in the clr, you can look for char(0) and grab the delimiter to use.
-- concat columns delimited by a comma
select grp,dbo.clrConcat(surname) as names
  from people

-- concat column delimited by specified character
select grp,dbo.clrConcat(surname + char(0) + '|') as names
  from people

Then in the clr code
''' <summary>
''' Initialize the internal data structures
''' </summary>
Public Sub Init()
    Me.intermediateResult = New StringBuilder()
    delimiter = ","
End Sub

''' <summary>
''' Accumulate the next value, not if the value is null
''' </summary>
''' <param name="value"></param>
Public Sub Accumulate(ByVal value As SqlString)
    Dim Str As String
    Dim Pos As Integer

    If value.IsNull Then Return

    Pos = value.Value.IndexOf(Chr(0))
    If Pos >= 0 Then
        Str = value.Value.Substring(0, Pos)
        If Pos + 1 < value.Value.Length Then
            delimiter = value.Value.Substring(Pos + 1, 1)
        End If
    Else
        Str = value.Value
    End If

    Me.intermediateResult.Append(Str).Append(delimiter)
End Sub


text:
Q: Unable to run spark-testing-base test with Spark v3.2.1 I was trying to run Spark UT with spark-testing-base and scalatest, getting following exceptions:
[error] sbt.ForkMain$ForkError: java.lang.IncompatibleClassChangeError: Expected instance not static method org.scalatest.Assertions.assertionsHelper()Lorg/scalatest/Assertions$AssertionsHelper;
[error]     at com.holdenkarau.spark.testing.StreamingSuiteBase.verifyOutput(StreamingSuiteBase.scala:77)
[error]     at com.holdenkarau.spark.testing.StreamingSuiteBase.verifyOutput$(StreamingSuiteBase.scala:61)
[error]     at com.central.spark.aggregation.streaming.BaseAggregatorSuite.verifyOutput(BaseAggregatorSuite.scala:23)
[error]     at com.holdenkarau.spark.testing.StreamingSuiteBase.$anonfun$testOperation$1(StreamingSuiteBase.scala:162)
[error]     at com.holdenkarau.spark.testing.StreamingSuiteBase.$anonfun$testOperation$1$adapted(StreamingSuiteBase.scala:158)
[error]     at com.holdenkarau.spark.testing.StreamingSuiteCommon.withOutputAndStreamingContext(StreamingSuiteCommon.scala:122)
[error]     at com.holdenkarau.spark.testing.StreamingSuiteCommon.withOutputAndStreamingContext$(StreamingSuiteCommon.scala:114)
[error]     at com.central.spark.aggregation.streaming.BaseAggregatorSuite.withOutputAndStreamingContext(BaseAggregatorSuite.scala:23)
[error]     at com.holdenkarau.spark.testing.StreamingSuiteBase.testOperation(StreamingSuiteBase.scala:158)
[error]     at com.holdenkarau.spark.testing.StreamingSuiteBase.testOperation$(StreamingSuiteBase.scala:149)
[error]     at com.central.spark.aggregation.streaming.BaseAggregatorSuite.testOperation(BaseAggregatorSuite.scala:23)
[error]     at com.central.spark.aggregation.streaming.BaseAggregatorSuite.$anonfun$new$1(BaseAggregatorSuite.scala:89)
[error]     at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23) (truc)

The dependency and their versions are:
  lazy val coreTestDeps = Seq(
    "org.mockito" % "mockito-all" % 1.10.19 % "test",
    "org.scalatest" %% "scalatest" % 3.2.12 % "it,test",
    "net.sf.opencsv" % "opencsv" % 2.3 % "test",
    "org.json4s" %% "json4s-native" % 3.7.0-M11 % "it,test",
    "org.json4s" %% "json4s-jackson" % 3.7.0-M11 % "it,test",
    "org.apache.spark" %% "spark-streaming" % 3.2.1 % "provided" classifier "tests",
    "org.apache.spark" %% "spark-core" % 3.2.1 % "provided" classifier "tests",
    "com.holdenkarau" %% "spark-testing-base" % "3.2.0_1.1.1" % "test",
    "org.elasticsearch.client" % "elasticsearch-rest-high-level-client" % 7.9.3 % "it,test"
  )

I tried downgrading the org.scalatest to 3.0.9 and other version, But it is not working. Have followings in build.sbt as suggested at spark-testing-base repo:
scalaVersion := "2.12.15",
Test / parallelExecution := false,
Test / fork := true,
javaOptions ++= Seq("-Xms512M", "-Xmx2048M", "-XX:MetaspaceSize=2048M", "-XX:+CMSClassUnloadingEnabled")

Any suggestion on how should i proceed?
Appreciate any help.


text:
Q: matlab: upsampling a zero contour I am using the undocumented contours function in Matlab to obtain the zero contour of a function mapping R^2 to R. The function contours() calls contourc() to obtain the zero contour in terms of array indices, and contours() then performs linear interpolation to convert from (M,N) array indices to (Y,X) data coordinates. This works well and gives a zero contour which is essentially accurate to machine precision. However, attempting to interpolate along this zero contour to obtain additional points fails, apparently because the interpolated points deviate to a small extent from the true zero contour; the resulting error is too large for the intended application.
As a simple example, one can compute a zero contour of the peaks function, compute the function values along the contour, and then compute the function values at new points interpolated along the contour. The maximum error is roughly eps(max(Z(:)) for the points found by countours/countourc and about ten orders of magnitude higher for the interpolated points.
% compute the zero contours; keep part of one contour
[X,Y,Z] = peaks(999);
XY0 = contours(X, Y, Z, [0 0]);
XY0 = XY0(:,140:(XY0(2,1)+1)); % keep only ascending values in the first contour for interpolation

% interpolate points along the zero contour
x2y = griddedInterpolant(XY0(1,:), XY0(2,:), 'linear','none');
X0i = linspace(XY0(1,1), XY0(1,end), 1e4);
Y0i = x2y(X0i);

% compute values of the function along the zero contour
Zi  = interp2(X,Y,Z, XY0(1,:), XY0(2,:), 'linear', NaN);
Z0i = interp2(X,Y,Z, X0i, Y0i, 'linear', NaN);

% plot results
figure;
subplot(1,3,1); plot(XY0(1,:), XY0(2,:), '.'); hold on; plot(X0i, Y0i, 'Linewidth',1);
xlabel('X_0'); ylabel('Y_0'); title('(X_0,Y_0), (X_{0i},Y_{0i})');
subplot(1,3,2); plot(XY0(1,:), Zi, '.');
xlabel('X_0'); ylabel('Z_0'); title('f(X_0,Y_0)');
subplot(1,3,3); plot(XY0(1,:), Zi, '.'); hold on; plot(X0i, Z0i, '.');
xlabel('X_0'); ylabel('Z_0'); title('f(X_{0i},Y_{0i})');

The error is almost certainly because the interpolant does not truly follow the zero contour (i.e., having the same tangent, curvature, and indeed all higher derivatives at each point). Each interpolated point thus deviates to a small degree from the path of the zero contour. This is true for all tested methods of interpolation. If the functional form of the zero contour were known, one could fit a function to the zero contour, which would likely give satisfactory results. However, for the application motivating this question, an analytical solution of the zero contour is not possible.
Given the inadequacy of interpolation to this task, how can new points along the zero contour be obtained? The points should be such that the value of the function is as close to zero as for the set of points returned by contourc. Increasing the grid resolution globally is not an option since the memory and computational expense increase with the square of the resolution. Locally sampling at high resolution in an iterative manner over consecutive short intervals of the zero contour is an option, but would take time to implement, and I'm not aware of existing code (e.g., in the FEX) to perform such a task. Also, since contourc is closed-source, adapting it to this task is not an option.

A: I solved this problem by taking the interpolated (X,Y) values as an approximation of the true zero contour and reinterpolating the Y coordinate of each pair with respect to Z values of the surface flanking the approximate zero in order to locate the Y coordinate at which Z=0 for each (X,Y) pair. In so doing, uniform spacing of the interpolated X values is preserved.
For each (iX,iY) pair, where iX and iY denote the (fractional) array indices of the X and Y coordinate grids for the points interpolated along the zero contour, the approximate iY values are reinterpolated with respect to the values of Z at positions flanking (in the Y dimension) the approximate zero, i.e., at (iX,floor(iY)) and (iX,ceil(iY)). The Z values at these flanking points are themselves obtained by performing bilinear interpolation of Z at these points.
After reinterpolation, the magnitude of the error is the same as that of the points originally returned by contourc/contours.


text:
Q: Why does memtest show a bitflip of the same bit across multiple addresses? I had the unfortunate experience of failing a memtest today, but the results seem a bit peculiar and I have several questions about them. Of course this will probably end in me returning the RAM, but I still want to understand what went wrong.
Memtest log pastebin.
What I noted was peculiar was that across multiple addresses, it was always the last bit of the first byte that failed. Here is a section of the log showing this.

2018-01-27 07:19:35 - [MEM ERROR - Data] Test: 6, CPU: 1, Address: 252A019F8, Expected: FEF7FFFF, Actual: FFF7FFFF
2018-01-27 07:19:35 - [MEM ERROR - Data] Test: 6, CPU: 1, Address: 253201A38, Expected: FEFEFFFF, Actual: FFFEFFFF
2018-01-27 07:19:35 - [MEM ERROR - Data] Test: 6, CPU: 2, Address: 255641A98, Expected: FEF7FFFF, Actual: FFF7FFFF
2018-01-27 07:19:35 - [MEM ERROR - Data] Test: 6, CPU: 2, Address: 255E41CB8, Expected: 00000000, Actual: 01000000
2018-01-27 07:19:35 - [MEM ERROR - Data] Test: 6, CPU: 2, Address: 257641A78, Expected: FEF7FFFF, Actual: FFF7FFFF
2018-01-27 07:19:35 - [MEM ERROR - Data] Test: 6, CPU: 2, Address: 257E41C98, Expected: 00000000, Actual: 01000000
2018-01-27 07:19:35 - [MEM ERROR - Data] Test: 6, CPU: 3, Address: 259201A58, Expected: FEFEFFFF, Actual: FFFEFFFF
2018-01-27 07:19:35 - [MEM ERROR - Data] Test: 6, CPU: 3, Address: 259201B58, Expected: FEEFFFFF, Actual: FFEFFFFF
2018-01-27 07:19:35 - [MEM ERROR - Data] Test: 6, CPU: 3, Address: 259645310, Expected: 01004000, Actual: 00004000
2018-01-27 07:19:36 - [MEM ERROR - Data] Test: 6, CPU: 3, Address: 259A01A18, Expected: FEFFF7FF, Actual: FFFFF7FF
2018-01-27 07:19:36 - [MEM ERROR - Data] Test: 6, CPU: 3, Address: 259A01AD8, Expected: FEFFBFFF, Actual: FFFFBFFF
2018-01-27 07:19:36 - [MEM ERROR - Data] Test: 6, CPU: 3, Address: 25B201A38, Expected: FEFEFFFF, Actual: FFFEFFFF
2018-01-27 07:19:36 - [MEM ERROR - Data] Test: 6, CPU: 3, Address: 25B201B38, Expected: FEEFFFFF, Actual: FFEFFFFF

I tested the RAM across two different computers and resulted in the same error. Do these results tell me anything about the error in internal logic that is happening? I would think it's because a set of bytes share the same addressing logic, but I would expect the failures to be sequential in memory bytes then. Or could it be that the failing bit across all of these addresses is the same and for some reason the same byte is given a different address every rerun?
Secondly, the memtest only failed a few tests, specifically it did not fail tests 0 through 2, even after multiple memtests. I only have basic knowledge of what each test does but I am surprised that the first few tests never resulted in an error. Any reason why?

A: This may be because of the layout described in this Wikipedia article: row hammer.

In dynamic RAM (DRAM), each bit of stored data occupies a separate memory cell […]
Memory cells (blue squares in the illustration) are further organized into matrices and addressed through rows and columns. A memory address applied to a matrix is broken into the row address and column address, which are processed by the row and column address decoders (in the illustration, vertical and horizontal green rectangles, respectively). After a row address selects the row for a read operation (the selection is also known as row activation), bits from all cells in the row are transferred into the sense amplifiers that form the row buffer (red squares in the illustration), from which the exact bit is selected using the column address.

Picture source (public domain)
Hypothesis: there's something wrong with one bit of a certain row buffer (red squares); it affects reading of any row the buffer corresponds to. I'm not claiming it will happen every time, for every row and any written data; yet I believe this matrix form and row buffer (or something similar) have something to do with the fact it's always the last bit of the first byte that failed.

Secondly, the memtest only failed a few tests, specifically it did not fail tests 0 through 2 […]. I am surprised that the first few tests never resulted in an error. Any reason why?

This manual explains what the tests are:

*

*Test 0 [Address test, walking ones, no cache]

Tests all address bits in all memory banks by using a walking ones address pattern.

*

*Test 1 [Address test, own address, Sequential]

Each address is written with its own address and then is checked for consistency. In theory previous tests should have caught any memory addressing problems. This test should catch any addressing errors that somehow were not previously detected. This test is done sequentially with each available CPU.

*

*Test 2 [Address test, own address, Parallel]

Same as test 1 but the testing is done in parallel using all CPUs and using overlapping addresses.

I understand tests 0-2 are designed to catch addressing errors, not necessarily actual data errors. Note if they were able to catch all errors then further testing wouldn't be needed.


text:
Q: capturing pressed keys in c++ windows application i would like to know which keys are pressed in my c++/windows application.
what should i put inside WM_KEYDOWN?
switch (message)
    {
       case WM_KEYDOWN:
           // for example, what should i write to know if "F" key was pressed?
    }

thank you!

A: Try folloiwng:
switch (message)
{
  case WM_KEYDOWN:
    switch (wParam)
    {
      // ...
      case 'F': DoSomething(); break;
      // ...
      case VK_RETURN: DoSomethingElse(); break;
      // ...
    }
    break;
}


text:
Q: not to show full URL on webpage by modifying sql query I created select query in SQL Server Management Studio. One was hyperlink. The hyperlink was clickable. However, the full URL was shown on webpage. Does anyone know how to modify the code below in order not to show full URL? Thanks.
'http://companyname' + Substring(lastPDF.[PDFPath], 14, 50) AS PDFTest


text:
Q: Datatable sorting group rows I have a table with columns : Office, Age, Start date, Salary.
I have created a Datatable by adding a grouping row per Office with as additional information the sum of the ages of the group.  (I wrote my example here : http://live.datatables.net/wuwaxiqe/235/edit)
What I would like to do is when the user clicks on "Age":

*

*Order each element of the group by age -> Done. this is easy by adding the parameter "orderFixed":[[groupColumn, 'asc']].

*Order the groups themselves by total age. In other words here on my example we would have first San francisco (total 632) then London (469) etc ....
I have difficulties on this second point. Thanks !

$(document).ready(function() {
  var groupColumn = 2;
  var table = $('#example').DataTable({
    "columnDefs": [{
      "visible": false,
      "targets": [0, 1]
    }],
    "orderFixed": [
      [groupColumn, 'asc']
    ],
    "order": [
      [groupColumn, 'asc']
    ],
    "displayLength": 25,
    "drawCallback": function(settings) {
      var api = this.api();
      var rows = api.rows({
        page: 'current'
      }).nodes();
      var last = null;

      api.column(groupColumn, {
        page: 'current'
      }).data().each(function(group, i) {
        if (last !== group) {
          let groupRows = api.rows({
            page: 'current'
          }).data().filter(
            function(value, index) {
              console.log(value);
              return value[2] === group;
            }
          );

          let sum_age = 0;
          for (let i = 0; i < groupRows.length; i++) {
            let r = groupRows[i];
            sum_age += parseInt(r[3]);
          }

          $(rows).eq(i).before(
            '
' + group + '	' + sum_age + '
'
          );

          last = group;
        }
      });
    }
  });

  // Order by the grouping
  $('#example tbody').on('click', 'tr.group', function() {
    var currentOrder = table.order()[0];
    if (currentOrder[0] === groupColumn && currentOrder[1] === 'asc') {
      table.order([groupColumn, 'desc']).draw();
    } else {
      table.order([groupColumn, 'asc']).draw();
    }
  });
});
tr.group,
tr.group:hover {
  background-color: #ddd !important;
}

<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />

      Name
      Position
      Office
      Age
      Start date
      Salary

      Tiger Nixon
      System Architect
      Edinburgh
      61
      2011/04/25
      $320,800

      Garrett Winters
      Accountant
      Tokyo
      63
      2011/07/25
      $170,750

      Ashton Cox
      Junior Technical Author
      San Francisco
      66
      2009/01/12
      $86,000

      Cedric Kelly
      Senior Javascript Developer
      Edinburgh
      22
      2012/03/29
      $433,060

      Airi Satou
      Accountant
      Tokyo
      33
      2008/11/28
      $162,700

      Brielle Williamson
      Integration Specialist
      New York
      61
      2012/12/02
      $372,000

      Herrod Chandler
      Sales Assistant
      San Francisco
      59
      2012/08/06
      $137,500

      Rhona Davidson
      Integration Specialist
      Tokyo
      55
      2010/10/14
      $327,900

      Colleen Hurst
      Javascript Developer
      San Francisco
      39
      2009/09/15
      $205,500

      Sonya Frost
      Software Engineer
      Edinburgh
      23
      2008/12/13
      $103,600

      Jena Gaines
      Office Manager
      London
      30
      2008/12/19
      $90,560

      Quinn Flynn
      Support Lead
      Edinburgh
      22
      2013/03/03
      $342,000

      Charde Marshall
      Regional Director
      San Francisco
      36
      2008/10/16
      $470,600

      Haley Kennedy
      Senior Marketing Designer
      London
      43
      2012/12/18
      $313,500

      Tatyana Fitzpatrick
      Regional Director
      London
      19
      2010/03/17
      $385,750

      Michael Silva
      Marketing Designer
      London
      66
      2012/11/27
      $198,500

      Paul Byrd
      Chief Financial Officer (CFO)
      New York
      64
      2010/06/09
      $725,000

      Gloria Little
      Systems Administrator
      New York
      59
      2009/04/10
      $237,500

      Bradley Greer
      Software Engineer
      London
      41
      2012/10/13
      $132,000

      Dai Rios
      Personnel Lead
      Edinburgh
      35
      2012/09/26
      $217,500

      Jenette Caldwell
      Development Lead
      New York
      30
      2011/09/03
      $345,000

      Yuri Berry
      Chief Marketing Officer (CMO)
      New York
      40
      2009/06/25
      $675,000

      Caesar Vance
      Pre-Sales Support
      New York
      21
      2011/12/12
      $106,450

      Doris Wilder
      Sales Assistant
      Sydney
      23
      2010/09/20
      $85,600

      Angelica Ramos
      Chief Executive Officer (CEO)
      London
      47
      2009/10/09
      $1,200,000

      Gavin Joyce
      Developer
      Edinburgh
      42
      2010/12/22
      $92,575

      Jennifer Chang
      Regional Director
      Singapore
      28
      2010/11/14
      $357,650

      Brenden Wagner
      Software Engineer
      San Francisco
      28
      2011/06/07
      $206,850

      Fiona Green
      Chief Operating Officer (COO)
      San Francisco
      48
      2010/03/11
      $850,000

      Shou Itou
      Regional Marketing
      Tokyo
      20
      2011/08/14
      $163,000

      Michelle House
      Integration Specialist
      Sydney
      37
      2011/06/02
      $95,400

      Suki Burks
      Developer
      London
      53
      2009/10/22
      $114,500

      Prescott Bartlett
      Technical Author
      London
      27
      2011/05/07
      $145,000

      Gavin Cortez
      Team Leader
      San Francisco
      22
      2008/10/26
      $235,500

      Martena Mccray
      Post-Sales support
      Edinburgh
      46
      2011/03/09
      $324,050

      Unity Butler
      Marketing Designer
      San Francisco
      47
      2009/12/09
      $85,675

      Howard Hatfield
      Office Manager
      San Francisco
      51
      2008/12/16
      $164,500

      Hope Fuentes
      Secretary
      San Francisco
      41
      2010/02/12
      $109,850

      Vivian Harrell
      Financial Controller
      San Francisco
      62
      2009/02/14
      $452,500

      Timothy Mooney
      Office Manager
      London
      37
      2008/12/11
      $136,200

      Jackson Bradshaw
      Director
      New York
      65
      2008/09/26
      $645,750

      Olivia Liang
      Support Engineer
      Singapore
      64
      2011/02/03
      $234,500

      Bruno Nash
      Software Engineer
      London
      38
      2011/05/03
      $163,500

      Sakura Yamamoto
      Support Engineer
      Tokyo
      37
      2009/08/19
      $139,575

      Thor Walton
      Developer
      New York
      61
      2013/08/11
      $98,540

      Finn Camacho
      Support Engineer
      San Francisco
      47
      2009/07/07
      $87,500

      Serge Baldwin
      Data Coordinator
      Singapore
      64
      2012/04/09
      $138,575

      Zenaida Frank
      Software Engineer
      New York
      63
      2010/01/04
      $125,250

      Zorita Serrano
      Software Engineer
      San Francisco
      56
      2012/06/01
      $115,000

      Jennifer Acosta
      Junior Javascript Developer
      Edinburgh
      43
      2013/02/01
      $75,650

      Cara Stevens
      Sales Assistant
      New York
      46
      2011/12/06
      $145,600

      Hermione Butler
      Regional Director
      London
      47
      2011/03/21
      $356,250

      Lael Greer
      Systems Administrator
      London
      21
      2009/02/27
      $103,500

      Jonas Alexander
      Developer
      San Francisco
      30
      2010/07/14
      $86,500

      Shad Decker
      Regional Director
      Edinburgh
      51
      2008/11/13
      $183,000

      Michael Bruce
      Javascript Developer
      Singapore
      29
      2011/06/27
      $183,000

      Donna Snider
      Customer Support
      New York
      27
      2011/01/25
      $112,000

      Name
      Position
      Office
      Age
      Start date
      Salary

A: You have to add the aggregate value of the location to each entry of that location and then sort by this helper column first. You can use a hidden column for it.
E.g. let's call the column 'officeAge' and add 345 to each row where office is Edinburgh, 469 where office is London and so on. For this you need two runs over the table:

*

*To calculate the aggregate value per office.

*To add the aggregate value to each row.


text:
Q: bullet point in text of plist I have a plist file which contains huge text. In middle of text I have to add bullet points. Is there any way to add bullets in the text like unicode character 2022 and plist will be used in iPad application ?
I googled for this but not found any solution.
Requesting to please provide me answer for this immediately.

A: In mac you can write - bullets = ALT + *


text:
Q: Enable Proguard on Android Library Project I have a standalone Android Library Project and I would like to compile this project with Proguard enabled. I'm using Android Studio 1.0 and I have enabled Proguard with             minifyEnabled true. However after a clean build I get the following error
Error:Execution failed for task ':test_sdk:proguardRelease'.
> java.io.IOException: The output jar is empty. Did you specify the proper '-keep' options?

Any idea on what I'm doing wrong ?

A: I added the following proguard rules
-keep public class * {
    public *;
}

-keepclassmembers class * {
    public *;
}

-keepattributes Exceptions,InnerClasses

It seems to work now


text:
Q: Custom "WHERE" in stored procedure (Informix)? I'm doing the specification for an application that has to search a table with different conditions in the WHERE clause.
For example (not an actual table):
type 1
select name from employees where active = true;

or type 2
select name from employees where idBoss = 3;

I would rather create one stored procedure with a parameter "type" than create two stored procedures with the same code and different "where" clauses.
Is this possible?
Note: I have 2 programmers; one knows only Informix, one knows only .NET.  To minimize problems, I'm doing all the calls to the database with stored procedures so the db programmer and the .net programmer don't have to need each other.

A: You can use dynamic SQL in informix - see this link for more details.
DEFINE v_sql VARCHAR(250);

LET v_sql = "select name from employees";

IF IN_PARAMETER = 1 THEN
   LET v_sql = v_sql || " WHERE active = true"
ELSE
   LET v_sql = v_sql || " WHERE idboss = 3"
END IF;

PREPARE stmt FROM v_sql;
EXECUTE stmt;

FREE stmt;

If you can't use dynamic SQL, the next best thing would be:
IF IN_PARAMETER = 1 THEN
   select name from employees WHERE active = true;
ELSE
   select name from employees WHERE idboss = 3;
END IF;

A: Why create a stored procedure for something this short?
Consider using Linq. Where is just a filter which takes a lambda/function which returns true/false.


text:
Q: Create multiple new columns based on set of previous columns (more efficiently) For my dataset i want to make some new column. These columns consist of a ratio, which is based on two other columns. Here is an example of what i mean:

import random
col1=[0,0,0,0,2,4,6,0,0,0,100,200,300,400]
col2=[0,0,0,0,4,6,8,0,0,0,200,900,400, 500]

d = {'Unit': [1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6],
 'Year': [2014, 2015, 2016, 2017, 2015, 2016, 2017, 2017, 2014, 2015, 2014, 2015, 2016, 2017], 'col1' : col1, 'col2' : col2 }
df = pd.DataFrame(data=d)

new_df = df.groupby(['Unit', 'Year']).sum()

new_df['col1/col2'] = (new_df.groupby(level=0, group_keys=False)
                  .apply(lambda x: x.col1/x.col2.shift())
                 )

           col1  col2      col1/col2
Unit Year
1    2014     0     0       NaN
     2015     0     0       NaN
     2016     0     0       NaN
     2017     0     0       NaN
2    2015     2     4       NaN
     2016     4     6  1.000000
     2017     6     8  1.000000
3    2017     0     0       NaN
4    2014     0     0       NaN
5    2015     0     0       NaN
6    2014   100   200       NaN
     2015   200   900  1.000000
     2016   300   400  0.333333
     2017   400   500  1.000000

however, this is a super simplified df. In reality I have cols 1 through 50. I what i do now feels super INefficient:
col1=[0,0,0,0,2,4,6,0,0,0,100,200,300,400]
col2=[0,0,0,0,4,6,8,0,0,0,200,900,400, 500]
col3=[0,0,0,0,4,6,8,0,0,0,200,900,400, 500]
col4=[0,0,0,0,4,6,8,0,0,0,200,900,400, 500]
col5=[0,0,0,0,4,6,8,0,0,0,200,900,400, 500]
col6=[0,0,0,0,4,6,8,0,0,0,200,900,400, 500]

# data in all cols is the same, just for example.

d = {'Unit': [1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6],
 'Year': [2014, 2015, 2016, 2017, 2015, 2016, 2017, 2017, 2014, 2015, 2014, 2015, 2016, 2017], 'col1' : col1, 'col2' : col2, 'col3' : col3, 'col4' : col4, 'col5' : col5, 'col6' : col6}
df = pd.DataFrame(data=d)

new_df = df.groupby(['Unit', 'Year']).sum()

new_df['col1/col2'] = (new_df.groupby(level=0, group_keys=False)
                  .apply(lambda x: x.col1/x.col2.shift())
                 )
new_df['col3/col4'] = (new_df.groupby(level=0, group_keys=False)
                  .apply(lambda x: x.col3/x.col4.shift())
                 )
new_df['col5/col6'] = (new_df.groupby(level=0, group_keys=False)
                  .apply(lambda x: x.col5/x.col6.shift())
                 )

I do the method for creating a new column 25 times. Can this be done more efficient/
Thank you in advance,
Jen

A: Idea is use DataFrameGroupBy.shift by all columns from list cols2 with divide with filtered DataFrame by list cols1:
col1=[0,0,0,0,2,4,6,0,0,0,100,200,300,400]
col2=[0,0,0,0,4,6,8,0,0,0,200,900,400, 500]

d = {'Unit': [1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6],
 'Year': [2014, 2015, 2016, 2017, 2015, 2016, 2017, 2017, 2014, 2015, 2014, 2015, 2016, 2017],
 'col1' : col1, 'col2' : col2 ,
 'col3' : col1, 'col4' : col2 ,
 'col5' : col1, 'col6' : col2 }
df = pd.DataFrame(data=d)

new_df = df.groupby(['Unit', 'Year']).sum()

cols1 = ['col1','col3','col5']
cols2 = ['col2','col4','col6']
new_df = new_df[cols1] / new_df.groupby(level=0)[cols2].shift().values
new_df.columns = [f'{a}/{b}' for a, b in zip(cols1, cols2)]
print (new_df)
           col1/col2  col3/col4  col5/col6
Unit Year
1    2014        NaN        NaN        NaN
     2015        NaN        NaN        NaN
     2016        NaN        NaN        NaN
     2017        NaN        NaN        NaN
2    2015        NaN        NaN        NaN
     2016   1.000000   1.000000   1.000000
     2017   1.000000   1.000000   1.000000
3    2017        NaN        NaN        NaN
4    2014        NaN        NaN        NaN
5    2015        NaN        NaN        NaN
6    2014        NaN        NaN        NaN
     2015   1.000000   1.000000   1.000000
     2016   0.333333   0.333333   0.333333
     2017   1.000000   1.000000   1.000000

A: have you thought about using Numpy? Pandas is actually based on Numpy, which
is why it works so fast. DFs are amazing, but for deeper or more complicated operations I would just convert it to Numpy, then work with it and convert back to pandas:
...
new_df = df.groupby(['Unit', 'Year']).sum()
new_array = new_df.values
print(type(new_array))

[out]: <type 'numpy.ndarray'>

Good luck


text:
Q: How I can set option value from select form to extbase controller In fluid I have select form
<f:form action="cityList" controller="City">
    <f:form.select
        class="js-select"
        property="city"
        name="cityId"
        options="{cityList}"
        optionLabelField="title"
        optionValueField="uid" />
    <f:form.submit value="Submit" />
</f:form>

In controller
/**
 * action city list
 *
 *
 * @return void
 */
public function cityListAction()
{

    $cityList = $this->cityRepository->findAll();
    $this->view->assign('cityList', $cityList);

    $cityData = $GLOBALS['TSFE']->fe_user->setKey('ses', 'citySessionData', $cityId);
    $cityData = $GLOBALS["TSFE"]->fe_user->getKey('ses', 'citySessionData');
    echo $cityData;
}

But I don't have any data. If I set manual $cityId, I have session data. How I can set city id from form to $cityId

A: Your  is not bound to an object so the  cannot use the propery property="city" correctly. Your listAction is also not expecting to get any parameters passed to it.
Please change the ViewHelpers accordingly:
<f:form action="cityList" controller="City" objectName="filter" object="{filter}">
  <f:form.select
        class="js-select"
        property="cityId"
        options="{cityList}"
        optionLabelField="title"
        optionValueField="uid" />
    <f:form.submit value="Submit" />
</f:form>

In the HTML output, the select field should become a name like name="tx_yourext_yourplugin[filter][cityId]". This is very important because otherwise the form values wont be submitted to your action.
Then change your Action:
/**
 * action city list
 * @param array $filter
 * @return void
 */
public function cityListAction($filter = [])
{

    $cityList = $this->cityRepository->findAll();
    $this->view->assign('cityList', $cityList);
    // Give $filter back to view so it will stay selected
    $this->view->assign('filter', $filter);

    $cityData = $GLOBALS['TSFE']->fe_user->setKey('ses', 'citySessionData', $filter['cityId']);
    $cityData = $GLOBALS["TSFE"]->fe_user->getKey('ses', 'citySessionData');

    // You shall not use echo in TYPO3
    // echo $cityData;
    \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($cityData);
}

I did not test this!
After changing the action you must clear the cache using the installtool or reinstall the extension.


text:
Q: Best Way to Update Multi-dimensional Array Value Using another Array with Key as the value being looked for and the value for what replaces it I have a a Multidimensional array with a lot of content that includes a label for each piece of content, and I have a separate array with a Key that is the label being searched for and the value that is to replace it.
I want to use the second array to replace nested label values in the first array. The function should find the first Array's label value based on the key of the second array, and replace it using that Key's value.
For Example the content Array:
Array
(
    [Name] => Array
        (
            [0] => Array
                (
                    [label] => Name
                    [content] => Important Paper
                )

            [1] => Array
                (
                    [label] => Item Type
                    [content] => Document
                )

            [2] => Array
                (
                    [label] => Author
                    [content] => Bob Jones
                )
        )

    [date] => Array
        (
            [0] => Array
                (
                    [label] => Date
                    [content] => 2009
                )
        )
)

And an example of the array looking to replace the value
Array
(
    [Name] => Record
    [Author] => Researcher
    [Date] => Year
)

The output I would want from this function would resemble
Array
(
    [Name] => Array
        (
            [0] => Array
                (
                    [label] => Record
                    [content] => Important Paper
                )

            [1] => Array
                (
                    [label] => Item Type
                    [content] => Document
                )

            [2] => Array
                (
                    [label] => Researcher
                    [content] => Bob Jones
                )
        )

    [date] => Array
        (
            [0] => Array
                (
                    [label] => Year
                    [content] => 2009
                )
        )
)

Right now I am attempting to get the results by using a series of forloops and if statements. I don't actually know the depth that the [label] key will be found at, and it should only update content with the key value [label].
Any insight on a way to do this more efficiently would be great. I've also been looking at all of the different php array functions and trying to find the best combinations.

A: you can use: array_walk_recursive
from:
php.net
$orig = array('Name' => [['label' => 'Name', 'content' => 'Important Paper'],
                         ['label' => 'Item Type', 'content' => 'Document'],
                         ['label' => 'Author', 'content' => 'Bob Jones']],
              'date' => [[['label' => 'Date', 'content' => '2009']]]);

// notice the `&` symbol, this allows us to change the original array on the fly
function replaceIt(&$item){
    $replaceArray = ['Name' => 'Record',
                     'Author' => 'Researcher',
                     'Date' => 'Year'];

    foreach ($replaceArray as $key => $value) {
        if($key == $item){ $item = $value; }
    }
}

array_walk_recursive($orig, 'replaceIt');

print('<pre>');
print_r($orig);
print('</pre>');


text:
Q: Creating users in 389 Directory Server: Autofill UID & GID I have a 389 Directory Server cluster as ldap.
I can create users using 389 management console but...
When Selecting "Posix User" tab and checking "Enable Posix User Attributes" is necessary manually fill "UID Number" and "GID Number" fields.
Can be configure 389 Directory Server to this fields be filled in automatic way?
Thanks.


text:
Q: If $\Gamma$ is consistent and $\Gamma\not\vdash\phi$, then $\Gamma\cup\{\neg\phi\}$ is also consistent. Why? I read this answer, but was a bit confused by one of the deductions. It is stated that for some first-order theory $\Gamma$ and statement $\phi$:

If $\Gamma$ is consistent and $\Gamma\not\vdash\phi$, then $\Gamma\cup\{\neg\phi\}$ is also consistent.

This looks natural at first, and the author stated that this is by definition. But for me it is far from obvious that $\neg\phi$ cannot be used to deduce $\phi$ when combined with the other axioms in $\Gamma$. Can someone explain? Am I missing some definition or an obvious point?

A: I came across a solution while writing the question when the key word Deduction Theorem popped up in the side bar. This was not as trivial (for me) as initially assumed. So I decided to give a self-answer, but I am open for answers which show that this may be far more obvious. Especially the "by definition" part in the mentioned answer seems to me like an over-simplification now.

The Deduction Theorem states

If $\Gamma\cup\{\phi\}\vdash\psi$, then $\Gamma\vdash \phi\to\psi$.

Using this result, we can justify the deduction in question.
Assume $\Gamma\cup\{\neg\phi\}$ is inconsistent and therefore proves $\phi$. The Deduction Theorem gives that we can conclude $\Gamma\vdash \neg\phi\to\phi$. This latter statement is equivalent to $\phi\lor\phi$ $-$ or simply $\phi$. So there is a proof of $\phi$ from $\Gamma$ alone. $\;\square$

A: Please note that you are asking two different questions here.
At some point you ask why you wouldn't be able to deduce $\phi$ when adding $\neg \phi$ to $\Gamma$...and how the author of the post you are referring to shows that 'by definition'. Well, the definition used here is that a set of statements is consistent if and only there is no statement such that that statement as well as the negation of that statement can be derived from that set of statements. Hence, since it is obvious that $\neg \phi$ can be derived from $\Gamma \cup \{ \neg \phi \}$, then the consistency of $\Gamma \cup \{ \neg \phi \}$ implies that $\phi$ cannot be derived from $\Gamma \cup \{ \neg \phi \}$, let alone from $\Gamma$ alone.
Ok, but note that the latter result is the converse of what you ask earlier in your post, and what you ask of in the title of your post and, for that matter, what the author should have argued for, which is that if $\Gamma \not \vdash \phi$ then $\Gamma \cup \{ \neg \phi \}$ is consistent. Indeed, it is likely that you are confused about the Answer you are referring to since it is in fact not a good answer to the question that was asked there. Ok, so then how do you show what needs to be shown? Well, see the answer by @M.Winter for one good answer!

A: Note that the above argument use nonconstructive law of reductio ad absurdum:
Let $X\cup\{\neg\varphi\}$ be an inconsistent set of formulas. Then $X\cup\{\neg\varphi\}\vdash\varphi $, so Deduction Theorem gives: $X\vdash\neg\varphi\rightarrow\varphi $. But reductio ad absurdum  $(\neg\varphi\rightarrow\varphi)\rightarrow \varphi $ is clasically valid, so by Modus Ponens, $X\vdash\varphi $. $\blacksquare$
This theorem is not true in Intuitionistic Logic. Indeed, $\not\vdash_{INT}p\vee\neg p$, but $\{\neg(p\vee\neg p)\}$ is inconsistent:
suppose that there is a finite Kripke model $K$, and a world $x\in K$, such that $x\Vdash \neg(p\vee\neg p)$. Then taking a maximal element $y$ over $x$, we have $y\not\Vdash p\vee\neg p$, which is mpossible. $\blacksquare$
In Intuitionistic Logic the weaker form holds: If  $X\cup\{\varphi\}$ is inconsistent, then $X\vdash_{INT}\neg\varphi $.


text:
Q: Does power only apply to the present and future? Does power only apply to the present and future?
What is different about this noun(power), why don't other nouns act this way? For example: (not real person) Frank was a billionaire and mayor 5 years ago.  However 4 years ago, his wealth plummeted due to bad investments, and he is no longer mayor.  In fact Frank is now living on the streets homeless.  One might say, "He is successful.  He used to be a billionaire and mayor.  Its weird seeing him homeless."  But they wouldn't say, "He is powerful.  He used to be a billionaire and mayor.  Its weird seeing him homeless."

A: One would normally say that "Frank was successful", and "Frank was powerful".  Tense is an aspect of English verbs, not nouns. There is no difference between "successful" and "powerful" here.
One might rhetorically say "Frank is successful", perhaps to imply that he has made a success of living rough, or to say that "success is not about money." However, this is a deliberately surprising use of the word "successful".


text:
Q: How can I set a background picture on my window in Tkinter in Python? This is the code setting the Background:
'''
Background picture:

'''
background_image=tk.PhotoImage("blood_PNG6140.png")
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

I am getting this Error:
Traceback (most recent call last):
  File "/Users/Lana/Desktop/Zaid/End_Projekt_MakE_YouR_ChoicE_zaid_zaim ON MAC/MakeYourChoice.py", line 275, in <module>
    background_image=tk.PhotoImage("blood_PNG6140.png")
NameError: name 'tk' is not defined
>>>

Thank you in advance!
ZZaim

A: You forgot to import tkinter. Place
import tkinter as tk

in the header of your .py file.

A: Add import tkinter as tk to the top of your code


text:
Q: How to gracefully close a two-way WebSocket in .Net I have a WebSocket server that accepts a stream of binary data from a client and responds with another stream of text data for every 4MB read. The server uses IIS 8 and asp.net web api.
Server
public class WebSocketController : ApiController
{
    public HttpResponseMessage Get()
    {
        if (!HttpContext.Current.IsWebSocketRequest)
        {
            return new HttpResponseMessage(HttpStatusCode.BadRequest);
        }

        HttpContext.Current.AcceptWebSocketRequest(async (context) =>
        {
            try
            {
                WebSocket socket = context.WebSocket;

                byte[] requestBuffer = new byte[4194304];
                int offset = 0;

                while (socket.State == WebSocketState.Open)
                {
                    var requestSegment = new ArraySegment<byte>(requestBuffer, offset, requestBuffer.Length - offset);
                    WebSocketReceiveResult result = await socket.ReceiveAsync(requestSegment, CancellationToken.None);

                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        // Send one last response before closing
                        var response = new ArraySegment<byte>(Encoding.UTF8.GetBytes("Server got " + offset + " bytes\n"));
                        await socket.SendAsync(response, WebSocketMessageType.Text, true, CancellationToken.None);

                        // Close
                        await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                        break;
                    }

                    offset += result.Count;
                    if (offset == requestBuffer.Length)
                    {
                        // Regular response
                        var response = new ArraySegment<byte>(Encoding.UTF8.GetBytes("Server got 4194304 bytes\n"));
                        await socket.SendAsync(response, WebSocketMessageType.Text, true, CancellationToken.None);
                        offset = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                // Log and continue
            }
        });

        return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
    }
}

The c# client uses the ClientWebSocket class to connect to the server and send requests. It creates a task for receiving responses from the server that runs in parallel with the request sending. When it is done sending the requests it calls CloseAsync on the socket and then waits for the Receive task to complete.
Client
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebSocketClient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                CallWebSocketServer().Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        static async Task CallWebSocketServer()
        {
            using (ClientWebSocket socket = new ClientWebSocket())
            {
                await socket.ConnectAsync(new Uri("ws://localhost/RestWebController"), CancellationToken.None);
                byte[] buffer = new byte[128 * 1024];

                Task receiveTask = Receive(socket);
                for (int i = 0; i < 1024; ++i)
                {
                    await socket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Binary, true, CancellationToken.None);
                }

                await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                receiveTask.Wait();

                Console.WriteLine("All done");
            }
        }

        static async Task Receive(ClientWebSocket socket)
        {
            try
            {
                byte[] recvBuffer = new byte[64 * 1024];
                while (socket.State == WebSocketState.Open)
                {
                    var result = await socket.ReceiveAsync(new ArraySegment<byte>(recvBuffer), CancellationToken.None);
                    Console.WriteLine("Client got {0} bytes", result.Count);
                    Console.WriteLine(Encoding.UTF8.GetString(recvBuffer, 0, result.Count));
                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        Console.WriteLine("Close loop complete");
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in receive - {0}", ex.Message);
            }
        }
    }
}

The problem is that the client blocks at the CloseAsync call.
What would be the correct way of gracefully closing the WebSocket in this scenario?

A: Figured this out.
Server
Basically, I had to call the ClientWebSocket.CloseOutputAsync (instead of the CloseAsync) method to tell the framework no more output is going to be sent from the client.
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);

Client
Then in the Receive function, I had to allow for socket state WebSocketState.CloseSent to receive the Close response from the server
static async Task Receive(ClientWebSocket socket)
{
    try
    {
        byte[] recvBuffer = new byte[64 * 1024];
        while (socket.State == WebSocketState.Open || socket.State == WebSocketState.CloseSent)
        {
            var result = await socket.ReceiveAsync(new ArraySegment<byte>(recvBuffer), CancellationToken.None);
            Console.WriteLine("Client got {0} bytes", result.Count);
            Console.WriteLine(Encoding.UTF8.GetString(recvBuffer, 0, result.Count));
            if (result.MessageType == WebSocketMessageType.Close)
            {
                Console.WriteLine("Close loop complete");
                break;
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception in receive - {0}", ex.Message);
    }
}

A: i suggest you to look at these links:
asynchronous server:
https://msdn.microsoft.com/en-us/library/fx6588te%28v=vs.110%29.aspx
asynchronous client:
https://msdn.microsoft.com/en-us/library/bew39x2a(v=vs.110).aspx
recently i implementled something similar with these links as an example. the methods "BeginReceive" (for server) and "BeginConnect" (for client) start each a new thread. so there won't be anything that blocks


text:
Q: jquery hide/show table / tr questions I have a table where by each row will have links and there will be a hidden row underneath it which should be opened upon clicking the link

      03/09/3012

        £66.36

        -£628.74

        Housing Benefit Direct

I am looking for the jquery so as any link with the class link_x will toggle the row desc_x
can anyone help please ?

A: Remove the id portion of the class name in the markup:
03/09/3012

and

Then use this JS:
$(".link").click(function(e){
    e.preventDefault();
    $(this).parents("tr").next("tr").show();
});

JS Fiddle: http://jsfiddle.net/3RJJe/2/


text:
Q: If $x$ and $y$ are conjugates, and $H_1$ the smallest normal subgroup containig $x$ and $H_2$ that containing $y$. Show that $|H_1| = |H_2|$ Problem:

If $x$ and $y$ are conjugates, show that the order of the smallest normal
  subgroup containing $x$ equals the order of the smallest normal subgroup
  containing $y$.

I proved (maybe wrongly) that $H_1 = H_2$, and not that $|H_1| = |H_2|$, so I would like some guidance here.
My attempt:
Let $H_1 \subset G$ be the smallest normal group containing $x$ and $H_2 \subset G$ the smallest subgroup containing $y$.
By definition (I am going to say ''definition'', but in my lectures notes it is actually a theorem) $H_1$ is normal $\iff \big[(\forall x \in H_1)(\forall g\in G) \implies gxg^{-1}\in H_1\big] \implies y \in H_1 \implies H_1 \subset H_2$.
On the other hand $H_2$ is normal $\iff \big[(\forall y \in H_2)(\forall g\in G) \implies gyg^{-1}\in H_2\big] \implies $ $\implies x \in H_2 \implies H_2 \subset H_1$.
Thus we have that $H_1 = H_2 \implies |H_1| = |H_2|$.

A: You're right. Easy argument: intersection of all normal subgroups containing subset $X \subset G$  is indeed the smallest one with such property and unique (it's usually called the normal closure of a subset). So if $x = g^{-1}yg$, then $y$ lies in normal closure of $x$ and vise versa.
("Theorem" you're referring to is probably telling that if you define normal subgroups as kernels of homomorphisms, then they are precisely those which are invariant under conjugation.)


text:
Q: Porqué no se ven los estilos en mi página?

<title></title>
<meta charset="utf-8">
<link rel="stilesheet" type="text/css"href="estilos.css">

        Marca
        Modelo

      Audi
      A3

      Audi
      A8

      Ford
      Fiesta

      Peugeot
      306

      Peugeot
      1008

       Listado de coches

y la hoja de estilos:
table {
  width: 300px;
   text-align:center;
   border-collapse: collapse;
 }

table, th, td {
border: 1 px solid black;
}

t foot, thead {
font-weight: bold;
background-color:orange;
}

.az{
  background-color: blue;
}

.cel{
  background-color: skyblue;

}

A: El problema es que en el tag link escribiste mal el rel, el atributo href está pegado al atributo anterior y en el CSS tfoot está mal escrito.
Así funciona bien:

table {
  width: 300px;
   text-align:center;
   border-collapse: collapse;
 }

table, th, td {
border: 1 px solid black;
}

tfoot, thead {
font-weight: bold;
background-color:orange;
}

.az{
  background-color: blue;
}

.cel{
  background-color: skyblue;

}

<title></title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css"href="estilos.css">

        Marca
        Modelo

      Audi
      A3

      Audi
      A8

      Ford
      Fiesta

      Peugeot
      306

      Peugeot
      1008

       Listado de coches

¡Suerte!


text:
Q: Django formsets, How do I create an index of checkboxes for selecting db items to delete? I have been RTFM for maybe three weeks solid and I cannot figure out how to do this. If I ever get good at this then I promise I will write a Django for Dummies book, the documentation is incomprehensible!
I have a simple note taking app with an index page that displays the title of each note in the database. I just want each item in the list to have a checkbox so you can select one or multiple notes and then press a delete button, redirect to an 'Are you sure you want to delete... "x, y and z" notes? page, with confirm or deny. Then back to the index list. Just like in the admin app.
I have deduced that I should need a modelformset layed out in a table as each object title and it's checkbox should constitute an individual form.
I have tried many approaches. The latest looks like this. It's not throwing any errors as it stands(I had a widgets attribute set in the forms.py function but it didn't like that. I took it out just to see if it would display something.) But it is not displaying anything at all. I also think the select_note_function should probably be a class instead. All the docs I can find explain CharFields and string inputs. I cant find a single fully fledged example of how to get widgets controlling the database.
forms.py:
from django import forms
from django.forms.models import modelformset_factory
from django.forms.widgets import CheckboxInput
from models import Note

def select_note_formset():
    SelectNote = modelformset_factory(Note)
    Form = modelformset_factory(
        Note,
        form=SelectNote,
        fields='title',

)

models.py:
def selection_index(request):
form = select_note_formset()
if request.method == 'POST':
    formset = form(request.POST)
    if formsest.is_valid():
        pass

else:
    formset=form
return render_to_response('select_index.html', {'formset':formset})

template:
<form method="post" action="">
  {{ formset.management_form }}
  <table>
    {% for form in formset %}
    {{ form }}
    {% endfor %}
  </table>
</form>

For all I know I could be barking up the totally wrong tree. If someone could spell this out I would appreciate it terribly!

A: I have a gist for this, I just figured it out for myself last week:
https://gist.github.com/bjb/5717314
In a nutshell:  make a new field type for a model that includes a hidden input for the model id and validates to the full model, put it in your form, and make a formset of these forms.
In my own search for the solution, people told me to use CheckboxSelectMultiple, but I didn't like that route because I would have had to put each model description into a single string.  I wanted to list the model attributes as columns, and also (I haven't tried this yet) optionally show some related models after each model.  So I wanted more control over the display than CheckboxSelectMultiple would have given me.
After a year or two you get the hang of the documentation ; -).  Also, don't be afraid to read the source code of django.


text:
Q: Using Tapjoy Adobe AIR sdk I wish to use Tapjoy in my Adobe AIR iOS project. However I have no clue how to integrate it in my app. The documentation provided by them is very poor and difficult to understand. Following is what I have done till now :
1 . Added required ANE and swc to the project.
2. Added following imports in my code
import com.tapjoy.extensions.ITapjoyConnectRequestCallback;
import com.tapjoy.extensions.TapjoyAIR;
import com.tapjoy.extensions.TapjoyEvent;
import com.tapjoy.extensions.TapjoyMacAddressOption;
import com.tapjoy.extensions.TapjoyPointsEvent;
import com.tapjoy.extensions.TapjoyTransition;
import com.tapjoy.extensions.TapjoyViewChangedEvent;
import com.tapjoy.extensions.TJEvent;
import com.tapjoy.extensions.ITJEventCallback;
import com.tapjoy.extensions.TJEventRequest;

*Inside Constructor checked for the Platform
if (Capabilities.manufacturer.search("iOS") != -1)
    {
        // iOS platform
        // If you are not using Tapjoy Managed currency, you would set      your own user ID here.
        //  connectFlags["TJC_OPTION_USER_ID"] ="A_UNIQUE_USER_ID";

        // You can also set your event segmentation parameters here.
        //  var segmentationParams:Object = { "iap": true }
        //  connectFlags["TJC_OPTION_SEGMENTATION_PARAMS"] = segmentationParams;

        // Enable logging
        connectFlags["TJC_OPTION_ENABLE_LOGGING"] = true;

        // Pass option to toggle the collection of MAC address
        connectFlags["TJC_OPTION_COLLECT_MAC_ADDRESS"] = TapjoyMacAddressOption.MacAddressOptionOffWithVersionCheck;

        TapjoyAIR.requestTapjoyConnect("13b0ae6a-8516-4405-9dcf-fe4e526486b2", "XHdOwPa8de7p4aseeYP0", connectFlags);
        //trace("" + connector);
    }
    else
    {
        // Android platform

        // If you are not using Tapjoy Managed currency, you would set your own user ID here.
        //  connectFlags["user_id"] ="A_UNIQUE_USER_ID";

        // You can also set your event segmentation parameters here.
        //  var segmentationParams:Object = { "iap": true }
        //  connectFlags["segmentation_params"] = segmentationParams;

        // Enable logging
        connectFlags["enable_logging"] = true;

        TapjoyAIR.requestTapjoyConnect("bba49f11-b87f-4c0f-9632-21aa810dd6f1", "yiQIURFEeKm0zbOggubu", connectFlags);
        //isAndroid = true;
    }

*Next I need to show theOfferWall if connection to Tapjoy has succeded. How do I do that?

A: Add listeners to the object (as defined in docs):
You must call requestTapjoyConnect before any other Tapjoy methods, ex:
TapjoyAIR.requestTapjoyConnect("YOUR_TAPJOY_APP_ID_HERE", "YOUR_TAPJOY_SECRET_KEY_HERE");

extension = TapjoyAIR.getTapjoyConnectInstance();

Register an event listener for all the events you want to capture, ex:
extension.addEventListener(type, function, …);

You can find all Tapjoy AIR events defined in TapjoyEvent, TapjoyDisplayAdEvent and TapjoyPointsEvent.


text:
Q: Let F denote $M(R)$, the set of all mappings $f : \mathbb{R} \rightarrow \mathbb{R}$, made into a group Let F denote $M(\mathbb{R})$, the set of all mappings $f : \mathbb{R} \rightarrow  \mathbb{R}$, made into a group
Let
$$H= \{ f \in F : f(x) \in  \mathbb Z   \mbox{ for each } x
 \in \mathbb{R} \}$$
prove that $H$ is a subgroup of $F$. State clearly the properties of $\mathbb Z$ that you use.
to prove that we need to check that:

*

*H is not empty

*if $a,b \in z $ then $a*b \in H$

*if $a \in H$ then $a^{-1} \in H$
I confused how to prove that H is not empty.


text:
Q: su: Cannot make/remove an entry for the specified session After configuring the 2 factor authentication I can't login to another user on Ubuntu 14.04.
The changes which I made for 2 factor authentication is

*

*edit /etc/pam.d/sshd; insert at the top this file:
auth required pam_google_authenticator.so

*edit /etc/pam.d/common-auth; insert before the pam_unix line:
auth required pam_google_authenticator.so

Only if I comment out these lines can I login as another user.

A: You have to add every user you want to authenticate with to your Google Authenticator app.
What I suggest is first add 2FA for your root user. From root you can su to any account without authentication at all. So when you have 2FA for root you just su to each user and then exit.
If you don't want to have 2FA for root you can check out this tutorial - section "Setting up the app" shows you what to do if you already have 2FA for one user.


text:
Q: can't save picture result within my apps own folder im trying to create an application that saves pictures and videos in
/storage/emulated/0/Android/data/com.example.appname/files
this is the code for the storage path:
"
lateinit var appFolder: File
appfolder=this.getExternalFilesDir(null)?.path"
and this is the method run when i press a button with a camera icon:
"
private var resultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
adapter.setFilesAndFolder(getFileAndFolder())
}
refreshData()
}
private fun openCameraApp() {
val photoURI: Uri = FileProvider.getUriForFile(
this,
"com.example.android.fileprovider",
        appFolder
    )
    refresh()
    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
    resultLauncher.launch(cameraIntent)
}"


text:
Q: How can remove first letters from a name in smarty? This code find my first letter and show it. But how can remove it?
Like: From EDCstreet to street.
{foreach from=$elements item=street}
  {if $street|substr:0:1 eq 'm'}
       {$street}
  {/if}
{/foreach}

A: You can use:
{foreach from=$elements item=street}
  {if $street|substr:0:1 eq 'm'}
       {$street|substr:1}
  {/if}
{/foreach}

to display text without this first letter


text:
Q: How to force NSUserActivity to save? NSUserActivity has a method setNeedsSave:.
[userActivity setNeedsSave:YES];

Unfortunately it doesn't save at once, but just tells a user activity object that it should be saved in the future. In case of a crash the state may not be saved. As a result the state may not be restored after a crash.
Does any workaround exist? Is it possible to implement the method save for NSUserActivity myself in a category to force it to save each time when the state updates, not only when the system decides to do saving?


text:
Q: Create a google password checkup process I need to create a workflow like google password checkup shows.
I wonder if exists a spring security branch or generally a java security framework that help me to reach this purpose. Hope this link can help me to explain better what I mean
Google checkup password


text:
Q: UWP App Template I'm developing a UWP application. The design of the UI is similar to the Email app in Windows 10 (My app design).
This is my XAML code:
<Page
x:Class="Milano.InWork"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Milano"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid BorderBrush="White" BorderThickness="1">
    <Grid.Background>
        <ImageBrush Stretch="Fill" ImageSource="Images/Background.png"/>
    </Grid.Background>
    <Grid HorizontalAlignment="Left" Height="720" VerticalAlignment="Top" Width="60" BorderBrush="#FFF5F1F1" BorderThickness="0,0,1,0">
        <Button x:Name="MenuButton" Content="" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="38" Width="38">
            <Button.Background>
                <ImageBrush Stretch="Uniform" ImageSource="Images/Menu-100.png"/>
            </Button.Background>
        </Button>
        <Button x:Name="logoutbutton" Content="" HorizontalAlignment="Left" Margin="10,650,0,0" VerticalAlignment="Top"  Height="43" Width="38">
            <Button.Background>
                <ImageBrush Stretch="Uniform" ImageSource="Images/Logout_Button.png"/>
            </Button.Background>
        </Button>

    </Grid>
    <Grid HorizontalAlignment="Left" Height="47" Margin="63,2,-121,0" VerticalAlignment="Top" Width="1338" BorderBrush="#FFFDFDFD" Padding="0,0,0,1" BorderThickness="0,0,0,1">
        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" TextWrapping="Wrap" Text="В Работе" VerticalAlignment="Top" Height="47" Width="1218" FontSize="32" FontFamily="SF UI Display" Padding="550,0,0,0" Foreground="White"/>
    </Grid>
    <ScrollViewer HorizontalAlignment="Left" Height="668" Margin="63,52,0,0" VerticalAlignment="Top" Width="350">
        <GridView   x:Name="OrdersGridView" >
            <GridView.ItemTemplate>
                <DataTemplate>
                    <StackPanel >
                        <Grid Height="204" BorderBrush="#FFFBF8F8" BorderThickness="0,0,1,1">
                            <TextBlock Text="{Binding date_created}"  HorizontalAlignment="Left" TextAlignment="Center" TextWrapping="Wrap"  VerticalAlignment="Top" Width="350" Height="50" FontFamily="SF UI Display" FontSize="25" FontWeight="Light" Foreground="White" />
                            <TextBlock  TextAlignment="Center"  HorizontalAlignment="Left" Margin="0,146,-1,0" TextWrapping="Wrap" Text="{Binding billing.address_1}" VerticalAlignment="Top" Height="58" Width="350" FontFamily="SF UI Display" FontSize="25" FontWeight="Light" Foreground="White" />
                            <TextBlock  HorizontalAlignment="Left" TextAlignment="Center" Margin="0,86,-1,0" TextWrapping="Wrap" Text="{Binding billing.first_name}" VerticalAlignment="Top" Height="60" Width="350" FontFamily="SF UI Display" FontSize="25" FontWeight="Light" Foreground="White" Padding="0,0,0,0"/>

                        </Grid>

                    </StackPanel>
                </DataTemplate>
            </GridView.ItemTemplate>
        </GridView>
    </ScrollViewer>

</Grid>

What I need to do: When user clicks on Grid in right place of screen app show something like Fragment (I know this is Android thing) with some fields and data, like in the Email Windows 10 app:

*

*Before clicking

*After clicking
How I can implement this?
Or where I can read tutorial or something like this?
Thank's for help!

A: It is a typical Master/Detail design in UWP, you can refer to the official Master/detail sample, when on wide-screen mode, it uses ContentPresenter to show the details, and when on narrow-screen mode, it navigates with parameter to the detail page. The official sample is so clear, you can have a check.
From your first image, I think you can use a ListView to replace your GridView, for both controls, you can use SelectionChanged or ItemClick event to show the details, if you want to use ItemClick event, please don't forget to enable the IsItemClickEnabled property.
There is a MasterDetails (Mail App) sample which uses Template 10 as project template, if you're interest in this sample, you can also have a check.