text:
Q: angular2 with ASP.NET 5 working in Chrome but not in Firefox and IE (Error in zone.js) Basic Problem with the following configuration is, that it is working in Chrome without exceptions. But FF and IE are throwing exceptions from zone.js. Alle files seem to be adressed correctly (no html instead of js in 404 case), but im still getting this errors:
Firefox

mutating the [[Prototype]] of an object will cause your code to run very slowly; instead create the object with the correct initial [[Prototype]] value using Object.create es6-shim.js:1541:11
Error: Zonehttp://localhost:5301/js/zone.js:323:20
      Zonehttp://localhost:5301/js/zone.js:216:25
      scheduleResolveOrReject/<@http://localhost:5301/js/zone.js:571:53
      Zonehttp://localhost:5301/js/zone.js:356:24
      Zonehttp://localhost:5301/js/zone.js:256:29
      drainMicroTaskQueue@http://localhost:5301/js/zone.js:474:26
      ZoneTask/this.invoke@http://localhost:5301/js/zone.js:426:22
Evaluating http://localhost:5301/app/app.component.js
      Error loading http://localhost:5301/app/app.component.js as "./app.component" from http://localhost:5301/app/boot.js

And IE

Error: SyntaxError: Syntaxfehler
       at ZoneDelegate.prototype.invoke (http://localhost:5301/js/zone.js:321:14)
       at Zone.prototype.run (http://localhost:5301/js/zone.js:216:18)
       at Anonymous function (http://localhost:5301/js/zone.js:571:18)  Evaluating http://localhost:5301/app/app.component.js   Error loading
  http://localhost:5301/app/app.component.js as "./app.component" from
  http://localhost:5301/app/boot.js    {
        [functions]: ,
        proto: { },
        description: "SyntaxError: Syntaxfehler
       at ZoneDelegate.prototype.invoke (http://localhost:5301/js/zone.js:321:14)
       at Zone.prototype.run (http://localhost:5301/js/zone.js:216:18)
       at Anonymous function (http://localhost:5301/js/zone.js:571:18)  Evaluating http://localhost:5301/app/app.component.js   Error loading
  http://localhost:5301/app/app.component.js as "./app.component" from
  http://localhost:5301/app/boot.js",
        message: "SyntaxError: Syntaxfehler
       at ZoneDelegate.prototype.invoke (http://localhost:5301/js/zone.js:321:14)
       at Zone.prototype.run (http://localhost:5301/js/zone.js:216:18)
       at Anonymous function (http://localhost:5301/js/zone.js:571:18)  Evaluating http://localhost:5301/app/app.component.js   Error loading
  http://localhost:5301/app/app.component.js as "./app.component" from
  http://localhost:5301/app/boot.js",
        name: "Error",
        originalErr: {
           [functions]: ,
           proto: {
              [functions]: ,
              proto: { },
              message: "",
              name: "SyntaxError"
           },
           description: "Syntaxfehler",
           message: "Syntaxfehler",
           name: "SyntaxError",
           number: -2146827286,
           stack: "SyntaxError: Syntaxfehler    at Q (http://localhost:5301/js/system.js:4:21818)    at Anonymous function
  (http://localhost:5301/js/system.js:5:9152)    at Anonymous function
  (http://localhost:5301/js/system.js:5:13662)    at Anonymous function
  (http://localhost:5301/js/system.js:5:16880)    at Anonymous function
  (http://localhost:5301/js/system.js:5:21223)    at Anonymous function
  (http://localhost:5301/js/system.js:5:24189)    at Anonymous function
  (http://localhost:5301/js/system.js:4:10269)    at
  ZoneDelegate.prototype.invoke
  (http://localhost:5301/js/zone.js:321:14)    at Zone.prototype.run
  (http://localhost:5301/js/zone.js:216:18)    at Anonymous function
  (http://localhost:5301/js/zone.js:571:18)"
        },
        stack: null    }

It seems, that there is some JS Error in one of the loaded angualr files, ut even using Firebug my JS debugging skills are poor and i'm not getting the error. On the other side maybe there is missing some package for the other browsers.
Here my config files
gulpfile.js

/// <binding BeforeBuild='default' />

"use strict";

var _ = require('lodash'),
    gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    cssmin = require('gulp-cssmin'),
    rename = require('gulp-rename'),
    ts = require('gulp-typescript'),
    clean = require('gulp-clean');

var angularJs = [
    './node_modules/@angular/**/*.js'
];

var js = [
    './node_modules/es6-shim/es6-shim.js',
    './node_modules/reflect-metadata/Reflect.js',
    './node_modules/reflect-metadata/Reflect.js.map',
    './node_modules/bootstrap/dist/js/bootstrap.js',
    './node_modules/systemjs/dist/system.js',
    './node_modules/systemjs/dist/system.js.map',
    './node_modules/rxjs/bundles/Rx.js',
    './node_modules/typescript/lib/typescript.js',
    './node_modules/jquery/dist/jquery.js',
    './node_modules/zone.js/dist/**/*.js',
    './node_modules/core-js/client/shim.js'
];

var rxAdditional = [
    './node_modules/rxjs/**/*.js'
];

var css = [
    './node_modules/bootstrap/dist/css/bootstrap.css'
];

var fonts = [
    './node_modules/bootstrap/dist/fonts/*.*'
];

gulp.task('copy-js', function () {
    _.forEach(js, function (file, _) {
        gulp.src(file).pipe(gulp.dest('./wwwroot/js'))
    });
    _.forEach(angularJs, function (file, _) {
        gulp.src(file).pipe(gulp.dest('./wwwroot/js/@angular'))
    });

    _.forEach(rxAdditional, function(file, _) {
        gulp.src(file).pipe(gulp.dest('./wwwroot/js/rxjs'))
    });
});

gulp.task('copy-min-js', function () {
    _.forEach(js, function (file, _) {
        gulp.src(file).pipe(uglify()).pipe(rename({ extname: '.min.js' })).pipe(gulp.dest('./wwwroot/js'))
    });
    _.forEach(angularJs, function (file, _) {
        gulp.src(file).pipe(uglify()).pipe(rename({ extname: '.min.js' })).pipe(gulp.dest('./wwwroot/js/@angular'))
    });
});

gulp.task('copy-css', function () {
    _.forEach(css, function (file, _) {
        gulp.src(file).pipe(gulp.dest('./wwwroot/css'))
    });
    _.forEach(fonts, function (file, _) {
        gulp.src(file).pipe(gulp.dest('./wwwroot/fonts'))
    });
});

var tsProject = ts.createProject('tsconfig.json');

gulp.task('ts', function (done) {
    //var tsResult = tsProject.src()

    gulp.src('./wwwroot/app/*.ts')
        .pipe(ts(tsProject), undefined, ts.reporter.fullReporter()).pipe(gulp.dest('./wwwroot/app'));
});

gulp.task('watch', ['watch.ts']);

gulp.task('watch.ts', ['ts'], function () {
    return gulp.watch('./wwwroot/app/*.ts', ['ts']);
});

gulp.task('default', ['copy-js', 'copy-css', 'watch']);

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "rootDir": "wwwroot/app",
    "outDir": "wwwroot/app",
    "listFiles": true,
    "noLib": false,
    "diagnostics": true
  },
  "exclude": [
    "node_modules",
    "typings"
  ]
}

package.json

{
    "name": "my-angular-project",
    "private": true,
    "version": "0.0.1",
    "dependencies": {
        "@angular/core": "2.0.0-rc.1",
        "@angular/common": "2.0.0-rc.1",
        "@angular/compiler": "2.0.0-rc.1",
        "@angular/platform-browser": "2.0.0-rc.1",
        "@angular/platform-browser-dynamic": "2.0.0-rc.1",
        "@angular/router": "2.0.0-rc.1",
        "@angular/http": "2.0.0-rc.1",

        "@angular/router-deprecated": "2.0.0-rc.1",
        "@angular/upgrade": "2.0.0-rc.1",

        "bootstrap": "3.3.6",
        "systemjs": "0.19.29",
        "es6-promise": "^3.2.1",
        "es6-shim": "^0.35.1",
        "core-js": "^2.4.0",
        "reflect-metadata": "0.1.3",
        "rxjs": "5.0.0-beta.8",
        "zone.js": "^0.6.12",
        "jquery": "2.2.4",
        "angular2-in-memory-web-api": "0.0.11"
    },
    "devDependencies": {
        "typescript": "^1.8.10",
        "path": "^0.12.7",
        "gulp": "3.9.1",
        "gulp-clean": "^0.3.2",
        "gulp-debug": "^2.1.2",
        "gulp-inject": "^4.1.0",
        "gulp-sourcemaps": "^1.6.0",
        "gulp-tslint": "^5.0.0",
        "gulp-typescript": "^2.13.6",
        "gulp-rimraf": "^0.2.0",
        "typings": "^1.0.4",
        "gulp-tsc": "^1.1.5",
        "gulp-concat": "2.6.0",
        "gulp-cssmin": "0.1.7",
        "gulp-uglify": "1.5.3",
        "gulp-rename": "1.2.2",
        "rimraf": "2.5.2",
        "lodash": "4.13.1"
    },
  "scripts": {
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "postinstall": "typings install",
    "typings": "typings"
  }
}

wwwroot/app/boot.ts

import {bootstrap}    from "@angular/platform-browser-dynamic";
import {AppComponent} from "./app.component";

bootstrap(AppComponent);

wwwroot/app/app.component.ts

import {Component, OnInit} from "@angular/core";
@Component({
    selector: "app",
    template: "
My First Angular 2 App
"
})

export class AppComponent implements OnInit {
    ngOnInit() {
        console.log("App init...");
    }
}

_Layout.cshtml

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"]</title>
    <environment names="Development">

        <link rel="stylesheet" asp-href-include="~/css/*.css">

    </environment>

        @RenderBody()

Home/Index.cshtml

@{
    ViewData["Title"] = "Angular 2";
}
<app class="container" style="display: block;">Loading...</app>

systemjs.config.js

(function (global) {

    // map tells the System loader where to look for things
    var map = {
        'app': 'app', // 'dist',
        'rxjs': 'js/rxjs',
        'angular2-in-memory-web-api': 'js/angular2-in-memory-web-api',
        '@angular': 'js/@angular'
    };

    // packages tells the System loader how to load when no filename and/or no extension
    var packages = {
        app: {
            main: 'boot.js',
            defaultExtension: 'js',
            format: 'register'
        },
        'rxjs': { defaultExtension: 'js' },
        'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' }
    };

    var ngPackageNames = [
        'common',
        'compiler',
        'core',
        'http',
        'platform-browser',
        'platform-browser-dynamic',
        'router',
        'router-deprecated',
        'upgrade'
    ];

    // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
    function packIndex(pkgName) {
            packages['@angular/' + pkgName] = { main: 'index.js', defaultExtension: 'js' };
    }

    function packUmd(pkgName) {
        packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js'}
    }

    // Most environments should use UMD; some (Karma) need the individual index files
    var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
    // Add package entries for angular packages
    ngPackageNames.forEach(setPackageConfig);

    var config = {
        map: map,
        packages: packages
    };

    // filterSystemConfig - index.html's chance to modify config before we register it.
    if (global.filterSystemConfig) { global.filterSystemConfig(config); }

    System.config(config);

})(this);


text:
Q: How to get distinct values from mongoose model according to 2 fields? i am struck over problem in which I have mongoose model message like this:
const MessageSchema = new mongoose.Schema(
  {
    by: {
      type: String,
      required: true,
    },
    to: {
      type: String,
      required: true,
    },
    body: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

I want to get all the unique users in this model to which the message is sent by and received by any particular user.
const users = await Message.find({
   $or: [
     { by: req.user.userName },
     { to: req.user.userName },
   ],
 });

This is my query it gives me result but they are not distinct.
I may use
.distinct()

method of mongoose but how to use it on both "to" and "by" field.
It will be great if you can also give solution of how to sort it as we cant use sort() method with distinct() in mongoose.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set custom Record Count to Collection pagination in Report Grid How we can set count of collection size before setting for the grid.
Main Sales collection:
$collection=Mage::getModel('sales/order')->getCollection()
    ->addAttributeToFilter('created_at', array('gteq' =>$fromDate))
    ->addAttributeToFilter('created_at', array('lteq' =>$toDate))
    ->addAttributeToFilter('status',array('eq'=>Mage_Sales_Model_Order::STATE_COMPLETE));

Had join on that Collection:
$Table = Mage::getModel('amorderattr/attribute')->getResource()->getTable('amorderattr/order_attribute');
$collection->getSelect()->joinLeft(array('custom_attributes' => $amastyTable), 'main_table.entity_id = custom_attributes.order_id',array('is_first_order'));

Another Collection loaded :
$CustomersCollection = Mage::getModel('customer/customer')->getCollection();
$newCustomersCollection = $CustomersCollection
    ->addAttributeToFilter('created_at',array('from'=>$fromDate,'to'=>$toDate));
if(strlen($storeId)==1)
    $newCustomersCollection->addFieldToFilter('website_id',array('eq'=>Mage::getModel('core/store')->load($storeId)->getWebsiteId()));
else if($storeArr){
    $newCustomersCollection->addFieldToFilter('website_id',array('eq'=>Mage::getModel('core/store')->load($storeArr[0])->getWebsiteId()));
}
$newCustomers = count($newCustomersCollection);

time periods :
$frm = date("d M Y", strtotime($filterData->getData('from')));
$to = date("d M Y", strtotime($filterData->getData('to')));
$period=(string)$frm." - ". (string)$to;

Another Collection :
$totalAccountsCollection = Mage::getModel('customer/customer')->getCollection();
if(strlen($storeId)==1)
    $totalAccountsCollection->addFieldToFilter('website_id',array('eq'=>Mage::getModel('core/store')->load($storeId)->getWebsiteId()));
else if($storeArr){
    $totalAccountsCollection->addFieldToFilter('website_id',array('eq'=>Mage::getModel('core/store')->load($storeArr[0])->getWebsiteId()));
}
$totalAccounts=count($totalAccountsCollection);

Again different collection Loaded:
$CustomersCollection1 = Mage::getModel('customer/customer')->getCollection()
    ->addAttributeToFilter('created_at',array('from'=>$fromDate,'to'=>$toDate));;

$i=0;
foreach ($CustomersCollection1->getData() as $customer) {
    $salesOrderCollection2 = Mage::getModel('sales/order')->getCollection()
        ->addAttributeToFilter('customer_id', array('eq' => $customer['entity_id']));
    if(!count($salesOrderCollection2->getData())) {
        $i++;
    }
}
$customer_having_account_but_no_order = $i;

Again some other Info loaded :
/* Total Customer Of USD Website starts */
$USDCustomersCollection = Mage::getModel('customer/customer')->getCollection();
$USDCustomersCollection
    ->addFieldToFilter('website_id',array('eq'=>1))
    ->addAttributeToFilter('created_at',array('from'=>$fromDate,'to'=>$toDate));;
$USDAccounts=count($USDCustomersCollection->getData());
/* Total Customer Of USD Website ends */

/* Total Customer Of EURO Website starts */
$EUROCustomersCollection = Mage::getModel('customer/customer')->getCollection();
$EUROCustomersCollection
    ->addFieldToFilter('website_id',array('eq'=>2))
    ->addAttributeToFilter('created_at',array('from'=>$fromDate,'to'=>$toDate));;
$EUROAccounts=count($EUROCustomersCollection->getData());
/* Total Customer Of EURO Website starts */

And Finally selecting Columns from it :
$collection->getSelect()
    ->reset(Zend_Db_Select::COLUMNS)
    ->columns('COUNT(*) as total_orders')
    ->columns('SUM(custom_attributes.is_first_order) as first_order')
    ->columns('SUM(main_table.customer_is_guest) as is_guest')
    ->columns('COUNT(*) - (SUM(main_table.customer_is_guest) + SUM(custom_attributes.is_first_order)) as returning_accounts');

$collection->getSelect()->columns(array('new_accounts_created' => new Zend_Db_Expr($newCustomers)))
    ->columns(array('period' => new Zend_Db_Expr("'".$period."'")))
    ->columns(array('customer_having_account_but_no_order' => new Zend_Db_Expr($customer_having_account_but_no_order)))
    ->columns(array('usd_customer_account' => new Zend_Db_Expr($USDAccounts)))
    ->columns(array('euro_customer_account' => new Zend_Db_Expr($EUROAccounts)))
    ->columns(array('total_accounts' => new Zend_Db_Expr($totalAccounts)));

And Lastly setting my colletion in prepareCollection :
$this->setCollection($collection);

I have to to optimize it and at final setting collection to  $this->setCollection() this method it is taking 25 count as result but i get only one row in out put .
Therefore my pagination in of grid showing 25 records instead of 1(row which is getting)


text:
Q: Select  values from ul li within a jQuery variable I have a jQuery variable as the following
var $data = "
Root node

Child node

Root 2 node

Child 2 Parent Node

Child 2 child1

Child 2 child2

";

I want to fetch the values of each  values and push it into an array.
Can any body help???

A: var arr = $($data).find('a[href="#"]').map(function(){
     return $(this).text()
}).get();

Demonstration (open the console)

A: You may use .map():
var values = $("a[href='#']", $data).map(function() {
    return this.innerHTML;
}).get();

DEMO: http://jsfiddle.net/Vp7tN/


text:
Q: Dynamic Generation of All Possible Combinations of Index of an Array My task is to generate all possible index combinations of an array, wherein the array might be a single, 2D, 3D, 4D ... nD array with different number of elements. For now, I can only support single, 2D and 3D array using nested for loop.
Example:
byte[,,] sampleArray = new byte[5,4,3];

Generated Index Combinations:
sampleArray[0,0,0]
sampleArray[0,0,1]
sampleArray[0,0,2]
sampleArray[0,1,0]
sampleArray[0,1,1]
sampleArray[0,1,2]
sampleArray[0,2,0]
sampleArray[0,2,1]
sampleArray[0,2,2]
sampleArray[0,3,0]
sampleArray[0,3,1]
sampleArray[0,3,2]
sampleArray[1,0,0]
sampleArray[1,0,1]
sampleArray[1,0,2]
sampleArray[1,1,0]
sampleArray[1,1,1]
sampleArray[1,1,2]
sampleArray[1,2,0]
sampleArray[1,2,1]
sampleArray[1,2,2]
sampleArray[1,3,0]
sampleArray[1,3,1]
sampleArray[1,3,2]
sampleArray[2,0,0]
sampleArray[2,0,1]
sampleArray[2,0,2]
sampleArray[2,1,0]
sampleArray[2,1,1]
sampleArray[2,1,2]
sampleArray[2,2,0]
sampleArray[2,2,1]
sampleArray[2,2,2]
sampleArray[2,3,0]
sampleArray[2,3,1]
sampleArray[2,3,2]
sampleArray[3,0,0]
sampleArray[3,0,1]
sampleArray[3,0,2]
sampleArray[3,1,0]
sampleArray[3,1,1]
sampleArray[3,1,2]
sampleArray[3,2,0]
sampleArray[3,2,1]
sampleArray[3,2,2]
sampleArray[3,3,0]
sampleArray[3,3,1]
sampleArray[3,3,2]
sampleArray[4,0,0]
sampleArray[4,0,1]
sampleArray[4,0,2]
sampleArray[4,1,0]
sampleArray[4,1,1]
sampleArray[4,1,2]
sampleArray[4,2,0]
sampleArray[4,2,1]
sampleArray[4,2,2]
sampleArray[4,3,0]
sampleArray[4,3,1]
sampleArray[4,3,2]

My Code:
     protected void GenerateIndexCombinations(int indexCounter,
     ref List<List<int>> indexList, Array arr, ref List<int> index)
        {
            int dimSize1 = arr.GetLength(0);
            int dimSize2 = 0;
            int dimSize3 = 0;
            if (indexCounter > 1)
            {
                dimSize2 = arr.GetLength(1);
                if (indexCounter > 2)
                {
                    dimSize3 = arr.GetLength(2);
                }
            }

            for (int a = 0; a < dimSize1; a++)
            {
                if (dimSize2 > 0)
                {
                    for (int b = 0; b < dimSize2; b++)
                    {
                        if (dimSize3 > 0)
                        {
                            for (int c = 0; c < dimSize3; c++)
                            {
                                index = new List<int>();
                                index.Add(a);
                                index.Add(b);
                                index.Add(c);
                                indexList.Add(index);
                            }
                        }
                        else
                        {
                            index = new List<int>();
                            index.Add(a);
                            index.Add(b);
                            indexList.Add(index);
                        }
                    }
                }
                else
                {
                    index = new List<int>();
                    index.Add(a);
                    indexList.Add(index);
                }
            }
        }

Where:
int indexCounter is number of dimension.
Array arr is the array accessed by using reflection:
Array arr = fieldInfoArray[j].GetValue(_classInstance) as Array;

ref List<List<int>> indexList will be the container of the combinations.
ref List<int> index is the individual number added to the indexList.
Since the dimension size is not fixed, as well the number of elements per dimension, I want to generate the combinations dynamically to replace my nested for loop, Is there a way to do it?
Thanks for your answers.

A: Eric Lippert has blogged about exactly this problem. In your specific case you're looking for the Cartesian product of Enumerable.Range(0, 5), Enumerable.Range(0, 4), and Enumerable.Range(0, 3). In general, you want something like this:
var dimensions =
     Enumerable.Range(0, array.Rank)
               .Select(r => Enumerable.Range(0, array.GetLength(r)));

And then invoke Eric's method on dimensions. Here, I'm using Array.Rank to get the dimensionality of the matrix, and then using Array.GetLength to get the length along each dimension, and then dynamically generating the sequences that we need to compute the Cartesian product of. So, for each dimension, we project that dimension to the sequence of valid indexes along that dimension for array. Thus, for
T[,,...,] array = new T[a_1, a_2, ..., a_n];

we end up with dimensions equaling the sequence
(Enumerable.Range(0, a_1),
 Enumerable.Range(0, a_2),
 .
 .
 .,
 Enumerable.Range(0, a_n)
)

using System.Linq;
using System.Collections.Generic;
using System;

static class EnumerableExtensions {
    // credit: Eric Lippert
    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
        this IEnumerable<IEnumerable<T>> sequences
    ) {
        IEnumerable<IEnumerable<T>> emptyProduct =
            new[] { Enumerable.Empty<T>() };
        return sequences.Aggregate(
            emptyProduct,
            (accumulator, sequence) =>
                 from accseq in accumulator
                 from item in sequence
                 select accseq.Concat(new[] { item })
        );
    }
}

class Program {
    public static void Main(string[] args) {
        int[,,] array = new int[5, 4, 3];
        var dimensions =
            Enumerable.Range(0, array.Rank)
                      .Select(r => Enumerable.Range(0, array.GetLength(r)));
        var indexes = dimensions.CartesianProduct();
        foreach(var index in indexes) {
            Console.WriteLine(String.Join(",", index));
        }
    }
}


text:
Q: Reading XML attribute values using OPENXML For the following .nodes() approach, I need an equivalent OPENXML approach. The Attributes will be different and can not be hard-coded.
DECLARE @Xml XML='<row>
                     <DeletedVal>
                        <row attribute1="value1" attribute2="value2"/>
                     </DeletedVal>
                   </row>';

SELECT x1.y.value('local-name(.)', 'VARCHAR(30)') AS [Key]
       , x1.y.value('.', 'VARCHAR(MAX)')          AS [Value]
FROM   @Xml.nodes('/row/DeletedVal//@*') x1(y)

Output:
Key                            Value
------------------------------ ------
attribute1                     value1
attribute2                     value2

The following OPENXML approach needs fixing, where I am not sure how to get the attributes.
DECLARE @DocHandle INT
EXEC sp_xml_preparedocument
  @DocHandle OUTPUT
  , @Xml;

SELECT *
FROM   OPENXML (@docHandle, N'/row/DeletedVal//@*')
          WITH ([Key]     VARCHAR(10) 'key' --- This line needs editing
                , [Value] VARCHAR(10) '.')

EXEC Sp_xml_removedocument
  @DocHandle;

Output:
Key        Value
---------- ----------
NULL       value1
NULL       value2

A: Referring this link, I found the solution as below:
DECLARE @Xml XML='<row><DeletedVal><row attribute1="value1" attribute2="value2"/></DeletedVal></row>';
DECLARE @DocHandle INT

EXEC sp_xml_preparedocument
  @DocHandle OUTPUT
  , @Xml;

SELECT *
FROM   OPENXML (@docHandle, N'/row/DeletedVal//@*')
          WITH ([Key]     VARCHAR(10) '@mp:localname'
                , [Value] VARCHAR(10) '.')

EXEC Sp_xml_removedocument
  @DocHandle;

A: As @Larnu correctly pointed out, Microsoft proprietary OPENXML and its companions sp_xml_preparedocument and sp_xml_removedocument are kept just for backward compatibility with the obsolete SQL Server 2000.
It is strongly recommended to re-write your SQL and switch it to XQuery. It is available in MS SQL Server starting from 2005 onwards.
I made some performance improvements to your T-SQL by removing the //@* (search for descendants everywhere down) from the .nodes() XQuery method.
DECLARE @Xml XML =
N'<row>
    <DeletedVal>
        <row attribute1="value1" attribute2="value2"/>
    </DeletedVal>
</row>';

SELECT c.value('local-name(.)', 'VARCHAR(30)') AS [Key]
    , c.value('.', 'VARCHAR(MAX)') AS [Value]
FROM   @Xml.nodes('/row/DeletedVal/row/@*') AS t(c);

Output
+------------+--------+
|    Key     | Value  |
+------------+--------+
| attribute1 | value1 |
| attribute2 | value2 |
+------------+--------+


text:
Q: Every minute for all day, but when Day Of Month is 2 and 7 need to trigger at 12:00AM-08:59AM and 11:00AM-11:59PM only I need to trigger every minute for Day 1, 3-16 and 18-31.
But need to trigger every minute between 12:00AM-08:59AM and 11:00AM-11:59PM for Day 2, 7.
Day 1   : Every minute
Day 2   : Every minute between 12:00AM-08:59AM and 11:00AM-11:59PM
Day 3   : Every minute
Day 4   : Every minute
Day 5   : Every minute
Day 6   : Every minute
Day 7   : Every minute
Day 8   : Every minute
Day 9   : Every minute
Day 10  : Every minute
Day 11  : Every minute
Day 12  : Every minute
Day 13  : Every minute
Day 14  : Every minute
Day 15  : Every minute
Day 16  : Every minute
Day 17  : Every minute between 12:00AM-08:59AM and 11:00AM-11:59PM
Day 18  : Every minute
Day 19  : Every minute
Day 20  : Every minute
Day 21  : Every minute
Day 22  : Every minute
Day 23  : Every minute
Day 24  : Every minute
Day 25  : Every minute
Day 26  : Every minute
Day 27  : Every minute
Day 28  : Every minute
Day 29  : Every minute
Day 30  : Every minute
Day 31  : Every minute

A: I think you have to set this up as two jobs.  I am pretty sure it can't be done with one.
* *          1,3-16,18-31 * * myjob
* 0-8,11-23  2,17         * * myjob


text:
Q: Xcode keyboard shortcut for scrolling down both cursor and line How can I define a keyboard shortcut in Xcode to scroll down both the cursor and the line?
In Xcode's key bindings terms, this would be equivalent to performing "Scroll Line Down (Scrolling)" followed by "Move Down (Selection)". I'm looking for a way to define a keyboard shortcut which will perform both actions at once.

A: Xcode
Assign some key combinations to the Scroll Line Up and Scroll Line Down actions:

Then install KeyRemap4MacBook and save a file like this as ~/Library/Application Support/KeyRemap4MacBook/private.xml:
<?xml version="1.0"?>
<root>
  <appdef>
    <appname>XCODE</appname>
    <equal>com.apple.dt.Xcode</equal>
  </appdef>
  <item>
    <name>xcodearrows</name>
    <identifier>xcodearrows</identifier>
    <only>XCODE</only>
    <autogen>__KeyToKey__ KeyCode::CURSOR_UP, VK_OPTION | ModifierFlag::NONE, KeyCode::CURSOR_UP, KeyCode::PAGEUP, ModifierFlag::CONTROL_L | ModifierFlag::OPTION_L</autogen>
    <autogen>__KeyToKey__ KeyCode::CURSOR_DOWN, VK_OPTION | ModifierFlag::NONE, KeyCode::CURSOR_DOWN, KeyCode::PAGEDOWN, ModifierFlag::CONTROL_L | ModifierFlag::OPTION_L</autogen>
  </item>
</root>

Then open the KeyRemap4MacBook application, press the ReloadXML button, and enable the setting.
Other applications
Create ~/Library/KeyBindings/ and save a property list like this like this as ~/Library/KeyBindings/DefaultKeyBinding.dict:
{
  "~\UF700" = (moveUp:, scrollLineUp:); // option-up
  "~\UF701" = (moveDown:, scrollLineDown:); // option-down
}

Then quit and reopen applications to apply the changes.
DefaultKeyBinding.dict stopped working in Xcode 4. See https://stackoverflow.com/questions/5626788/custom-key-bindings-xcode-4.
This would make option-up and option-down scroll eight lines and center the view around the caret:
{
  "~\UF700" = (moveUp:, moveUp:, moveUp:, moveUp:, moveUp:, moveUp:, moveUp, moveUp, centerSelectionInVisibleArea:);
  "~\UF701" = (moveDown:, moveDown:, moveDown:, moveDown:, moveDown:, moveDown:, moveDown, moveDown, centerSelectionInVisibleArea:);
  "~$\UF700" = (moveUpAndModifySelection:, moveUpAndModifySelection:, moveUpAndModifySelection:, moveUpAndModifySelection:, moveUpAndModifySelection:, moveUpAndModifySelection:, moveUpAndModifySelection, moveUpAndModifySelection);
  "~$\UF701" = (moveDownAndModifySelection:, moveDownAndModifySelection:, moveDownAndModifySelection:, moveDownAndModifySelection:, moveDownAndModifySelection:, moveDownAndModifySelection:, moveDownAndModifySelection, moveDownAndModifySelection);
}


text:
Q: How to find min and max of multiple y-axes in FLOT I am using FLOT to plot charts, and I am not providing max or min value for Y-axis. It is getting auto-scaled. Now I want to get the min and max value of Y-axes. The following code works for only the first y-axis, but I want it for multiple axes.
var min = plot.getAxes().yaxis.min;

A: Loop through the yaxes array in the options:
var yaxes = plot.getOptions().yaxes;
var min = yaxes[0].min;
var max = yaxes[0].max;
for (var i = 1; i < yaxes.length; i++) {
    if (yaxes[i].min < min) {
        min = yaxes[i].min;
    }
    if (yaxes[i].max > max) {
        max = yaxes[i].max;
    }
}


text:
Q: mouse hover in layer_lines ggvis R I have similar question as question. Is it possible to see different vaules (using add_tooltip of ggvis) when I click in different place in line? Right now,it shows only one value.
mtcars %>% ggvis(~wt, ~mpg) %>%
  layer_lines() %>%
  add_tooltip(function(df) df$wt)


text:
Q: Bootstrap 4 fullscreen carousel bug: captions are centered with a delay I am working on a full-screen Bootstrap 4 carousel. The slides contain not images, but videos and captions.
It came out nice but it does have a bug: since all slides but the active one have display: none (a Bootstrap 4 default), the centering of the captions within the slides is delayed, as you can see below.

html,body {
  padding: 0;
  margin: 0;
  height: 100%;
}
.page-wrapper {
  min-height: 100%;
}
#full_slider .carousel-item {
  height: 100vh;
  justify-content: center;
  align-items: center;
}
#full_slider .carousel-item.active {
  display: flex;
  position: relative;
}
#full_slider video {
  position: absolute;
  left: 0;
  top: 0;
  width: 100vw;
  height: auto;
  z-index: -1;
}
#full_slider .video-caption {
  max-width: 585px;
  color: #fff;
}
#full_slider h3 {
  font-weight: 900;
  font-size: 96px;
  text-shadow: 2px 1px 1px rgba(0, 0, 0 , 0.6)
}
#full_slider .allcases a {
  color: #fff;
  margin-top: auto;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>

        <video src="https://code-love.tk/video/koffee.mp4" autoplay loop muted></video>

All about us

            See more

        <video src="https://code-love.tk/video/flamenco.mp4" autoplay loop muted></video>

Lorem ipsum dolor

            See more

        <video src="https://code-love.tk/video/wittgenstein.mp4" autoplay loop muted></video>

Wittgenstein's philosophy

            See more

I can not just set the display of the carousel items to block, as that would ruin the slider.
What shall I do instead?

A: Try adding the CSS rules:
.carousel-item.active, .carousel-item-left, .carousel-item-right {
  display: flex !important;
}

The problem seems to be coming from the fact that during the animation, display: flex is not set on the carousel item container, but that is required for proper alignment of the children.
Working snippet:

html,body {
  padding: 0;
  margin: 0;
  height: 100%;
}
.page-wrapper {
  min-height: 100%;
}
#full_slider .carousel-item {
  height: 100vh;
  justify-content: center;
  align-items: center;
}
#full_slider .carousel-item.active {
  display: flex;
  position: relative;
}
#full_slider video {
  position: absolute;
  left: 0;
  top: 0;
  width: 100vw;
  height: auto;
  z-index: -1;
}
#full_slider .video-caption {
  max-width: 585px;
  color: #fff;
}
#full_slider h3 {
  font-weight: 900;
  font-size: 96px;
  text-shadow: 2px 1px 1px rgba(0, 0, 0 , 0.6)
}
#full_slider .allcases a {
  color: #fff;
  margin-top: auto;
}

.carousel-item.active, .carousel-item-left, .carousel-item-right {
  display: flex !important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>

        <video src="https://code-love.tk/video/koffee.mp4" autoplay loop muted></video>

All about us

            See more

        <video src="https://code-love.tk/video/flamenco.mp4" autoplay loop muted></video>

Lorem ipsum dolor

            See more

        <video src="https://code-love.tk/video/wittgenstein.mp4" autoplay loop muted></video>

Wittgenstein's philosophy

            See more


text:
Q: Spring Data @Query with Joins I am fairly new to Spring Data and I want to create a query that will allow me to do an Inner Join between two entities.
I have been using this stack overflow to try to clarify certain aspects:
How To Define a JPA Repository Query with a Join
It gives the answer of structuring the query as so:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

However in this query I dont see where it manages to define "ar" as neither of the entity classes actually define "ar" within themselves? Any clarification on this would be greatly appreciated!

A: Consider this example
SELECT c FROM Country c

Here, c is called a range variable.

Range variables are query identification variables that iterate over
  all the database objects of a specific entity class hierarchy (i.e. an
  entity class and all its descendant entity classes)

You can read more about range variables here
As per your query that there is no "Area ar" you need to understand that this query is based on JPQL (not SQL). Consider the below query:
SELECT c1, c2 FROM Country c1 INNER JOIN c1.neighbors c2

JPQL provides something called as a join variable, which represent a more limited iteration over specified collections of objects. In the above query, c1 is a range variable while c2 is a join variable that is bound to the path c1.neighbours and iterates only over objects in that collection.
You can read about it in more detail in this article

A: area is actually defined in User entity class and in your query area is aliased with "ar" and used as second entity of the join.
@Query("select u.userName from User u inner join **u.area** ar
        where ar.idArea = :idArea")


text:
Q: Wordpress get_pages based on page category I need to get_pages or get an array of pages in WP based on it 's category
I know WP doesn't come with categories on pages but I'm using this in the functions.php to get categories on the pages.
    add_action('admin_init', 'reg_tax');

    function reg_tax() {
        register_taxonomy_for_object_type('category', 'page');
        add_post_type_support('page', 'category');
    }

Now I need to use these categories in get_pages or WP_Query to get in the pages with a category.

                <?php

                $product_page_args = array(

                    'post_type' => 'page',
                    'order' => 'ASC',
                    'orderby' => 'menu_order',
                    'child_of' => $post->ID,
                    'category_name' => 'pillar-product'
                );

                //$product_pages = get_pages($product_page_args);

                $product_pages = new WP_Query($product_page_args);

                foreach ($product_pages as $product_page){

                ?>

<?php echo $product_page->post_title; ?>

                <?php
                }
                ?>

A:
Respectfully this answer does NOT work anymore in 2021. This is an obsolete answer and includes all of the pages. Please use the other answer.

Try this: (won't work on wordpress 5.8)
$product_page_args = array(

                'post_type' => 'page',
                'order' => 'ASC',
                'orderby' => 'menu_order',
                'child_of' => $post->ID,
                'taxonomy' => 'category',
                        'field' => 'slug',
                        'term' => 'pillar-product'
            );

A:
The accepted answer for this question won't work anymore and includes all of the pages because 'taxonomy', 'field' and 'term' must be inside an array which resides inside 'tax_query' array, for this query to work.

For more comprehensive answer on how to query wordpress pages based on specific category see the following link:

How to query pages based on specific categories

Here's the correct answer for this question, fully tested on wordpress 5.8.
$product_page_args = array(
  'post_type' => 'page',
  'order' => 'ASC',
  'orderby' => 'menu_order',
  'child_of' => $post->ID,
  'tax_query' => array(
    array(
      'taxonomy' => 'category',
      'field'    => 'slug',
      'terms'    => array('pillar-product'),
    )
  )
);


text:
Q: How to UPDATE ALL OLD ROWS in A TABLE with AFTER/BEFORE INSERT ON trigger IN THE SAME TABLE in mysql? I need to update the status column of all the old rows of a table to false before/after inserting a new row into that table.
I have visited these but didn't solve my query.
MySQL - Trigger for updating same table after insert
DELIMITER $$
DROP TRIGGER update_old_status $$
CREATE TRIGGER update_old_status
BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
    DECLARE MYCOUNTER INT;
    SELECT COUNT(*) INTO MYCOUNTER FROM table_name;

    IF (MYCOUNTER > 0) THEN
        UPDATE table_name SET status = false WHERE status = true;
    END IF;

END $$
DELIMITER ;

Here what i have as error message:
Caused by: java.sql.SQLException: Can't update table 'table_name' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

A: You can't use a trigger to update the same table for which the trigger is running, because there's too high a risk of creating an infinite loop.
For example, an insert trigger updates its table, which runs another trigger on update, that inserts to the same table, which runs the insert trigger...
You can't and don't need to use a trigger for this. Instead, use a transaction and run the UPDATE before your INSERT in your application.
Pseudocode:
START TRANSACTION;
UPDATE table_name SET status = false;
INSERT INTO table_name ...values...
COMMIT;


text:
Q: Página de formulario de contacto con PHP Mailer no se ejecuta Soy nuevo en el mundo del desarrollo web y de a poco voy conociendo cosas.
Escuche sobre PHP Mailer y lo quise implementar en mi proyecto, pero estoy teniendo problemas al querer entrar a la página de contacto donde implemente el PHP Mailer. Me aparece "Esta página no funciona en este momento. HTTP ERROR 500".
Seguramente debo haber escrito algo mal en mi código porque no tengo idea de PHP. El  código lo  copie de un video. Lo raro  es que hice todo exactamente igual y no me funciona.
Ya probé en dos servidores con PHP y también en XAMPP y nada. No tengo dudas que hice algo mal.
Acá les dejo el código. Gracias de antemano.
<?php
$result="";
if(isset($_POST['submit'])){
   require 'php-mailer/PHPMailerAutoload.php';
    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->Host='smtp.gmail.com';
    $mail->Port=587;
    $mial->SMTPAuth=true;
    $mial->SMTPSecure='tls';
    $mial->Username='mi-email@gmail.com';
    $mial->Password='contraseña'

    $mail->setFrom($_POST['email'],$_POST['nombre']);
    $mail->addAddress('mi-email@gmail.com');
    $mial->addReplyTo($_POST['email'],$_POST['nombre']);

    $mail->isHTML(true);
    $mail->Subject='Enviado por'.$_POST['nombre'];
    $mial->Body='
Nombre: '.$_POST['nombre']. '
Email: '.$_POST['email'.'
Mensaje: '.$_POST['mensaje'].'
';

    if(!$mail->send()){
        $result="Algo esta mal. Intente de nuevo o mas tarde."
    }
    else
      {
          $result="Gracias. Estaremos respondiendo a la brevedad."
      }
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <title>WEB</title>

    <link rel="shortcut icon" href="" type="image/x-icon">
    <link rel="apple-touch-icon" href="">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet">
    <link rel="shortcut icon" href="" type="image/x-icon">
    <link rel="apple-touch-icon">

    <link rel="stylesheet" href="Bootstrap/css/bootstrap.min.css">

    <link rel="stylesheet" href="style.css">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css">

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,300;0,500;1,600&display=swap" rel="stylesheet">

Contacto

        <form action="" method="post">

                Nombre
                <input name="nombre" type="text" class="form-control" id="exampleFormControlInput1" placeholder="Nombre completo" required>

                Correo electrónico
                <input name="email" type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="ejemplo@mail.com" required>

                Mensaje
                <textarea name="mensaje" class="form-control" id="exampleFormControlTextarea1" placeholder="Escriba su mensaje aquí" rows="3" required></textarea>

            <button type="submit" name="submit" class="btn btn-primary">Enviar</button>

 <?= $result; ?>

        </form>

A: Puede ocurrir por muchos motivos, te sugiero que pruebes con un tutorial más extenso, prueba con esto
También revisa que tienes instalado composer y que la cuenta de google tenga activado el permiso para usarlo con el SMTP


text:
Q: Could not resolve all files for configuration ':app:debugRuntimeClasspath'. > Could not find com.android.support:appcompat-v7:30.0.3 This my build.gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"
    defaultConfig {
        applicationId "com.howietian.jianshi"
        minSdkVersion 15
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'com.android.support:appcompat-v7:30.0.3'
    implementation 'com.android.support:design:30.0.3'
    implementation 'com.android.support:support-v4:30.0.3'
    implementation 'com.android.support.constraint:constraint-layout:2.0.4'
    implementation 'com.ashokvarma.android:bottom-navigation-bar:1.2.0'
    implementation 'com.jakewharton:butterknife:10.2.3'
    implementation 'com.android.support:recyclerview-v7:30.0.3'
    implementation 'com.android.support:cardview-v7:30.0.3'
    debugImplementation 'com.amitshekhar.android:debug-db:1.0.0'
    implementation 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
    implementation 'com.google.zxing:core:3.4.1'
    testImplementation 'junit:junit:4.13.2'
    implementation 'org.kie.modules:com-google-code-gson:6.5.0.Final'
    implementation files('libs/iTextpdf.jar')
}

can you please help me?

A: You should migrate your support libraries to androidx.
You can find artifact mappings here: https://developer.android.com/jetpack/androidx/migrate/artifact-mappings
And here is the androidx migration doc: https://developer.android.com/jetpack/androidx/migrate


text:
Q: Using $timeout-Mock in AngularJS with delay I've used $timeout with a delay of e.g. 600ms in some service code. In the according test I want to assert that the code really does what it is expected to do after the given 600 ms. Is there any way to progress in time with a certain amount of time (similar to jasmine.Clock.tick(600))? I only know about $timeout.flush(), but that fires everything currently in the $timeout-queue.

A: In AngularJS version 1.2 you can do $timeout.flush(600), which is analogous to Jasmine's jasmine.Clock.tick(600).
In addition to that Angular 1.2 provides a very handy $timeout.flushNext(msec) method. It differs from the flush(msec) in that that instead of simply putting a clock given time ahead for you to then check if an expected thing happened or not, the flushNext() method does both tasks at once. It puts a clock ahead up until the next deferred event is fired and then verifies that the elapsed time equals the given one.
Link to the documentation


text:
Q: Avoid Getting negative Value on Time Subtraction Laravel php I'm subtracting 2 different times and getting negative values, to explain it further here is my code:
        {{date('l',strtotime($mydate->logon))}}
        {{date('jS F, Y',strtotime($mydate->logon))}}
        {{$date1=date('h:i A',strtotime($mydate->logon))}}
        {{$date2=date('h:i A',strtotime($mydate->logoff))}}
        {{$result=$date2-$date1}}

The $result value sometimes goes negative because its somethimes subtracting pm and am. Any ways to avoid this? thanks


text:
Q: How can I send a request like in python and return the site response? Why my code in js dont sends the post data and in python works ?
In js
const options = {
    url: "https://asd.com",
    method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Accept-Charset': 'utf-8',
            'User-Agent': 'my-reddit-client',
            'data': {"user.login":"login","user.senha":"pass"}
        }
    };

    request(options, function(err, resx, body) {
        console.log(resx);
        res.send(body)
    });

In python
import requests
data = {
  "user.login":"login",
  "user.senha":"pass"
}
r = requests.post('https://asd.com', params=data)
print(r.text)

I just want to send a custom form without json format, but it never works.

A: to make POST request in vanilla JS:
fetch("https://asd.com", {
  method: 'POST',
  body: {"user.login":"login","user.senha":"pass"},
  headers: {
   'Accept': 'application/json',
   'Accept-Charset': 'utf-8',
   'User-Agent': 'my-reddit-client',
  }
 }).then(res => res.json())

I suggest you also to read about the fetch API so It won't be hard for you anymore to make any other kind of request in JS https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.


text:
Q: Deligne-Mumford moduli spaces and compactification of symmetric matrices The real Deligne-Mumford moduli space $\bar M_{0,n+1}(\mathbb R)$ of stable genus
zero curves with $n+1$ marked points is a compactification of the space of
configurations of $n$ distinct ordered points on the real line modulo affine
transformations.  This space is a smooth projective variety and carries a
natural action of the permutation group $S_n$.  We can interpret the
configurations of distinct points on the real line as diagonal $n\times n$
matrices with distinct eigenvalues, $S_n$ acting via conjugation with signed
permutation matrices.
Question:  What is the right compactification of the space of arbitrary symmetric $n\times n$ matrices with distinct eigenvalues modulo affine transformations?  I am looking for a projective variety carrying a natural $SO(n)$-action, such that if we restrict to diagonal matrices, we recover $\bar M_{0,n+1}(\mathbb R)$ with the above $S_n$-action.  Is this variety smooth?  Does it have an interpretation in terms of curves with marked points?


text:
Q: Exchange 2007: Cannot send any messages After P2V, Exchange 2007 does not appear to be receiving any messages from internal clients (Outlook 2010) for delivery.
We can receive messages sent from external recipients, and we can receive messages from devices and services running internally that use their own smtp servers, and when we send messages, they appear to go through, showing up in our Sent boxes, but we do not receive any messages sent from internal Outlook clients either at our internal clients or at our external accounts.
Looking at the Exchange server, viewing the queues, these internal messages never appear in the queues for processing. It is as if the Outlook clients think they are connecting successfully, but the messages are never picked up by the Exchange server.
The old physical server is not powered on. The IP address and network name is configured properly (the same).

A: Verify the settings on the "Client" Receive Connector that the appropriate authentication is set and that the permission group is set to Exchange Users.

A: System details:
VMWare - ESXi 4
Windows Server 2008 sp2 (not R2)
Exchange 2007
P2V steps:
Used VConverter (current version), stopped Exchange services prior to P2V, left config default.
Verified NIC config. Ghost NIC in system, but 2008 removing config from Ghost when config on new (virtual) NIC takes over same config.
====================================
This turned out to be quite the beast, and it's not even fully vanquished.
I did not ever figure out what was going on with the first P2V process, it was just bad in some way. All the configuration matched exactly with the physical (functioning) exchange server, and there was just no communication over what appeared to be valid connections.
Not having enough time to continue diagnosing, we ran a second P2V on a subsequent evening, which also didn't work, but this time it was just that the new VM never loaded the OS. Third try appeared to be similar, but turned out to actually be a good copy. At first it appeared to have the not loading issue of try #2 and so I backed out of that too. However, it turned out the issue was a compatibility problem between the RDP console and the vSphere machine viewer resulting in nothing showing in the viewer window when viewed over an RDP connection.
We used this good copy to test the sending and verified it was all working OK. Some Outlook clients needed to have the Cache disabled and then reenabled to "see" the new server in test. It seems the Cache keeps some record besides the domain name and IP address and so if the client is running during the migration, it can get hung up looking in the wrong place for the Exchange server once it comes back online.
So, we've figured out that and I'll be giving it another try tonight, eschewing the RDP console to ensure maximal chance of success.
Regarding the initial issue, Microsoft and our Consultants both recommended simply re-
P2Ving as there was no reason they were aware of that the original issue should have occurred.


text:
Q: multiple dojo pie chart How can I add trow pie charts in the same chart? If I add two plots then the pie charts are both in the center. I need to have one on the left side and one on the right side.
I need them in one chart because I want to create an SVG image of it.

A: I'm also looking about that and up to now haven't found the solution.
But we can position the pie-chart by modifying 'g' element of svg with javascript after render.
    var a=document.getElementsByTagName('svg')[0];
    var b=document.getElementsByTagName('g')[1];
    b.setAttribute('transform','translate(-598.25037,-71.249953)'); //put your own

Hope this help.


text:
Q: Retrieve text from a textbox to place in another textbox on same windows form I have created a good windows form. What I have been asked to do is break it down some more. What I would like the users to be able to do is type in a TextBox but include some sort of tag that would represent text from another TextBox.
I have four text boxes:
1- to_fromTextBox
2- city1TextBox
3- city2TextBox
4- enterTextbox
So if a user types in city1TextBox - Orlando, then types in city2TextBox - Longwood.
Then while typing in enterTextBox - From (some tag to insert city1TextBox) to (some tag to insert city1TextBox) e.g. from some identifier to some identifie.
This would concatenate in to_fromTextBox to save in the database table.
e.g. From Orlando to Longwood
The reason this has to be separate is when a report is created other textboxes will have map coordinates in it and will follow the city textboxes.
reported text e.g. From Orlando (H-5) to Longwood (H-4)
I have tried my best in searching for this answer with no luck. Could someone point me in the correct direction.

A: If ^^ and ## are predefined, you could write this code on keyup event of the enterTextbox like this
var text = "From ^^ to ##";
if (text.IndexOf("^^") != -1 && text.IndexOf("##") != -1)
{
    to_fromTextBox.Text = text
        .Replace("^^", city1TextBox.Text)
        .Replace("##", city2TextBox.Text);
}

But if you use {0} and {1} as identifiers, you could use String.Format like this
var text = "From {0} to {1}";
if (text.IndexOf("{0}") != -1 && text.IndexOf("{1}") != -1)
{
    to_fromTextBox.Text = String.Format(
        text,
        city1TextBox.Text,
        city2TextBox.Text);
}

A: You can access the string in the textboxes with .Text (is a Get/Set, so you can change their values the same form).
textBox1.Text = "1"
textBoxt2.Text = "2"
textBoxN.Text = "n...";

textBoxTarget.Text = textBox1.Text +" - "+ textBoxt2.Text +" - "+ TextBoxN.Text;

textBoxTarget.Text = "1 - 2 - n..."


text:
Q: How to reverse this custom hash So I have this hashing algorithm in JS, and I was wondering how I could reverse a hash it made? I know people ask these questions a lot, but this hashing algorithm is unique (I think). Here it is:
const stringToHash = string => {
  var hash = 0;

  if (string.length == 0) return hash;

  for (i = 0; i < string.length; i++) {
    char = string.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash;
  }

  return hash;
}

Here's an example output it gave me: -566853151

A: Your hash is easily reversible for messages known to be very short (e.g. 4 upper-case ASCII characters or less)
If your message is solely upper case or solely lower case, the characters only differ within a block of 32, which is 2^5. Therefore when you shift the number by 5 bit positions, the next incoming character does not overlap.
Therefore you can start at the highest order bits, and read the first character, then think about how that character will have evolved through the various steps (shifting and subtracting). This will allow you to "undo" the effect of the first character.
You now have the first character removed and the remaining hash is simpler, being the hash of the remaining characters of the message. You can then repeat until all the characters are done.
If the message is longer, and especially if it is allowed to include a wider array of symbols, your task is much harder.
Let me know if this helps you get started:

const stringToHash = string => {
  var hash = 0;

  if (string.length == 0) return hash;

  for (i = 0; i < string.length; i++) {
    char = string.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash;
  }

  return hash;
}

console.log(stringToHash("A").toString(2))
console.log(stringToHash("AA").toString(2))
console.log(stringToHash("AAA").toString(2))

console.log(stringToHash("B").toString(2))
console.log(stringToHash("BA").toString(2))
console.log(stringToHash("BAA").toString(2))


text:
Q: XSLT transformation to move an element into another or set it as attribute What is a XSLT template that will get the <title></title> that contains the name of a blog and put it in every <entry></entry> or as an attribute in every <entry> ?
from
<feed>
<title>title of feed</title>
<entry>...</entry>
<entry>...</entry>
</feed>

to
<feed>
<entry><blog>title of feed</blog>...</entry>
<entry><blog>title of feed</blog>...</entry>
</feed>

or
<feed>
<entry blog="title of blog">...</entry>
<entry blog="title of blog">...</entry>
</feed>

A: for the attribute solution, something like this should work :
<xsl:template match="entry">
    <entry blog="{/feed/title}">
        <xsl:apply-templates/>
    </entry>
</xsl:template>


text:
Q: Specifying navigation buttons I am making a Navigation based application and i've noticed a flaw in my app. Even though i have multiple buttons, each having its own title the button leads you to the same screen no matter what button i press. Is there a way to make sure that each button leads to a page specific to the button pressed. Such as clicking Options and it bringing you to the option menu not clicking images and it bringing you to the options menu. Any help would be appreciated Thank you.
This is my stack popping method:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    Anotherviewcontroller *detailViewController = [[Anotherviewcontroller alloc] initWithNibName:@"Anotherviewcontroller" bundle:nil];

    detailViewController.currentItem = @"Years";

    [self.navigationController pushViewController:detailViewController animated:YES];

    [detailViewController release];

}

A: You should use the indexPath to determine which button/cell has been selected and then, maybe with a switch statement if there are alot, create the the appropriate controller.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
      if(indexPath.row == 0) {
         Anotherviewcontroller *detailViewController = [[Anotherviewcontroller alloc] initWithNibName:@"Anotherviewcontroller" bundle:nil];
         detailViewController.currentItem = @"Years";
         [self.navigationController pushViewController:detailViewController animated:YES];
         [detailViewController release];

      } else {
         MessageViewController *messageViewController = [[MessageViewController alloc] initWithNibName:@"Messageviewcontroller" bundle:nil];
         [self.navigationController pushViewController:messageViewController animated:YES];
         [messageViewController release];
      }
}

A: You can set indexPath.row as a tag of each btn when you are creating cells and then in didSelectRowAtIndexPath you can check for that tag.


text:
Q: Unable to figure how to delete a row from Moor (drift) database after dart NNBD Been trying to implement simple expense tracking app and got myself tangled in dependencies.
Before null-safety deleting rows was easy, now I have to use """companions""" and their concept is a bit unintuitive for me. I've been trying to upgrade this app as a learning attempt of mvvm in flutter (kinda useless knowledge) (https://github.com/musabagab/Money-Manager-Expenses-tracker-app)
Pre-ambula: they did NBBD and now auto-increment id param is marked as required and I have 0 idea how to implement deletions without knowing said ID. And moor docs are not helpful with examples, I want to delete by ID\in any way they intended to do this (https://drift.simonbinder.eu/docs/getting-started/writing_queries/#updates-and-deletes)
Before null-safety db code looked like this + generated file, and inserts\deletions worked just fine:
import 'package:moor_flutter/moor_flutter.dart';
part 'moor_database.g.dart';

class Transactions extends Table {
  TextColumn get type => text()(); //expense /income
  IntColumn get id => integer().autoIncrement()();
  IntColumn get amount => integer()(); // 300 or 200
}

@UseMoor(tables: [Transactions], daos: [TransactionDao])
class AppDatabase extends _$AppDatabase {
  AppDatabase()
      : super(FlutterQueryExecutor.inDatabaseFolder(
            path: "db.sqlite", logStatements: true));
  int get schemaVersion => 1;
}

// Denote which tables this DAO can access
@UseDao(
  tables: [Transactions],
  queries: {
    // this method will be generated
    'getTransactionForMonth': 'SELECT * FROM transactions WHERE month = :month',
    'sumTheMoneyForMonth':
        'SELECT SUM(amount) FROM transactions WHERE month = :month AND type = :type'
  },
)
class TransactionDao extends DatabaseAccessor<AppDatabase>
    with _$TransactionDaoMixin {
  final AppDatabase db;

  // Called by the AppDatabase class
  TransactionDao(this.db) : super(db);

  Future insertTransaction(Transaction transaction) =>
      into(transactions).insert(transaction);

  Future deleteTransaction(Transaction transaction) =>
      delete(transactions).delete(transaction);
}

and database service
import 'package:finances/core/database/moor_database.dart';

class MoorDatabaseService {
  final AppDatabase _database = AppDatabase();

  getAllTransactions(String month) async {
    List<Transaction> allTrans = List<Transaction>();

    TransactionDao transactionDao = _database.transactionDao;

    allTrans = await transactionDao.getTransactionForMonth(month).get();
    return allTrans;
  }

  Future deleteTransaction(Transaction transaction) async {
    return await _database.transactionDao.deleteTransaction(transaction);
  }

  Future insertTransaction(Transaction transaction) async {
    return await _database.transactionDao.insertTransaction(transaction);
  }

insert model (yes mvvm in flutter lol)
class InsertTransactionModel extends BaseModel {
  TextEditingController memoController = TextEditingController();
  TextEditingController amountController = TextEditingController();

  final MoorDatabaseService _moorDatabaseService =
      locator<MoorDatabaseService>();

<code skipped>

    Transaction newTransaction = new Transaction(
        type: type,
        day: selectedDay,
        month: selectedMonth,
        memo: memoController.text,
        amount: int.parse(amount),
        categoryindex: cateogryIndex);
    // insert it!
    await _moorDatabaseService.insertTransaction(newTransaction);

    Toast.show("Added successfully!", context,
        duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
    // return to the home
    Navigator.of(context)
        .pushNamedAndRemoveUntil('home', (Route<dynamic> route) => false);
  }
}

insert viewmodel
class InsertTranscationView extends StatelessWidget {
  final Category category;
  final int selectedCategory;
  InsertTranscationView(this.category, this.selectedCategory);
  @override
  Widget build(BuildContext context) {
    return BaseView<InsertTransactionModel>(
      onModelReady: (model) => model.init(selectedCategory, category.index),
      builder: (context, model, child) => Scaffold(
        appBar: AppBar(
          title: selectedCategory == 1 ? Text('Income') : Text('Expense'),
        ),
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: ListView(
              children: <Widget>[
                ListTile(

                **<code skipped>**

                    Align(
                  alignment: Alignment.centerLeft,
                  child: RaisedButton(
                    child: Text(
                      'ADD',
                      style: TextStyle(fontSize: 16),
                    ),
                    color: backgroundColor,
                    textColor: Colors.black,
                    **onPressed: () async {
                      await model.addTransaction(context);**
                    },
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

FIXING INSERT FOR NULL-SAFETY##
this was the easy part.
    final newTransaction = TransactionsCompanion(
        type: Value.ofNullable(type),
        day: Value.ofNullable(selectedDay),
        month: Value.ofNullable(selectedMonth),
        memo: Value.ofNullable(memoController.text),
        amount: Value.ofNullable(int.parse(amount)),
        categoryindex: Value.ofNullable(categoryIndex));
    // insert it!
    await _databaseService.insertTransaction(newTransaction);

and in service
  Future<int> insertTransaction(TransactionsCompanion transaction) async {
    return await _database.transactionDao.insertTransaction(transaction);
  }

and in database
  Future<int> insertTransaction(TransactionsCompanion transaction) =>
      into(transactions).insert(transaction);

Delete is a bit hard
My attempt at fixing null errors:
in delete model
  Future deleteTransacation(Transaction transaction) async {

    final newTransaction = TransactionsCompanion(
        type: Value.ofNullable(transaction.type),
        day: Value.ofNullable(transaction.day),
        month: Value.ofNullable(transaction.month),
        memo: Value.ofNullable(transaction.memo),
        amount: Value.ofNullable(transaction.amount),
        categoryindex: Value.ofNullable(transaction.categoryindex));
    // delet it!

    return await _databaseService.deleteTransaction(newTransaction);
}

and service
  Future deleteTransaction(TransactionsCompanion transaction) async {
    return await _database.transactionDao.deleteTransaction(transaction);
  }

and database
  Future deleteTransaction(TransactionsCompanion transaction) =>
      delete(transactions).delete(transaction);

I suppose delete method in database itself is faulty, because insertions work without issues. I tried assembling TransactionCompanion and pass it as an argument into db service for it to delete same transaction by 1:1 comparision i guess?
Thanks for your efforts!


text:
Q: Pass Variable Google Apps Script To HTML I would like to pass the variable 'MyLink' from the Google Scripts Code to HTML code.
This is the GS Code.
 function FirstView(){
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var MyNewBook = ss.copy("A Copy of " + ss.getName());
 var MyLink = MyNewBook.getUrl()

 var html = HtmlService.createHtmlOutputFromFile('Index');
 SpreadsheetApp.getUi().showModalDialog(html, "hello");
 }

 function DOUBLE() {
 var linkButton = document.getElementById("link-button");
linkbutton.setAttribute('href', MyLink);
}

This is the HTML Code.

<base target="_top">

Click here
<input type="button" value="Close" onclick="google.script.host.close()" />

</html

The Code Will show a dialog box with the 'MyLink' URL.

A: I would update the href with the link like:
var ss = SpreadsheetApp.getActiveSpreadsheet();
     var MyNewBook = ss.copy("A Copy of " + ss.getName());
     var MyLink = MyNewBook.getUrl()

var linkButton = document.getElementById("link-button");
linkButton.setAttribute('href', MyLink);

and then add the id to the anchor:
Click here

Update:
Create function to set the href in the link:
initFunction() {
    var linkButton = document.getElementById("link-button");
    linkButton.setAttribute('href', MyLink);
}

Call the function onload of the body tag:

A: You can just select the element by id for example and modify its href
Reference
var ss = SpreadsheetApp.getActiveSpreadsheet();
var MyNewBook = ss.copy("A Copy of " + ss.getName());
document.getElementById("link").href = MyNewBook.getUrl()

  <base target="_top">

  Click here
  <input type="button" value="Close" onclick="google.script.host.close()" />


text:
Q: JavaScript: Login/Register with localStorage Hey there I know it's probably an easy question but I've a problem with my Login/Register in JavaScript. I'm storing the users data via localStorage and when I try to login he always returns my alert message, that the typed in data is wrong.
EDIT: storedName is undefined but password isn't. I still don't get it..
EDIT: Problem solved. Thanks to Hank! Solution is in the comments.
Here is my HTML code:
<!DOCTYPE html>
<html>
    <head>
        <title>Learning JavaScript</title>
    </head>
    <body>
        <form id="register-form">
            <input id="name" type="text" placeholder="Name" value=""/>
            <input id="pw" type="password" placeholder="Password" value=""/>
            <input id="rgstr_btn" type="submit" value="get Account" onClick="store()"/>
        </form>

        <form id="login-form">
            <input id="userName" type="text" placeholder="Enter Username" value=""/>
            <input id="userPw" type="password" placeholder="Enter Password" value=""/>
            <input id="login_btn" type="submit" value="Login" onClick="check()"/>
       </form>

    <script type="text/javascript" src="jquery-1.11.3.min.js"></script>
    <script type="text/javascript" language="javascript" src="login.js"></script>

    </body>
</html>

And here is my JavaScript code:
// Name and Password from the register-form
var name = document.getElementById('name');
var pw = document.getElementById('pw');

// storing input from register-form
function store() {
    localStorage.setItem('name', name.value);
    localStorage.setItem('pw', pw.value);
}

// check if stored data from register-form is equal to entered data in the   login-form
function check() {

    // stored data from the register-form
    var storedName = localStorage.getItem('name');
    var storedPw = localStorage.getItem('pw');

    // entered data from the login-form
    var userName = document.getElementById('userName');
    var userPw = document.getElementById('userPw');

    // check if stored data from register-form is equal to data from login form
    if(userName.value !== storedName || userPw.value !== storedPw) {
        alert('ERROR');
    }else {
        alert('You are loged in.');
    }
}

A: you have 2 issues:
1. "name" is a reserved word, it's gonna act goffy on you, change it to something else like name1 or nm or something.
2. don't use !==, != will do, you logic is faulty anyways, change it to this:
if(userName.value == storedName && userPw.value == storedPw) {
        alert('You are loged in.');
    }else {
        alert('ERROR.');
    }

But yeah, I know you are just practicing, but don't actually save usernames and passwords on the client side.

A: // entered data from the login-form
var userName=document.getElementById('userName');
var userPw = document.getElementById('userPw');

This is where the issue came to you.
You wanted to compare the entered values with the localStorage data. This is good but it should have been like this:
var userName = document.getElementById('userName').value;
var userPw = document.getElementById('userPw').value;

This is the correct way to get the value of the input field.

A:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>logSign</title>
</head>

<body>
  <form id="signup-form">
    <input id="name1" type="text" placeholder="Username" value="" required>
    <input id="pass1" type="password" placeholder="Password" value="" required>
    <input id="signup_btn" type="submit" value="Signup">
  </form>

  <form id="login-form">
    <input id="name2" type="text" placeholder="Username" value="" required>
    <input id="pass2" type="password" placeholder="Password" value="" required>
    <input id="login_btn" type="submit" value="Login">
  </form>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    $(document).ready(function () {
      $("#signup-form").submit(function () {
        var nm1 = $("#name1").val();
        var ps1 = $("#pass1").val();
        localStorage.setItem("n1", nm1);
        localStorage.setItem("p1", ps1);

      });

      $("#login-form").submit(function () {
        var enteredName = $("#name2").val();
        var enteredPass = $("#pass2").val();

        var storedName = localStorage.getItem("n1");
        var storedPass = localStorage.getItem("p1");

        if (enteredName == storedName && enteredPass == storedPass) {
          alert("You are logged in!");
        }
        else {
          alert("Username and Password do not match!");
        }

      });

    });
  </script>
</body>

</html>


text:
Q: Python module import fails for unknown reason I am trying to import a module in python that contains the following lines:
#setup.py
def isnumber(pause):
    try:
        float(pause)
        return True
    except ValueError:
        return False

I am trying to call it like this:
#program.py
import setup

but I get the following error:
    Traceback (most recent call last):
  File "C:\Users\rthompson@iingen.unam.mx\ralph\programas\python\scraper\release\program.py", line 4, in <module>
    import setup
  File "C:\Users\rthompson@iingen.unam.mx\ralph\programas\python\lib\setup.py", line 55, in <module>
    download_url="http://www.crummy.com/software/BeautifulSoup/download/"
  File "C:\Users\rthompson@iingen.unam.mx\ralph\programas\python\lib\distutils\core.py", line 140, in setup
    raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg
SystemExit: usage: program.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: program.py --help [cmd1 cmd2 ...]
   or: program.py --help-commands
   or: program.py cmd --help

error: no commands supplied

Line 55 in setup.py corresponds to return True in the code above.
Without the isnumber function the import works as expected.
Can anyone see what I'm doing wrong?

A: You've decided to call your module "setup.py". This is a dangerous name to pick since it's commonly used for the build/install script for Python modules, much like the one yours already has. Pick a different name.


text:
Q: Margin/padding on IE7 problem - how to fix it? Why, with this code, the input type=text get the margin/padding from the div parents?
Input are padded-top of 50px (inherit from .loc_title) and marged-left of 30px (inherit from loc_main).
It really doesnt make sense :(
The funny things is that If I swap margin/padding on loc_main and loc_cerca the input get the right align! So I need to use padding with left-right and margin with top-bottom? I can't believe this...

A: set overflow: visible on the input field and the margins should disappear. It's a classic ie bug.


text:
Q: Access Calendar through Coded UI For Coded UI, I want to access the Calendar through Hand Coding and Note that Textbox which displays the selected date is not editable manually so Setproperty does not work.
Please Help.


text:
Q: After normal shutdown, pc doesn't start/boot, leds and fans light/spin for a second Sometimes after shutting my pc down in the evening and starting it back up in the morning the pc will not boot. The fans spin for a second, LEDs light up also for a second but the pc stays off.
While the LEDs of the RAM will stay on, the power button is unresponsive (Case and Motherboard). The only way to reset my pc is to drain the PSU with the main switch on the PSU.
After that it boots up then I try it a second time, but sometimes i need more attempts to successfully boot. (Doing the same steps above, Drain PSU, etc.)
I switched the Motherboard and CPU after one died (Didn't have spare parts to troubleshoot them). Also unplugged my corsair commander pro after USB issues.
My current setup is

*

*MB Asus x570 PRO

*CPU AMD Ryzen 7 5700x

*GPU EVGA RTX 3070 XC3 Ultra

*PSU Bitfenix Whisper M 650w Gold (bought 01/18)

I hope I have listed everything, if not I'm happy to provide more informations.


text:
Q: using winapi in mingw assembler I'm tring to compile the following assembly code into shared library (dll)
.extern _GetProcAddress

.global _main
_main:
    CALL _GetProcAddress

using the following commend:
i686-w64-mingw32-gcc -shared -o file.dll file.S

but I'm getting the following link error:
`_GetProcAddress' referenced in section `.text' of /tmp/ccamwU4N.o: defined in discarded section `.text' of /usr/lib/gcc/i686-w64-mingw32/4.6/../../../../i686-w64-mingw32/lib/../lib/libkernel32.a(dxprbs00553.o)

how can I fix this error and call winapi functions?

A: This code:
// file: winapi0.s
.extern  ___main
.extern  _GetStdHandle@4
.extern  _WriteConsoleA@20

        .data
_text:
        .ascii "Hello World!\12\0"

        .section .text.startup,"x"
        .p2align 2,,3

.globl  _main
_main:
        leal    4(%esp), %ecx
        andl    $-16, %esp
        pushl   -4(%ecx)
        pushl   %ebp
        movl    %esp, %ebp
        pushl   %ecx
        subl    $52, %esp
        call    ___main
        movl    $-11, (%esp)
        call    _GetStdHandle@4
        pushl   %edx
        movl    $0, 16(%esp)
        leal    -12(%ebp), %edx
        movl    %edx, 12(%esp)
        movl    $14, 8(%esp)
        movl    $_text, 4(%esp)
        movl    %eax, (%esp)
        call    _WriteConsoleA@20
        subl    $20, %esp
        xorl    %eax, %eax
        movl    -4(%ebp), %ecx
        leave
        leal    -4(%ecx), %esp
        ret

Compiles for me just fine with:
gcc -Wall -O2 winapi0.s -o winapi0.exe

And it works by printing this:
Hello World!

It's a slightly cleaned up version of this C code translated by gcc into assembly with the -S switch:
// file: winapi.c
#include <windows.h>
#include <tchar.h>

TCHAR text[] = _T("Hello World!\n");

int main(void)
{
  DWORD err;

  WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE),
               text,
               sizeof(text) / sizeof(text[0]),
               &err,
               NULL);

  return 0;
}

I got originally this:
        .file   "winapi.c"
        .def    ___main;        .scl    2;      .type   32;     .endef
        .section        .text.startup,"x"
        .p2align 2,,3
        .globl  _main
        .def    _main;  .scl    2;      .type   32;     .endef
_main:
LFB14:
        .cfi_startproc
        leal    4(%esp), %ecx
        .cfi_def_cfa 1, 0
        andl    $-16, %esp
        pushl   -4(%ecx)
        pushl   %ebp
        movl    %esp, %ebp
        .cfi_escape 0x10,0x5,0x2,0x75,0
        pushl   %ecx
        .cfi_escape 0xf,0x3,0x75,0x7c,0x6
        subl    $52, %esp
        call    ___main
        movl    $-11, (%esp)
        call    _GetStdHandle@4
        pushl   %edx
        movl    $0, 16(%esp)
        leal    -12(%ebp), %edx
        movl    %edx, 12(%esp)
        movl    $14, 8(%esp)
        movl    $_text, 4(%esp)
        movl    %eax, (%esp)
        call    _WriteConsoleA@20
        subl    $20, %esp
        xorl    %eax, %eax
        movl    -4(%ebp), %ecx
        .cfi_def_cfa 1, 0
        leave
        leal    -4(%ecx), %esp
        .cfi_def_cfa 4, 4
        ret
        .cfi_endproc
LFE14:
        .globl  _text
        .data
_text:
        .ascii "Hello World!\12\0"
        .def    _GetStdHandle@4;        .scl    2;      .type   32;     .endef
        .def    _WriteConsoleA@20;      .scl    2;      .type   32;     .endef

Can't you do the same for the 64-bit case?

A: Link with the import library for the Windows DLL that contains the function you want to call.
I believe that symbol is contained in kernel32.dll.  You'll need to make an import library and then link with it.


text:
Q: Trigger on Table A Does Merge (Upsert) into Table B I am trying to add a trigger to Table A that does an upsert into Table B whenever an insert or update is performed.  I am using a MERGE to accomplish this.
This database is running on SQL Server 2008 R2.
Here is my script:
USE [XMPie]
GO

/****** Object:  Trigger [dbo].[tr_targetupd40836-09]    Script Date: 5/25/2017 10:18:30 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[tr_targetupd40872-01a]
ON [dbo].[40872-01]
after update, insert as

DECLARE @CJ int, @BPID int, @Email varchar(100)

IF (SELECT TOP 1 OptOut FROM inserted) = 1
BEGIN
    SELECT top 1 @CJ = CAST([MicrositeNumber] AS int) FROM inserted

    SELECT TOP 1 @BPID =  bp.BPID
            FROM JandLreporting.dbo.ControlJob cj
            INNER JOIN JandLreporting.dbo.BusinessPartner bp
            ON cj.JLMReferenceID = bp.JLMReferenceID
            WHERE cj.ControlJob = @CJ

    SELECT top 1 @Email = RTRIM(LTRIM(Email)) FROM inserted

    IF @BPID IS NOT NULL AND NOT EXISTS (SELECT * FROM [DoNotContactEmail] where Email = @Email and BPID = @BPID)
    INSERT [DoNotContactEmail](email, bpid) VALUES(@Email, @BPID)
END
ELSE
BEGIN
    MERGE JandLreporting.dbo.MicrositeResponseAdor AS T
    USING inserted AS S
    ON T.RecipientKey = S.RecipientKey
    WHEN MATCHED THEN
         UPDATE set T.[MicrositeResponse_ID]= (s.[MicrositeResponse_ID])
        ,T.[MicrositeNumber]=LEFT(s.[MicrositeNumber],50)
        ,T.[RecipientKey]=LEFT(s.[RecipientKey],101)
        ,T.[Vin]=LEFT(s.[Vin],30)
        ,T.[FirstName]=LEFT(s.[FirstName],50)
        ,T.[MiddleInitial]=LEFT(s.[MiddleInitial],1)
        ,T.[LastName]=LEFT(s.[LastName],50)
        ,T.[FullName]=LEFT(s.[FullName],100)
        ,T.[Address1]=LEFT(s.[Address1],100)
        ,T.[Address2]=LEFT(s.[Address2],50)
        ,T.[City]=LEFT(s.[City],50)
        ,T.[State]=LEFT(s.[State],2)
        ,T.[ZipCode]=LEFT(s.[ZipCode],10)
        ,T.[PhoneNumber]=LEFT(s.[PhoneNumber],15)
    WHEN NOT MATCHED THEN
      INSERT (T.[ID]
        ,T.[MicrositeResponse_ID]
        ,T.[MicrositeNumber]
        ,T.[RecipientKey]
        ,T.[Vin]
        ,T.[FirstName]
        ,T.[MiddleInitial]
        ,T.[LastName]
        ,T.[FullName]
        ,T.[Address1]
        ,T.[Address2]
        ,T.[City]
        ,T.[State]
        ,T.[ZipCode]
        ,T.[PhoneNumber]
        )
      VALUES (s.[ID]
        ,s.[MicrositeResponse_ID]
        ,s.[MicrositeNumber]
        ,s.[RecipientKey]
        ,s.[Vin]
        ,s.[FirstName]
        ,s.[MiddleInitial]
        ,s.[LastName]
        ,s.[FullName]
        ,s.[Address1]
        ,s.[Address2]
        ,s.[City]
        ,s.[State]
        ,s.[ZipCode]
        ,s.[PhoneNumber])
END

GO

When I try to apply this trigger, I get the following error:
Msg 102, Level 15, State 1, Procedure tr_targetupd40872-01a, Line 26 [Batch Start Line 9]
Incorrect syntax near ' '.

I can't figure out where the syntax error is.  Any help would be appreciated!

A: You need to wrap the code for the trigger in a BEGIN/END, as follows:
CREATE TRIGGER [dbo].[tr_targetupd40872-01a]
ON [dbo].[40872-01]
after update, insert as
BEGIN --begin trigger
  DECLARE @CJ int, @BPID int, @Email varchar(100)

  IF (SELECT TOP 1 OptOut FROM inserted) = 1
  BEGIN
    SELECT top 1 @CJ = CAST([MicrositeNumber] AS int) FROM inserted

    SELECT TOP 1 @BPID =  bp.BPID
      FROM JandLreporting.dbo.ControlJob cj
        INNER JOIN JandLreporting.dbo.BusinessPartner bp
          ON cj.JLMReferenceID = bp.JLMReferenceID
      WHERE cj.ControlJob = @CJ

    SELECT top 1 @Email = RTRIM(LTRIM(Email)) FROM inserted

    IF @BPID IS NOT NULL AND NOT EXISTS (SELECT * FROM [DoNotContactEmail] where Email = @Email and BPID = @BPID)
    INSERT [DoNotContactEmail](email, bpid) VALUES(@Email, @BPID)
  END
  ELSE
  BEGIN
    MERGE JandLreporting.dbo.MicrositeResponseAdor AS T
      USING inserted AS S
      ON T.RecipientKey = S.RecipientKey
      WHEN MATCHED THEN UPDATE
        set T.[MicrositeResponse_ID]= (s.[MicrositeResponse_ID])
           ,T.[MicrositeNumber]=LEFT(s.[MicrositeNumber],50)
           ,T.[RecipientKey]=LEFT(s.[RecipientKey],101)
           ,T.[Vin]=LEFT(s.[Vin],30)
           ,T.[FirstName]=LEFT(s.[FirstName],50)
           ,T.[MiddleInitial]=LEFT(s.[MiddleInitial],1)
           ,T.[LastName]=LEFT(s.[LastName],50)
           ,T.[FullName]=LEFT(s.[FullName],100)
           ,T.[Address1]=LEFT(s.[Address1],100)
           ,T.[Address2]=LEFT(s.[Address2],50)
           ,T.[City]=LEFT(s.[City],50)
           ,T.[State]=LEFT(s.[State],2)
           ,T.[ZipCode]=LEFT(s.[ZipCode],10)
           ,T.[PhoneNumber]=LEFT(s.[PhoneNumber],15)
      WHEN NOT MATCHED THEN INSERT (
            T.[ID]
           ,T.[MicrositeResponse_ID]
           ,T.[MicrositeNumber]
           ,T.[RecipientKey]
           ,T.[Vin]
           ,T.[FirstName]
           ,T.[MiddleInitial]
           ,T.[LastName]
           ,T.[FullName]
           ,T.[Address1]
           ,T.[Address2]
           ,T.[City]
           ,T.[State]
           ,T.[ZipCode]
           ,T.[PhoneNumber]
        ) VALUES (
           s.[ID]
          ,s.[MicrositeResponse_ID]
          ,s.[MicrositeNumber]
          ,s.[RecipientKey]
          ,s.[Vin]
          ,s.[FirstName]
          ,s.[MiddleInitial]
          ,s.[LastName]
          ,s.[FullName]
          ,s.[Address1]
          ,s.[Address2]
          ,s.[City]
          ,s.[State]
          ,s.[ZipCode]
          ,s.[PhoneNumber]
        )
  END
END  -- End of trigger
GO


text:
Q: How to export an fbx from an imported obj using assimp I am creating my C++ game engine and I wanted to be able to export my scenes using the FBX format.
So, when I tried to export an FBX from a previously imported OBJ file, that actually renders correctly. But it is not exported correctly when exporting to anything other than what it was originally imported from.
std::unique_ptr<Assimp::Exporter> exporter = std::make_unique<Assimp::Exporter>();

const auto* scene = mesh->mScene;
exporter->Export(scene, "fbx", "assets/output.fbx");

Here, mesh->mScene is the aiScene imported previously.
This code actually works and Export() returns success; however, the output file does not include the proper data of the mesh. Only when imported from an FBX is it correct and can be imported in Maya without problems.
I need a way to convert Assim::aiScene to be exported in the FBX format, because Assimp only allows to export meshes to the same format as it is imported from.
Also, I wanted to be able to modify the meshes, let's say I want to replace the diffuse texture.
//Yeah, sorry I am still a beginner :)
auto* aiMaterial = mesh->mScene->mMaterials[index];

if (aiMaterial->RemoveProperty("$clr.diffuse") != 0 || aiMaterial->AddProperty(texture->getPath().c_str(), 1, "$clr.diffuse") != 0)
{
    assert(false, "Failed to add property!");
}

This code also runs fine but it does not change anything in the mesh.


text:
Q: I can´t download Apache jsvc I want to install Jboss eap 7 as a services on windows server 2012.
I'm following the tutorial in Red Hat; and it ask to download "JBoss Core Services Jsvc Package" (Apache Jsvc).
I click the link in the Red Hat page: JBoss Software Downloads page. But I get an empty combo (image) and I can't download it
I have a Red Hat account, I'm log in and I have my email authenticated but the download combo is still empty

A: Well I found the problem.
I have to pay for a client account to download the Apache jsvc


text:
Q: Cómo ejecutar correctamente un proyecto de Xamarin? Tengo el siguiente mensaje al ejecutar un proyecto de Xamarin, ya lo probé en dos máquinas y me sale el mismo error. Instalé Xamarin desde el mismo Visual Studio Installer, se debe a eso o qué podría hacer para solucionarlo, ya que no responde cuando trato de ejecutarlo y se cuelga durante mucho tiempo. Gracias por su ayuda.
Extension 'Xamarin  Templates 1.0.56' likely caused 9 seconds of unresponsiveness...

Aparecen estos warnings:

Severity  Code    Description Project Path    File    Line    Suppression State
  Warning   NU1605  Detected package downgrade: Xamarin.Forms from
  2.5.1.444934 to 2.5.0.280555. Reference the package directly from the project to select a different version.   SmartReport.Android ->
  SmartReport -> Xamarin.Forms (>= 2.5.1.444934)   SmartReport.Android
  -> Xamarin.Forms (>= 2.5.0.280555)

otro:

Severity  Code    Description Project Path    File    Line    Suppression State
  Warning   NU1605  Detected package downgrade: Xamarin.Forms from
  2.5.1.444934 to 2.5.0.280555. Reference the package directly from the project to select a different version.   SmartReport.iOS ->
  SmartReport -> Xamarin.Forms (>= 2.5.1.444934)   SmartReport.iOS ->
  Xamarin.Forms (>= 2.5.0.280555)

A: Los warnings son porque tienes diferentes versiones del paquete Xamarin.Forms en el core y en iOS, revisa y actualiza los paquetes de nuget de toda la solución, para que este todo igualado.
Lo del unresponsive... pf... a mi me daba por ejemplo por culpa del antivirus, que me escaneaba cosas de mis proyectos mientras los usaba. Si no tienes ssd y tienes "poca" ram puede ser hasta normal. Intenta tener todo actualizado, visual studio, extensiones y paquetes.


text:
Q: Django: modify model's field before save I have a model, course, with an ImageField and FileField so I'd like to create a folder each time the user create a course. I think I can do this before the model is saved so here is my question.
How can I access a model's fields in a method?
Models.py
Class Course(models.Model):
 Thumbnail = model.ImageField(upload_to="...",...)

    def save(self, *args, **kwargd):
        ... #How can I alter here the ImageField parameters?
        super().save(*args, **kwargs)

A: See here on getting the model's fields.
To get field of an object instance then it should just be as
def save(self, *args, **kwargs):
     #### How can I alter here the ImageField parameters?
     self.Thumbnail = #do whatever you want here
     super().save(*args, **kwargs)

It's not possible to alter field's params in a method. It must only be done in the field definitions because the model must be saved first

A: Instance of the models field can be accessed using self like a normal instance variable.
For example in a model class below,
class DummyModel(models.Model):
    key = models.CharField()
    value = models.TextField()

    def save(self, *args, **kwargs):
        value = self.value # self.value is a model field.
        super().save(*args, **kwargs)

In your case, you can access it using self.Thumbnail

A: Since it's not possible to modify the model field's parameters before create it, as @azyCrw4282 said in his answer, it's possible to create a directory with the name of the model's instance and upload there the files parsing a function to upload_to
models.py
def upload_to(instance, filename):
    return 'user_course/{0}/{1}'.format(instance.name, filename) #instance.name will be the name of the course

class Course(models.Model):
    name       = model.CharField(...)
    thumbnail  = models.ImageField(upload_to=upload_to, ...)