text:
Q: Is there a way to chain Result mapping and unwrapping? I have this code.
if let Ok(file) = env::var("CONF") {
    if let Ok(mut reader) = fs::File::open(&file) {
        if let Ok(conf) = Json::from_reader(&mut reader) {
            // do something with conf
        }
    }
}

I'm trying to make it less like a festive holiday tree and was thinking about chaining. Notice that each step in this chain produces another Result, so clearly this won't work (we get Result in Result).
let conf = env::var("CONF")
    .map(fs::File::open)
    .map(Json::from_reader);

// do something with conf

Also my error types differ for each step, which means I can't just replace .map with .and_then.
I think I'm looking for something that is similar to JavaScript's promises. That is, a promise returned from inside a promise unwraps the inner promise. The signature should probably be along the lines of:
impl<T, E> Result<T, E> {
    fn map_unwrap<F, U, D>(&self, op: F) -> Result<U, D>
        where F: FnOnce(T) -> Result<U, D>
}

Is there such a mechanism in Rust? Is there another way to get rid of my festive holiday tree?

A: If you actually want to ignore the results as you are doing with if let you can use a macro like this:
macro_rules! iflet {
    ([$p:pat = $e:expr] $($rest:tt)*) => {
        if let $p = $e {
            iflet!($($rest)*);
        }
    };
    ($b:block) => {
        $b
    };
}

fn main() {
    iflet!([Ok(file) = env::var("CONF")]
           [Ok(mut reader) = File::open(&file)]
           [Ok(conf) = Json::from_reader(&mut reader)] {
        // do something with conf
    });
}

Playground (without Json part)
The macro is originally from an answer I made to a similar question on Options, but it works with any if let. Though, with Result you often want to use the Err in some way, so I would usually lean towards the approach explained by Shepmaster or ?/try!.

A:
Is there such a mechanism in Rust?

Yes — although not all in one shot like you've presented. Let's review your theoretical signature:
impl<T, E> Result<T, E> {
    fn map_unwrap<F, U, D>(&self, op: F) -> Result<U, D>
    where
        F: FnOnce(T) -> Result<U, D>,
    {}
}

This cannot work - assume that we start with an Err variant - how would this code know how to convert from E to D? Additionally, &self isn't appropriate for functions that want to convert types; those usually take self.
There are two components that you will need to combine:

*

*Result::and_then
impl<T, E> Result<T, E> {
    fn and_then<U, F>(self, op: F) -> Result<U, E>
    where
        F: FnOnce(T) -> Result<U, E>,
    {}
}

*Result::map_err
impl<T, E> Result<T, E> {
    fn map_err<F, O>(self, op: O) -> Result<T, F>
    where
        O: FnOnce(E) -> F,
    {}
}

Then you will need a type that can represent both error types. I'll be lazy and use Box<Error>
Combined together, you need something like:
use std::env;
use std::fs::File;
use std::error::Error;

fn main() {
    let conf = env::var("CONF")
        .map_err(|e| Box::new(e) as Box<Error>)
        .and_then(|f| File::open(f).map_err(|e| Box::new(e) as Box<Error>));
}

Now each call converts the error value to a shared type, and the result is chainable with and_then. Presumably, your real code would create an error type that is suited to your problem, and then you would use that in the map_err call. I'd implement From, then you can have just:
let conf: Result<_, Box<Error>> = env::var("CONF")
    .map_err(Into::into)
    .and_then(|f| File::open(f).map_err(Into::into));

A: The anyhow crate makes it possible to chain different error types together, and combined with the ? operator you can express sequences of Results very concisely. The downside is you need to return a Result from the function, so in certain cases you'll need to create a helper. If you only need the helper in one place though you can define it inside the calling function so it doesn't pollute the surrounding namespace.
Here's a simple example where I wanted to get a usize from an environment variable:
fn main() {
    fn env_int(key: &str) -> anyhow::Result<usize> {
        Ok(std::env::var(key)?.parse()?)
    }

    println!("{:?}", env_int("MISSING"));
    println!("{:?}", env_int("CARGO_PKG_VERSION"));
    println!("{:?}", env_int("PLAYGROUND_EDITION"));
}


text:
Q: AngularJS expression in Razor tag helper I try to use an AngularJS expression in a Razor tag helper, like this:
Edit

But the AngularJS expression is not expanded. What is the correct syntax? Is it even possible? Are there alternatives?

A: You have to remove tag helpers and it will work !.
Edit

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error:cannot access NotNull I encounter the error above when compiling, and it doesn't goes to to any source file. After slowly identify the changes that cause the issue, found out it is apparently the dagger 2 inject is causing issue.
@FragmentScope
@Subcomponent
public interface MyComponent {
    void inject(MyJavaFragment myJavaFragment);

    void inject(MyJavaClass myJavaClass);

    void inject(MyKotlinClass myKotlinClass); // <- if change to Java, all works
}

I converted MyKotlinClass from Java code to Kotlin, and the error happens. This is in a library, and I already use that in build.gradle
kapt "com.google.dagger:dagger-compiler:$daggerVersion"

Why? (note: the app code is originally Java, so I didn't change all to Kotlin yet unless needed).

A: After long hours of investigation, found out that, the calling Feature to this library, still using the Java Annotation
annotationProcessor "com.google.dagger:dagger-compiler:$daggerVersion"

But my library is using kapt as mentioned in the question above. So that's a clash of annotation processor used, and Java annotation processor is used instead I suspect. By changing the calling library annotation processor to
kapt "com.google.dagger:dagger-compiler:$daggerVersion"

would solve the problem. (remember to add apply plugin: 'kotlin-kapt' at the top as well)

A: Besides the case mentioned by Elye, this can also happen when a field annotated with @Inject has no corresponding @Provides method on a Dagger module, or at least a constructor annotated with @Inject
I know there is already a Dagger error complaining about this, but I stumbled accross this today after removing the module with the @Provides method and expecting a clean rebuild to tell me what was missing via that error... but I got this error instead.


text:
Q: How to capture full output of `git clone`? When I run git clone like usual, I see this:
$ git clone https://github.com/bensmithett/webpack-css-example
Cloning into 'webpack-css-example'...
remote: Counting objects: 179, done.
remote: Total 179 (delta 0), reused 0 (delta 0), pack-reused 179
Receiving objects: 100% (179/179), 24.07 KiB | 0 bytes/s, done.
Resolving deltas: 100% (79/79), done.
Checking connectivity... done

However, when I try to redirect that to a file (or store it in a shell variable) I only see this:
Cloning into 'webpack-css-example'...

Here is what I tried:
$ git clone https://github.com/bensmithett/webpack-css-example 2>&1 | tee out.log
$ cat out.log
Cloning into 'sample-data'...

I tried it in Node.js as well, and it does the same thing:
const fs = require('fs');
const child = spawn('git clone https://github.com/bensmithett/webpack-css-example');
child.stdout.on('data', function(data){
  console.log(String(data));
});
child.stderr.on('data', function(data){
  console.log(String(data));
});
// Cloning into 'webpack-css-example'...

Why is all the remote: etc. stuff not getting piped to either stdin/stderr? Is there any way to capture the output? If not, what is happening that makes it so the output is displayed in the terminal, yet it is not being passed through either stdout or stderr?

A: By default Git will display the cloning progress only when the standard error stream is directed to a terminal. Since you're redirecting it to the pipe, the output stream is no longer attached to the terminal. So in order to capture the output, you need to add --progress parameter to force the progress status, e.g.
git clone --progress https://github.com/foo/bar 2> out.log

or, in order to store the output in a shell variable
out=$(git clone --progress https://github.com/foo/bar 2>&1)

See: man git-clone

--progress
Progress status is reported on the standard error stream by default when it is attached to a terminal, unless -q is specified. This flag forces progress status even if the standard error stream is not directed to a terminal.

To force the terminal in any other way, you'll have to preload some library to force isatty() to return always true (see: man isatty). This function is used by git across the source code.


text:
Q: No me captura el error de mi procedimiento Spring Boot Tengo un procedimiento con raiserror y el spring no me captura el error o tal vez estoy haciendo algo mal.
Dejo el codigo.
Procedure
ALTER PROC [dbo].[SP_CRUD_USERS]
@OPCION INT = 0,
@NOM_USER VARCHAR(50) = NULL,
@EMA_USER VARCHAR(50) = NULL,
@COD_USER INT = 0
AS
BEGIN
    SET NOCOUNT ON
    BEGIN TRY
        IF @OPCION = 1
            BEGIN
                SELECT * FROM TB_USERS
            END
        ELSE IF @OPCION = 2
            BEGIN
                IF NOT EXISTS (SELECT * FROM TB_USERS WHERE EMA_USER = @EMA_USER)
                    BEGIN
                        IF @NOM_USER IS NULL OR @NOM_USER = '' AND @EMA_USER IS NULL OR @EMA_USER = ''
                            RAISERROR('Ingresar un dato para registrar',16,1)
                        ELSE
                            INSERT INTO TB_USERS VALUES (@NOM_USER, @EMA_USER)
                    END
                ELSE
                    RAISERROR('El email ya existe',16,1)
            END
        ELSE IF @OPCION = 3
            BEGIN
                IF EXISTS (SELECT * FROM TB_USERS WHERE COD_USER = @COD_USER)
                    BEGIN
                        IF @NOM_USER IS NULL OR @NOM_USER = '' AND @EMA_USER IS NULL OR @EMA_USER = ''
                            RAISERROR('Ingresar un dato para actualizar',16,1)
                        ELSE
                            UPDATE TB_USERS SET NOM_USER = @NOM_USER, EMA_USER = @EMA_USER WHERE COD_USER = @COD_USER
                    END
                ELSE
                    RAISERROR('El usuario no existe',16,1)
            END
        ELSE IF @OPCION = 4
            BEGIN
                IF EXISTS (SELECT * FROM TB_USERS WHERE COD_USER = @COD_USER)
                    DELETE FROM TB_USERS WHERE COD_USER = @COD_USER
                ELSE
                    RAISERROR('El usuario no existe',16,1)
            END
        END TRY
    BEGIN CATCH
        PRINT ERROR_MESSAGE()
    END CATCH
END

Service
@Service
public class CrudUserService implements CrudUserDAO{

    @PersistenceContext
    private EntityManager em;

    @SuppressWarnings({ "unchecked" })
    @Override
    public ValidateApiResponse MntUser(Integer op, String nom, String ema, Integer cod) {
        ValidateApiResponse vapi = new ValidateApiResponse();
        Session session = em.unwrap(Session.class);
        try {
            ProcedureCall call = session.createStoredProcedureCall("SP_CRUD_USERS");
            call.registerParameter(1, Integer.class, ParameterMode.IN);
            call.registerParameter(2, String.class, ParameterMode.IN).enablePassingNulls(true);
            call.registerParameter(3, String.class, ParameterMode.IN).enablePassingNulls(true);
            call.registerParameter(4, Integer.class, ParameterMode.IN).enablePassingNulls(true);
            call.setParameter(1, op);
            call.setParameter(2, nom);
            call.setParameter(3, ema);
            call.setParameter(4, cod);
            vapi.dTable = call.getResultList();
            vapi.Attr = "OK";
            //call.execute();
        } catch (Exception e) {
            vapi.Error = e.getMessage();
        } finally {
            session.close();
        }
        return vapi;
    }
}

Controller
@RestController
public class CrudUserController {

    @Autowired
    private CrudUserService service;

    @RequestMapping(value = "/CrudUsers", method = RequestMethod.POST)
    public @ResponseBody ApiResponse CrudUsers(@RequestParam(value = "option", required = true) Integer op,
                                 @RequestParam(value = "nomUser", required = false) String nom,
                                 @RequestParam(value = "emaUser", required = false) String ema,
                                 @RequestParam(value = "codUser", required = false) Integer cod){

        ValidateApiResponse vapi = new ValidateApiResponse();
        ApiResponse  api = new ApiResponse();

        try {
            vapi = service.MntUser(op,nom,ema,cod);
            if (vapi.Error == null || vapi.Error == "") {
                if (vapi.Attr == "OK") {
                    api.MsjCode = 200;
                    api.Msj = "OK";
                    api.dtCollection = vapi.dTable;
                } else {
                    api.MsjCode = 400;
                    api.Msj = "Dismissed Request";
                    api.MsjDetail = vapi.Attr;
                }
            } else {
                api.Msj = "Internal Server Error";
                api.MsjDetail = vapi.Error;
                api.MsjCode = 500;
            }
        } catch (Exception e) {
            api.Msj = "Internal Server Error";
            api.MsjDetail = e.getMessage();
            api.MsjCode = 500;
        }
        return api;
    }
}

ApiResponse
public class ApiResponse {

    public String Msj;
    public String MsjDetail;
    public List<Object> dtCollection;
    public int MsjCode;

    public ApiResponse() {
        this.Msj = "";
        this.MsjDetail = "";
        this.MsjCode = -1;
        this.dtCollection = new ArrayList<>();
    }
}

ValidateApiResponse
public class ValidateApiResponse {

    public String Error;
    public String Attr;
    public List<Object> dTable;

    public ValidateApiResponse() {
        this.Error = "";
        this.Attr = "";
        this.dTable = new ArrayList<>();
    }
}

Ademas tengo otro problema, cuando me muestra el json no me genera las "keys". Tal vez me diran que deba crear la entidad, pero yo quisiera que sea algo dinamico, tal vez agregar algunos datos mas al procedure y estar creando el atributo de esa entidad, me parece algo tedioso, pero quisas estea equivocado.
{
    "Msj": "OK",
    "MsjDetail": "",
    "dtCollection": [
        [
            1,
            "AAA",
            "AAA@HOTMAIL.COM"
        ],
        [
            2,
            "BBB",
            "BBB@HOTMAIL.COM"
        ],
        [
            3,
            "CCC",
            "CCC@HOTMAIL.COM"
        ]
    ],
    "MsjCode": 200
}

Ademas quisiera que estea dentro de corchetes y llaves osea [{3,"ccc","ccc@hotmail.com"}] algo asi


text:
Q: How to solve eclipse weblogic plugin jdk version compliance error How can you set the java home property to a jdk in the eclipse weblogic server tools plugin - when it prompts that "Java 8 is required"?  The jdk I specify is java 8.
I'm on Windows 10 - I tried eclipse 2019-03 (4.11.0) and an older eclipse photon(4.8.0): they both have this behavior.  My machine has Weblogic 12.2.1.3.0 on it.
The plugin version on my eclipse 2019-03 is: Oracle WebLogic Server Tools   17.3.0.201903121357
I installed the plugin through the "add new server" wizard dialog - not through the marketplace by pasting a zip or jar.

The error prompts in the window after I select my weblogic install.
I'm using the Oracle jdk1.8.0_192.  It's included in my path and JAVA_HOME and JDK_HOME environment variables.
My eclipse preferences do show the expected system java runtime:

I tried deleting my eclipse workspace and deleting the eclipse temp files under user home app data - but it did not fix the error prompt.
The closest post I've seen is here, but still doesn't address the version compliance error.
Eclipse - no Java (JRE) / (JDK) ... no virtual machine

A: I had the same problem and found the solution:
Your weblogic installation needs to include a copy of your JDK.
If your weblogic server is installed to D:\Oracle\wlserver then
copy your JDK directory's content (all files and folders from C:\Program Files\Java\jdk1.8.0_211) to  D:\Oracle\oracle_common\jdk\.
On the next screen choose your domain directory, which should be something like: D:\Oracle\user_projects\domains\base_domain
This looks like a bug, as if Oracle Weblogic Server Tools did not take the path you provide into account. It always searches the same directory for JDK, which is oracle_common in the parent directory of your Weblogic installation.


text:
Q: Is the Android Emulator browser suitable and reliable for testing an HTML/Javascript Application? I'm developing an HTML / Javascript application meant to run on an Android device running Froyo (2.2). Assuming I don't need multitouch functionality, will the emulator's browser be a reliable means of debugging HTML, CSS and Javascript? Or is it possible that I would work out all the bugs in the emulator but find the actual device handles things differently?

A: The underlying code for WebKit is identical in the emulator and the actual device. The only thing you need to worry about are the other components inbetween (some carriers have proxies, for example. I used to have problems with T-Mobile where it would simply send me a outdated cached version of a site instead of even contacting the site).


text:
Q: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER for distributed transactions I am trying to set dataflow tasks in a sequence container from SourceDb(exists on my local machine) to TargetDb(exists on azure & can be accessible from SSMS).
I am getting following error whenever I run the package with transaction as Required.
Error: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER.  The AcquireConnection method call to the connection manager "TargetDb" failed with error code 0xC0202009.  There may be error messages posted before this with more information on why the AcquireConnection method call failed.
It works if I remove the transaction for that container. I have set all the distributed transaction settings correctly. I went through many link on stack overflow but nothing worked for me. Please suggest the solution.
I have also tried this process by restoring both db's on my local machine. It works with transaction successfully. There is nothing wrong with the package.

A: In order to use transaction in ssis you need to switch on Distributed Transaction coordinator. Another way is to use begin Transaction in execute sql task and in the connection properties set retainsameconnection = True in control flow and all the dft task that needs to be in transaction will follow after this and the last task will be another execute sql task with commit transaction.
Follow the below link to use transaction without switchung on distributed transaction -
https://www.mssqltips.com/sqlservertip/3072/sql-server-integration-services-ssis-transactions-without-msdtc/

A: Azure cannot participate in transactions with local SQL Servers AFAIK.

Limitations
     The following limitations currently apply to elastic database transactions in SQL DB:

*

*Only transactions across databases in SQL DB are supported. Other X/Open
  XA resource providers and databases outside of SQL DB cannot
  participate in elastic database transactions. That means that elastic
  database transactions cannot stretch across on premises SQL Server and
  Azure SQL Databases. For distributed transactions on premises,
  continue to use MSDTC.

*Only client-coordinated transactions from a .NET application are supported. Server-side support for T-SQL such as BEGIN DISTRIBUTED
  TRANSACTION is planned, but not yet available.

*Transactions across WCF services are not supported. For example, you have a WCF service method that executes a transaction. Enclosing
  the call within a transaction scope will fail as a
  System.ServiceModel.ProtocolException.

See this documentation at Microsoft for a complete discussion of distributed transactions and Azure.


text:
Q: Hey i am making a social media app and want to save a post to my db. but i keep get getting the error sqlalchemy.exc.OperationalError
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: blogpost [SQL: 'INSERT INTO blogpost (title, author, date_posted, content) VALUES (?, ?, ?, ?)'] [parameters: ('qedqdq', 'qwdqdwd', '2018-12-31 22:51:35.669388', 'qwdqwdqwdqwdqwdqwdqwdqwdw')] (Background on this error at: http://sqlalche.me/e/e3q8)
After i send the post to get published in my database i get ^^ the error
here are some of the code i am using.
Any help would be great thanks!!!
app.py
import os
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URL'] = 'sqlite:///Users/------/Desktop/face0/face/blog.db'

db = SQLAlchemy(app)

class Blogpost(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50))
    author = db.Column(db.String(20))
    date_posted = db.Column(db.DateTime)
    content = db.Column(db.Text)

@app.route('/addpost', methods=['POST'])
def addpost():
    title = request.form['title']
    author = request.form['author']
    content = request.form['content']

    post = Blogpost(title=title, author=author, content=content, date_posted=datetime.now())

    db.session.add(post)
    db.session.commit()

    return redirect(url_for('index'))

A: As mentioned in the flask-sqlalchemy documentation, you will need to first create the database by calling the create_all function.

To create the initial database, just import the db object from an
  interactive Python shell and run the SQLAlchemy.create_all() method to
  create the tables and database:

>>> from yourapplication import db
>>> db.create_all()

In your case this may look something like the following:
$ python
>>> from app import db
>>> db.create_all()
>>> exit()


text:
Q: What is an exponential function that extends from infinity to $0$ as as $x$ moves from $0$ to $1.$ Basically, I need a function $f(x)$ (or a family of functions) such that $f(0) = \infty$ and $f(1) = 0.$ The function must decrease from infinity to $0$ for all values of $x$ between $0$ and $1.$
I can't think of any.

A: Several kinds of functions will work. Since you cite 'exponential' in your question, I would suggest 'logarithmic'. Note that $f(x)=-\alpha\log x$ satisfies your conditions for all positive $\alpha$.


text:
Q: PowerShell - For each - duplicate I have a PowerShell script with a foreach loop. The Write-Host within this always writes duplicate on the screen. I added a send-mail and it sends duplicate email per record. What am I doing wrong here?
Import-module ActiveDirectory

$web = get-SPWeb "http://inside.nov.com/sales"
$list = $web.Lists["Shared Documents"]
$now = get-date;
$SearchBase = "OU=Sales,DC=NOV,DC=com"
$LdapServer = "AD748.NOV.COM"
$From = "intranet@NOV.com"
$To = "Shawna_Richardson@NOV.com"
$Cc = "TBD"
$Subject = "Testing Powershell email"
$Body = "Active Directory updates"
$SMTPServer = "smtp74.NOV.com"
$CAML = '
   <Where>
     <Eq>
        <FieldRef Name="Region" />
        <Value Type="Choice">Northwest</Value>
     </Eq>
   </Where>
'
$query = new-object Microsoft.SharePoint.SPQuery
$query.RowLimit = 10
$query.Query = $CAML
$listitems = $list.GetItems($query)
$count = $listitems.count
Write-Host $count

function Get-Data()
{
    if ($count -ge 1)
    {
        foreach($item in $listitems)
        {
            $NOVEmpID = $item["NOVEmpID"]

            if($item["NOVEmpID"] -ne $null)
            {
                $LDAPResult = Get-ADUser -SearchBase $searchbase -SearchScope 'subtree' -Server $ldapserver -filter "NOVEmpID -like '*$NOVEmpID*'" -Properties * | Select -Property AccountExpirationDate, userAccountControl
                $pair1, $pair2 = $LDAPResult -replace '^@{|}$' -split '; '
                $null, $ADExpDate = $pair1 -split '=', 2
                $null, $userAccountControl = $pair2 -split '=', 2
                if($ADExpDate){
                    $ADExpDate = [DateTime]::Parse($ADExpDate).ToShortDateString()
                }
                $SPEndDate = [DateTime]::Parse($item["SPExpDate"]).ToShortDateString()

                $data = @{
                            "Emp ID" = $item["NOVEmpID"]
                            "Sales Name" = $item["EmployeeName"]
                            "SP End Date" = $item["SPExpDate"]
                            "AD End Date" = $ADExpDate
                            "AD Account Status" = $userAccountControl
                         }
                New-Object PSObject -Property $data
                if($ADExpDate)
                {
                    if($ADExpDate -gt $SPEndDate)
                    {
                        write-host $item["NOVEmpID"] $item["EmployeeName"]    $item["SPExpDate"] $ADExpDate
                        $item["NewDate"] = $ADExpDate
                        $item.SystemUpdate()
                        $list.update()
                    }
                    if($ADExpDate -lt $SPEndDate)
                    {
                        $subject = $item["EmployeeName"] + " - " + $NOVEmpID + " date is greater than AD Date"
                        $Body = $item["EmployeeName"] + " - " + $NOVEmpID + " - "  + $item["SPExpDate"] + " - " + $ADExpDate
                        Send-MailMessage -From $From -to $To -Subject $subject -Body $Body -SmtpServer $SMTPServer
                    }
                }
                else
                {
                    $subject = $item["EmployeeName"] + " - " + $NOVEmpID + " AD Date is empty"
                    $Body = $item["EmployeeName"] + " - " + $NOVEmpID + " - "  + $item["SPExpDate"] + " - " + $ADExpDate
                    Send-MailMessage -From $From -to $To -Subject $subject -Body $Body -SmtpServer $SMTPServer
                }
            }
        }
    }
}
$csvFileForFacilities = "$((Get-Date).ToString('MM-dd-yyyy')).csv"
Write-Host $csvFileForFacilities
Get-Data | Export-Csv -NoTypeInformation -Path "G:\\Result\\export.csv"
Get-Data | Out-File $csvFileForFacilities
$web.dispose()

A: Everything inside Get-Data happens twice - because you call Get-Data twice:
get-data | Export-Csv -NoTypeInformation -Path "G:\\Result\\export.csv"
get-data | Out-File $csvFileForFacilities

Call it once and store the output in a variable, and then re-use that:
$Data = Get-Data
$Data | Export-Csv -NoTypeInformation -Path "G:\\Result\\export.csv"
$Data | Out-File $csvFileForFacilities


text:
Q: UI Automation events not getting caught from PowerPoint 2007 I am trying to capture UI Automation events from PowerPoint 2007 (or ideally any version) when the user selects a new Ribbon tab.  Using the SDK tools Inspect and AccEvent I have determined that a reasonable "parent" element to catch these events is the "Ribbon Tabs" element.
When I Scope AccEvent to that element, and register for SelectionItem_ElementSelected within the automation events, I get the events as I would expect - when a tab is clicked, AccEvent catches and logs it.
I am only allowed to post two links and can't inline images yet so I have made some mosaics to  try and squeeze as much relevant info into each link as possible, here is the link relating to the above mentioned behavior:
http://hirstius.com/media/stackoverflow/UIA_sdk_tools.png
Based upon that, I came up with the following code to catch these events from my program:
// Prior code gets foreground window, determines if it's PPT, and gets a handle to it
currentApp = AutomationElement.FromHandle(foregroundWindow);

// Create condition to find the "Ribbon Tabs" element
Condition propCondition = new PropertyCondition(
  AutomationElement.NameProperty, "Ribbon Tabs",
  PropertyConditionFlags.IgnoreCase);

// Subscribe to events on the "Ribbon Tabs" Element
SubscribeToEvents(currentApp.FindFirst(TreeScope.Descendants, propCondition));

public void SubscribeToEvents(AutomationElement element)
{
  if (element != null)
  {
    Console.WriteLine("Subscribing to PowerPoint UIA Events on object {0} ({1})",
      elementItem.GetCurrentPropertyValue(AutomationElement.NameProperty),
      elementItem.GetCurrentPropertyValue(AutomationElement.AutomationIdProperty));
    UIAeventHandler = new AutomationEventHandler(OnUIAutomationEvent);

    // Subscribe to SelectionItemPattern.ElementSelectedEvent based off AccEvent
    Automation.AddAutomationEventHandler(
      SelectionItemPattern.ElementSelectedEvent,
      element,
      TreeScope.Descendants,
      UIAeventHandler);

    Console.WriteLine("Subscribed to PowerPoint UIA Events");
  }
}

private void OnUIAutomationEvent(object src, AutomationEventArgs e)
{
  // Make sure the element still exists
  AutomationElement sourceElement;
  try
  {
    sourceElement = src as AutomationElement;
  }
  catch (ElementNotAvailableException)
  {
    return;
  }
  Console.WriteLine("UIA Event ( {0} ) for item: {1}",
    e.EventId.ProgrammaticName,
    sourceElement.GetCurrentPropertyValue(AutomationElement.NameProperty));
}

This code results in, well, nothing.
If I subscribe to the top level "Window", still nothing.
If I instead just subscribe to the top level automation element, I DO get the expected events - but with a catch.  In AccEvent, the events only appear when the tabs are clicked, truly "selected".  When I bind to the Root AutomationElement, I get the events on mouseover/hover and nothing on click.  I need the events to come only when the tab is actually selected (which is exactly the behavior AccEvent presents when Scoped to the "Ribbon Tabs" Element).
Results link: http://hirstius.com/media/stackoverflow/UIA_Result.png
I need a way to notify my .NET application when the user selects a new tab on the ribbon, am I missing something obvious?


text:
Q: how to call a htmlhelper from javascript is it possible to call a htmlhelper from javascript ?
I have tried to include it in my javascript variable but the razor view just renders the actual text rather than the dropbox.
   var statusSelector = ['Status',
                        '<input id="selectstatusList" name="selectList" type="hidden">',
                        '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp',
                         '@Html.StatusDropDownListFor(model => model.Reportstatus)',
                        '

'].join('\n');

This is all that gets rendered....
   @Html.StatusDropDownListFor(model => model.Reportstatus)

To put it into context, I only want this dropdown to appear based on the users selection in another dropdown (which would be the previous step in the workflow before this StatusDropdown)
Please note this is an mvc 3 application using razor views.

A: No its not.  When you call return View(); in your action method, the view engine parses the view and generates the html. When it encounters a @Html.Helper method, that method generate specific html (e.g. input, select etc.). It can not recognise a string within a script tag as being a @Html.Helper (and if it did, to would render it at the time).
Javascript has no concept of what a HtmlHelper is. HtmlHelpers generate html on the server side and Javascript runs on the client.
I suggest you create the dropdown inside a hidden element and use javascript to show it based on the selection in the other dropdown. Alternatively you could use AJAX to return the html for the dropdown.


text:
Q: Class not found Exception from Weblogic 9.2 In my JSF project workspace, I have a Java project A and a Weblogic EJB project B that uses the Java project.
On generating the EAR I can see that the jar for Project A and B are there in the EAR as well as that of other projects in the workspace.
However, on trying to access class from A in B i am getting a class not found exception.
The Ejb Project B has the managedbean/dao/ejb/delegate and at this point the EJB is not getting called at all. The managedbean is instantiated and from another action call I am calling the method(loadWorklist) from where the offending class is called.
Is there any specific setting I am missing?
Note this is deployed as EAR in weblogic 9.2 in UNIX server.
All required jars are loaded from inside the EAR at runtime only the classes in project A is missing.
Stack trace from the error:
javax.faces.FacesException: Error calling action method of component with id worklistForm:_idJsp131
        at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:72)
        at javax.faces.component.UICommand.broadcast(UICommand.java:109)
        at javax.faces.component.UIViewRoot._broadcastForPhase(UIViewRoot.java:97)
        at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:171)
        at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:32)
        Truncated. see log file for complete stacktrace
javax.faces.el.EvaluationException: Exception while invoking expression #{worklistManagedBean.loadWorklist}
        at org.apache.myfaces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:156)
        at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:61)
        at javax.faces.component.UICommand.broadcast(UICommand.java:109)
        at javax.faces.component.UIViewRoot._broadcastForPhase(UIViewRoot.java:97)
        at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:171)
        Truncated. see log file for complete stacktrace
java.lang.NoClassDefFoundError: com/tcs/nextgen/workflow/util/WorkflowUtil
        at com.ultimatix.nextgen.worklist.managedbean.WorklistManagedBean.loadWorklist(WorklistManagedBean.java:36)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:585)
        Truncated. see log file for complete stacktrace

Ear structure:
EAR
|
|-META-INF
|-library1.jar
|-library2.jar
|-A.jar
|-B.jar

Since this is an existing legacy app, jars are not in APP-INF/lib.

A: If module B uses classes from module A, then module A must be declared in the class path in the MANIFEST.MF of module B. The class path entries in this file is relative, so since the modules are at the same level, you can just specifiy A.jar. Other common libraries can be put in APP-INF/lib and will be automatically added to the class path. This however, is WebLogic specific behaviour.


text:
Q: How to increment the value of a (decimal) variable (with leading zero) by +1? I have a file in the name of Build.number with the content value 012 which I need to increment by +1.
So, I tried this
BN=$($cat Build.number)
BN=$(($BN+1))
echo $BN >Build.number

but here I am getting the value 11 when I am expecting 013.
Can anyone help me?

A: In any POSIX shell, you can prevent a number from being considered octal by stripping its leading zeros with a combination of the ${var#prefix} and ${var%%suffix} expansion forms:
BN=001002; BN=$(( ${BN#${BN%%[!0]*}} + 1 )); echo "$BN"
1003

In shells which support the ${var//pat/repl} syntax, you can also do that by prepending it a 1 and subtracting it from 10^{number_of_digits}:
BN=000012; BN=$(( 1$BN - 1${BN//?/0} )); echo "$BN"; BN=$((BN+1)); echo "$BN"
12
13

This works in bash, zsh, ksh93, mksh and yash.
In bash,  ksh93 and zsh (but not in yash and mksh) you can also use the fortranish ** operator (exponentiation):
BN=000012; BN=$(( 1$BN - 10**${#BN} ))

A: The leading 0 causes Bash to interpret the value as an octal value; 012 octal is 10 decimal, so you get 11.
To force the use of decimal, add 10# (as long as the number has no leading sign):
BN=10#$(cat Build.number)
echo $((++BN)) > Build.number

To print the number using at least three digits, use printf:
printf "%.3d\n" $((++BN)) > Build.number

A: bash treats constants that start with 0 as octal numbers in its arithmetic expressions, so 011 is actually 9.
That's actually a POSIX requirement.
Some other shells like mksh or zsh ignore it (unless in POSIX compliant mode) as it gets in the way far more often than it is useful.
With ksh93, BN=011; echo "$(($BN))" outputs 9, but echo "$((BN))" outputs 11.
In bash, you can use BN=$((10#$(<Build.number))), which should work as long as the number doesn't start with - or +.

A: Here is a function to increment a numeric string. It observes leading zeros and tries to preserve the number of digits. It uses no variables, so it doesn't require any shell extension for declaring local variables, and doesn't pollute the variable namespace:
# $1 -- decimal string, possibly with leading zeros or sign
# $2 -- integer increment, no leading zeros.
incnumstr()
{
  if [ $1 -lt 0 ] ; then
    set -- $(incnumstr ${1#-} $((- $2)))
    [ $1 -le 0 ] && printf "%s" ${1#-}  \
                 || printf "%s" -$1
    return
  fi

  set -- ${1#-} $2 # strip leading minus from zero

  [ $1 -eq 0 ] && printf "%s%0.*d" "$3" ${#1} $2 \
               || printf "%s%0.*d" "$3" ${#1} $(( ${1#${1%%[1-9]*}} + $2 ))
}

Interactive tests:
$ echo $(incnumstr 0 0)
0
$ echo $(incnumstr -0 0)
0
$ echo $(incnumstr 0 1)
1
$ echo $(incnumstr 0 -1)
-1
$ echo $(incnumstr 00 1)
01
$ echo $(incnumstr 00 -1)
-01
$ echo $(incnumstr -10 10)
00
$ echo $(incnumstr -10 11)
01
$ echo $(incnumstr -10 20)
10
$ echo $(incnumstr -10 99)
89
$ echo $(incnumstr -10 110)
100
$ echo $(incnumstr 100 -90)
010
$ echo $(incnumstr 100 -99)
001
$ echo $(incnumstr 100 -100)
000
$ echo $(incnumstr 100 -101)
-001
$ echo $(incnumstr 100 -1234)
-1134
$ echo $(incnumstr -0000 0)
0000
$ echo $(incnumstr -0000 1)
0001
$ echo $(incnumstr -0000 -2)
-0002


text:
Q: Pygame: What's the difference between a blit() and a flip() function? And when to use one or the other? I want to know the difference between a blit() and a flip() function, some of the tutorials I follow uses either of the two I have yet to see any actually use both and explain the difference.
I know that blit() works on surface and flip() only works on display, but both seems to be doing the exact same thing, so I'm confused - in the documentation (correct me if I'm wrong) blit() seems to be putting another surface on top of the other and flip() just swapes the surface, if that's the case - wouldn't flip() be faster then blit() considering that blit() will just keep on stacking on top of the surface behind it and slowly building up memory?
EDIT: The question is not an exact duplicate of another, the link the user provided me where two completely different ones - but mentions the same function. It, did not however, answered my question at all. Please remove the duplicate tag from this post - Thanks


text:
Q: $D$-modules and quasi-projective varieties? Until recently I was under the impression, that for any morphism $f:X\rightarrow Y$ of smooth complex varieties there exist functors six functors $f^*,f_{*},...$ between the derived categories of $\cal D$-modules with bounded holonomic cohomology.
However the experts assume, that all varieties are quasi-projective (See for example Bernsteins notes 1.7 or Hotta, Takeuchi Tanisaki 1.4.19)! It seems that this assumption is manily used to guarantee that certain (finite) resolutions exist, but also on a couple of other occasions.
My questions are:
1) Is there a "philosophical" reason why one should restrict to quasi-projective case?
2) Is this assumption crucial or does the whole machinery also work for arbitrary smooth complex varieties?
3) Without the assumption is there still a six functors formalism between unbounded complexes with holonomic cohomology?
4) Does the Riemann-Hilbert correspondence fail for arbitrary smooth complex varieties?


text:
Q: How to interpret weka classification? How can we interpret the classification result in weka using naive bayes?
How is mean, std deviation, weight sum and precision calculated?
How is kappa statistic, mean absolute error, root mean squared error etc calculated?
What is the interpretation of the confusion matrix?

A: Below is some sample output for a naive Bayes classifier, using 10-fold cross-validation. There's a lot of information there, and what you should focus on depends on your application. I'll explain some of the results below, to get you started.
=== Stratified cross-validation ===
=== Summary ===

Correctly Classified Instances          71               71      %
Incorrectly Classified Instances        29               29      %
Kappa statistic                          0.3108
Mean absolute error                      0.3333
Root mean squared error                  0.4662
Relative absolute error                 69.9453 %
Root relative squared error             95.5466 %
Total Number of Instances              100

=== Detailed Accuracy By Class ===

               TP Rate   FP Rate   Precision   Recall  F-Measure   ROC Area  Class
                 0.967     0.692      0.686     0.967     0.803      0.709    0
                 0.308     0.033      0.857     0.308     0.453      0.708    1
Weighted Avg.    0.71      0.435      0.753     0.71      0.666      0.709

=== Confusion Matrix ===

  a  b   <-- classified as
 59  2 |  a = 0
 27 12 |  b = 1

The correctly and incorrectly classified instances show the percentage of test instances that were correctly and incorrectly classified. The raw numbers are shown in the confusion matrix, with a and b representing the class labels. Here there were 100 instances, so the percentages and raw numbers add up, aa + bb = 59 + 12 = 71, ab + ba = 27 + 2 = 29.
The percentage of correctly classified instances is often called accuracy or sample accuracy. It has some disadvantages as a performance estimate (not chance corrected, not sensitive to class distribution), so you'll probably want to look at some of the other numbers. ROC Area, or area under the ROC curve, is my preferred measure.
Kappa is a chance-corrected measure of agreement between the classifications and the true classes. It's calculated by taking the agreement expected by chance away from the observed agreement and dividing by the maximum possible agreement. A value greater than 0 means that your classifier is doing better than chance (it really should be!).
The error rates are used for numeric prediction rather than classification. In numeric prediction, predictions aren't just right or wrong, the error has a magnitude, and these measures reflect that.
Hopefully that will get you started.

A: To elaborate on michaeltwofish's answer, some notes on the remaining values:

*

*TP Rate: rate of true positives (instances correctly classified as a given class)

*FP Rate: rate of false positives (instances falsely classified as a given class)

*Precision: proportion of instances that are truly of a class divided by the total instances classified as that class

*Recall: proportion of instances classified as a given class divided by the actual total in that class (equivalent to TP rate)

*F-Measure: A combined measure for precision and recall calculated as 2 * Precision * Recall / (Precision + Recall)
As for the ROC area measurement, I agree with michaeltwofish that this is one of the most important values output by Weka. An "optimal" classifier will have ROC area values approaching 1, with 0.5 being comparable to "random guessing" (similar to a Kappa statistic of 0).
It should be noted that the "balance" of the data set needs to be taken into account when interpreting results. Unbalanced data sets in which a disproportionately large amount of instances belong to a certain class may lead to high accuracy rates even though the classifier may not necessarily be particularly good.
Further reading:

*

*https://www.cs.auckland.ac.nz/courses/compsci367s1c/tutorials/IntroductionToWeka.pdf

*http://en.wikipedia.org/wiki/Receiver_operating_characteristic#Basic_concept

*http://en.wikipedia.org/wiki/Information_retrieval#Performance_and_correctness_measures

A: What is Naive Bayes?
This explanation might help clarify what Naive Bayes means; it assumes independence of variables.  To make this concrete, say we want to predict whether someone has walked through Prospect Park in Brooklyn.  We have data on whether they
a) live in New York City
b) live in a city
Naive Bayes would assume those two variables are independent.  But clearly, if they live in NYC, they also live in a city.  This is a stupid example because (hopefully) no one would ever use data science with these variables, but it shows what independence means.  If a, then b.  Also, if not b, then not a.
There is dependence, so Naive Bayes' naive assumption does not hold.
Weka Tutorial
This page may be of use to newbies.  It's helping me a lot; it walks through
I am not affiliated with Jason Brownlee.  He seems kind of sales-y, but the benefit of that is he keeps it simple since he's targeting beginners

A: It is giving each value of "50050000" for some algorithms while for other classifiers these values are around 49.7, 87.4, 98.2, and so on.


text:
Q: I want to copy from array to char Hello guys and sorry if my English are not that good .
I am trying to make a program that has 5 players and each player has 5 random ints
that sum up for each player . Then I want to check who has the most points and print his name with a message .
I am trying to do :
for (int i=0;i<5;i++)
{
    if (p[i].sum>p[i+1].sum)
    {
       strcpy(p[i].name,winner);
    }
    else strcpy(p[i+1].name, winner);
}
cout << "The winner is : " << winner << endl;

but the winner value does not change .
here is a screenshot http://prntscr.com/abxqd3
Thank you in advance.

A: I think first you should fix your logical error. You just compare the sum of player i and it's next player.It does not make sense.
for example consider you have these sum scores 8,3,1,4,6. so in first iteration you set winner with the name of player 0 which it has value 8 but in next iteration set 3 and so on. in last iteration you got the name of player with 6  score but you should have player with 8 score.
So always You have the player name with bigger score between to last element of array as winner.
you should define an object with player type for storing  player with max sum like pmax and change the if condition as bellow
if (p[i].sum>pmax.sum)
{
    pmax.name=p[i].name;
    pmax.sum=p[i].sum;
}
cout << "The winner is : " << pmax.name << endl;

A: The value of 'winner' won't obviously change as you are not modifying its value anywhere and your code's logic to find the maximum element is incorrect. If you are trying to find the maximum and copy the name to winner variable you should try this
int max = 0;     // index of the largest sum, initially assumed to be 0
for (int i=1;i<5;i++)
{
 if (p[i].sum>p[max].sum)
 {
  max = i;
 }
}
strcpy(winner, p[max].name);
cout << "The winner is : " << winner << endl;


text:
Q: Object inside a class - Undefined Symbol Error I am getting the following error whenever I try to have a Hand object inside the Player class. As soon as the constructor of the Player class is invoked it shows the following error message:

Undefined symbols for architecture x86_64:
  "Hand::Hand()", referenced from:
  Player::Player() in player-939de2.
  ld: symbol(s) not found for architecture x86_64

Player.h
#ifndef h_player
#define h_player
#include <string>
#include "hand.h"
using namespace std;

class Player{

private:
    Hand* hand;
    string name;

public:
    Player();
    void setName(string);
    void setHand(Card);
    string print() const;
    void showHand() const;
};

#endif

Player.cpp
#include <iostream>
#include <string>
#include "player.h"
#include <iomanip>
using namespace std;

Player::Player() {
    name = "";
    hand = new Hand();
    //std::cout<< "here";
}

void Player::setName(string name) {
    this->name = name;
}

string Player::print() const {
    return this->name;
}

void Player::setHand(Card add) {
    hand->addCard(add);
}

void Player::showHand() const {

    for(int i = 0; i < 7; i++) {
        Card myCard = hand->showCard();
        std::cout << "|" << std::setfill(' ') << std::setw(18) << std::right << myCard.print() << std::setfill(' ') << std::setw(18) << std::right << "|" << std::endl;
    }
}

Hand.h
#ifndef h_hand
#define h_hand
#include <string>
#include "card.h"

using namespace std;

const int number_of_cards = 7;

class Hand {

private:
    Card *cards;
    int no_of_books;
    int cards_remaining;
public:
    Hand();
    void addCard(Card);
    bool checkHand();
    Card showCard() const;
    void withdraw();

};

#endif

Hand.cpp
#include <iostream>
#include <string>
#include "hand.h"
using namespace std;

Hand::Hand() {
    cards = new Card[7];
    cards_remaining = 7;
    no_of_books = 0;
}

void Hand::addCard(Card add) {

    if(cards_remaining > 0) {
        cards[cards_remaining] = add;
        cards_remaining--;
    }
}

Card Hand::showCard() const {
    return cards[cards_remaining++];
}


text:
Q: BasicHttpBinding equivalent CustomBinding using WCF Client and PHP WebService I was running my Visual Studio 2008 Unit Test C# with a WebService PHP using WCF and I received the following error:

System.ServiceModel.Security.MessageSecurityException:
  The HTTP request is unauthorized with
  client authentication scheme
  'Anonymous'. The authentication header
  received from the server was
  'NTLM,Basic realm="(null)"'. --->
  System.Net.WebException: The remote
  server returned an error: (401)
  Unauthorized..

I am using Windows XP SP3 machine, unit test VS 2008 and WCF for connect to PHP WebService.
I have no control about PHP WebService. I cannot modify it (neither configuration security).
Here is my config file for the client that use the webservice PHP:
 <system.serviceModel>

    <extensions>
      <bindingElementExtensions>
        <add name="customTextMessageEncoding"
             type="COMPANY.IntegracionEasyVista.CustomTextEncoder.CustomTextMessageEncodingElement,COMPANY.IntegracionEasyVista.CustomTextEncoder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9744987c0853bf9e" />
      </bindingElementExtensions>

    </extensions>

        <bindings>

              <customBinding>
                    <binding name="ISO8859Binding">
                          <customTextMessageEncoding messageVersion="Soap11WSAddressing10"
                                encoding="ISO-8859-1" />
                          <httpTransport />
                    </binding>
              </customBinding>
        </bindings>
        <client>
              <endpoint address="http://serverphp/webservice/SmoBridge.php"
                    binding="customBinding" bindingConfiguration="ISO8859Binding"
                    contract="ServiceEasyVista.WebServicePortType" name="EasyVistaSvcEndPoint" />
        </client>
    </system.serviceModel>

Really, I use C# code:
var endpointAddress = Config.AppSettings.Settings[EasyVistaSvcEndPointAddress].Value;
var endpoint = new System.ServiceModel.EndpointAddress(endpointAddress);

var endpointBinding = new System.ServiceModel.Channels.CustomBinding();
endpointBinding.Name = "ISO8859Binding";

var bindingElement = new  IntegracionEasyVista.CustomTextEncoder.CustomTextMessageBindingElement();

bindingElement.Encoding = "ISO-8859-1";
bindingElement.MessageVersion = System.ServiceModel.Channels.MessageVersion.Soap11WSAddressing10; // "Soap11WSAddressing10"
endpointBinding.Elements.Add(bindingElement);

var transportBinding = new HttpTransportBindingElement();
endpointBinding.Elements.Add(transportBinding);

ConfigurarBinding(endpointBinding);

var svcClient = new WebServicePortTypeClient(endpointBinding, endpoint);
return svcClient;

Update: tests
I add this line:
transportBinding.AuthenticationScheme = System.Net.AuthenticationSchemes.Negotiate;

I get this error: The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'NTLM,Basic realm="(null)"'
I add this line:
transportBinding.AuthenticationScheme = System.Net.AuthenticationSchemes.Basic;

I get thiserror:

System.ServiceModel.CommunicationObjectFaultedException:
  El objeto de comunicación,
  System.ServiceModel.Channels.ServiceChannel,
  no se puede usar para la comunicación
  porque se encuentra en el estado
  Faulted.
//Server stack trace:  //   en
  System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan
  timeout)

I add this line:
 transportBinding.AuthenticationScheme = System.Net.AuthenticationSchemes.Ntlm;

I get thiserror:

/Exception =
  System.ServiceModel.CommunicationException:
  Versión de mensaje no reconocida.
//Server stack trace:  //   en
  System.ServiceModel.Channels.ReceivedMessage.ReadStartEnvelope(XmlDictionaryReader
  reader)
//   en
  System.ServiceModel.Channels.StreamedMessage..ctor(XmlDictionaryReader
  reader, Int32 maxSizeOfHeaders,
  MessageVersion desiredVersion)
//   en
  System.ServiceModel.Channels.Message.CreateMessage(XmlDictionaryReader
  envelopeReader, Int32
  maxSizeOfHeaders, MessageVersion
  version)
//   en
  System.ServiceModel.Channels.Message.CreateMessage(XmlReader
  envelopeReader, Int32
  maxSizeOfHeaders, MessageVersion
  version)
//   en
  CustomTextEncoder.CustomTextMessageEncoder.ReadMessage(Stream
  stream, Int32 maxSizeOfHeaders, String
  contentType) en
  E:\TFS\pro\CustomTextEncoder\CustomTextMessageEncoder.cs:línea
  66
//   en
  System.ServiceModel.Channels.MessageEncoder.ReadMessage(Stream
  stream, Int32 maxSizeOfHeaders)
//   en
  CustomTextEncoder.CustomTextMessageEncoder.ReadMessage
  (ArraySegment`1 buffer, BufferManager
  bufferManager, String contentType) en
  E:\TFS\pro\CustomTextEncoder\CustomTextMessageEncoder.cs:línea
  60
//   en
  System.ServiceModel.Channels.MessageEncoder.ReadMessage(Stream
  stream, BufferManager bufferManager,
  Int32 maxBufferSize, String
  contentType)
//   en
  System.ServiceModel.Channels.HttpInput.ReadChunkedBufferedMessage(Stream
  inputStream)

I think, the following is right configuration (if were basichttpbinding)
<security mode="TransportCredentialOnly">
    <transport clientCredentialType="Basic" />
</security>

Web service of WCF in basichttpbinding might not be flexible enough. CustomBinding as the name describes that it alllows users design their own web service binding.
I need use CustomBinding and SecurityMode (like basichttpbinding): WCF BasicHttpBinding equivalent CustomBinding
I need Security Mode: TransportCredentialOnly, Basic, HTTP transport and  encoding="ISO-8859-1"
http://www.codemeit.com/security/wcf-basichttpbinding-equivalent-custombinding.html
http://social.msdn.microsoft.com/Forums/en/wcf/thread/6cefadf1-9939-4f3b-a502-2d79a30c7d3a
http://offroadcoder.com/2008/03/23/CallingYourNusoapPHPWebServiceFromWCF.aspx
http://msdn.microsoft.com/en-us/library/ms731092(v=VS.90).aspx
I try again using this configuration, and I get the error:
svcPro.ClientCredentials.UserName.UserName = "MY USER";
svcPro.ClientCredentials.UserName.Password = "XXXX";

Config:
<customBinding>

<binding name="ISO8859Binding">
    <customTextMessageEncoding messageVersion="Soap11WSAddressing10"        encoding="ISO-8859-1" />

    <!--<textMessageEncoding MessageVersion="Soap11" />-->
    <!--<httpTransport />-->
    <httpTransport authenticationScheme="Basic" />

</binding>

</customBinding>

The error (InnerException is null):

Error: Unrecognized message version
Tipo:
  System.ServiceModel.CommunicationException
  Mensaje: Versión de mensaje no
  reconocida. StackTrace:  Server stack
  trace:
en
  System.ServiceModel.Channels.ReceivedMessage.ReadStartEnvelope(XmlDictionaryReader
  reader)
en
  System.ServiceModel.Channels.StreamedMessage..ctor(XmlDictionaryReader
  reader, Int32 maxSizeOfHeaders,
  MessageVersion desiredVersion)
en
  System.ServiceModel.Channels.Message.CreateMessage(XmlDictionaryReader
  envelopeReader, Int32
  maxSizeOfHeaders, MessageVersion
  version)
en
  System.ServiceModel.Channels.Message.CreateMessage(XmlReader
  envelopeReader, Int32
  maxSizeOfHeaders, MessageVersion
  version)
en
  Reale.IntegracionEasyVista.CustomTextEncoder.CustomTextMessageEncoder.ReadMessage(Stream
  stream, Int32 maxSizeOfHeaders, String
  contentType) en
  E:\IntegracionEasyVista\CustomTextEncoder\CustomTextMessageEncoder.cs:línea
  66
en
  System.ServiceModel.Channels.MessageEncoder.ReadMessage(Stream
  stream, Int32 maxSizeOfHeaders)
      en Reale.IntegracionEasyVista.CustomTextEncoder.CustomTextMessageEncoder.ReadMessage(ArraySegment`1
  buffer, BufferManager bufferManager,
  String contentType) en
  E:\IntegracionEasyVista\CustomTextEncoder\CustomTextMessageEncoder.cs:línea
  60
en
  System.ServiceModel.Channels.MessageEncoder.ReadMessage(Stream
  stream, BufferManager bufferManager,
  Int32 maxBufferSize, String
  contentType)
en
  System.ServiceModel.Channels.HttpInput.ReadChunkedBufferedMessage(Stream
  inputStream)
en
  System.ServiceModel.Channels.HttpInput.ParseIncomingMessage(Exception&
  requestException)
en
  System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
  timeout)
en
  System.ServiceModel.Channels.RequestChannel.Request(Message
  message, TimeSpan timeout)
en
  System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message
  message, TimeSpan timeout)
en
  System.ServiceModel.Channels.ServiceChannel.Call(String
  action, Boolean oneway,
  ProxyOperationRuntime operation,
  Object[] ins, Object[] outs, TimeSpan
  timeout)
en
  System.ServiceModel.Channels.ServiceChannel.Call(String
  action, Boolean oneway,
  ProxyOperationRuntime operation,
  Object[] ins, Object[] outs)
en
  System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime
  operation)
en
  System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)

More info: part of WDSL of Service.php
<?xml version="1.0" encoding="ISO-8859-1" ?>
 <definitions
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:si="http://soapinterop.org/xsd"
xmlns:tns="http://192.168.110.50/WebService" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://192.168.110.50/WebService">
 <types>
 <xsd:schema targetNamespace="http://192.168.110.50/WebService">
  <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
  <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" />
  </xsd:schema>
  </types>

A: Your PHP service requires authentication but your client doesn't send any. Change your custom binding to support authentication. You can set authentication in httpTransport element:
<httpTranposrt authenticationScheme="..." />

Use Basic or Negotiate. Basic will require you to provide client credentials when communicating with the service. Negotiate will require that both service and client are in the same domain.


text:
Q: How to pass SwipeEvent to view parent? I have LinearLayout and 3 TextViews in it. I petted swipeListner to linearLayout, but it's Childs overshadow swipes. I tried some things as onInterceptTouchEvent(), setted texts non-clickable, non-focusable, but it didn't help.
How can I listen swipes over this texts on the whole linear layout?
Thanks everyone for the answers in advance !

A: Do it like this,
<SwipeRefreshLayout>
  <ScrollView>
    <LinearLayout><Your Views></LinearLayout>
  </ScrollView>
 </SwipeRefreshLayout>

A: There was a problem cause I wasn't able to extend any ViewGroup, but than I figured it out and just added this:
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return true
    }


text:
Q: How to calculate the maximum data rate or frequency of a bus driver I'm searching a suitable bus driver for a project. I found the Nexperia 74VHC244D. On the website they say the maximum frequency is 60MHz (here).
But how do I calculate the 60MHz? Because it's not mentioned in the datasheet. Is it just the inverse value of the propagation delay?

A: The manufacture states a cryptic Tpd = 15ns (Cl=50pf, Vdd=3.3V) as usable test values, but in addition the test is with a square wave of ~50 % duty cycle at 60 MHz at \$25 Deg^oC\$. Maximum frequency also depends on if the part is commercial, industrial or military grade, as they guarantee operation over a specific range of temperatures.
Be sure to read ALL of the datasheet as it often includes drift from maximum frequency based on ambient temperature. Look at the charts in the datasheet. If it MUST work at 60 MHz then look for all the reasons why it may not. Usually \$F_{max}\$ is obtained under ideal (but possible) conditions.

A: Looks like they're using Tpd = 15ns (Cl=50pf, Vdd=3.3V) as the figure to arrive at 60 MHz, with a little bit of margin.
If I had to guess why, it was the marketing droid badgering the tech writer for a 'MHz' figure, so they settled on 1/Tpd.


text:
Q: Android how to log in to exchange server I have been searching the web for many days, and I still have not found a good tutorial for beginners to log into an exchange server. I know there are protocols available e.g. http://msdn.microsoft.com/en-us/library/cc425499(v=EXCHG.80).aspx, but I am hardly skilled enough to interpret.
I'm sure other beginners in app development would be curious as well. Thanks!

A: If you want to use ActiveSync, I have an ActiveSync client that works on Android. It logs into Exchange, and is able to perform GAL searches.
See Corporate Addressbook

A: You can use the Exchange Web Services to access Exchange Mailboxes.
Additionally, there is a managed API for Java, but I'm not sure whether it will run on Android.


text:
Q: Test for correlated vs uncorrelated increments in random walks Is there a test that can distinguish the strictest form of the random walk,
$$P_{t}=P_{t-1}+\varepsilon_{t}, \varepsilon_{t} \sim \mathrm{IID}\left(0, \sigma^{2}\right)$$
where each step is assumed to be identical and independently distributed, from the most general form of the random walk,
$$Cov(\varepsilon_{t}, \varepsilon_{t-k} ) = 0, k \neq 0$$
where each step may not be identical?
I realize that for uncorrelated increments, all of the autocorrelations of the increments are zero, but I'm having difficulty establishing a "threshold" above which I can confidently say that my random walk has identical increments.


text:
Q: Ruby - Can I choose a location to put some code in a method inherited with Super? I will put here an example:
class A

    def go(name = "girls")

        print "hello "
        print name
        puts " !"
    end
end

class B < A

    def go

        super("boys")
    end
end

A.new.go
B.new.go

result:
hello girls !
hello boys !

I need to do that but not with just params changing but adding some variables:
class A

    def go(name = "girls")

        dad_variable = "coders"

        print "hello "

        superAnchor("myAnchor") # put a "super anchor" here

        puts " !"
    end
end

class B < A

    def go

        superAnchor("myAnchor"){
            print dad_variable # do some code in relation with Daddy
            # do some other things but with the parent variables
            # interacting with the inherited environnement
        }
    end
end

A.new.go
B.new.go

result:
hello girls !
hello coders !

In summary I want to know if we can put anchor in the son class who inherit of the parent method and put some codes in association with the position of the anchors in the parent method and the environnement variables of the parent method ?
Is there a system to do that ?
Thank you guys :)

A: It looks like instead of superAnchor("myAnchor") you could just have a method call that gets overridden in the subclass, no?  Perhaps the superclass could pass the dad_variable object into this method, which the method could use or ignore.  Also, subclasses shouldn't be able to read private state (or variables) of superclasses...

A: I believe credit for this suggestion goes to Max. I'll just elaborate on the idea as I understand it.
You can insert a method call like do_specialized_stuff (with a better name) where the subclass behavior needs to diverge. Then, to customize the behavior in the subclass, just override the definition of do_specialized_stuff.
class A
    def go(name = "girls")

        dad_variable = "coders"

        print "hello "

        do_specialized_stuff(dad_variable)

        puts " !"
    end

    def do_specialized_stuff(dad_variable)
        # perhaps this is empty in class A or maybe it does something
    end
end

class B < A

    # no need to redefine the 'go' method

    def do_specialized_stuff(dad_variable)
        # specialized stuff is different in class B
    end
end

A: I'm not sure if this is what you are looking for, but when you invoke super A#go is executed on the instance of B and, like any other method, returns (to the instance of B) the last calculation made by the method.  If, for example, you put dad_variable = "coders" (or just "coders") on the last line of A#go, "coders" will be returned:
class A
  def go(name = "girls")
    puts "hello from A"
    dad_variable = "coders"
  end
end

class B < A
  def go
    puts super
  end
end

A.new.go
  # hello from A
B.new.go
  #hello from A
  #coders

A: Boys, I think, I find, that's the yield system
http://fr.wikipedia.org/wiki/Yield_(instruction) (sorry for the french source)
but I am not really sure...


text:
Q: How to remove a class of all element expect one in one Array I am learning Vanilla JS and DOM. Today I have a problem when I want to remove a class of all elements expect one.
const panels = document.querySelectorAll(".panel");
  function toggleOpen() {
    this.classList.toggle("open");
    console.log(panels);
  }
  function toggleActive(e) {
    if (e.propertyName.includes("flex")) {
      this.classList.toggle("open-active");
    }
  }

  panels.forEach((panel) => panel.addEventListener("click", toggleOpen));
  panels.forEach((panel) =>
    panel.addEventListener("transitionend", toggleActive)
  );

I want when I click "panel" the only panel be clicked have class "open" and remove all class "open" of all another "panel". (Exactly I want only a panel to have class "open" in all time, and it can toggle.) Thank you for your help.

A: In toggleOpen, iterate over all panels (except this one) and remove their open class first:
function toggleOpen() {
  // Close all other panels:
  for (const panel of panels) {
    if (panel !== this) {
      panel.classList.remove('open');
    }
  }
  // Either open this panel or close it:
  this.classList.toggle("open");
}


text:
Q: C# Method Name Expected Error using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DebtCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            double creditcardbalance;
            Console.WriteLine("Enter in credit card balance:");
            creditcardbalance = double.Parse(Console.ReadLine());

            double monthlypayementamount;
            Console.WriteLine("Enter in the monthly payement amount:");
            monthlypayementamount = double.Parse(Console.ReadLine());

            double percentagerate;
            Console.WriteLine("Enter in annual percentage rate:");
            percentagerate = double.Parse(Console.ReadLine());

            int payoff;
            double dailyinterestrate;
            dailyinterestrate = percentagerate / 365;
            payoff = -(1 / 30) * Math.Log(1 + creditcardbalance / monthlypayementamount (1 - (1 + dailyinterestrate), Math.Pow(0, 30))) / Math.Log(1 + dailyinterestrate);
        }

    }
}

the "payoff = -(1 / 30) * Math.Log(1 + creditcardbalance / monthlypayementamount " where it says monthlypayementamount it returns an error of "method name expected" how do i resolve?

A: Looking at the formula your equation should be like this.
payoff = -(1d / 30) * Math.Log(1 + creditcardbalance / monthlypayementamount * (1 - Math.Pow(1 + dailyinterestrate, 30))) / Math.Log(1 + dailyinterestrate);

Your problems. in mathematics p(2) may translate to p*(2) but in coding you have to write everything p*(2).
And the part Math.Pow(0,30) evaluates to 0^30. you have to put 1 + dailyinterestrate (according to formula) instead of 0.
Also the result of this equation is type of double. but payoff as i see now is type of int. change the type of payoff to double or cast the result to int.
The other problem is -(1/30). they are both integer means the result is without decimal. so put d after the number so it will be type of double which holds decimal part. thanks to @A.S.H
You must Write the result in the console with Console.WriteLine() method
your code should look like this.
double payoff;
double dailyinterestrate;
dailyinterestrate = percentagerate / 365;
payoff = -(1d / 30) * Math.Log(1 + creditcardbalance / monthlypayementamount * (1 - Math.Pow(1 + dailyinterestrate, 30))) / Math.Log(1 + dailyinterestrate);

Console.WriteLine(payoff);


text:
Q: window.print(); Not working in this.Page.ClientScript.RegisterStartupScript I need to print web page after done some events on server side but window.print in not working. how i solve this problem.
My page source code
<asp:ImageButton ID="butPrint" runat="server" ImageUrl="~/Images/print.gif"
                    ToolTip="Click to Print"
                    onclick="butPrint_Click" />

 protected void butPrint_Click(object sender, ImageClickEventArgs e)
    {
        ///my events
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "print", "printPage();", true);
    }

function printPage() {
     // here i have hide some controls

     window.print();

    }

This is working on firefox but not working in IE 8


text:
Q: Sum of lowest numbers that are part of an arithmetic sequence I would like to iterate through a list of integers, calculate the sum of the lowest numbers that belongs to an arithmetic sequence with common difference 1 + the numbers that are not part of a sequence:
mylist = [2,3,4,10,12,13]

So, from mylist it would be 2 (from 2,3,4) + 10 (not part of a sequence) + 12 (from 12,13)
I've managed to make something work, but I could only figure out how to do it, if the list is reversed. And I am sure there is a better/cleaner solution that mine:
mylist = [13,12,10,4,3,2]

result = mylist[-1] #if I don't do this, I don't know how to grab the last item in the list
for i in range(len(mylist)-1):
    if mylist[i] - mylist[i+1] == 1:
        continue
    else:
        result += mylist[i]

Hope someone will help me out, and that I get a little wiser in my coding journey. Thanks.

A: @KennethRasch - earlier post would work. Alternatively, you can do this as well:
Try to find each possible subsequence's starting numbers as starts then just sum them to get answer.
L = [13,12,10,4,3,2]
L.sort()

starts = [x for x in L if x-1 not in L]
print(starts)

result = sum(starts)
print(result)  # 24

Alternatively, you can put this into a function for future re-use it:
def sum_lowests(L):
    '''L is a numbers sequence '''

    L.sort()
    starts = [x for x in L if x-1 not in L]
    #ans = sum(starts)       # can skip this step; just to make it clear

    return sum(starts)

if __name__ == '__main__':
    L = [13,12,10,4,3,2]

    A = [1, 2, 3, 5,6, 9,10,11, 16]

    print(sum_lowests(L))
    print(sum_lowests(A)) # 31

A: Keep a running sum, a running index, and iterate while it's still a sequence:
mylist = [13,12,10,4,3,2]
mylist.sort() # this way sequences will be contiguous in the list

cur_index = 0
cur_sum = 0

while cur_index < len(mylist):
    # add the current element to the sum
    cur_sum += mylist[cur_index]
    # now iterate through while it's a contiguous sequence
    cur_index += 1
    while cur_index < len(mylist) and mylist[cur_index] == mylist[cur_index - 1] + 1:
        cur_index += 1

print(cur_sum)


text:
Q: How disable RequiredFieldValidator in script I have TextBox with RequiredFieldValidator on my page.
I also have link that calls some simple javascript.
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator
ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox1"
Display="Dynamic" />
<asp:LinkButton   ID="Link1" runat="server" OnClientClick="DoSomething(); return false;" CausesValidation="false"Text="Do" />

function DoSomething() {
textbox1.val("blah"); }

When user type something into textbox and then delete that text and focus next control - then validator fires.
Then user can use link that adds text using javascript. TextBox1 text is no longer empty but RequiredFieldValidator still shows error message. How to prevent that?

A: you can use javascript ValidatorEnable function
ValidatorEnable(document.getElementById('<%= ValidatorID.ClientID %>'), true);

A: I would recommend a CustomValidator here since you do NOT want the normal RequiredFieldValidator behavior.  The CustomValidator client method will only run on postback.

A: The whole point of the validators is that they are to be used for both server side and client side validation.
If you only want to validate on the server side, don't use a validator and simply check that the values are valid and report an error.


text:
Q: show an image on a div before setting the same div with some text REACT.js Im making a chatting application in which i get the response from the back end and it is displayed without any delay. I am mapping the messages after setting the state Chat with the messages of .
Below is the response I get from the back end.
 var tesBotMessages = this.state.Chat.map(function (msg, key) {

                    {(msg.Botresponse === undefined || msg.Botresponse === "")
                        ?

Sorry I don't get it.. :(

                                <time className="chat-time"></time>

                         :

{msg.Botresponse}

                                <time className="chat-time"></time>

}

How can I show an image on this JSX id="message" before showing the actual
{msg.Botresponse}
 Here I first check if the the response undefined of null. if its not null it is displayed.
I just need to show it for an interval of 1 second.


text:
Q: how to force config transform on an xml file? I've just installed Configuration Transform for VS2017, hoping to transform some XML files.
Unfortunately, it looks like it only does *.config files?!
For example, when I write click on a *.config file, I get the "add config transform" option, but it's not available for XML files:

How do I transform an XML file?

A:
Unfortunately, it looks like it only does *.config files?!

Not true. You can transform any XML file. For example, in MvcSiteMapProvider, XML Transformation is used to build the .nuspec XML files for NuGet.
MvcSiteMapProvider.Core.Shared.nuspec
This is a "base" file that is later transformed.
<?xml version="1.0"?>
<!-- MvcSiteMapProvider.MVCx.Core shared Nuget specification file; all packages share this -->
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
    <metadata>
        <id>MvcSiteMapProvider.MVC#mvc_version#.Core</id>
        <title>MvcSiteMapProvider MVC#mvc_version# Core</title>
        <version>$version$</version>
        <authors>Maarten Balliauw, Shad Storhaug</authors>
        <requireLicenseAcceptance>false</requireLicenseAcceptance>
        <summary>MvcSiteMapProvider is a tool that provides flexible menus, breadcrumb trails, and SEO features for the ASP.NET MVC framework, similar to the ASP.NET SiteMapProvider model. The project is hosted on http://github.com/maartenba/MvcSiteMapProvider.</summary>
        <description>This package contains only the core library for MvcSiteMapProvider. Use this package if you need to reference the library from a non-MVC project such as a class library.</description>
        <language>en-US</language>
        <tags>mvc mvc#mvc_version# sitemap mvcsitemap menu breadcrumb navigation mvcsitemapprovider</tags>
        <projectUrl>http://github.com/maartenba/MvcSiteMapProvider</projectUrl>
        <iconUrl>https://raw.githubusercontent.com/maartenba/MvcSiteMapProvider/master/map-icon.gif</iconUrl>
        <dependencies>
            <group targetFramework="net35">
            </group>
            <group targetFramework="net40">
            </group>
            <group targetFramework="net45">
            </group>
        </dependencies>
    </metadata>
</package>

MvcSiteMapProvider.MVC5.Core.nutrans
Here is an XML transformation file that converts elements for MVC 5:
<?xml version="1.0"?>
<!-- Nuget specification file for MVC5 -->
<package inherits="MvcSiteMapProvider.Shared.nuspec" xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd" xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <metadata>
    <dependencies>
        <group targetFramework="net45" xdt:Locator="Match(targetFramework)">
            <dependency id="Microsoft.AspNet.Razor" version="[3,4)" xdt:Transform="Insert" />
            <dependency id="Microsoft.AspNet.WebPages" version="[3,4)" xdt:Transform="Insert" />
            <dependency id="Microsoft.AspNet.Mvc" version="[5,6)" xdt:Transform="Insert" />
        </group>
    </dependencies>
  </metadata>
</package>

Transformation
Here is an MSBuild file named TransformXml.proj that is used to execute the XML transform:
<Project ToolsVersion="4.0" DefaultTargets="Transform" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <UsingTask TaskName="TransformXml"
        AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll"/>

    <PropertyGroup>
        <Source></Source>
        <Transform></Transform>
        <Destination></Destination>
    </PropertyGroup>

    <Target Name="Transform">
        <TransformXml Source="$(Source)"
                  Transform="$(Transform)"
                  Destination="$(Destination)" />
    </Target>
</Project>

See Which installer installs Microsoft.Web.Publishing.Tasks.dll? for information about how to obtain Microsoft.Web.Publishing.Tasks.dll.
And the command to execute from PowerShell looks like:
function Transform-Nuspec ([string] $source, [string] $transform, [string] $destination) {
    $transform_xml = "$tools_directory\TransformXml.proj"
    Write-Host "Creating nuspec for $destination" -ForegroundColor Green
    Exec { msbuild $transform_xml /p:Source=$source /p:Transform=$transform /p:Destination=$destination /v:minimal /nologo }
    $nuspec
}

The MSBuild command could be run from any type of script or process that can execute MSBuild.exe.


text:
Q: Change ids and names for cloned elements I have a form where I allow the user to enter multiple delegate details.Here is the snippet of the html page.

Delegate #1

*First Name:
                            <input type="text" class="w-input" maxlength="256" name="first_name" data-name="first_name" placeholder="First Name" id="first_name" required="">

*Last Name:
                            <input type="text" class="w-input" maxlength="256" name="last_name" data-name="last_name" placeholder="Last Name" id="last_name" required="">

*Job Title / Position
                    <select id="title" name="title" class="w-select">
                        <option value="">What best describes your role?</option>
                        <option value="Partner/Principal">Partner/Principal</option>
                        <option value="Director/CEO/CFO">Director/CEO/CFO</option>
                        <option value="General Manager">General Manager</option>
                        <option value="Senior Manager">Senior Manager</option>
                        <option value="Manager">Manager</option>

   </select>

*Email Address
                            <input type="email" class="w-input" maxlength="256" name="email_address" data-name="email_address" placeholder="Email Address" id="email_address" required="">

Mobile
                            <input type="text" class="w-input" maxlength="256" name="mobile" data-name="mobile" placeholder="Mobile Number" id="mobile">

                    *Postal Address
                    <input type="text" class="w-input" maxlength="256" name="mailing_street" data-name="mailing_street" placeholder="Postal Address" id="mailing_street" required="">

*Suburb
                            <input type="text" class="w-input" maxlength="256" name="mailing_suburb" data-name="mailing_suburb" placeholder="Enter your email" id="mailing_suburb" required="">

*State
                            <input type="text" class="w-input" maxlength="256" name="mailing_state" data-name="mailing_state" placeholder="State" id="mailing_state" required="">

*Postcode
                            <input type="text" class="w-input" maxlength="256" name="mailing_postcode" data-name="mailing_postcode" placeholder="Postcode" id="mailing_postcode" required="">

                    Please note any special requirements (eg. dietary, mobility, hearing or sight)
                    <input type="text" class="w-input" maxlength="256" name="message" data-name="message" placeholder="Special Requirements" id="message">

<button type="button" id="btnAdd" class="delegate-button w-button">Add New Delegate</button>

<button type="button" id="btnDel" class="delegate-button remove w-button">Remove Above Delegate</button>

Now when I click on addbtn, it will clone a new set of delegate fields and I have to change the cloned elements' id and name to a certain format for my back end to process the form.I am using jquery to do this.
$(function() {
$('#btnAdd').click(function() {
    var num = $('.clonedInput').length,
        newNum = new Number(num + 1),
        newElem = $('#Delegate' + num).clone().attr('id', 'Delegate' + newNum).fadeIn('slow');
    newElem.find('.heading-reference').attr('id', 'ID' + newNum + '_reference').attr('name', 'ID' + newNum + '_reference').html('Delegate #' + newNum);
    newElem.find('.w-select').attr('id', 'ID' + newNum + '_title').attr('name', 'ID' + newNum + '_title').val('');
    newElem.find('.w-input').attr('id', 'ID' + newNum + '_first_name').attr('name', 'ID' + newNum + '_first_name').val('');
    newElem.find('.w-input').attr('id', 'ID' + newNum + '_last_name').attr('name', 'ID' + newNum + '_last_name').val('');
    newElem.find('.w-input').attr('id', 'ID' + newNum + '_email_address').attr('name', 'ID' + newNum + '_email_address').val('');
    newElem.find('.w-input').attr('id', 'ID' + newNum + '_mobile').attr('name', 'ID' + newNum + '_mobile').val('');
    newElem.find('.w-input').attr('id', 'ID' + newNum + '_message').attr('name', 'ID' + newNum + '_message').val('');
    $('#Delegate' + num).after(newElem);
    $('#ID' + newNum + '_title').focus();
    $('#btnDel').attr('disabled', false);
    if (newNum == 5)
        $('#btnAdd').attr('disabled', true).prop('value', "You've reached the limit");
    $('#number_of_delegate').val(newNum);
});

I am able to change the attributes of heading-reference successfully but I am unable to pick up the input field attributes as they belong to the same class 'w-input'. What am I doing wrong here? Thanks in advance!

A: Because you are targeting .w-input, and their are multiple elements with that class, you are targeting all elements with that class.  If you were to console.log('newElem.find('.w-input')), you would receive an array.  By iterating through each element, you can target them individually, use regex test for a digit in the string, and replace accordingly.
Solution:
$('#btnAdd').click(function () {
      var num = $('.clonedInput').length,
        newNum = new Number(num + 1),
        newElem = $('#Delegate' + num).clone().attr('id', 'Delegate' + newNum).fadeIn('slow');

      newElem.find('.heading-reference').attr('id', 'ID' + newNum + '_reference').attr('name', 'ID' + newNum + '_reference').html('Delegate #' + newNum);
      newElem.find('.w-select').attr('id', 'ID' + newNum + '_title').attr('name', 'ID' + newNum + '_title').val('');

      //loop through each element
      newElem.find('.w-input').each(function(el) {
        var currentId = $(this).attr('id');
        var uniqueId; //hold a var for the unique id
        if(/(\d+)/.test(currentId)) {  //if digits exist
          uniqueId = currentId.replace(/(\d+)/, newNum);  //replace digits with the new number
        } else {
          uniqueId = 'ID' + newNum + '_' + currentId; //otherwise, replace with current id plus number etc.
        }
        $(this).attr('id', uniqueId).attr('name', uniqueId).val('');  //the the name and id to the new unique id
      });

      $('#Delegate' + num).after(newElem);
      $('#ID' + newNum + '_title').focus();
      $('#btnDel').attr('disabled', false);
      if (newNum == 5)
        $('#btnAdd').attr('disabled', true).prop('value', "You've reached the limit");
      $('#number_of_delegate').val(newNum);
    });

Snippet

$(function () {
    $('#btnAdd').click(function () {
      var num = $('.clonedInput').length,
        newNum = new Number(num + 1),
        newElem = $('#Delegate' + num).clone().attr('id', 'Delegate' + newNum).fadeIn('slow');

      newElem.find('.heading-reference').attr('id', 'ID' + newNum + '_reference').attr('name', 'ID' + newNum + '_reference').html('Delegate #' + newNum);
      newElem.find('.w-select').attr('id', 'ID' + newNum + '_title').attr('name', 'ID' + newNum + '_title').val('');

      newElem.find('.w-input').each(function(el) {
        var currentId = $(this).attr('id');
        var uniqueId;
        if(/(\d+)/.test(currentId)) {
          uniqueId = currentId.replace(/(\d+)/, newNum);
        } else {
          uniqueId = 'ID' + newNum + '_' + currentId;
        }
        $(this).attr('id', uniqueId).attr('name', uniqueId).val('');
      });

      $('#Delegate' + num).after(newElem);
      $('#ID' + newNum + '_title').focus();
      $('#btnDel').attr('disabled', false);
      if (newNum == 5)
        $('#btnAdd').attr('disabled', true).prop('value', "You've reached the limit");
      $('#number_of_delegate').val(newNum);
    });
  })

Delegate #1

*First Name:
   <input type="text" class="w-input" maxlength="256" name="first_name" data-name="first_name"
          placeholder="First Name" id="first_name" required="">

*Last Name:
   <input type="text" class="w-input" maxlength="256" name="last_name" data-name="last_name"
          placeholder="Last Name" id="last_name" required="">

 *Job Title / Position
 <select id="title" name="title" class="w-select">
  <option value="">What best describes your role?</option>
  <option value="Partner/Principal">Partner/Principal</option>
  <option value="Director/CEO/CFO">Director/CEO/CFO</option>
  <option value="General Manager">General Manager</option>
  <option value="Senior Manager">Senior Manager</option>
  <option value="Manager">Manager</option>

 </select>

*Email Address
   <input type="email" class="w-input" maxlength="256" name="email_address" data-name="email_address"
          placeholder="Email Address" id="email_address" required="">

Mobile
   <input type="text" class="w-input" maxlength="256" name="mobile" data-name="mobile"
          placeholder="Mobile Number" id="mobile">

 *Postal Address
 <input type="text" class="w-input" maxlength="256" name="mailing_street" data-name="mailing_street"
        placeholder="Postal Address" id="mailing_street" required="">

*Suburb
   <input type="text" class="w-input" maxlength="256" name="mailing_suburb" data-name="mailing_suburb"
          placeholder="Enter your email" id="mailing_suburb" required="">

*State
   <input type="text" class="w-input" maxlength="256" name="mailing_state" data-name="mailing_state"
          placeholder="State" id="mailing_state" required="">

*Postcode
   <input type="text" class="w-input" maxlength="256" name="mailing_postcode" data-name="mailing_postcode"
          placeholder="Postcode" id="mailing_postcode" required="">

 Please note any special requirements (eg. dietary, mobility, hearing or sight)
 <input type="text" class="w-input" maxlength="256" name="message" data-name="message"
        placeholder="Special Requirements" id="message">

  <button type="button" id="btnAdd" class="delegate-button w-button">Add New Delegate</button>

  <button type="button" id="btnDel" class="delegate-button remove w-button">Remove Above Delegate</button>


text:
Q: gcc "can't be more simple" program got Undefined symbols for architecture x86_64 compile error Before posting this question I've read hundreds of Google search result pages, searching solution of this problem in vain. My program can't be more simple — these are the only 3 files:
test.h
#ifndef SYMBOL
#define SYMBOL

#include <stdio.h>

void output(void);

#endif

test.c
#include "test.h"

void output(void)
{
  printf("%s\n", "Hello world");
}

untitled.c
#include <stdio.h>
#include "test.h"

void main()
{
  output();
  return;
}

I use terminal and enter the following command to compile:
gcc -o aaa untitled.c

Output should print the "Hello world", but instead it keeps throwing this error:
Undefined symbols for architecture x86_64:
  "_output", referenced from:
      _main in untitled-00f904.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I spent the whole day searching for solution, tried all the suggestions as possible but none helped.
Something notable: If I change the file included in untitled.c (#include "test.h" to #include "test.c"), compiler goes without problem.
Can someone please explain to me why, and how to resolve it?

A: You have to compile and link both source files into the executable; the linker is telling you it cannot find the output() function defined in test.c:
$ gcc -o aaa untitled.c test.c


text:
Q: XStream dynamically convert list I'm trying to implement a generic XStream reader to read my xml. My XML have all the same tagname, but with differents ID.
Example:
XML from URL 1 returns:
<rss>
    <reg id="someClass">
        <ds>bla bla</ds>
    </reg>
</rss>

XML from URL2 returns:
<rss>
    <reg id="differentClass">
        <id> 1 </id>
        <location> etc </location>
    </reg>
    <reg id="differentClass">
        <id> 2 </id>
        <location> etc2 </location>
    </reg>
</rss>

So as you can see, they're all the same until my reg tag starts, it can be a list or a single value. But that's so far ok.
However if I implement my RSS class with my reg object referencing my "someClass" class,it works just fine, it converts and gives me the values I expect, however I need to make it generic, instead of creating N classes for same struct, I was trying to implement my RSS class this way:
public class RSS {
    private List<?> reg;
    public List<?> getReg() {
        return reg;
    }
    public void setReg(List<?> reg) {
        this.reg = reg;
    }
}

my SomeClass class:
public class SomeClass{
    private String ds;
    //getters and setters
}

my differentClass:
public class DifferentClass{
    private String id, location;
    //getters and setters
}

and trying to read my XML as follows for the first url:
response = client.execute(httpPost, httpContext);
    xstream.ignoreUnknownElements();
    xstream.alias("rss", RSS.class);
    xstream.alias("reg", SomeClass.class);
    RSS rss = (RSS) xstream.fromXML(new InputStreamReader(response.getEntity().getContent()));
    Object user = rss.getReg();
    return (SomeClass) user;

and for the second url, instead of 'SomeClass', use 'differentClass'. But this approach is not working, since I get the following exception:
---- Debugging information ----
cause-exception     : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message       : ds
class               : java.util.ArrayList
required-type       : java.util.ArrayList
converter-type      : com.thoughtworks.xstream.converters.collections.CollectionConverter
path                : /rss/reg/ds
line number         : 12
class[1]            : br.com.test.RSS
converter-type[1]   : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
version             : 1.4.9
-------------------------------
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:79)
    at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:70)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshallField(AbstractReflectionConverter.java:503)
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.doUnmarshal(AbstractReflectionConverter.java:429)
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:281)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
    at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:70)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:134)
    at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:32)
    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1230)
    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1214)
    at com.thoughtworks.xstream.XStream.fromXML(XStream.java:1085)
    at br.com.test.Test.get(Test.java:64)
Caused by: com.thoughtworks.xstream.mapper.CannotResolveClassException: ds
    at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:81)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.DynamicProxyMapper.realClass(DynamicProxyMapper.java:55)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.PackageAliasingMapper.realClass(PackageAliasingMapper.java:88)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.ClassAliasingMapper.realClass(ClassAliasingMapper.java:79)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.ArrayMapper.realClass(ArrayMapper.java:74)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.SecurityMapper.realClass(SecurityMapper.java:71)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
    at com.thoughtworks.xstream.mapper.CachingMapper.realClass(CachingMapper.java:47)
    at com.thoughtworks.xstream.core.util.HierarchicalStreams.readClassType(HierarchicalStreams.java:29)
    at com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter.readItem(AbstractCollectionConverter.java:72)
    at com.thoughtworks.xstream.converters.collections.CollectionConverter.addCurrentElementToCollection(CollectionConverter.java:98)
    at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:91)
    at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:85)
    at com.thoughtworks.xstream.converters.collections.CollectionConverter.unmarshal(CollectionConverter.java:80)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
    ... 78 more

I'm stuck in here, is it possible to implement this approach using XStream? If yes, how? I can make it work without this lib (reading tag by tag), however it would be easier for future use this lib.

A: The error message says that xstream tries to convert your ds as ArrayList.
Tell xstream that it is a String:
xstream.aliasType("ds", String.class);


text:
Q: InputMask para DisplayFor Utilizo o jQuery Inputmask para adicionar máscaras em meus TextBox. Porém necessito adicionar máscara ao listar esses campos( telefone, cpf, etc). Utilizo o DisplayFor para listar, porém a máscara não funciona com o mesmo.
Codigo em minha View:
                Cargo: @Html.DisplayFor(model => model.sTelefone)

Função JavaScript:
<script>

jQuery(function ($) {
    $("#sTelefone").mask("9999-9999");
});

Agora, quando utilizo o TextBoxFor, a máscara funciona normalmente, porém necessito apenas listar os dados em um dataTable, e o textBox não me atende.
@Html.TextBoxFor(model => model.sTelefone)

A: Use algo mais simples. Um ToString() formatado resolve tudo:
@Model.sTelefone.ToString(@"0000\-0000")

Não é preciso formatar por JavaScript porque o campo vai aparecer estático.