问:
Run Macro from LibreOffice extension JAVA
I am trying to run a Macro (the macro is in Writer Standard.Voto.Main) from a java button in a extension.

This is the button:

```<code><dlg:button dlg:id="Bt_voto" dlg:tab-index="2" dlg:left="78" dlg:top="15" dlg:width="52" dlg:height="12" dlg:tag="B" dlg:value="Voto"><script:eventscript:event-name="on-performaction" script:macro-name="vnd.sun.star.UNO:ConfigChange" script:language="UNO"/>
</code>```

I call the method from this class:

```<code>public boolean callHandlerMethod(XDialog dialog, Object eventObject, String methodName)
        throws WrappedTargetException {
    if (methodName.equals(ConfigChange)) {

        try {
            String param = "";
            // String cmd =
            // "Standard.Conversion.ConvertHTMLToWord?langauge=Basic&location=application";
            String cmd = "Standard.Voto.Main?langauge=Basic&location=Document";
            System.out.println("Running macro on " + param);
            Macro macObj = new Macro();
            macObj.executeMacro(cmd, new Object[] { param });
            System.out.println("Completed?");
            onOkButtonPressed();
        } catch (Exception e) {
            System.out.println(e.toString());
            // e.printStackTrace();
        }
</code>```

and the Macro.class is:

```<code>class Macro {

    public Object executeMacro(String strMacroName, Object[] aParams) throws BootstrapException
    {

        String oooExecFolder = "C:/Program Files (x86)/LibreOffice 5/program";

        try {
            System.out.println("Completed1");
            XComponentContext xContext = BootstrapSocketConnector.bootstrap(oooExecFolder);
            XMultiComponentFactory xMultiComponentFactory = xContext.getServiceManager();
            XComponentLoader xcomponentloader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class,xMultiComponentFactory.createInstanceWithContext("com.sun.star.frame.Desktop", xContext));
            System.out.println("Completed2");

            com.sun.star.text.XTextDocument mxDoc = openWriter(xContext);

            XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, xcomponentloader);
            XScriptProvider xScriptProvider = xScriptPS.getScriptProvider();
            XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+strMacroName);

            short[][] aOutParamIndex = new short[1][1];
            Object[][] aOutParam = new Object[1][1];

            aParams = new String[2];

            @SuppressWarnings("unused")
            Object result = xScript.invoke(aParams, aOutParamIndex, aOutParam);
            System.out.println("xScript invoke macro " + strMacroName);

        } catch (Exception e) {
            throw new RuntimeException(e);

        }
        return oooExecFolder;
    }

    public static com.sun.star.text.XTextDocument openWriter(com.sun.star.uno.XComponentContext xContext)
    {

        com.sun.star.frame.XComponentLoader xCLoader;
        com.sun.star.text.XTextDocument xDoc = null;
        com.sun.star.lang.XComponent xComp = null;

        try {
            // get the remote office service manager
            com.sun.star.lang.XMultiComponentFactory xMCF =
                xContext.getServiceManager();

            Object oDesktop = xMCF.createInstanceWithContext(
                                        "com.sun.star.frame.Desktop", xContext);

            xCLoader = (com.sun.star.frame.XComponentLoader)
                UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class,
                                          oDesktop);
            com.sun.star.beans.PropertyValue [] szEmptyArgs =
                new com.sun.star.beans.PropertyValue [0];
           /*
            ArrayList<PropertyValue> props = new ArrayList<PropertyValue>();
            PropertyValue p = new PropertyValue();
            p.Name = "Hidden";
            p.Value = new Boolean(true);
            props.add(p);

            PropertyValue[] properties = new PropertyValue[props.size()];
            props.toArray(properties);
            String strDoc = "private:factory/swriter";
            xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, properties);
            */
            String strDoc = "private:factory/swriter";
            xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, szEmptyArgs);
            xDoc = (com.sun.star.text.XTextDocument)
                UnoRuntime.queryInterface(com.sun.star.text.XTextDocument.class,
                                          xComp);

        } catch(Exception e){
            System.err.println(" Exception " + e);
            e.printStackTrace(System.err);
        }
        return xDoc;
    }
}
</code>```

If I run this class the bootstrap works, but it's terminated at this line:

```<code>XComponentContext xContext = BootstrapSocketConnector.bootstrap(oooExecFolder);
</code>```

without error. Can you help me?

答:
It is much easier to call the Basic macro directly from the dialog.  This works even if the rest of the extension uses Java.  Be sure to use the correct Script URI.

```<code><dlg:button dlg:id="Bt_voto" dlg:tab-index="3" dlg:left="173" dlg:top="88" dlg:width="51" dlg:height="13" dlg:value="Voto">
  <script:event script:event-name="on-performaction" script:macro-name="vnd.sun.star.script:Standard.Voto.Main?language=Basic&location=application" script:language="Script"/>
</dlg:button>
</code>```

However if you do need to go through Java for some other reason, then keep reading.  It looks like you tried to combine code from two different projects:

https://github.com/smehrbrodt/libreoffice-starter-extension

https://github.com/kinow/bootstrapconnector

The problem is that some commands should only be done once, and each project does them, resulting in duplication.  Don't bootstrap a second time.  Instead, store the context somewhere so it can be passed to the Macro class when needed.

Below are the relevant parts of the code that worked for me.  For testing, I added a main method to StarterProjectImpl.java.  This made it possible to see the error messages.

```<code>public static void main (String [] args) {
    com.sun.star.uno.XComponentContext xContext = null;
    try {
        xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
        ActionOneDialog actionOneDialog = new ActionOneDialog(xContext);
        actionOneDialog.show();
    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

public ActionOneDialog(XComponentContext xContext) {
    m_xContext = xContext;
    this.dialog = DialogHelper.createDialog("ActionOneDialog.xdl", xContext, this);
}

public boolean callHandlerMethod(XDialog dialog, Object eventObject, String methodName) throws WrappedTargetException {
    if (methodName.equals(ConfigChange)) {
        try {
            String cmd = "Standard.Voto.Main?language=Basic&location=application";
            Macro macObj = new Macro(m_xContext);
        }
    }

public Object executeMacro(String strMacroName, Object[] aParams)
{
    String oooExecFolder = "C:/Program Files (x86)/LibreOffice 5/program";
    try {
        XMultiComponentFactory xMultiComponentFactory = m_xContext.getServiceManager();
        Object oDesktop = xMultiComponentFactory.createInstanceWithContext(
                        "com.sun.star.frame.Desktop", m_xContext);
        XComponentLoader xcomponentloader = (com.sun.star.frame.XComponentLoader)
            UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class,
                                  oDesktop);
        com.sun.star.text.XTextDocument mxDoc = openWriter(m_xContext);

        XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(
                XScriptProviderSupplier.class, mxDoc);
        XScriptProvider xScriptProvider = xScriptPS.getScriptProvider();
        XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+strMacroName);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
</code>```

EDIT:

Here are step by step instructions.  In LibreOffice, go to Tools -> Macros -> Organize Macros -> LibreOffice Basic.  Under My Macros & Dialogs -> Standard -> Voto, paste this code:

Sub Main
    MsgBox("Hello, Voto!")
End Sub
```

<p>Next follow the Get Started instructions.
Expand <code>dialog -> ActionOneDialog.xdl</code> and go to the <code>Source</code> tab.  Paste the following code after <code></dlg:button></code>.</p>

```<dlg:button dlg:id="Bt_voto" dlg:tab-index="4" dlg:left="100" dlg:top="88" dlg:width="51" dlg:height="13" dlg:value="Voto">

Body:
I am trying to run a Macro (the macro is in Writer Standard.Voto.Main) from a java button in a extension.

This is the button:

<dlg:button dlg:id="Bt_voto" dlg:tab-index="2" dlg:left="78" dlg:top="15" dlg:width="52" dlg:height="12" dlg:tag="B" dlg:value="Voto">

Body:
It is much easier to call the Basic macro directly from the dialog.  This works even if the rest of the extension uses Java.  Be sure to use the correct Script URI.

<dlg:button dlg:id="Bt_voto" dlg:tab-index="3" dlg:left="173" dlg:top="88" dlg:width="51" dlg:height="13" dlg:value="Voto">
  <script:event script:event-name="on-performaction" script:macro-name="vnd.sun.star.script:Standard.Voto.Main?language=Basic&amp;location=application" script:language="Script"/>
</dlg:button>

However if you do need to go through Java for some other reason, then keep reading.  It looks like you tried to combine code from two different projects:

https://github.com/smehrbrodt/libreoffice-starter-extension

https://github.com/kinow/bootstrapconnector

The problem is that some commands should only be done once, and each project does them, resulting in duplication.  Don't bootstrap a second time.  Instead, store the context somewhere so it can be passed to the Macro class when needed.

Below are the relevant parts of the code that worked for me.  For testing, I added a main method to StarterProjectImpl.java.  This made it possible to see the error messages.

public static void main (String [] args) {
    com.sun.star.uno.XComponentContext xContext = null;
    try {
        xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
        ActionOneDialog actionOneDialog = new ActionOneDialog(xContext);
        actionOneDialog.show();
    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

public ActionOneDialog(XComponentContext xContext) {
    m_xContext = xContext;
    this.dialog = DialogHelper.createDialog("ActionOneDialog.xdl", xContext, this);
}

public boolean callHandlerMethod(XDialog dialog, Object eventObject, String methodName) throws WrappedTargetException {
    if (methodName.equals(ConfigChange)) {
        try {
            String cmd = "Standard.Voto.Main?language=Basic&location=application";
            Macro macObj = new Macro(m_xContext);
        }
    }

public Object executeMacro(String strMacroName, Object[] aParams)
{
    String oooExecFolder = "C:/Program Files (x86)/LibreOffice 5/program";
    try {
        XMultiComponentFactory xMultiComponentFactory = m_xContext.getServiceManager();
        Object oDesktop = xMultiComponentFactory.createInstanceWithContext(
                        "com.sun.star.frame.Desktop", m_xContext);
        XComponentLoader xcomponentloader = (com.sun.star.frame.XComponentLoader)
            UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class,
                                  oDesktop);
        com.sun.star.text.XTextDocument mxDoc = openWriter(m_xContext);

        XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(
                XScriptProviderSupplier.class, mxDoc);
        XScriptProvider xScriptProvider = xScriptPS.getScriptProvider();
        XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+strMacroName);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

EDIT:

Here are step by step instructions.  In LibreOffice, go to Tools -> Macros -> Organize Macros -> LibreOffice Basic.  Under My Macros & Dialogs -> Standard -> Voto, paste this code:

Sub Main
    MsgBox("Hello, Voto!")
End Sub

Next follow the Get Started instructions.
Expand dialog -> ActionOneDialog.xdl and go to the Source tab.  Paste the following code after </dlg:button>.

<dlg:button dlg:id="Bt_voto" dlg:tab-index="4" dlg:left="100" dlg:top="88" dlg:width="51" dlg:height="13" dlg:value="Voto">
  <script:event script:event-name="on-performaction" script:macro-name="vnd.sun.star.script:Standard.Voto.Main?language=Basic&amp;location=application" script:language="Script"/>
</dlg:button>

Now run it to add the extension.  Finally in LibreOffice, go to Starter Project -> Action One and click Voto.  The result should be this:

EDIT 2:

From my experience, it is not possible to insert a field from within a dialog event handler.  Instead, wait until after the dialog has finished executing and then insert the field.

For this project, it should work to modify show() in ActionOneDialog.java.  After the command dialog.execute(), write Java code to insert the field using the dispatcher.


来源: stackexchange

问:
Swift Images cannot be read in Asset Catalog
I'm trying to save some images into my bundle. The images reads just fine when I save them in the main bundle.
in main bundle

However, if I place them into the asset catalog, they can no longer be read.
In asset catelog

Below are the codes I use to access them. If I save the pictures inside the asset catalog, the for item in items loop doesn't pick up any of the pictures.

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let fm = FileManager.default
    let path = Bundle.main.resourcePath!
    let items = try! fm.contentsOfDirectory(atPath: path)

    for item in items {
        if item.hasPrefix("nssl") {
            pictures.append(item)
        }
    }
}
</code>```

答:
There's no documented way to iterate through the images contained in an xcasset file. At build time the assets get compiled to a .car file, but the only way to read images out of the asset is through UIImaged(named:).

If you need to be able to iterate through some resources in this way, it's best to store them in a simple folder inside your bundle.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to save some images into my bundle. The images reads just fine when I save them in the main bundle.
in main bundle

However, if I place them into the asset catalog, they can no longer be read.
In asset catelog

Below are the codes I use to access them. If I save the pictures inside the asset catalog, the for item in items loop doesn't pick up any of the pictures.

override func viewDidLoad() {
    super.viewDidLoad()

    let fm = FileManager.default
    let path = Bundle.main.resourcePath!
    let items = try! fm.contentsOfDirectory(atPath: path)

    for item in items {
        if item.hasPrefix("nssl") {
            pictures.append(item)
        }
    }
}


问:
How to call / access a label in button action programmatically?
```<code>//This is the label

let changeLbl = UILabel(frame: CGRect(x: 20, y: 170, width: 300, height: 21))

self.view.addSubview(changeLbl)

//This is the button

let submitButton = UIButton(type: .system) // let preferred over var here

submitButton.addTarget(self, action: #selector(buttonAction) , for: UIControlEvents.touchUpInside)

self.view.addSubview(submitButton)

//and this is action of above button

func buttonAction(sender: UIButton!) {

}
</code>```

I want to call the above label in the following button function? like

```<code>func buttonAction(sender: UIButton!) {
    changeLbl.ishidden = true
</code>```

// want to access label here, but it's not working this way.
    }

答:
changeLbl is a local variable. It's only visible in the scope of the method where the label is created.

If you don't want to use an instance variable – which is the normal way – and there is only one UILabel you can get the label from the subviews array

```<code>func buttonAction(sender: UIButton) {
    if let changeLbl = self.view.subviews.filter({ $0 is UILabel}).first {
       changeLbl.ishidden = true
    }
}
</code>```

Body:
//This is the label

let changeLbl = UILabel(frame: CGRect(x: 20, y: 170, width: 300, height: 21))

self.view.addSubview(changeLbl)

//This is the button

let submitButton = UIButton(type: .system) // let preferred over var here

submitButton.addTarget(self, action: #selector(buttonAction) , for: UIControlEvents.touchUpInside)

self.view.addSubview(submitButton)

//and this is action of above button

func buttonAction(sender: UIButton!) {

}

I want to call the above label in the following button function? like

func buttonAction(sender: UIButton!) {
    changeLbl.ishidden = true

// want to access label here, but it's not working this way.
    }

Body:
changeLbl is a local variable. It's only visible in the scope of the method where the label is created.

If you don't want to use an instance variable – which is the normal way – and there is only one UILabel you can get the label from the subviews array

func buttonAction(sender: UIButton) {
    if let changeLbl = self.view.subviews.filter({ $0 is UILabel}).first {
       changeLbl.ishidden = true
    }
}


问:
Create a class constructor from scratch in ByteBuddy
I am trying to create a Java class from scratch using ByteBuddy. A class is supposed to have a bunch of private final properties and one constructor which initializes them with the arguments passed. I started with:

```<code>DynamicType.Builder<?> builder = new ByteBuddy()
                .subclass(Object.class)
                .implement(Serializable.class)
                .modifiers(Visibility.PUBLIC, TypeManifestation.FINAL)
                .name("Structure");

// for each property to be declared
builder = builder.defineField(bindingName, bindingType, visibility.PRIVATE, FieldManifestation.FINAL);
// end of for

builder = builder.defineConstructor(Visibility.PUBLIC)
                .withParameters(bindings)
                .intercept(/* Some implementation is supposed to go here*/);
</code>```

I have several questions:

Does ByteBuddy provide some suitable Implementation for that out-of-the-box?

Is there somewhere an overview of ByteBuddy Implementation classes, provided out-of-the-box?

If there is no such Implementation out-of-the-box, I'd be appreciated for some hints on how to make my own Implementation instance serving my purpose.

答:
You can implement such a constructor by a combination of MethodCall and FieldAccessor:

```<code>DynamicType.Builder<?> builder = ...;
Implementation interceptor = StubMethod.INSTANCE;

// for each field
builder = builder.defineField(bindingName,
              bindingType, visibility.PRIVATE, FieldManifestation.FINAL);
interceptor = FieldAccessor.ofField(bindingName)
                  .setsArgumentAt( ... )
                  .andThen(interceptor);

interceptor = MethodCall.invoke( ... ).andThen(interceptor);
</code>```

The method call must invoke a specific constructor of either the instrumented class or the super class constructor (might be the default constructor of Object). The argument index needs to be the index of the argument that is assigned to the field (zero-based).

Body:
I am trying to create a Java class from scratch using ByteBuddy. A class is supposed to have a bunch of private final properties and one constructor which initializes them with the arguments passed. I started with:

DynamicType.Builder<?> builder = new ByteBuddy()
                .subclass(Object.class)
                .implement(Serializable.class)
                .modifiers(Visibility.PUBLIC, TypeManifestation.FINAL)
                .name("Structure");

// for each property to be declared
builder = builder.defineField(bindingName, bindingType, visibility.PRIVATE, FieldManifestation.FINAL);
// end of for

builder = builder.defineConstructor(Visibility.PUBLIC)
                .withParameters(bindings)
                .intercept(/* Some implementation is supposed to go here*/);

I have several questions:

Does ByteBuddy provide some suitable Implementation for that out-of-the-box?

Is there somewhere an overview of ByteBuddy Implementation classes, provided out-of-the-box?

If there is no such Implementation out-of-the-box, I'd be appreciated for some hints on how to make my own Implementation instance serving my purpose.

Body:
You can implement such a constructor by a combination of MethodCall and FieldAccessor:

DynamicType.Builder<?> builder = ...;
Implementation interceptor = StubMethod.INSTANCE;

// for each field
builder = builder.defineField(bindingName,
              bindingType, visibility.PRIVATE, FieldManifestation.FINAL);
interceptor = FieldAccessor.ofField(bindingName)
                  .setsArgumentAt( ... )
                  .andThen(interceptor);

interceptor = MethodCall.invoke( ... ).andThen(interceptor);

The method call must invoke a specific constructor of either the instrumented class or the super class constructor (might be the default constructor of Object). The argument index needs to be the index of the argument that is assigned to the field (zero-based).


问:
How to create a subversion repository
I have an apache server running and working with a username and password.  I want to create a subversion project - how do I connect to the apache server in Terminal (if I have to) and create the project structure etc before configuring in Xcode?</p>

答:
```<code>svnadmin create myproject
</code>```

Will create you a repository

More complete information about creating repositories can be found here Creating and Configuring Your Repository

ContentLicense: CC BY-SA 2.5

Title: How to create a subversion repository

Body:
svnadmin create myproject

Will create you a repository

More complete information about creating repositories can be found here Creating and Configuring Your Repository


问:
Checking if a Python array only includes a set list of numbers
To check user input, I'm trying to see of the input only includes a list of numbers. The input is a 100x100 array with numbers -1,0 and 1. And now I'm trying with an if statement to check if this array only includes the above numbers.

```<code>if np.all(Array) == (-1,0,1):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

I also tried:

```<code>if np.any(Array) == -1 and np.any(Array) == 0 and np.any(Array) == 1:

if np.all(Array) == -1 and 0 and 1:
</code>```

But nothing worked...

答:
You can use numpy.unique to get a sorted array of the unique elements in the array.

Try the following:

```<code>import numpy as np
a = np.array([[1,1],[0,1],[1,-1]]

def foo(a):
  lst = [-1,0,1]
  if isinstance(np.unique(a) == lst, bool) and not(np.unique(a) == lst):
    return False
  elif np.all(np.unique(a) == lst) == True:
    return True

print foo(a) ##prints True because the array 3x3 array 'a' only contains the elements -1,0,1
</code>```

Note: comparing the 2 arrays returns False if all the elements are not equal and returns an array of 3 'True' elements if all the elements are true, therefore we need to use np.all to make sure all the 3 elements returned by the equality comparison are True

Body:
To check user input, I'm trying to see of the input only includes a list of numbers. The input is a 100x100 array with numbers -1,0 and 1. And now I'm trying with an if statement to check if this array only includes the above numbers.

if np.all(Array) == (-1,0,1):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I also tried:

if np.any(Array) == -1 and np.any(Array) == 0 and np.any(Array) == 1:

if np.all(Array) == -1 and 0 and 1:

But nothing worked...

Body:
You can use numpy.unique to get a sorted array of the unique elements in the array.

Try the following:

import numpy as np
a = np.array([[1,1],[0,1],[1,-1]]

def foo(a):
  lst = [-1,0,1]
  if isinstance(np.unique(a) == lst, bool) and not(np.unique(a) == lst):
    return False
  elif np.all(np.unique(a) == lst) == True:
    return True

print foo(a) ##prints True because the array 3x3 array 'a' only contains the elements -1,0,1

Note: comparing the 2 arrays returns False if all the elements are not equal and returns an array of 3 'True' elements if all the elements are true, therefore we need to use np.all to make sure all the 3 elements returned by the equality comparison are True


问:
What do internal compiler error messages mean, and what can I do?
I was trying to compile my C++ program, which uses MPICH and NAG C library (I use NAG to generate random numbers), with a pgCC compiler.

However, the compiler gave me the following error message:

```<code>PGCC-S-0000-Internal compiler error. linearize: bad ili #:       0 (mpisim.C: 225)
PGCC-S-0000-Internal compiler error. gen_aili: unrec. ili opcode:       0 (mpisim.C: 225)
PGCC-S-0000-Internal compiler error. linearize: bad ili #:       0 (mpisim.C: 266)
PGCC-S-0000-Internal compiler error. gen_aili: unrec. ili opcode:       0 (mpisim.C: 266)
PGCC/x86 Linux 12.4-0: compilation completed with severe errors
</code>```

I have no idea what these messages are referring to. Can someone explain to me what they mean?

Is there a way for me to figure out the position of the problematic line(s)? Does the 255 in (mpisim.C: 225) indicate the line number in my code?

答: If you get an internal compiler error odds are that it could be due to bad hardware. Maybe your RAM is faulty? Try running memtest86.</p>

Body:
I was trying to compile my C++ program, which uses MPICH and NAG C library (I use NAG to generate random numbers), with a pgCC compiler.

However, the compiler gave me the following error message:

PGCC-S-0000-Internal compiler error. linearize: bad ili #:       0 (mpisim.C: 225)
PGCC-S-0000-Internal compiler error. gen_aili: unrec. ili opcode:       0 (mpisim.C: 225)
PGCC-S-0000-Internal compiler error. linearize: bad ili #:       0 (mpisim.C: 266)
PGCC-S-0000-Internal compiler error. gen_aili: unrec. ili opcode:       0 (mpisim.C: 266)
PGCC/x86 Linux 12.4-0: compilation completed with severe errors

I have no idea what these messages are referring to. Can someone explain to me what they mean?

Is there a way for me to figure out the position of the problematic line(s)? Does the 255 in (mpisim.C: 225) indicate the line number in my code?


问:
POST request with Authorization
Instead of returning me data why does it say Object {status: 200, message: "Key Missing", data: null} in the console

Here's my service

```<code>import {Injectable} from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
    export class GetValueService {
        constructor(private http: Http){
            console.log('Init');
        }

        getValue(){
            let headers = new Headers();
            headers.append( 'Authorization', 'afkdihnadbufgadbg325423' )
            return this.http.post('url', { headers: headers }).map(response => response.json())
        }
    }
</code>```

Here's the component

```<code>import { Component } from '@angular/core';
import { GetValueService } from '../../services/getvalue/getValue.service';

@Component({
    moduleId: module.id,
    selector: 'selectValue',
    templateUrl: 'selectValue.component.html',
    providers: [GetValueService ]
})
export class selectValueComponent  {
    constructor(private getValueService : GetValueService ){

        this.getValueService.getValue().subscribe(data => {
            console.log(data);
        })

    }
}
</code>```

I did read the documentation and there aren't any great tutorials on this. I don't get what I am doing wrong here.

答:
```<code>post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>;
</code>```

This is the way you should post data in Angular.

Title: POST request with Authorization

Body:
Instead of returning me data why does it say Object {status: 200, message: "Key Missing", data: null} in the console

Here's my service

import {Injectable} from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
    export class GetValueService {
        constructor(private http: Http){
            console.log('Init');
        }

        getValue(){
            let headers = new Headers();
            headers.append( 'Authorization', 'afkdihnadbufgadbg325423' )
            return this.http.post('url', { headers: headers }).map(response => response.json())
        }
    }

Here's the component

import { Component } from '@angular/core';
import { GetValueService } from '../../services/getvalue/getValue.service';

@Component({
    moduleId: module.id,
    selector: 'selectValue',
    templateUrl: 'selectValue.component.html',
    providers: [GetValueService ]
})
export class selectValueComponent  {
    constructor(private getValueService : GetValueService ){

        this.getValueService.getValue().subscribe(data => {
            console.log(data);
        })

    }
}

I did read the documentation and there aren't any great tutorials on this. I don't get what I am doing wrong here.

Body:
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>;

This is the way you should post data in Angular.


问:
Android fanotify_init: Function not implemented
I'm trying to use fanotify on Android and like to archive that with an executable file (compiled with the ndk). I'm using fsmon (small application which calls the fanotify systemcall) to start the monitor. But on executing the file (on a rooted device as root) I'm getting following error:

```<code>generic_x86:/data/local/tmp # ./fsmon -B fanotify /storage/emulated/0/
fanotify_init: Function not implemented
</code>```

fanotify is available in kernel version > 2.6.37 (which is shipped in Android 5+).

I had tried it on a x86-emulator (Android 7) and on a Samsung I9300 armeabi-v7a (Android 6) with CM13 (both rooted).
Kernel version of the x86 emulator: 3.4.67+ and of the Samsung device: 3.0.101-CM-g9c98896

Then I had a look into the x86-emulator goldfish kernel files in /goldfish/fs/notify/fanotify/Kconfig:

```<code>config FANOTIFY
    bool "Filesystem wide access notification"
    select FSNOTIFY
    select ANON_INODES
    default n
    ---help---
       Say Y here to enable fanotify suport.  fanotify is a file access
       notification system which differs from inotify in that it sends
       an open file descriptor to the userspace listener along with
       the event.

       If unsure, say Y.

config FANOTIFY_ACCESS_PERMISSIONS
    bool "fanotify permissions checking"
    depends on FANOTIFY
    depends on SECURITY
    default n
    ---help---
       Say Y here is you want fanotify listeners to be able to make permissions
       decisions concerning filesystem events.  This is used by some fanotify
       listeners which need to scan files before allowing the system access to
       use those files.  This is used by some anti-malware vendors and by some
       hierarchical storage managent systems.

       If unsure, say N.
</code>```

So, I set both to Y, make clean and recompile the kernel - but same problem like before.. Have I overlooked something?

答: Ok apparently was the fault to use an uppercase "Y" instead of a lowercase "y" ... </p>

Body:
I'm trying to use fanotify on Android and like to archive that with an executable file (compiled with the ndk). I'm using fsmon (small application which calls the fanotify systemcall) to start the monitor. But on executing the file (on a rooted device as root) I'm getting following error:

generic_x86:/data/local/tmp # ./fsmon -B fanotify /storage/emulated/0/
fanotify_init: Function not implemented

fanotify is available in kernel version > 2.6.37 (which is shipped in Android 5+).

I had tried it on a x86-emulator (Android 7) and on a Samsung I9300 armeabi-v7a (Android 6) with CM13 (both rooted).
Kernel version of the x86 emulator: 3.4.67+ and of the Samsung device: 3.0.101-CM-g9c98896

Then I had a look into the x86-emulator goldfish kernel files in /goldfish/fs/notify/fanotify/Kconfig:

config FANOTIFY
    bool "Filesystem wide access notification"
    select FSNOTIFY
    select ANON_INODES
    default n
    ---help---
       Say Y here to enable fanotify suport.  fanotify is a file access
       notification system which differs from inotify in that it sends
       an open file descriptor to the userspace listener along with
       the event.

       If unsure, say Y.

config FANOTIFY_ACCESS_PERMISSIONS
    bool "fanotify permissions checking"
    depends on FANOTIFY
    depends on SECURITY
    default n
    ---help---
       Say Y here is you want fanotify listeners to be able to make permissions
       decisions concerning filesystem events.  This is used by some fanotify
       listeners which need to scan files before allowing the system access to
       use those files.  This is used by some anti-malware vendors and by some
       hierarchical storage managent systems.

       If unsure, say N.

So, I set both to Y, make clean and recompile the kernel - but same problem like before.. Have I overlooked something?


问:
Link Loaded from other file via jquery is not working
I opened a link which looks exactly like this: http://localhost/anysite/#data_aa

Then, jquery performs the following:

```<code>$('a[href^="data_"]').click(function(){
    //code to be executed and at end,
    $("anyDIV").load('anyfile.php?parameter=anyvalue');
});
</code>```

This selects all the links where the href attribute starts with "data_" to load data from PHP file.

Data and links are loaded successfully but the loaded links do not work which exactly looks as same I mentioned in beginning like this http://localhost/anysite/#data_ss...

Hope, You understood my problem and will be able to help me......

答:
You need to use the live method.

```<code>$('a[href^="data_"]').live('click',function() {
    //code to be executed and at end,
    $("anyDIV").load('anyfile.php?parameter=anyvalue');
});
</code>```

The click bind happens at page load, so any content dynamically added afterwards wont be included in that bind, the live method facilitates this.

Body:
I opened a link which looks exactly like this: http://localhost/anysite/#data_aa

Then, jquery performs the following:

$('a[href^="data_"]').click(function(){
    //code to be executed and at end,
    $("anyDIV").load('anyfile.php?parameter=anyvalue');
});

This selects all the links where the href attribute starts with "data_" to load data from PHP file.

Data and links are loaded successfully but the loaded links do not work which exactly looks as same I mentioned in beginning like this http://localhost/anysite/#data_ss...

Hope, You understood my problem and will be able to help me......

Body:
You need to use the live method.

$('a[href^="data_"]').live('click',function() {
    //code to be executed and at end,
    $("anyDIV").load('anyfile.php?parameter=anyvalue');
});

The click bind happens at page load, so any content dynamically added afterwards wont be included in that bind, the live method facilitates this.


问:
Multi line comment in ZipArchive
I am trying to set a multi-line comment with ZipArchive.Below is a simplified demo.

```<code><?php
$comment = "File \t Stats\r\n";
$comment .= "Second line ...some another text \r\n";
$zip->setArchiveComment($comment);
</code>```

I then open the zip file with Winrar on my windows machine and in the comment you can see \r\n , \t appearing as is ... indicating that either winrar don't allow this or i wrong set the zipArchive comment.

答:
I cannot reproduce your problem based on your simplified demo. WinRAR displays it as expected. But I can mimic the result you get by using single quotes for the comment string. </p>

```<code><?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');

    $zip->setArchiveComment("File \t Stats\r\nSecond line ... some other text \r\n"); // OK
    $comment = "File \t Stats\r\n";
    $comment .= 'Second line ... some other text \r\n';
    $zip->setArchiveComment($comment); // NOT OK for the second line

    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
</code>```

Title: Multi line comment in ZipArchive

Body:
I am trying to set a multi-line comment with ZipArchive.Below is a simplified demo.

<?php
$comment = "File \t Stats\r\n";
$comment .= "Second line ...some another text \r\n";
$zip->setArchiveComment($comment);

I then open the zip file with Winrar on my windows machine and in the comment you can see \r\n , \t appearing as is ... indicating that either winrar don't allow this or i wrong set the zipArchive comment.

Body:
I cannot reproduce your problem based on your simplified demo. WinRAR displays it as expected. But I can mimic the result you get by using single quotes for the comment string.

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');

    $zip->setArchiveComment("File \t Stats\r\nSecond line ... some other text \r\n"); // OK
    $comment = "File \t Stats\r\n";
    $comment .= 'Second line ... some other text \r\n';
    $zip->setArchiveComment($comment); // NOT OK for the second line

    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}


问:
Why do I need a Virtual Private Server(VPS)?
I have Linux Ubuntu installed and I want to code my Flask app in Linux only.But certain tutorials are coding the web app in a VPS.Why do I need a VPS?Can't I build my web app locally and directly host my site on Heroku?</p>

答:
You can host your application in any form you like.

VPS are an abstraction of a machine, giving you all the resources your application would need often at a fraction of the price required to get a physical server just for you. So it may be a good idea to use a VPS for the development and first phase in the life of your website.

You may also directly choose to deploy your website in one of the many cloud providers. Often they will not charge you until you start hitting a certain amount of resource utilization. So that may also be a cost saver.

You can find some additional info about the benefits of VPS here.

Note I am not associated with the website in any way, I just found it to be quite thorough in talking about VPS.


问:
many-to-one mapping with composite key in nhibernate
I have following nhibernate mapping , I want to save composite key values into separate column in other entity TimesheetCellTransactionLine with one to one mapping. any ideas ? following doesnt save the values passes null in both foreign key column.

<hibernate-mapping
    xmlns="urn:nhibernate-mapping-2.2"
    assembly="ManpowerUK.Indigo.Domain"
    namespace="ManpowerUK.Indigo.Domain.Timesheets">
    <class name="CMSTimesheetCell" lazy="false" table="vw_TimesheetCell" mutable="false">
        <composite-id >
            <key-property name="TimesheetCellId"/>
            <key-property name="TimesheetCellVersion" column="Version"/>
        </composite-id>
        <property name="TimesheetId" not-null="true" />
        <property name="IsRemoved" />
    </class>
</hibernate-mapping>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="ManpowerUK.Indigo.Domain" namespace="ManpowerUK.Indigo.Domain">
  <class name="TimesheetCellTransactionLine" lazy="false">
      <id column="TransactionLineId"/>
      <many-to-one name="Timesheet" class="ManpowerUK.Indigo.Domain.Timesheets.TimesheetCellWrite" column="TimesheetId" not-null="true" lazy="proxy"/>
      <many-to-one name="CMSTimesheetCell" class="ManpowerUK.Indigo.Domain.Timesheets.CMSTimesheetCell" not-null="true" lazy="proxy" cascade="none">
        <column name="TimesheetCellId"/>
        <column name="TimesheetCellVersion"/>
      </many-to-one>
  </class>
</hibernate-mapping>
```

答:
I solved by adding additional property mapping to insert the composite keys

```<code>  <property name="TimesheetCellId" not-null="true" />
  <property name="TimesheetCellVersion" not-null="true" />
</code>```

and while fetching I used following mapping with insert and update false and cascade none.

```<code> <many-to-one name="CMSTimesheetCell" class="ManpowerUK.Indigo.Domain.Timesheets.CMSTimesheetCell" not-null="true" lazy="proxy" cascade="none" insert="false" update="false">
    <column name="TimesheetCellId"/>
    <column name="TimesheetCellVersion"/>
  </many-to-one>
</code>```

full mapping file which works is as follows.

```<code>     <?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="ManpowerUK.Indigo.Domain" namespace="ManpowerUK.Indigo.Domain">
  <class name="TimesheetCellTransactionLine"  lazy="false">
      <id column="TransactionLineId" />
      <property name="TimesheetCellId" not-null="true" />
      <property name="TimesheetCellVersion" not-null="true" />
           <many-to-one name="CMSTimesheetCell" class="ManpowerUK.Indigo.Domain.Timesheets.CMSTimesheetCell" not-null="true" lazy="proxy" cascade="none" insert="false" update="false">
        <column name="TimesheetCellId"/>
        <column name="TimesheetCellVersion"/>
      </many-to-one>
    </class>
</hibernate-mapping>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I solved by adding additional property mapping to insert the composite keys

  <property name="TimesheetCellId" not-null="true" />
  <property name="TimesheetCellVersion" not-null="true" />

and while fetching I used following mapping with insert and update false and cascade none.

 <many-to-one name="CMSTimesheetCell" class="ManpowerUK.Indigo.Domain.Timesheets.CMSTimesheetCell" not-null="true" lazy="proxy" cascade="none" insert="false" update="false">
    <column name="TimesheetCellId"/>
    <column name="TimesheetCellVersion"/>
  </many-to-one>

full mapping file which works is as follows.

     <?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="ManpowerUK.Indigo.Domain" namespace="ManpowerUK.Indigo.Domain">
  <class name="TimesheetCellTransactionLine"  lazy="false">
      <id column="TransactionLineId" />
      <property name="TimesheetCellId" not-null="true" />
      <property name="TimesheetCellVersion" not-null="true" />
           <many-to-one name="CMSTimesheetCell" class="ManpowerUK.Indigo.Domain.Timesheets.CMSTimesheetCell" not-null="true" lazy="proxy" cascade="none" insert="false" update="false">
        <column name="TimesheetCellId"/>
        <column name="TimesheetCellVersion"/>
      </many-to-one>
    </class>
</hibernate-mapping>


问:
How to Pass params in g:link
I need to pass two params via g:link like below

<g:link controller="ClaimDetails" action="downloadFile1" params="[basePath:${session.basePath}, projCode:${session.projCode}]"><g:message code="claimDetails.ling.notice" /></g:link>

but it gives me an error like

Attribute value quote wasn't closed (controller="ClaimDetails" action="downloadFile1" params="[basePath:${session.basePath}, projCode:${session.projCode}]")

When i give params like basePath:'${session.basePath}'

It gives me the text only.

What i need to do?

答:
Try:</p>

```<code><g:link controller="ClaimDetails" action="downloadFile1" params="${[basePath: session.basePath, projCode: session.projCode]}"><g:message code="claimDetails.ling.notice" /></g:link>
</code>```

Title: How to Pass params in g:link

Body:
Try:

<g:link controller="ClaimDetails" action="downloadFile1" params="${[basePath: session.basePath, projCode: session.projCode]}"><g:message code="claimDetails.ling.notice" /></g:link>


问:
Best way to handle runtime permission in android
i have an old project with target sdk 21, now i have to put run time permission in that so can anyone suggest me any best and simple way to do that.</p>

答:
You can handle permission on Splash Screen or First Screen.

if multiple permission then handle all one time.

if user denied any permission then it show message some permission required.

hope it will help you.

Here is example how to handle multiple permission.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

 if(checkAndRequestPermissions()){
     //all permission granted
 }else{
     //require all permission.
 }

}

private boolean checkAndRequestPermissions() {
    int camerapermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    int phonestate = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
    int location = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
    int recordaudio = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
    int permissionLocation = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    List<String> listPermissionsNeeded = new ArrayList<>();

    if (camerapermission != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.CAMERA);
    }
    if (phonestate != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
    }
    if (location != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
    }
    if (recordaudio != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.RECORD_AUDIO);
    }

    if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
        return false;
    }
    return true;
}

 @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {

    switch (requestCode) {
        case REQUEST_ID_MULTIPLE_PERMISSIONS: {

            Map<String, Integer> perms = new HashMap<>();

            perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);

            // Fill with actual results from user
            if (grantResults.length > 0) {
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // Check for both permissions
                if (perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        ) {
                    Log.d(TAG, "camera & location services permission granted");

                    // here you can do your logic all Permission Success Call
                        moveToNxtScreen();

                } else {
                    Log.d(TAG, "Some permissions are not granted ask again ");
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        showDialogOK("Some Permissions are required for Open Camera",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        switch (which) {
                                            case DialogInterface.BUTTON_POSITIVE:
                                                checkAndRequestPermissions();
                                                break;
                                            case DialogInterface.BUTTON_NEGATIVE:
                                                // proceed with logic by disabling the related features or quit the app.
                                                dialog.dismiss();
                                                break;
                                        }
                                    }
                                });
                    } else {
                        explain("You need to give some mandatory permissions to continue. Do you want to go to app settings?");
                    }
                }
            }
        }
    }

}

private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
    new AlertDialog.Builder(this)
            .setMessage(message)
            .setPositiveButton("OK", okListener)
            .setNegativeButton("Cancel", okListener)
            .create()
            .show();
}

private void explain(String msg) {
    final android.support.v7.app.AlertDialog.Builder dialog = new android.support.v7.app.AlertDialog.Builder(this);
    dialog.setMessage(msg)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    Utils.startInstalledAppDetailsActivity(LoginActivity.this);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    dialog.create().dismiss();
                    finish();
                }
            });
    dialog.show();
}
</code>```

Body:
You can handle permission on Splash Screen or First Screen.

if multiple permission then handle all one time.

if user denied any permission then it show message some permission required.

hope it will help you.

Here is example how to handle multiple permission.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

 if(checkAndRequestPermissions()){
     //all permission granted
 }else{
     //require all permission.
 }

}

private boolean checkAndRequestPermissions() {
    int camerapermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    int phonestate = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
    int location = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
    int recordaudio = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
    int permissionLocation = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    List<String> listPermissionsNeeded = new ArrayList<>();

    if (camerapermission != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.CAMERA);
    }
    if (phonestate != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
    }
    if (location != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
    }
    if (recordaudio != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.RECORD_AUDIO);
    }

    if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
        return false;
    }
    return true;
}

 @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {

    switch (requestCode) {
        case REQUEST_ID_MULTIPLE_PERMISSIONS: {

            Map<String, Integer> perms = new HashMap<>();

            perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);

            // Fill with actual results from user
            if (grantResults.length > 0) {
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // Check for both permissions
                if (perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        ) {
                    Log.d(TAG, "camera & location services permission granted");

                    // here you can do your logic all Permission Success Call
                        moveToNxtScreen();

                } else {
                    Log.d(TAG, "Some permissions are not granted ask again ");
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        showDialogOK("Some Permissions are required for Open Camera",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        switch (which) {
                                            case DialogInterface.BUTTON_POSITIVE:
                                                checkAndRequestPermissions();
                                                break;
                                            case DialogInterface.BUTTON_NEGATIVE:
                                                // proceed with logic by disabling the related features or quit the app.
                                                dialog.dismiss();
                                                break;
                                        }
                                    }
                                });
                    } else {
                        explain("You need to give some mandatory permissions to continue. Do you want to go to app settings?");
                    }
                }
            }
        }
    }

}

private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
    new AlertDialog.Builder(this)
            .setMessage(message)
            .setPositiveButton("OK", okListener)
            .setNegativeButton("Cancel", okListener)
            .create()
            .show();
}

private void explain(String msg) {
    final android.support.v7.app.AlertDialog.Builder dialog = new android.support.v7.app.AlertDialog.Builder(this);
    dialog.setMessage(msg)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    Utils.startInstalledAppDetailsActivity(LoginActivity.this);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    dialog.create().dismiss();
                    finish();
                }
            });
    dialog.show();
}


问:
C callbacks and non-Go threads

How does one call Go code in C from threads that weren't created by Go?

What do I assign to a C function pointer such that threads not created by Go can call that pointer and enter into Go code?

Update0

I don't want to use SWIG.

The callbacks will be coming from threads Go hasn't seen before. Neither cgo/life nor anything in pkg/runtime demonstrates this behaviour AFAICT.

答:
I'll assume you mean from C code compiled with gcc?

IIRC, this either can't be done or can't easily be done using 6g+cgo and friends. Go uses a different calling convention (as well as the segmented stacks and such).

However, you can write C code for [685]c (or even [685]a) and call into go easily using package·function() (you can even call methods IIRC). See the Source of the runtime package for examples.

Update:

Coming back to this question after the update, and giving it some more thought. This can't be done in a standard fashion using 6c or cgo. Especially because the threads are not started by the go runtime, the current implementation would fail. The scheduler would suddenly have a thread under its control that it does not know about; additionally, that thread would be missing some thread-local variables the go runtime uses for managing stacks and some other things. Also, if the go function returns a value (or several) the C code can't access it on the currently supported platforms, as go returns values on the stack (you could access them with assembly though). With these things in mind, I do believe you could still do this using channels. It would require your C code to be a little too intimate with the inner workings of the go runtime, but it would work for a given implementation. While using channels may not be the solution you're looking for, it could possibly fit more nicely with the concepts of Go than callbacks. If your C code reimplemented at least the sending methods in The channel implementation (that code is written for 6c, so it would have to be adapted for gcc most likely, and it calls the go runtime, which we've determined can't be done from a non-go thread), you should be able to lock the channel and push a value to it. The go scheduler can continue to manage it's own threads, but now it can receive data from other threads started in C.

Admittedly, it's a hack; I haven't looked close enough, but it would probably take a few other hacks to get it working (I believe the channels themselves maintain a list of the goroutines that are waiting on them [EDIT: confirmed: runtime·ready(gp);], so you'd need something in your go code to wake up the receiving channel or to warranty the go code won't receive on the channel until you've already pushed a value). However, I can't see any reason this can't work, whereas there are definite reasons that running code generated by 6g on a thread created in C can't.

My original answer still holds though: barring an addition to the language or runtime, this can't yet be done the way you'd like (I'd love to be proven wrong here).

Title: C callbacks and non-Go threads


问:
gzip_decompressor not found in CLion (cpp boost library)
I tried to decompress gzip file using the sample code from boost documentation

```<code>#include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>

int main()
{
    using namespace std;

    ifstream file("example.txt.gz", ios_base::in | ios_base::binary);
    boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
    in.push(boost::iostreams::gzip_decompressor());
    in.push(file);
    boost::iostreams::copy(in, cout);
}
</code>```

I installed boost with $brew install boost.
I've included boost library using Live Template in CLion as instructed in CLion documentation.

However, this simple code doesn't work. (Edited the error message)

```<code>libc++abi.dylib: terminating with uncaught exception of type boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::iostreams::gzip_error> >: gzip error: unspecified iostream_category error
</code>```

I'm suspecting that gzip_decompressor is not recognized somehow.

Looking for a solution!

Edit:

1) This is CMakeLists.txt file.

```<code>cmake_minimum_required(VERSION 3.7)
project(practice_cpp)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)

find_package(Boost REQUIRED COMPONENTS system iostreams)

if(Boost_FOUND)

    message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
    message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
    message(STATUS "Boost_VERSION: ${Boost_VERSION}")

    include_directories(${Boost_INCLUDE_DIRS})

endif()

add_executable(practice_cpp ${SOURCE_FILES})

if(Boost_FOUND)

    target_link_libraries(practice_cpp ${Boost_LIBRARIES})

endif()
</code>```

2) Also, I tried this command on terminal.

```<code>c++ -I /usr/local/Cellar/boost/1.63.0 main.cpp -lboost_iostreams -o main
</code>```

which outputs

```<code>$ ./main
libc++abi.dylib: terminating with uncaught exception of type boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::iostreams::gzip_error> >: gzip error: unspecified iostream_category error
Abort trap: 6
</code>```

3) This is commands_compile.json.

```<code>[
{
  "directory": "/path/to/practice_cpp",
  "command": "/Library/Developer/CommandLineTools/usr/bin/c++    -I/usr/local/include  -g   -std=gnu++11 -o CMakeFiles/practice_cpp.dir/main.cpp.o -c /path/to/practice_cpp/main.cpp",
  "file": "/path/to/practice_cpp/main.cpp"
}
]
</code>```

4) $ make VERBOSE=ON

```<code>$ make VERBOSE=ON
/usr/local/Cellar/cmake/3.7.2/bin/cmake -H/path/to/practice_cpp -B/path/to/practice_cpp --check-build-system CMakeFiles/Makefile.cmake 0
/usr/local/Cellar/cmake/3.7.2/bin/cmake -E cmake_progress_start /path/to/practice_cpp/CMakeFiles /path/to/practice_cpp/CMakeFiles/progress.marks
/Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/Makefile2 all
/Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/practice_cpp.dir/build.make CMakeFiles/practice_cpp.dir/depend
cd /path/to/practice_cpp && /usr/local/Cellar/cmake/3.7.2/bin/cmake -E cmake_depends "Unix Makefiles" /path/to/practice_cpp /path/to/practice_cpp /path/to/practice_cpp /path/to/practice_cpp /path/to/practice_cpp/CMakeFiles/practice_cpp.dir/DependInfo.cmake --color=
/Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/practice_cpp.dir/build.make CMakeFiles/practice_cpp.dir/build
make[2]: Nothing to be done for `CMakeFiles/practice_cpp.dir/build'.
[100%] Built target practice_cpp
/usr/local/Cellar/cmake/3.7.2/bin/cmake -E cmake_progress_start /path/to/practice_cpp/CMakeFiles 0
</code>```

答:
I am on a similar configuration (macOS + brew installed boost) so I tested it. The cmake configuration listed in the answer now is Okay.

```<code>cmake_minimum_required(VERSION 3.7)

project(practice_cpp)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)

find_package(Boost REQUIRED COMPONENTS system iostreams)

if(Boost_FOUND)

    message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
    message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
    message(STATUS "Boost_VERSION: ${Boost_VERSION}")

    include_directories(${Boost_INCLUDE_DIRS})

endif()

add_executable(practice_cpp ${SOURCE_FILES})

if(Boost_FOUND)

    target_link_libraries(practice_cpp ${Boost_LIBRARIES})

endif()
</code>```

Problem is, this seems different from the original file posted in the question:

```<code>cmake_minimum_required(VERSION 3.7)
project(practice_cpp)

set(CMAKE_CXX_STANDARD 11)

    set(SOURCE_FILES main.cpp)
add_executable(practice_cpp ${SOURCE_FILES})

find_package(Boost REQUIRED COMPONENTS system iostreams)

if(Boost_FOUND)

    message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
    message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
    message(STATUS "Boost_VERSION: ${Boost_VERSION}")

include_directories(${Boost_INCLUDE_DIRS})

endif()

add_executable(BoostTest main.cpp)

target_link_libraries(practice_cpp ${Boost_LIBRARIES})
</code>```

When I first saw the problem, the file looked like this. I tested it and got the exact error as is in the problem.

So actually BoostTest is (was) the executable and you should add target_link_libraries(BoostTest ${Boost_LIBRARIES}).

Body:
I tried to decompress gzip file using the sample code from boost documentation

#include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>

int main()
{
    using namespace std;

    ifstream file("example.txt.gz", ios_base::in | ios_base::binary);
    boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
    in.push(boost::iostreams::gzip_decompressor());
    in.push(file);
    boost::iostreams::copy(in, cout);
}

I installed boost with $brew install boost.
I've included boost library using Live Template in CLion as instructed in CLion documentation.

However, this simple code doesn't work. (Edited the error message)

libc++abi.dylib: terminating with uncaught exception of type boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::iostreams::gzip_error> >: gzip error: unspecified iostream_category error

I'm suspecting that gzip_decompressor is not recognized somehow.

Looking for a solution!

Edit:

1) This is CMakeLists.txt file.

cmake_minimum_required(VERSION 3.7)
project(practice_cpp)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)

find_package(Boost REQUIRED COMPONENTS system iostreams)

if(Boost_FOUND)

    message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
    message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
    message(STATUS "Boost_VERSION: ${Boost_VERSION}")

    include_directories(${Boost_INCLUDE_DIRS})

endif()

add_executable(practice_cpp ${SOURCE_FILES})

if(Boost_FOUND)

    target_link_libraries(practice_cpp ${Boost_LIBRARIES})

endif()

2) Also, I tried this command on terminal.

c++ -I /usr/local/Cellar/boost/1.63.0 main.cpp -lboost_iostreams -o main

which outputs

$ ./main
libc++abi.dylib: terminating with uncaught exception of type boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::iostreams::gzip_error> >: gzip error: unspecified iostream_category error
Abort trap: 6

3) This is commands_compile.json.

[
{
  "directory": "/path/to/practice_cpp",
  "command": "/Library/Developer/CommandLineTools/usr/bin/c++    -I/usr/local/include  -g   -std=gnu++11 -o CMakeFiles/practice_cpp.dir/main.cpp.o -c /path/to/practice_cpp/main.cpp",
  "file": "/path/to/practice_cpp/main.cpp"
}
]

4) $ make VERBOSE=ON

$ make VERBOSE=ON
/usr/local/Cellar/cmake/3.7.2/bin/cmake -H/path/to/practice_cpp -B/path/to/practice_cpp --check-build-system CMakeFiles/Makefile.cmake 0
/usr/local/Cellar/cmake/3.7.2/bin/cmake -E cmake_progress_start /path/to/practice_cpp/CMakeFiles /path/to/practice_cpp/CMakeFiles/progress.marks
/Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/Makefile2 all
/Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/practice_cpp.dir/build.make CMakeFiles/practice_cpp.dir/depend
cd /path/to/practice_cpp && /usr/local/Cellar/cmake/3.7.2/bin/cmake -E cmake_depends "Unix Makefiles" /path/to/practice_cpp /path/to/practice_cpp /path/to/practice_cpp /path/to/practice_cpp /path/to/practice_cpp/CMakeFiles/practice_cpp.dir/DependInfo.cmake --color=
/Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/practice_cpp.dir/build.make CMakeFiles/practice_cpp.dir/build
make[2]: Nothing to be done for `CMakeFiles/practice_cpp.dir/build'.
[100%] Built target practice_cpp
/usr/local/Cellar/cmake/3.7.2/bin/cmake -E cmake_progress_start /path/to/practice_cpp/CMakeFiles 0

Body:
I am on a similar configuration (macOS + brew installed boost) so I tested it. The cmake configuration listed in the answer now is Okay.

cmake_minimum_required(VERSION 3.7)

project(practice_cpp)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)

find_package(Boost REQUIRED COMPONENTS system iostreams)

if(Boost_FOUND)

    message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
    message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
    message(STATUS "Boost_VERSION: ${Boost_VERSION}")

    include_directories(${Boost_INCLUDE_DIRS})

endif()

add_executable(practice_cpp ${SOURCE_FILES})

if(Boost_FOUND)

    target_link_libraries(practice_cpp ${Boost_LIBRARIES})

endif()

Problem is, this seems different from the original file posted in the question:

cmake_minimum_required(VERSION 3.7)
project(practice_cpp)

set(CMAKE_CXX_STANDARD 11)

    set(SOURCE_FILES main.cpp)
add_executable(practice_cpp ${SOURCE_FILES})

find_package(Boost REQUIRED COMPONENTS system iostreams)

if(Boost_FOUND)

    message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
    message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
    message(STATUS "Boost_VERSION: ${Boost_VERSION}")

include_directories(${Boost_INCLUDE_DIRS})

endif()

add_executable(BoostTest main.cpp)

target_link_libraries(practice_cpp ${Boost_LIBRARIES})

When I first saw the problem, the file looked like this. I tested it and got the exact error as is in the problem.

So actually BoostTest is (was) the executable and you should add target_link_libraries(BoostTest ${Boost_LIBRARIES}).


问:
Unable to begin a distributed transaction
I'm trying to run SQL against a linked server, but I get the errors below :

```<code>BEGIN DISTRIBUTED TRANSACTION
SELECT TOP 1 * FROM Sessions

OLE DB provider "SQLNCLI" for linked server "ASILIVE" returned message "No transaction is active.".

Msg 7391, Level 16, State 2, Line 3
The operation could not be performed because OLE DB provider "SQLNCLI" for linked server "ASILIVE" was unable to begin a distributed transaction.
</code>```

There are two errors returned by the provider:

Error #1:

```<code>Number: $80040E14
Source: Microsoft OLE DB Provider for SQL Server
Description: OLE DB provider "SQLNCLI" for linked server "ASILIVE" returned message "No transaction is active.".
HelpFile:
HelpContext: $00000000
SQLState: 01000
NativeError: 7412
</code>```

Error #2

```<code>Number: $80040E14
Source: Microsoft OLE DB Provider for SQL Server
Description: The operation could not be performed because OLE DB provider "SQLNCLI" for linked server "ASILIVE" was unable to begin a distributed transaction.
HelpFile:
HelpContext: $00000000
SQLState: 42000
NativeError: 7391
</code>```

How do I get Microsoft to favor functionality over security?

Or, at least, how can I get two SQL Severs to talk to each other?

Related questions

The operation could not be performed because OLE DB provider “SQLNCLI10”... (*linked server name is (null))

Distributed transaction error? (using Oracle provider)

Unable to enlist in a distributed transaction with NHibernate (using Hibernate)

Error using distributed transaction in SQL Server 2008 R2 (SQL Server 2008 R2, no answer)

Distributed Transaction Error Only Through Code (caused by connection pooling)

Error performing distributed transaction coordinator in linked server (SQL Server 2008, no answer)

Distributed transaction error? (no accepted answer; only answer doesn't help)

How to Insert into remote table using Linked server withint Transaction? (accepted answer doesn't resolve)

What I have done is irrelevant, but I'll post it anyway.

Ensure Distributed Transaction Coordinator service is running on both machies:

Disable all MSDTC security on both machines:

Turn on random options on the linked server:

Cursed and swore.

Smashed things.

Checked that a SELECT can use the linked server:

```<code>    SELECT * FROM ASILive.CustomerManagementSystem.dbo.Users
    ....

    (763 row(s) affected)
</code>```

Checked that client server can ping the remote server:

```<code>     C:\Documents and Settings\avatar>ping asicmstest.contoso.com

     Pinging asicmstest.contoso.com [10.0.0.40] with 32 bytes of data:

     Reply from 10.0.0.40: bytes=32 time<1ms TTL=128
     Reply from 10.0.0.40: bytes=32 time<1ms TTL=128
     Reply from 10.0.0.40: bytes=32 time<1ms TTL=128
     Reply from 10.0.0.40: bytes=32 time<1ms TTL=128

     Ping statistics for 10.0.0.40:
         Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
     Approximate round trip times in milli-seconds:
         Minimum = 0ms, Maximum = 0ms, Average = 0ms
</code>```

Checked that the remote server can commnicate back, by name, to the initiating server:

```<code>     C:\Documents and Settings\avatar>ping asitestserver.contoso.com

     Pinging asitestserver.contoso.com [10.0.0.22] with 32 bytes of data:

     Reply from 10.0.0.22: bytes=32 time<1ms TTL=128
     Reply from 10.0.0.22: bytes=32 time<1ms TTL=128
     Reply from 10.0.0.22: bytes=32 time<1ms TTL=128
     Reply from 10.0.0.22: bytes=32 time<1ms TTL=128

     Ping statistics for 10.0.0.22:
         Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
     Approximate round trip times in milli-seconds:
         Minimum = 0ms, Maximum = 0ms, Average = 0ms
</code>```

Checked that @@SERVERNAME matches the server name on both servers:

```<code>   SELECT @@SERVERNAME, SERVERPROPERTY('MachineName')

   -------------  -------------
   ASITESTSERVER  ASITESTSERVER
</code>```

and

```<code>   SELECT @@SERVERNAME, SERVERPROPERTY('MachineName')

   ----------  ----------
   ASIGROBTEST  ASIGROBTEST
</code>```

Screamed

Issued SET XACT_ABORT ON before issuing my query:

```<code>SET XACT_ABORT ON
GO
BEGIN DISTRIBUTED TRANSACTION
SELECT TOP 1 * FROM Sessions
</code>```

Granted Everyone Full Control to:

```<code>HKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServer
</code>```

on both servers.

答:
If your Destination server is on another cloud or data-center then need to add host-entry of MSDTC service(Destination Server) in your source server.

Try this one if problem doesn't resolved, After enable the MSDTC settings.

Body:
I'm trying to run SQL against a linked server, but I get the errors below :

BEGIN DISTRIBUTED TRANSACTION
SELECT TOP 1 * FROM Sessions

OLE DB provider "SQLNCLI" for linked server "ASILIVE" returned message "No transaction is active.".

Msg 7391, Level 16, State 2, Line 3
The operation could not be performed because OLE DB provider "SQLNCLI" for linked server "ASILIVE" was unable to begin a distributed transaction.

There are two errors returned by the provider:

Error #1:

Number: $80040E14
Source: Microsoft OLE DB Provider for SQL Server
Description: OLE DB provider "SQLNCLI" for linked server "ASILIVE" returned message "No transaction is active.".
HelpFile:
HelpContext: $00000000
SQLState: 01000
NativeError: 7412

Error #2

Number: $80040E14
Source: Microsoft OLE DB Provider for SQL Server
Description: The operation could not be performed because OLE DB provider "SQLNCLI" for linked server "ASILIVE" was unable to begin a distributed transaction.
HelpFile:
HelpContext: $00000000
SQLState: 42000
NativeError: 7391

How do I get Microsoft to favor functionality over security?

Or, at least, how can I get two SQL Severs to talk to each other?

Related questions

The operation could not be performed because OLE DB provider “SQLNCLI10”... (*linked server name is (null))

Distributed transaction error? (using Oracle provider)

Unable to enlist in a distributed transaction with NHibernate (using Hibernate)

Error using distributed transaction in SQL Server 2008 R2 (SQL Server 2008 R2, no answer)

Distributed Transaction Error Only Through Code (caused by connection pooling)

Error performing distributed transaction coordinator in linked server (SQL Server 2008, no answer)

Distributed transaction error? (no accepted answer; only answer doesn't help)

How to Insert into remote table using Linked server withint Transaction? (accepted answer doesn't resolve)

What I have done is irrelevant, but I'll post it anyway.

Ensure Distributed Transaction Coordinator service is running on both machies:

Disable all MSDTC security on both machines:

Turn on random options on the linked server:

Cursed and swore.

Smashed things.

Checked that a SELECT can use the linked server:

    SELECT * FROM ASILive.CustomerManagementSystem.dbo.Users
    ....

    (763 row(s) affected)

Checked that client server can ping the remote server:

     C:\Documents and Settings\avatar>ping asicmstest.contoso.com

     Pinging asicmstest.contoso.com [10.0.0.40] with 32 bytes of data:

     Reply from 10.0.0.40: bytes=32 time<1ms TTL=128
     Reply from 10.0.0.40: bytes=32 time<1ms TTL=128
     Reply from 10.0.0.40: bytes=32 time<1ms TTL=128
     Reply from 10.0.0.40: bytes=32 time<1ms TTL=128

     Ping statistics for 10.0.0.40:
         Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
     Approximate round trip times in milli-seconds:
         Minimum = 0ms, Maximum = 0ms, Average = 0ms

Checked that the remote server can commnicate back, by name, to the initiating server:

     C:\Documents and Settings\avatar>ping asitestserver.contoso.com

     Pinging asitestserver.contoso.com [10.0.0.22] with 32 bytes of data:

     Reply from 10.0.0.22: bytes=32 time<1ms TTL=128
     Reply from 10.0.0.22: bytes=32 time<1ms TTL=128
     Reply from 10.0.0.22: bytes=32 time<1ms TTL=128
     Reply from 10.0.0.22: bytes=32 time<1ms TTL=128

     Ping statistics for 10.0.0.22:
         Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
     Approximate round trip times in milli-seconds:
         Minimum = 0ms, Maximum = 0ms, Average = 0ms

Checked that @@SERVERNAME matches the server name on both servers:

   SELECT @@SERVERNAME, SERVERPROPERTY('MachineName')

   -------------  -------------
   ASITESTSERVER  ASITESTSERVER

and

   SELECT @@SERVERNAME, SERVERPROPERTY('MachineName')

   ----------  ----------
   ASIGROBTEST  ASIGROBTEST

Screamed

Issued SET XACT_ABORT ON before issuing my query:

SET XACT_ABORT ON
GO
BEGIN DISTRIBUTED TRANSACTION
SELECT TOP 1 * FROM Sessions

Granted Everyone Full Control to:

HKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServer

on both servers.


问:
The use of **.join()** in this particular code
The code is from an UVA. It goes like:

Consider a list (list = []). You can perform the following commands:

```<code> insert, print, remove, append, sort, pop, reverse.
</code>```

Initialize your list and read in the value of  followed by  lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.

Inputs:
The first line contains an integer, denoting the number of commands.
Each line  of the  subsequent lines contains one of the following commands.

Sample Input

```<code>12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
</code>```

Sample Output

```<code>[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
</code>```

A neat solution I found is:

```<code>n = input()
l = []
for _ in range(n):
    s = raw_input().split()
    cmd = s[0]
    args = s[1:]
    if cmd !="print":
        cmd += " ("+ ",".join(args) +") "
        eval("l."+cmd)
    else:
        print l
</code>```

I don't really understand how the part  " ("+ ",".join(args) +") " works. Especially why the + in the beginning and at the end. An explanation would be great. Thanks.

答:
.split will divide your your string into an array.  Each space will create a new element, so if you have "I like food", it will become ["I","like","food"].  Now we can look at our .join. The .join is doing the reverse.  So if we were to call ','.join(["I","like","food"]), we'd get "I,like,food". In your function, we are using .join to combine a series of list elements into a series of string arguments, then we invoke eval and it executes.

And, eval is not recommended.  So, instead, we can write a chain for if and elif statements:

```<code>inpu = """12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print"""

li = []

for line in inpu.split("\n"):
    args = line.split()
    if args[0] == "insert":
        li.insert(int(args[1]),int(args[2]))
    elif args[0] == "print":
        print(li)
    elif args[0] == "remove":
        li.remove(int(args[1]))
    elif args[0] == "sort":
        li.sort()
    elif args[0] == "reverse":
        li = li[::-1]
    elif args[0] == "append":
        li.append(int(args[1]))
    elif args[0] == "pop":
        li.pop()
</code>```

Body:
The code is from an UVA. It goes like:

Consider a list (list = []). You can perform the following commands:

 insert, print, remove, append, sort, pop, reverse.

Initialize your list and read in the value of  followed by  lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.

Inputs:
The first line contains an integer, denoting the number of commands.
Each line  of the  subsequent lines contains one of the following commands.

Sample Input

12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print

Sample Output

[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]

A neat solution I found is:

n = input()
l = []
for _ in range(n):
    s = raw_input().split()
    cmd = s[0]
    args = s[1:]
    if cmd !="print":
        cmd += " ("+ ",".join(args) +") "
        eval("l."+cmd)
    else:
        print l

I don't really understand how the part  " ("+ ",".join(args) +") " works. Especially why the + in the beginning and at the end. An explanation would be great. Thanks.

Body:
.split will divide your your string into an array.  Each space will create a new element, so if you have "I like food", it will become ["I","like","food"].  Now we can look at our .join. The .join is doing the reverse.  So if we were to call ','.join(["I","like","food"]), we'd get "I,like,food". In your function, we are using .join to combine a series of list elements into a series of string arguments, then we invoke eval and it executes.

And, eval is not recommended.  So, instead, we can write a chain for if and elif statements:

inpu = """12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print"""

li = []

for line in inpu.split("\n"):
    args = line.split()
    if args[0] == "insert":
        li.insert(int(args[1]),int(args[2]))
    elif args[0] == "print":
        print(li)
    elif args[0] == "remove":
        li.remove(int(args[1]))
    elif args[0] == "sort":
        li.sort()
    elif args[0] == "reverse":
        li = li[::-1]
    elif args[0] == "append":
        li.append(int(args[1]))
    elif args[0] == "pop":
        li.pop()