问:
Finding duplicate usernames in the database using Firebase Cloud Functions
I’m trying to find duplicate usernames in the database when a new user registers before a user is authenticated using Firebase Cloud Functions as I was suggested, as the .queryEqual(toValue) locally won’t work every time. What I can’t get my head around now is how to make use of it in my app. Here’s the cloud function I deployed:

```<code>// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.uniqueUsername = functions.https.onRequest((req, res) => {
    const username = req.query.username
    admin.database().ref('users').orderByChild('username').equalTo(username).once('value').then(snap => {
        // if the child exists, then the username is taken
        if (snap.exists()) {
            res.send('username not available');
        } else {
            res.send('username available');
        }
    });
});
</code>```

The equalTo(username) is a value picked from UITextField and then compared to in the database. The error I get here is:

```<code>Error: Query.equalTo failed: First argument contains undefined in property 'users'
    at Error (native)
    at Ae (/user_code/node_modules/firebase-admin/lib/database/database.js:105:67)
    at ze (/user_code/node_modules/firebase-admin/lib/database/database.js:104:400)
    at W.h.Jf (/user_code/node_modules/firebase-admin/lib/database/database.js:142:60)
    at exports.uniqueUsername.functions.https.onRequest (/user_code/index.js:10:60)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:26:47)
    at /var/tmp/worker/worker.js:649:7
    at /var/tmp/worker/worker.js:633:9
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)
</code>```

And the error I get when I use the URL in the browser is:

```<code>Error: could not handle the request
</code>```

What am I doing wrong? And what should I do next?

答:
From that error message, you are passing a value of undefined into the equalTo function.

Before performing the query (and for any query) you want to use a "fail-fast" methodology. In this case, if req.query.username is falsy, return an error.

```<code>exports.uniqueUsername = functions.https.onRequest((req, res) => {
  const username = req.query.username;
  if (!username) {
    res.status(400).json({error: 'Missing username GET parameter'});
    return;
  }
  // rest of your code.
}
</code>```

A Better Approach

For any key that requires uniqueness, you want to use an index. In your database, it would look similar to:

```<code>"/usernames": {
  "bob": "userId1",
  "frank": "userId2",
  "c00lguy": "userId3"
}
</code>```

In order to check if a username is free, I would recommend getting a user logged in and authenticated first. This makes sure that we have a User ID to associate with the username. Once they log in, check if they haven't set a username yet and if they don't, prompt them for one using some form of dialog/input.

To check the availability of a username and claim it in a 'single' operation, you can call the following code: (internally it's not a single operation)

```<code>var desiredUsername = '...'; // from the form.
var userId = '...'; // the current logged in user's ID (normally from user.uid)
var ref = firebase.database().ref('/usernames').child(desiredUsername);
ref.transaction(function (currentData) {
  if (currentData !== null && currentData !== userId) {
    return; // returns undefined. Which aborts the operation because there is data here. (someone owns that username other than the current user).
  }
  // if here, username is available or owned by this user.
  return userId; // returning a value will write it to the database at the given location.
})
.then(function(transactionResult) {
  if (transactionResult.committed) {
    // username is now owned by current user
    // do something
  } else {
    // username already taken.
    // do something
  }
})
.catch(function (error) {
  // if here, an error has occured
  // (probably a permissions error, check database rules)
  // do something
});
</code>```

This snippet makes use of a Transaction operation which allows you to read a value from the database and then act on it instantly. In your original code, between the time you call the uniqueUsername function and claim that username, someone else could do so. Using a transaction minimises the window of opportunity to do this by claiming the username for the user as soon as it knows it's free.

This method is faster than searching over the database, and allows you to lookup users by username using a simple query.

The below code is an example of such a query and will return null for unclaimed usernames.

```<code>function findUserIdByUsername(username) {
  if (!username) {
    return Promise.reject('username is falsy');
  }
  firebase.database().ref('/usernames').child(username).once('value')
  .then(snapshot => {
    if (!snapshot.exists()) {
      return null; // no user with that username
    }
    return snapshot.val(); // the owner's user ID
  });
}
</code>```

Combined with your original code, it would look like this:

```<code>exports.uniqueUsername = functions.https.onRequest((req, res) => {
  const username = req.query.username;
  if (!username) {
    res.status(400).json({error: 'Missing username GET parameter'});
    return;
  }
  var ownerID = findUserIdByUsername(username);
  res.json({taken: (ownerID !== null)}); // Returns {"taken": "true"} or {"taken": "false"}
}
</code>```

Body:
I’m trying to find duplicate usernames in the database when a new user registers before a user is authenticated using Firebase Cloud Functions as I was suggested, as the .queryEqual(toValue) locally won’t work every time. What I can’t get my head around now is how to make use of it in my app. Here’s the cloud function I deployed:

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.uniqueUsername = functions.https.onRequest((req, res) => {
    const username = req.query.username
    admin.database().ref('users').orderByChild('username').equalTo(username).once('value').then(snap => {
        // if the child exists, then the username is taken
        if (snap.exists()) {
            res.send('username not available');
        } else {
            res.send('username available');
        }
    });
});

The equalTo(username) is a value picked from UITextField and then compared to in the database. The error I get here is:

Error: Query.equalTo failed: First argument contains undefined in property 'users'
    at Error (native)
    at Ae (/user_code/node_modules/firebase-admin/lib/database/database.js:105:67)
    at ze (/user_code/node_modules/firebase-admin/lib/database/database.js:104:400)
    at W.h.Jf (/user_code/node_modules/firebase-admin/lib/database/database.js:142:60)
    at exports.uniqueUsername.functions.https.onRequest (/user_code/index.js:10:60)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:26:47)
    at /var/tmp/worker/worker.js:649:7
    at /var/tmp/worker/worker.js:633:9
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)

And the error I get when I use the URL in the browser is:

Error: could not handle the request

What am I doing wrong? And what should I do next?

Body:
From that error message, you are passing a value of undefined into the equalTo function.

Before performing the query (and for any query) you want to use a "fail-fast" methodology. In this case, if req.query.username is falsy, return an error.

exports.uniqueUsername = functions.https.onRequest((req, res) => {
  const username = req.query.username;
  if (!username) {
    res.status(400).json({error: 'Missing username GET parameter'});
    return;
  }
  // rest of your code.
}

A Better Approach

For any key that requires uniqueness, you want to use an index. In your database, it would look similar to:

"/usernames": {
  "bob": "userId1",
  "frank": "userId2",
  "c00lguy": "userId3"
}

In order to check if a username is free, I would recommend getting a user logged in and authenticated first. This makes sure that we have a User ID to associate with the username. Once they log in, check if they haven't set a username yet and if they don't, prompt them for one using some form of dialog/input.

To check the availability of a username and claim it in a 'single' operation, you can call the following code: (internally it's not a single operation)

var desiredUsername = '...'; // from the form.
var userId = '...'; // the current logged in user's ID (normally from user.uid)
var ref = firebase.database().ref('/usernames').child(desiredUsername);
ref.transaction(function (currentData) {
  if (currentData !== null && currentData !== userId) {
    return; // returns undefined. Which aborts the operation because there is data here. (someone owns that username other than the current user).
  }
  // if here, username is available or owned by this user.
  return userId; // returning a value will write it to the database at the given location.
})
.then(function(transactionResult) {
  if (transactionResult.committed) {
    // username is now owned by current user
    // do something
  } else {
    // username already taken.
    // do something
  }
})
.catch(function (error) {
  // if here, an error has occured
  // (probably a permissions error, check database rules)
  // do something
});

This snippet makes use of a Transaction operation which allows you to read a value from the database and then act on it instantly. In your original code, between the time you call the uniqueUsername function and claim that username, someone else could do so. Using a transaction minimises the window of opportunity to do this by claiming the username for the user as soon as it knows it's free.

This method is faster than searching over the database, and allows you to lookup users by username using a simple query.

The below code is an example of such a query and will return null for unclaimed usernames.

function findUserIdByUsername(username) {
  if (!username) {
    return Promise.reject('username is falsy');
  }
  firebase.database().ref('/usernames').child(username).once('value')
  .then(snapshot => {
    if (!snapshot.exists()) {
      return null; // no user with that username
    }
    return snapshot.val(); // the owner's user ID
  });
}

Combined with your original code, it would look like this:

exports.uniqueUsername = functions.https.onRequest((req, res) => {
  const username = req.query.username;
  if (!username) {
    res.status(400).json({error: 'Missing username GET parameter'});
    return;
  }
  var ownerID = findUserIdByUsername(username);
  res.json({taken: (ownerID !== null)}); // Returns {"taken": "true"} or {"taken": "false"}
}


来源: stackexchange

问:
how to convert .HTML file to .DOC file...?
i am working in JSF Application and in this application using some code i have create a HTML file that is store in my server and now i want to convert that HTML file in to .DOC file ..... so please help me </p>

答:
A solution is i have Download a </p>

```<code>officetools.OfficeFile;
</code>```

<p>this jar file and after write some code that can easy get from the net... </p>

ContentLicense: CC BY-SA 2.5

Body:
A solution is i have Download a

officetools.OfficeFile;

this jar file and after write some code that can easy get from the net...


问:
Unable to build firebase gradle in Android studio
I am adding Firebase database gradle into my Android Project, but gradle is unable to build.I added Firebase gradle in my app gradle and one google gradle in Project gradle  I am getting this message:

this is my app gradle

```<code> apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "iamrajendra.github.io"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-database:11.0.2'

}
</code>```

and this is my project gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
         classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
You can try this dependencies,

// FirebaseUI Database only
 compile 'com.firebaseui:firebase-ui-database:2.0.1'

// Single target that includes all FirebaseUI libraries above
 compile 'com.firebaseui:firebase-ui:2.0.1'

ContentLicense: CC BY-SA 3.0

Body:
I am adding Firebase database gradle into my Android Project, but gradle is unable to build.I added Firebase gradle in my app gradle and one google gradle in Project gradle  I am getting this message:

this is my app gradle

 apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "iamrajendra.github.io"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-database:11.0.2'

}

and this is my project gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
         classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


问:
Collapse all sections in accordion on page load in jQuery Accordion
I am using JQuery Accordion, I want to hide all the sections on page load. Only when user clicks on header that section should open.</p>

答:
By url parameters you can expand specific tab or collapse all,
for collapsing all use:

```<code> $("#accordion").accordion('option', 'active' , 'null');
</code>```

for expanding specific use:

```<code>$("#accordion").accordion('option', 'active' , <?php if($_GET['tab']!='')echo $_GET['tab'];else echo 'null'; ?>);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
By url parameters you can expand specific tab or collapse all,
for collapsing all use:

 $("#accordion").accordion('option', 'active' , 'null');

for expanding specific use:

$("#accordion").accordion('option', 'active' , <?php if($_GET['tab']!='')echo $_GET['tab'];else echo 'null'; ?>);


问:
Callee RC: NS_ERROR_FACTORY_NOT_REGISTERED 0x80040154
I have been running VirtualBox for a few months now and I recently updated El Capitan. After do so, the VirtualBox would no longer start. The error message that displayed was:

"Callee RC: NS_ERROR_FACTORY_NOT_REGISTERED 0x80040154". Does anyone have a solution to this problem?

Thank you.

答:
Virtual Box was not loading the VM, and I kept getting this error:

06/08/2017  MacBook Pro 2017 Sierra issue loading the vm virtual
  machine

Result Code:  NS_ERROR_FAILURE (0x80004005) Component:  MachineWrap
  Interface:  IMachine {b2547866-a0a1-4391-8b86-6952d82efaa0}

Failed to create the VirtualBox COM object.Callee RC:
  NS_ERROR_FACTORY_NOT_REGISTERED (0x80040154)

After poking around I found a solution:

open virtual box and right click on the virtual machine thats not working and select remove then select remove only! (stack overflow will not allow me to post more than 2 links or pictures so this picture is not available wtf?)

after removing the VM, navigate to machine and select add.
Screen shot of step

now a window should have popped up, navigate to the VM's you want and select open and everything should work as normal.
enter image description here


问:
Could i use react-virtualized for rendering and modifying large tabular data?
I would like to build a service that can manage large dataset by grid view. It's similar to Excel or Google's Spreadsheet. The service can render and modify directly on the grid view.

I would like to use react or some latest technology to develop the front-end. I found a react component named react-virtualized.

I still wonder that can it implement modification functionality on it.

Could you explain me more about how it work or under the hood ? Actually i need some idea to propose the solution like this.

答:
Could i use react-virtualized for rendering and modifying large tabular data?

Yes.

Sounds like you're looking to build something like this. It is built with react-virtualized and the source code for it can be found here.

Could you explain me more about how it work or under the hood ? Actually i need some idea to propose the solution like this.

This question is a bit too vague for Stack Overflow I think. You might find this talk informative since it kind of covers the basics of react-virtualized. After that I would suggest browsing the documentation.

Once you have a foundation then more specific questions could be directed here or to the react-virtualized Slack channel.


问:
How can a memory address (pointer variables) be initialized using constructor?
Notes: 1) Person is the base class of Student
         2) Person contains  name as the only data variable
         3) Student contains  society . The society acts as a pointer to a text string which contains the name of the student's club.

I have difficulty in understanding the fourth line:

```<code>int main (){
Person* p1;
p1=new Student("John", "Drama Society");   //This line
delete p1;
}
</code>```

Isn't p1 a Person pointer pointing to a memory address in the heap? As far as I know, pointer variable is just a 32-bit or 64-bit(system-dependent) location in memory.
How can it be initialized just like objects of type Person?

I know my concept is wrong, please help me find them out :(

答:
What is happening is that the call to new allocates a Student object on the heap and then returns a pointer to it.  Then you assign that pointer to p1.  So p1 now points to a Student object on the heap.

The constructor call after new is just how C++ syntax for new works.  That constructor will be used to initialize the object on the heap.

Body:
Notes: 1) Person is the base class of Student
         2) Person contains  name as the only data variable
         3) Student contains  society . The society acts as a pointer to a text string which contains the name of the student's club.

I have difficulty in understanding the fourth line:

int main (){
Person* p1;
p1=new Student("John", "Drama Society");   //This line
delete p1;
}

Isn't p1 a Person pointer pointing to a memory address in the heap? As far as I know, pointer variable is just a 32-bit or 64-bit(system-dependent) location in memory.
How can it be initialized just like objects of type Person?

I know my concept is wrong, please help me find them out :(


问:
NodeJS: load html with res.write()
I'm new to Node so I'm trying to learn it. I'm trying to load a simple HTML file in Node but that gives me an error as HTML is not defined when I use res.write(html) I saw some examples where are similar to me so I would like to understand what is wrong here.
I wrote this:

```<code>const http = require('http');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000;

fs.readFile('./index.html', (err, html) => {
    if(err){
        throw err;
    }
});

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-type', 'text/html');
    res.write(html);
    res.end();
});

server.listen(port, hostname, () => {
    console.log('Server started on port ' + port);
});
</code>```

答:
Your problems is that html variable is not set in the scope that you are trying to use it.

Almost everything in javascript is async, and you need to handle and build your logic so that values that is returned from an async call can be used elsewhere in the program.

In your case the readFile is an async call that reads and returns the file -- unfortunately for you the callback where you receive the html has it's own scope, and is not available after you have completed the execution of that callback.

The canonical mandatory readthough of how to do that is found here: How do I return the response from an asynchronous call?

There are many good solutions on this problem, for example using structures of closure or promises as well as other solutions.

A direct solution is to combine the and make use of the callback structure -- like in your example to make the user of html variable happen within the scope of the callback from the readFile, like

```<code>const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-type', 'text/html');
    fs.readFile('./index.html', (err, html) => {
        if(err)
           res.write("Error");
        else
           res.write(html);
        res.end();
    });
});
</code>```

Title: NodeJS: load html with res.write()

Body:
I'm new to Node so I'm trying to learn it. I'm trying to load a simple HTML file in Node but that gives me an error as HTML is not defined when I use res.write(html) I saw some examples where are similar to me so I would like to understand what is wrong here.
I wrote this:

const http = require('http');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000;

fs.readFile('./index.html', (err, html) => {
    if(err){
        throw err;
    }
});

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-type', 'text/html');
    res.write(html);
    res.end();
});

server.listen(port, hostname, () => {
    console.log('Server started on port ' + port);
});

Body:
Your problems is that html variable is not set in the scope that you are trying to use it.

Almost everything in javascript is async, and you need to handle and build your logic so that values that is returned from an async call can be used elsewhere in the program.

In your case the readFile is an async call that reads and returns the file -- unfortunately for you the callback where you receive the html has it's own scope, and is not available after you have completed the execution of that callback.

The canonical mandatory readthough of how to do that is found here: How do I return the response from an asynchronous call?

There are many good solutions on this problem, for example using structures of closure or promises as well as other solutions.

A direct solution is to combine the and make use of the callback structure -- like in your example to make the user of html variable happen within the scope of the callback from the readFile, like

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-type', 'text/html');
    fs.readFile('./index.html', (err, html) => {
        if(err)
           res.write("Error");
        else
           res.write(html);
        res.end();
    });
});


问:
Registration-Free COM for standalone VB.NET application - complex case
I need your help.

I read whole internet about Registration-Free COM/DLLs but my problem is more complex.

I'm preparing an application in VB.NET which will be used in an environment in which users don't have admin rights, so I can't simpy install it or register COM. This COM is a LogParser library designed by microsoft.
DLL also doesn't have to be embeded - would be nice, but it may be also extracted from exe during startup - i'm ok with this approach

Generally in a main form i've got a button which invokes another form by:
 LogParser_Form.Show()

This another Form 'Imports MSUtil', which is a Interop.MSUtil.dll and which is embeeded to exe by Fody Costura add-on.
Form contains also a class which has multiple declarations of variables defined in COM, eg:
Dim IISW3CLOG As New COMIISW3CInputContextClass
(there is more than one)

But this dll refers somewhere to bigger: LogParser.dll which is acutally a COM component which requires registration, so my LogParser_Form doesn't appear when button is clicked, but it throws an exception that COM component is not found...
Unfortunately Fody Costura or Ilmerge don't work for the COM...

I tried multiple tricks wich manifest files, etc, but no luck...

You are my last hope - please help me... How to embed this COM to exe without registering it?
I suppose that properly used manifest files may help, but I didn't find a way to successfully use it ...

答:
Getting Registration-Free COM to work can be tricky, but works when configured properly. The key issue is creating manifests, which document all required dependencies. In your case, you'll need two manifests:

Client manifest for your application

Server manifest for the LogParser library. This part requires a tool for analyzing type libraries, such as the OLE/COM Object Viewer (oleview.exe). It allows looking into the embedded type library inside LogParser.dll.

Let's take the (slightly modified) C# example, which is documented in the LogParser help file. The client is named "logqryclient.exe" in this case, and the Runtime Callable Wrapper has been created via the type library importer (tlbimp).

```<code>using System;
using Interop.MSUtil;

namespace logqryclient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Instantiate the LogQuery object
                ILogQuery oLogQuery = new LogQueryClassClass();

                // Create the query
                string query = @"SELECT TOP 50 SourceName, EventID, Message FROM System";

                // Execute the query
                ILogRecordset oRecordSet = oLogQuery.Execute(query, null);

                // Browse the recordset
                for (; !oRecordSet.atEnd(); oRecordSet.moveNext())
                {
                    ILogRecord rec = oRecordSet.getRecord();
                    Console.WriteLine(rec.toNativeString(","));
                }

                // Close the recordset
                oRecordSet.close();
            }
            catch (System.Runtime.InteropServices.COMException exc)
            {
                Console.WriteLine("Unexpected error: " + exc.Message);
            }
        }
    }
}
</code>```

To use this code without registering the COM classes, you'll first need to place the LogParser.dll into the same directory as the client executable.

Next, you'll need to create an accompanying server manifest (named "LogParser.manifest" here). This documents all necessary classes and marshalling information for the interfaces (required for thread switching). As mentioned earlier, you'll need a type library analyzer to gain access to the class and interface identifiers.

In the above case, you'll need identifiers for:

ILogQuery interface & LogQueryClass class

ILogRecordset interface

ILogRecord interface

Hence, the server manifest could look as follows:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <assemblyIdentity type="win32" name="LogParser" version="1.0.0.0" />
    <file name = "LogParser.dll">
        <!-- LogQueryClass -->
        <comClass
            clsid="{8CFEBA94-3FC2-45CA-B9A5-9EDACF704F66}"
            threadingModel = "Apartment" />
        <!-- Embedded type library -->
        <typelib
            tlbid="{A7E75D86-41CD-4B6E-B4BD-CC2ED34B3FB0}"
            version="1.0"
            helpdir=""/>
    </file>
    <!-- Marshalling information for interfaces -->
    <comInterfaceExternalProxyStub
        name="ILogQuery"
        iid="{3BDE06BC-89E4-42FD-BE64-832A5F33D7D3}"
        proxyStubClsid32="{00020424-0000-0000-C000-000000000046}"
        baseInterface="{00000000-0000-0000-C000-000000000046}"
        tlbid = "{A7E75D86-41CD-4B6E-B4BD-CC2ED34B3FB0}" />
    <comInterfaceExternalProxyStub
        name="ILogRecordset"
        iid="{C9452B1B-093C-4842-ABD1-F81410926874}"
        proxyStubClsid32="{00020424-0000-0000-C000-000000000046}"
        baseInterface="{00000000-0000-0000-C000-000000000046}"
        tlbid = "{A7E75D86-41CD-4B6E-B4BD-CC2ED34B3FB0}" />
    <comInterfaceExternalProxyStub
        name="ILogRecord"
        iid="{185FFF88-E24A-4984-9621-AA41BEAE8513}"
        proxyStubClsid32="{00020424-0000-0000-c000-000000000046}"
        baseInterface="{00000000-0000-0000-c000-000000000046}"
        tlbid = "{A7E75D86-41CD-4B6E-B4BD-CC2ED34B3FB0}" />
</assembly>
</code>```

To allow the client to find the server manifest and ultimately the LogParser library, embed the following client manifest into the "logqryclient.exe" client:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <assemblyIdentity
        type = "win32"
        name = "logqryclient"
        version = "1.0.0.0" />
    <dependency>
        <dependentAssembly>
            <assemblyIdentity
                type="win32"
                name="LogParser"
                version="1.0.0.0" />
        </dependentAssembly>
    </dependency>
</assembly>
</code>```

Now, all required information is located in the manifests, so that you can run the code in registration-free configuration.

Body:
Getting Registration-Free COM to work can be tricky, but works when configured properly. The key issue is creating manifests, which document all required dependencies. In your case, you'll need two manifests:

Client manifest for your application

Server manifest for the LogParser library. This part requires a tool for analyzing type libraries, such as the OLE/COM Object Viewer (oleview.exe). It allows looking into the embedded type library inside LogParser.dll.

Let's take the (slightly modified) C# example, which is documented in the LogParser help file. The client is named "logqryclient.exe" in this case, and the Runtime Callable Wrapper has been created via the type library importer (tlbimp).

using System;
using Interop.MSUtil;

namespace logqryclient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Instantiate the LogQuery object
                ILogQuery oLogQuery = new LogQueryClassClass();

                // Create the query
                string query = @"SELECT TOP 50 SourceName, EventID, Message FROM System";

                // Execute the query
                ILogRecordset oRecordSet = oLogQuery.Execute(query, null);

                // Browse the recordset
                for (; !oRecordSet.atEnd(); oRecordSet.moveNext())
                {
                    ILogRecord rec = oRecordSet.getRecord();
                    Console.WriteLine(rec.toNativeString(","));
                }

                // Close the recordset
                oRecordSet.close();
            }
            catch (System.Runtime.InteropServices.COMException exc)
            {
                Console.WriteLine("Unexpected error: " + exc.Message);
            }
        }
    }
}

To use this code without registering the COM classes, you'll first need to place the LogParser.dll into the same directory as the client executable.

Next, you'll need to create an accompanying server manifest (named "LogParser.manifest" here). This documents all necessary classes and marshalling information for the interfaces (required for thread switching). As mentioned earlier, you'll need a type library analyzer to gain access to the class and interface identifiers.

In the above case, you'll need identifiers for:

ILogQuery interface & LogQueryClass class

ILogRecordset interface

ILogRecord interface

Hence, the server manifest could look as follows:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <assemblyIdentity type="win32" name="LogParser" version="1.0.0.0" />
    <file name = "LogParser.dll">
        <!-- LogQueryClass -->
        <comClass
            clsid="{8CFEBA94-3FC2-45CA-B9A5-9EDACF704F66}"
            threadingModel = "Apartment" />
        <!-- Embedded type library -->
        <typelib
            tlbid="{A7E75D86-41CD-4B6E-B4BD-CC2ED34B3FB0}"
            version="1.0"
            helpdir=""/>
    </file>
    <!-- Marshalling information for interfaces -->
    <comInterfaceExternalProxyStub
        name="ILogQuery"
        iid="{3BDE06BC-89E4-42FD-BE64-832A5F33D7D3}"
        proxyStubClsid32="{00020424-0000-0000-C000-000000000046}"
        baseInterface="{00000000-0000-0000-C000-000000000046}"
        tlbid = "{A7E75D86-41CD-4B6E-B4BD-CC2ED34B3FB0}" />
    <comInterfaceExternalProxyStub
        name="ILogRecordset"
        iid="{C9452B1B-093C-4842-ABD1-F81410926874}"
        proxyStubClsid32="{00020424-0000-0000-C000-000000000046}"
        baseInterface="{00000000-0000-0000-C000-000000000046}"
        tlbid = "{A7E75D86-41CD-4B6E-B4BD-CC2ED34B3FB0}" />
    <comInterfaceExternalProxyStub
        name="ILogRecord"
        iid="{185FFF88-E24A-4984-9621-AA41BEAE8513}"
        proxyStubClsid32="{00020424-0000-0000-c000-000000000046}"
        baseInterface="{00000000-0000-0000-c000-000000000046}"
        tlbid = "{A7E75D86-41CD-4B6E-B4BD-CC2ED34B3FB0}" />
</assembly>

To allow the client to find the server manifest and ultimately the LogParser library, embed the following client manifest into the "logqryclient.exe" client:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <assemblyIdentity
        type = "win32"
        name = "logqryclient"
        version = "1.0.0.0" />
    <dependency>
        <dependentAssembly>
            <assemblyIdentity
                type="win32"
                name="LogParser"
                version="1.0.0.0" />
        </dependentAssembly>
    </dependency>
</assembly>

Now, all required information is located in the manifests, so that you can run the code in registration-free configuration.


问:
my bundle.js doesn't seem to be created
I am building a simple app with the use of webpack to combine all my modules. My webpack seem to be running (although, I have battled its not-working).
Now it looks like a bundle.js necessary to see my app cannot be found. I get this error:

the error

So here are my files that might cause the issue

the config.webpack.js file

my packageJSON

```<code>{
 "name": "quiz",
 "version": "1.0.0",
 "description": "",
 "main": "app.js",
 "scripts": {
   "test": "mocha specs"
 },
 "author": "",
 "license": "ISC",
 "devDependencies": {
   "mocha": "^3.4.2",
   "webpack": "1.12.15"
 }
}
</code>```

and the html file that looks for the bundle.js file

```<code><!DOCTYPE html>
<html>
<head>
    <title>Quiz game</title>
</head>
<body>
    <script src = "build.js "></script>
    <div>
    Quiz game
    </div>
</body>
</html>
</code>```

Any ideas on what might be wrong?

答: Your problem is that the build.js file cannot be found because the path to the file in the index.html is wrong, it should be should be  in your index.html not

Title: my bundle.js doesn't seem to be created

Body:
I am building a simple app with the use of webpack to combine all my modules. My webpack seem to be running (although, I have battled its not-working).
Now it looks like a bundle.js necessary to see my app cannot be found. I get this error:

the error

So here are my files that might cause the issue

the config.webpack.js file

my packageJSON

{
 "name": "quiz",
 "version": "1.0.0",
 "description": "",
 "main": "app.js",
 "scripts": {
   "test": "mocha specs"
 },
 "author": "",
 "license": "ISC",
 "devDependencies": {
   "mocha": "^3.4.2",
   "webpack": "1.12.15"
 }
}

and the html file that looks for the bundle.js file

<!DOCTYPE html>

    <title>Quiz game</title>

    Quiz game

Any ideas on what might be wrong?

Body: Your problem is that the build.js file cannot be found because the path to the file in the index.html is wrong, it should be should be <script src = "/build.js "></script> in your index.html not <script src = "build.js "></script>


问:
send message from android telegram source to to specific user id
I want to know, how can i send a message (for ex: text) from owner client to some body's id with coding(dynamically)in android telegram source?
what is that method?and objects?
if i want explain more i mean send message (to specific user id )from one of telegram source classes.
here is telegram source GitHub take look on it(the bad point is, it haven't any comment)

these classes may help to find it, but i cant figure it out

```<code>MessageObject.java
TLRPC.Message.java
ChatAttachAlert.java
SendMessagesHelper.java
ChatActivity.java
</code>```

thanks.

答:
you should use something like this method: SendMessagesHelper.getInstance().sendMessage(). note that it's a network call and you should call it in a thread other than ui thread.

simplest way to send a message is like calling:

```<code>   SendMessagesHelper.getInstance().sendMessage("Hi there", to_user_id, null, null, false, null, null, null);
</code>```

There are different types of messages and different ways to use this function. if you want to find out how to send other types of messages, search the java codes directory for "sendmessageshelper" and find how the sendMessage function is used in them.

Body:
I want to know, how can i send a message (for ex: text) from owner client to some body's id with coding(dynamically)in android telegram source?
what is that method?and objects?
if i want explain more i mean send message (to specific user id )from one of telegram source classes.
here is telegram source GitHub take look on it(the bad point is, it haven't any comment)

these classes may help to find it, but i cant figure it out

MessageObject.java
TLRPC.Message.java
ChatAttachAlert.java
SendMessagesHelper.java
ChatActivity.java

thanks.

Body:
you should use something like this method: SendMessagesHelper.getInstance().sendMessage(). note that it's a network call and you should call it in a thread other than ui thread.

simplest way to send a message is like calling:

   SendMessagesHelper.getInstance().sendMessage("Hi there", to_user_id, null, null, false, null, null, null);

There are different types of messages and different ways to use this function. if you want to find out how to send other types of messages, search the java codes directory for "sendmessageshelper" and find how the sendMessage function is used in them.


问:
How to use FontAwesome on fxml JavaFX without Maven
I'm using fontawesomefx-8.9 because I couldn't find a tutorial for adding a newer version to the project(I don't even know how to download it from Bintray).
The problem is when I add an icon it shows up like an empty rectangle. I've added the library to both SceneBuilder and the project library. I've tried changing the IDE but it's the same.

Here is the project, I'm still learning Java btw.

答:
Maven uses The Central Repository to download dependency automatically for you from there. I would recommend you to embrace maven or another dependency management tool for java. It will makes you life way easier.

But if you can't use dependency management. For some reason unknown to me. You still can download jars manually from the central repository. In your case choose any published version of fontawesomefx, download the jar(s) and add them to your project's classpath.


问:
reading textfile from url and populate in Gridview Asp.net
I have codded for reading and textfile from url and populate in Gridview. The problem is the textfile has in first row splited by one space but in 2nd and 3rd row has many rows. How to populate in gridview below in my textfile and and C# code Txt file has data like this strong text

*

strong text

*
Misdate ServiceName ProductName SubsCount   SubsRevenue RenewalCount    RenewalRevenue  TotalRev

20170310    PayPerUse   PayPerUse_ATN_News_VideoAlert   546 1110.81 0   0   1110.81
20170311    PayPerUse   PayPerUse_ATN_News_VideoAlert   549 1063.23 0   0   1063.23

And the C# code to read and populate is

```<code>Stream data = client.OpenRead("my URL text File ");
            DataTable table = new DataTable();
            table.Columns.Add("Misdate."); //Misdate ServiceName ProductName SubsCount   SubsRevenue RenewalCount    RenewalRevenue TotalRev
            table.Columns.Add("ServiceName.");
            table.Columns.Add("ProductName");
            table.Columns.Add("SubsCount");
            table.Columns.Add("SubsRevenue");
            table.Columns.Add("RenewalCount");
            table.Columns.Add("RenewalRevenue");
            table.Columns.Add("TotalRev");
            using (StreamReader reader = new StreamReader(data))

            //using (StreamReader reader = new StreamReader(@"E:\textfile\usss.txt"))
            {
                // string s = reader.ReadToEnd();

                while (!reader.EndOfStream)
                {
                    //  List<string> parts = reader.ReadLine().Split(',').ToList();
                    string[] parts = reader.ReadLine().Split(' ');
                    // Response.Write(parts);
                    // table.Rows.Add(parts.ToString());
                    //string s = parts[0];
                   table.Rows.Add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7]);
                }

            }
            GridView1.DataSource = table;
            GridView1.DataBind();
</code>```

答:
Try something like this:

```<code>var newRow = table.NewRow();
for (int k=0; k<table.Columns.Count(); k++)
   newRow[k] = parts[k];

table.Rows.add(newRow);
</code>```

Hope it will help

Body:
I have codded for reading and textfile from url and populate in Gridview. The problem is the textfile has in first row splited by one space but in 2nd and 3rd row has many rows. How to populate in gridview below in my textfile and and C# code Txt file has data like this strong text

*

strong text

*
Misdate ServiceName ProductName SubsCount   SubsRevenue RenewalCount    RenewalRevenue  TotalRev

20170310    PayPerUse   PayPerUse_ATN_News_VideoAlert   546 1110.81 0   0   1110.81
20170311    PayPerUse   PayPerUse_ATN_News_VideoAlert   549 1063.23 0   0   1063.23

And the C# code to read and populate is

Stream data = client.OpenRead("my URL text File ");
            DataTable table = new DataTable();
            table.Columns.Add("Misdate."); //Misdate ServiceName ProductName SubsCount   SubsRevenue RenewalCount    RenewalRevenue TotalRev
            table.Columns.Add("ServiceName.");
            table.Columns.Add("ProductName");
            table.Columns.Add("SubsCount");
            table.Columns.Add("SubsRevenue");
            table.Columns.Add("RenewalCount");
            table.Columns.Add("RenewalRevenue");
            table.Columns.Add("TotalRev");
            using (StreamReader reader = new StreamReader(data))

            //using (StreamReader reader = new StreamReader(@"E:\textfile\usss.txt"))
            {
                // string s = reader.ReadToEnd();

                while (!reader.EndOfStream)
                {
                    //  List<string> parts = reader.ReadLine().Split(',').ToList();
                    string[] parts = reader.ReadLine().Split(' ');
                    // Response.Write(parts);
                    // table.Rows.Add(parts.ToString());
                    //string s = parts[0];
                   table.Rows.Add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7]);
                }

            }
            GridView1.DataSource = table;
            GridView1.DataBind();

Body:
Try something like this:

var newRow = table.NewRow();
for (int k=0; k<table.Columns.Count(); k++)
   newRow[k] = parts[k];

table.Rows.add(newRow);

Hope it will help


问:
MongoDB DataSource Configuration In JBoss Server
How to configure MongoDB DataSource JNDI in JBoss Server.
I downloaded MongoDB jar (mongo-java-driver-3.4.2.jar) and deployed using admin console, it got successfully deployed but when I went to add Datasource in customize option I am not able to see MongoDB driver, the only one option available was h2. Why so? Do I have to do any other configuration change or am I missing any step?

I Even tried to manually create the MongoDB driver and datasource but that is also not working.
I placed module.xml and mongo-java-driver- 3.4.2.jar to the following path
..\devstudio\runtimes\jboss-eap\modules\system\layers\base\org\mongodb\main

```<code>--------- module.xml ---------------------

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.0" name="org.mongodb">
<resources>
<resource-root path="mongo-java-driver-3.4.2.jar"/>
</resources>
<dependencies>
<module name="javax.api"/>
<module name="javax.transaction.api"/>
</dependencies>
</module>

--------------standalone.xml ------------

<datasource jndi-name="java:jboss/datasources/mongodb" pool-name="mongodb"
enabled="true" use-java-context="true">
  <connection-url>jdbc:mongodb://127.0.0.1:27017/example;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
   <driver>mongodb</driver>
 </datasource>
<driver name="mongodb" module="org.mongodb">
   <xa-datasource-class>mongodb.jdbc.MongoXADataSource</xa-datasource-class>
 </driver>
</code>```

I was getting the following error when i started the server

```<code>("subsystem" => "datasources"),
("data-source" => "mongodb")
]) - failure description: {"WFLYCTL0180: Services with missing/unavailable
dependencies" => [
"org.wildfly.data-source.mongodb is missing [jboss.jdbc-driver.mongodb]",
"jboss.driver-demander.java:jboss/datasources/mongodb is missing
[jboss.jdbc-driver.mongodb]"
]}
23:51:44,277 ERROR [org.jboss.as.controller.management-operation]
(Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "datasources"),
("data-source" => "mongodb")
]) - failure description: {"WFLYCTL0180: Services with missing/unavailable
dependencies" => [
"org.wildfly.data-source.mongodb is missing [jboss.jdbc-driver.mongodb]",
"jboss.driver-demander.java:jboss/datasources/mongodb is missing
[jboss.jdbc-driver.mongodb]",
"org.wildfly.data-source.mongodb is missing [jboss.jdbc-driver.mongodb]"
]}
</code>```

Could you let me know how to do JNDI Datasource configuration in JBoss Server ?? Please explain in detail as I am new for JNDI Configuration

答: Refer https://www.progress.com/blogs/configure-connect-for-jdbc-mongodb-driver-with-jboss-eap-64enter link description here</p>

Body:
How to configure MongoDB DataSource JNDI in JBoss Server.
I downloaded MongoDB jar (mongo-java-driver-3.4.2.jar) and deployed using admin console, it got successfully deployed but when I went to add Datasource in customize option I am not able to see MongoDB driver, the only one option available was h2. Why so? Do I have to do any other configuration change or am I missing any step?

I Even tried to manually create the MongoDB driver and datasource but that is also not working.
I placed module.xml and mongo-java-driver- 3.4.2.jar to the following path
..\devstudio\runtimes\jboss-eap\modules\system\layers\base\org\mongodb\main

--------- module.xml ---------------------

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.0" name="org.mongodb">
<resources>
<resource-root path="mongo-java-driver-3.4.2.jar"/>
</resources>
<dependencies>
<module name="javax.api"/>
<module name="javax.transaction.api"/>
</dependencies>
</module>

--------------standalone.xml ------------

<datasource jndi-name="java:jboss/datasources/mongodb" pool-name="mongodb"
enabled="true" use-java-context="true">
  <connection-url>jdbc:mongodb://127.0.0.1:27017/example;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
   <driver>mongodb</driver>
 </datasource>
<driver name="mongodb" module="org.mongodb">
   <xa-datasource-class>mongodb.jdbc.MongoXADataSource</xa-datasource-class>
 </driver>

I was getting the following error when i started the server

("subsystem" => "datasources"),
("data-source" => "mongodb")
]) - failure description: {"WFLYCTL0180: Services with missing/unavailable
dependencies" => [
"org.wildfly.data-source.mongodb is missing [jboss.jdbc-driver.mongodb]",
"jboss.driver-demander.java:jboss/datasources/mongodb is missing
[jboss.jdbc-driver.mongodb]"
]}
23:51:44,277 ERROR [org.jboss.as.controller.management-operation]
(Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "datasources"),
("data-source" => "mongodb")
]) - failure description: {"WFLYCTL0180: Services with missing/unavailable
dependencies" => [
"org.wildfly.data-source.mongodb is missing [jboss.jdbc-driver.mongodb]",
"jboss.driver-demander.java:jboss/datasources/mongodb is missing
[jboss.jdbc-driver.mongodb]",
"org.wildfly.data-source.mongodb is missing [jboss.jdbc-driver.mongodb]"
]}

Could you let me know how to do JNDI Datasource configuration in JBoss Server ?? Please explain in detail as I am new for JNDI Configuration


问:
fusioncharts and wkhtmltoimage
I'm trying to export fusionChart Images on the Server Without Rendering in a Browser.. i would like to use the image in tcpdf

i followed the example here
http://www.fusioncharts.com/blog/2013/03/how-to-save-charts-as-images-at-server-side/

```<code>    < ?php
    $webpageURLWithChart = "mychart.php";
    $outputImageFileName = "savedImage.png";
    $delay = 500;
    $shellout = shell_exec("wkhtmltoimage --javascript-delay $delay $webpageURLWithChart $outputImageFileName" );
    echo $shellout;
    ?>
</code>```

mychart.php is working fine but image is not generated

path is set C:\Program Files\wkhtmltopdf

any help is much apreciated

答: Try to keep images and files inside your project folder and give the source names correctly.</p>

Title: fusioncharts and wkhtmltoimage

Body:
I'm trying to export fusionChart Images on the Server Without Rendering in a Browser.. i would like to use the image in tcpdf

i followed the example here
http://www.fusioncharts.com/blog/2013/03/how-to-save-charts-as-images-at-server-side/

    < ?php
    $webpageURLWithChart = "mychart.php";
    $outputImageFileName = "savedImage.png";
    $delay = 500;
    $shellout = shell_exec("wkhtmltoimage --javascript-delay $delay $webpageURLWithChart $outputImageFileName" );
    echo $shellout;
    ?>

mychart.php is working fine but image is not generated

path is set C:\Program Files\wkhtmltopdf

any help is much apreciated


问:
Updating ObservableCollection bound to Pivot crashes for SelectedIndex >= 2 (wp7)
I have an observableCollection bound to a pivot control in my UI. When I try to update the collection (clear() items and recreate) everything works fine unless the selectedIndex of the pivot control is bigger or equal to 2.

In that case I get an ArgumentOutOfRange exception when I try to call Add() to the observable collection. It is very strange.

I tried creating a new observable collection and then Add() items there, this seems to work but I doesn't refresh the UI unless I call my update function twice.

What can be wrong? Is this a bug?

答: As mentioned. The Pivot control is optimised to not load all the panels. If you are trying what I think you're trying, then I would suggest you switch to a Panorama Control which initalises all the PanoramaItems.</p>


问:
how to get a value from function
i have a function that check if the value that the user entered is nil or not (spouse to be double). all the vars are declare inside the function.
now, I'm trying to get the var from the function and use it in my other code (outside the function). i tried to do it with return option but its show me an error.
i look for it in google and as i see there I'm not sure if i can actually do it.
does anyone have an idea how can i solve it?
here is my code:

```<code>func numbers() -> Double  {
print("enter plate heigh")
let num1 = Double(readLine()!)

if checkIfNil(value1: num1){
    print("plaese enter valid heigh")
    numbers()
}
else{
    let x = num1
    print("good! \(num1)")
    return x!
}
return 0.0
}

let platHeigh = numbers()
print("is: \(platHeigh)")
</code>```

tnx!

答:
In this line:

```<code>let num1 = Double(readLine()!)
</code>```

there will be already a crash, if readLine() returns nil. Because you are force unwrapping it using the !.

A better way is to use the if let statement:

```<code>var input: Double? = nil

func numbers() -> Double? {
    if let num1 = input {
        print("good! \(num1)")
        return num1
    } else {
        print("plaese enter valid heigh")
        return nil
    }
}
</code>```

In this function num1 is assigned the value from your field only if it is not nil. Then it is returned.

Otherwise an error message is printed and nil is return. Outside of your function you now know, that nothing was entered.

Title: how to get a value from function

Body:
i have a function that check if the value that the user entered is nil or not (spouse to be double). all the vars are declare inside the function.
now, I'm trying to get the var from the function and use it in my other code (outside the function). i tried to do it with return option but its show me an error.
i look for it in google and as i see there I'm not sure if i can actually do it.
does anyone have an idea how can i solve it?
here is my code:

func numbers() -> Double  {
print("enter plate heigh")
let num1 = Double(readLine()!)

if checkIfNil(value1: num1){
    print("plaese enter valid heigh")
    numbers()
}
else{
    let x = num1
    print("good! \(num1)")
    return x!
}
return 0.0
}

let platHeigh = numbers()
print("is: \(platHeigh)")

tnx!

Body:
In this line:

let num1 = Double(readLine()!)

there will be already a crash, if readLine() returns nil. Because you are force unwrapping it using the !.

A better way is to use the if let statement:

var input: Double? = nil

func numbers() -> Double? {
    if let num1 = input {
        print("good! \(num1)")
        return num1
    } else {
        print("plaese enter valid heigh")
        return nil
    }
}

In this function num1 is assigned the value from your field only if it is not nil. Then it is returned.

Otherwise an error message is printed and nil is return. Outside of your function you now know, that nothing was entered.


问:
Yii2 sending emails in the background
I have a RESTful API which registers a user and later sends an email to that user for account activation.
This works just fine but there is a great delay, since my code has to send the account activation email which sometimes takes time. How can I schedule jobs to run later or in the background for that task?

This is what I am doing currently:

```<code>actionCreateUser(){

   //HERE REGISTRATION

  if($model->save()){  //successifull registration

    //send email here which takes time
    if($emailsent){
      return ["data"=>true];
     }else{
        return ["data"=>false];
     }
   }

}
</code>```

Then in the front-end I am checking the response of the POST request which is data(true or false).

How can I send the email in the background?

答:
as thread implemntation is hard in php I suggest you to:
if you need to imediatly send your mail you can write action to send mail and just call it in your self action and don't wait for result and if user didn't got activation mail you can set an option for him to send it again.

you have to use cron jobs options too.by default yii don't implemented cronjobs
you can use repository like cron-manager or something like this.just save your information in db and you can set every one minute your cron tab to run.

yii also is implementing queue but it's experimental yet.you can see it here : https://github.com/yiisoft/yii2-queue

Title: Yii2 sending emails in the background

Body:
I have a RESTful API which registers a user and later sends an email to that user for account activation.
This works just fine but there is a great delay, since my code has to send the account activation email which sometimes takes time. How can I schedule jobs to run later or in the background for that task?

This is what I am doing currently:

actionCreateUser(){

   //HERE REGISTRATION

  if($model->save()){  //successifull registration

    //send email here which takes time
    if($emailsent){
      return ["data"=>true];
     }else{
        return ["data"=>false];
     }
   }

}

Then in the front-end I am checking the response of the POST request which is data(true or false).

How can I send the email in the background?


问:
Compute midnight timestamp in UTC +0 using DateTime python 3.5
I need to scrap an online database which contain +/- 24h of data at fixed interval using an API query which contain a timestamp. Because i don't know where the server is choose something simple like midnigth UTC.

I found lot of documentation on SO to compute UTC aware of local zone. I'm actually using this protocole to get actual UTC Date :

```<code>import datetime
myDate = datetime.datetime.now(datetime.timezone.utc)
print("TZ INFO = ", myDate.tzinfo) # return UTC+00:00
print("DATE ", myDate) # return 2017-07-08 14:14:24.137003+00:00
print("ISO DATE = ", myDate.timestamp()) # return 1499523264.137003
</code>```

First question, why the timestamp() returned take in account the local timezone : 1499523264.137003 is equal to ~16h15, so UTC +2 corresponding to France Zone. Why timestamp() doesn't return only the UTC + 0 timestamp ? How can i get an UTC + 0 timestamp ?

Second question, i try to generate a midnight date to query the API, so like i saw on many post on SO, i try to use the replace() function :

```<code>myDate = myDate.replace(hour=0, minute=0, second=0,microsecond=0).astimezone(pytz.utc)
print (myDate) # return 2017-07-08 00:00:00+00:00
</code>```

But when i try to print (myDate.timestamp()) return another time a UTC + 2 timestamp, so 2AM of 2017-07-08. How can i get midnight UTC + 0 timestamp easily ?

答:
I would suggest using the pendulum module since it makes timezone and date calculations easy to perform.

pendulum is aware of daylight savings time schemes, as indicated here for London and Paris. It can also provide the UTC time shorn of an adjustment for daylight savings time. When you need to provide an adjustment to UTC you can simply using the replace method in conjunction with UTC.

```<code>>>> import pendulum
>>> pendulum.create(2017,7,9,0,0,0,0,'Europe/London')
<Pendulum [2017-07-09T00:00:00+01:00]>
>>> pendulum.create(2017,7,9,0,0,0,0,'Europe/Paris')
<Pendulum [2017-07-09T00:00:00+02:00]>
>>> pendulum.create(2017,7,9,0,0,0,0,'UTC')
<Pendulum [2017-07-09T00:00:00+00:00]>
>>> t = pendulum.create(2017,7,9,0,0,0,0,'UTC')
>>> t.replace(hour=+2)
<Pendulum [2017-07-09T02:00:00+00:00]>
</code>```

Body:
I need to scrap an online database which contain +/- 24h of data at fixed interval using an API query which contain a timestamp. Because i don't know where the server is choose something simple like midnigth UTC.

I found lot of documentation on SO to compute UTC aware of local zone. I'm actually using this protocole to get actual UTC Date :

import datetime
myDate = datetime.datetime.now(datetime.timezone.utc)
print("TZ INFO = ", myDate.tzinfo) # return UTC+00:00
print("DATE ", myDate) # return 2017-07-08 14:14:24.137003+00:00
print("ISO DATE = ", myDate.timestamp()) # return 1499523264.137003

First question, why the timestamp() returned take in account the local timezone : 1499523264.137003 is equal to ~16h15, so UTC +2 corresponding to France Zone. Why timestamp() doesn't return only the UTC + 0 timestamp ? How can i get an UTC + 0 timestamp ?

Second question, i try to generate a midnight date to query the API, so like i saw on many post on SO, i try to use the replace() function :

myDate = myDate.replace(hour=0, minute=0, second=0,microsecond=0).astimezone(pytz.utc)
print (myDate) # return 2017-07-08 00:00:00+00:00

But when i try to print (myDate.timestamp()) return another time a UTC + 2 timestamp, so 2AM of 2017-07-08. How can i get midnight UTC + 0 timestamp easily ?

Body:
I would suggest using the pendulum module since it makes timezone and date calculations easy to perform.

pendulum is aware of daylight savings time schemes, as indicated here for London and Paris. It can also provide the UTC time shorn of an adjustment for daylight savings time. When you need to provide an adjustment to UTC you can simply using the replace method in conjunction with UTC.

>>> import pendulum
>>> pendulum.create(2017,7,9,0,0,0,0,'Europe/London')
<Pendulum [2017-07-09T00:00:00+01:00]>
>>> pendulum.create(2017,7,9,0,0,0,0,'Europe/Paris')
<Pendulum [2017-07-09T00:00:00+02:00]>
>>> pendulum.create(2017,7,9,0,0,0,0,'UTC')
<Pendulum [2017-07-09T00:00:00+00:00]>
>>> t = pendulum.create(2017,7,9,0,0,0,0,'UTC')
>>> t.replace(hour=+2)
<Pendulum [2017-07-09T02:00:00+00:00]>


问:
How can I make a nil compatible completion handler?
I created a function with a completion handler. Sometimes I need to use the completion block,  sometimes not.

Here is the function:

```<code>func numberCheck(number: String , completion : @escaping (Bool)->()){
     //some task do here
    completion(true)
}
</code>```

use:

```<code>numberCheck(number: "77" , completion: {_ in
    //some task do here
})
</code>```

But I want to leave it completion block nil:

```<code>numberCheck(number: "77" ,  completion: nil)
</code>```

but it is gives me an error:

Nil is not compatible with expected argument type '(Bool) -> ()'

答:
Just make your closure parameter optional like:

```<code>func numberCheck(number: String, completion: @escaping ((Bool)->())?)
</code>```

Also, you can set a default value like:

```<code>func numberCheck(number: String, completion: @escaping ((Bool)->())? = nil)
</code>```

This way you can call without informing nil to the completion parameter, simply:

```<code>numberCheck(number: "123")
</code>```

Body:
I created a function with a completion handler. Sometimes I need to use the completion block,  sometimes not.

Here is the function:

func numberCheck(number: String , completion : @escaping (Bool)->()){
     //some task do here
    completion(true)
}

use:

numberCheck(number: "77" , completion: {_ in
    //some task do here
})

But I want to leave it completion block nil:

numberCheck(number: "77" ,  completion: nil)

but it is gives me an error:

Nil is not compatible with expected argument type '(Bool) -> ()'

Body:
Just make your closure parameter optional like:

func numberCheck(number: String, completion: @escaping ((Bool)->())?)

Also, you can set a default value like:

func numberCheck(number: String, completion: @escaping ((Bool)->())? = nil)

This way you can call without informing nil to the completion parameter, simply:

numberCheck(number: "123")


问:
Help with SQL Stored procedure
I need some help with an SQL stored procedure, I haven't got alot of experience with it.
I have a table "dbo.Lookup_Country". It contains 3 fields: ID, Name, Code.
Now I wrote a stored procedure that retrieves the country name by Code.

```<code>Select Name from Lookup_Country where Code = @Code
</code>```

I need to adjust the stored procedure so that if there are 0 results it has to see if there are results by searching with ID:

Select Name from Lookup_Country where Id = @Code

So basically I need some kind of 'IF' structure:

```<code>if (Select Name from Lookup_Country where Code = @Code) == 0 results
      Select Name from Lookup_Country where Id = @Code
</code>```

Is this possible?

thx

Thx for the help everyone, I used this:

```<code>DECLARE @Name nvarchar(50)

-- Insert statements for procedure here
SET @Name = (SELECT Name from dbo.Lookup_Country WHERE Code = @CODE)
IF @Name != ''
    SELECT Name from dbo.Lookup_Country WHERE Code = @CODE
ELSE
    SELECT Name from dbo.Lookup_Country WHERE ID = @CODE
</code>```

答:
You can probably just use an or:

```<code>Select Name from Lookup_Country where Code = @Code or Id = @Code
</code>```

Title: Help with SQL Stored procedure

Body:
I need some help with an SQL stored procedure, I haven't got alot of experience with it.
I have a table "dbo.Lookup_Country". It contains 3 fields: ID, Name, Code.
Now I wrote a stored procedure that retrieves the country name by Code.

Select Name from Lookup_Country where Code = @Code

I need to adjust the stored procedure so that if there are 0 results it has to see if there are results by searching with ID:

Select Name from Lookup_Country where Id = @Code

So basically I need some kind of 'IF' structure:

if (Select Name from Lookup_Country where Code = @Code) == 0 results
      Select Name from Lookup_Country where Id = @Code

Is this possible?

thx

Thx for the help everyone, I used this:

DECLARE @Name nvarchar(50)

-- Insert statements for procedure here
SET @Name = (SELECT Name from dbo.Lookup_Country WHERE Code = @CODE)
IF @Name != ''
    SELECT Name from dbo.Lookup_Country WHERE Code = @CODE
ELSE
    SELECT Name from dbo.Lookup_Country WHERE ID = @CODE

Body:
You can probably just use an or:

Select Name from Lookup_Country where Code = @Code or Id = @Code


问:
Unable to build firebase gradle in Android studio
I am adding Firebase database gradle into my Android Project, but gradle is unable to build.I added Firebase gradle in my app gradle and one google gradle in Project gradle  I am getting this message:

this is my app gradle

```<code> apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "iamrajendra.github.io"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-database:11.0.2'

}
</code>```

and this is my project gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
         classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
Add this under the last line in your app gradle .. in the bottom of the file</p>

```<code>    apply plugin: 'com.google.gms.google-services'
</code>```

Body:
I am adding Firebase database gradle into my Android Project, but gradle is unable to build.I added Firebase gradle in my app gradle and one google gradle in Project gradle  I am getting this message:

this is my app gradle

 apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "iamrajendra.github.io"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-database:11.0.2'

}

and this is my project gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
         classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Body:
Add this under the last line in your app gradle .. in the bottom of the file

    apply plugin: 'com.google.gms.google-services'


问:
How to wrap text around an image placed at the END of a block of text?
What I want to do is shown by the "Float Right" illustration in this drawing that opens the post at https://css-tricks.com/all-about-floats/ :

I want to place an image at the end of a block of text, so that the bottom of the image lines up with the baseline of the last line of the text, pushing up into the text and the text flowing around it.

Using the float:right instruction though, the best I've been able to achieve is an image that hangs off the bottom of the paragraph, not one that pushes up into it, as shown in the illustration.

There are description on how to use float:left in many places but nothing I found in the CSS-TRICKS post, on here, or elsewhere explains how to achieve the positioning and wrapping of text around the image using float:right - which is what I'm trying to achieve.

Does anyone know how to do it?

答:
In short, you cannot accomplish that exact appearance you are seeking without some markup changes, either with a left or right float.

The reason that the left float works on the first image is that a floated element will have the block level content following it "flow" around it. If you started with a right float on that first image the same effect would be achieved. So when you put an image at the very end of your block-level content (paragraphs), there is nothing to flow around it.

You can achieve a similar look by outputting the last image while there is still some content remaining. For example:

https://codepen.io/andrewborem/pen/PjyNyY

Relevant Code:

div {
  max-width: 750px;
  margin: 0 auto;
  font-size: 1.125em;
}

img.left {
  float: left;
  margin: 0 0.5em 0.5em 0;
  line-height: 0;
}

img.right {
  float: right;
  margin: 0.5em 0 0.5em 0.5em;
  line-height: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <img class="left" src="https://placehold.it/400x300" />
  <p>Bacon ipsum dolor amet tenderloin sirloin pork belly alcatra, flank cow pig. Chicken rump andouille bacon, turkey strip steak pastrami salami chuck shank flank ball tip. Pork belly doner salami alcatra tail strip steak. Tongue boudin leberkas brisket
    burgdoggen capicola tri-tip corned beef filet mignon pancetta strip steak short ribs. Biltong drumstick jerky, filet mignon bresaola t-bone sirloin tail pig. Meatball sirloin burgdoggen tail t-bone.</p>
  <p>Ham jerky bacon ground round, pork tongue fatback landjaeger short loin flank brisket ribeye cow. Jowl capicola flank shoulder strip steak spare ribs pig boudin. Burgdoggen beef ribs kevin meatball frankfurter turkey pork loin ground round capicola
    shoulder ribeye t-bone cow prosciutto boudin. Porchetta rump bacon swine, hamburger ham hock beef ribs picanha turkey leberkas. Venison pork ham, biltong bacon prosciutto spare ribs pig picanha capicola. Pastrami pancetta bresaola chuck biltong venison.
    Leberkas chicken pastrami shoulder, turducken drumstick spare ribs picanha capicola pancetta rump salami tail t-bone.</p>
  <p>Picanha doner burgdoggen sausage. Corned beef pork belly alcatra, ground round beef ribs tenderloin ball tip pork loin pig hamburger pork chop tri-tip brisket. Jowl doner tail shankle venison frankfurter. Spare ribs pig chicken t-bone. Beef sirloin
    tongue picanha pork capicola fatback, meatball boudin porchetta shank tri-tip pork belly.</p>
  <img class="right" src="https://placehold.it/400x300" />
  <p>Leberkas chicken short loin kevin tri-tip kielbasa ham hock meatball, ball tip ground round tongue filet mignon. Venison tongue pork belly pig. Kielbasa short ribs sirloin venison alcatra hamburger bacon boudin. Pork ball tip brisket strip steak pig,
    pork loin turkey jowl kevin spare ribs tenderloin. Landjaeger sirloin spare ribs ribeye ball tip, venison shank bresaola chicken pork loin doner shoulder jowl shankle pastrami. Shoulder tri-tip pork loin swine, leberkas salami ground round bresaola
    pastrami kielbasa chuck chicken.</p>

  <p>Pancetta tail sirloin corned beef frankfurter burgdoggen kielbasa leberkas chicken chuck meatball pork belly flank venison. Porchetta shankle capicola, strip steak biltong alcatra pastrami. Frankfurter shankle drumstick tail, pancetta pork belly andouille.
    Ball tip pancetta strip steak venison pork loin hamburger. Drumstick landjaeger cupim, ham hock boudin beef kielbasa pancetta pig.</p>

</div></code>```

The caveat here is that if you are using a CMS to input this, and end up creating an article with two images that only has three paragraph elements, the output is going to look pretty broken. Alternately, if you have two extremely long, or extremely short, paragraph elements that follow the last image, it is not going to behave exactly as expected.

Body:
In short, you cannot accomplish that exact appearance you are seeking without some markup changes, either with a left or right float.

The reason that the left float works on the first image is that a floated element will have the block level content following it "flow" around it. If you started with a right float on that first image the same effect would be achieved. So when you put an image at the very end of your block-level content (paragraphs), there is nothing to flow around it.

You can achieve a similar look by outputting the last image while there is still some content remaining. For example:

https://codepen.io/andrewborem/pen/PjyNyY

Relevant Code:

div {
  max-width: 750px;
  margin: 0 auto;
  font-size: 1.125em;
}

img.left {
  float: left;
  margin: 0 0.5em 0.5em 0;
  line-height: 0;
}

img.right {
  float: right;
  margin: 0.5em 0 0.5em 0.5em;
  line-height: 0;
}

<div>
  <img class="left" src="https://placehold.it/400x300" />
  <p>Bacon ipsum dolor amet tenderloin sirloin pork belly alcatra, flank cow pig. Chicken rump andouille bacon, turkey strip steak pastrami salami chuck shank flank ball tip. Pork belly doner salami alcatra tail strip steak. Tongue boudin leberkas brisket
    burgdoggen capicola tri-tip corned beef filet mignon pancetta strip steak short ribs. Biltong drumstick jerky, filet mignon bresaola t-bone sirloin tail pig. Meatball sirloin burgdoggen tail t-bone.</p>
  <p>Ham jerky bacon ground round, pork tongue fatback landjaeger short loin flank brisket ribeye cow. Jowl capicola flank shoulder strip steak spare ribs pig boudin. Burgdoggen beef ribs kevin meatball frankfurter turkey pork loin ground round capicola
    shoulder ribeye t-bone cow prosciutto boudin. Porchetta rump bacon swine, hamburger ham hock beef ribs picanha turkey leberkas. Venison pork ham, biltong bacon prosciutto spare ribs pig picanha capicola. Pastrami pancetta bresaola chuck biltong venison.
    Leberkas chicken pastrami shoulder, turducken drumstick spare ribs picanha capicola pancetta rump salami tail t-bone.</p>
  <p>Picanha doner burgdoggen sausage. Corned beef pork belly alcatra, ground round beef ribs tenderloin ball tip pork loin pig hamburger pork chop tri-tip brisket. Jowl doner tail shankle venison frankfurter. Spare ribs pig chicken t-bone. Beef sirloin
    tongue picanha pork capicola fatback, meatball boudin porchetta shank tri-tip pork belly.</p>
  <img class="right" src="https://placehold.it/400x300" />
  <p>Leberkas chicken short loin kevin tri-tip kielbasa ham hock meatball, ball tip ground round tongue filet mignon. Venison tongue pork belly pig. Kielbasa short ribs sirloin venison alcatra hamburger bacon boudin. Pork ball tip brisket strip steak pig,
    pork loin turkey jowl kevin spare ribs tenderloin. Landjaeger sirloin spare ribs ribeye ball tip, venison shank bresaola chicken pork loin doner shoulder jowl shankle pastrami. Shoulder tri-tip pork loin swine, leberkas salami ground round bresaola
    pastrami kielbasa chuck chicken.</p>

  <p>Pancetta tail sirloin corned beef frankfurter burgdoggen kielbasa leberkas chicken chuck meatball pork belly flank venison. Porchetta shankle capicola, strip steak biltong alcatra pastrami. Frankfurter shankle drumstick tail, pancetta pork belly andouille.
    Ball tip pancetta strip steak venison pork loin hamburger. Drumstick landjaeger cupim, ham hock boudin beef kielbasa pancetta pig.</p>

</div>

The caveat here is that if you are using a CMS to input this, and end up creating an article with two images that only has three paragraph elements, the output is going to look pretty broken. Alternately, if you have two extremely long, or extremely short, paragraph elements that follow the last image, it is not going to behave exactly as expected.


问:
How to reliably count preceding rows in MySQL?
I would like to know how to count preceding number of rows of a given row, in a given order by clause, in MySQL.
Also the rows may be inserted randomly, so auto_increment is unreliable.

```
MyAgenda - List

ID   FROM                  TO
32   2017-09-26 12:35:00   2017-09-26 13:35:00
33   2017-10-10 12:35:00   2017-10-10 13:35:00
32   2017-10-17 12:35:00   2017-10-17 13:35:00
32   2017-10-24 12:35:00   2017-10-24 13:35:00
```

Like in this case, The rows are sorted by the "From" column, but apparently row 34 is inserted before row 36, but after sorting 36 is above 34, and if another row 37 is inserted it maybe above or below any row, or even at the top. So how can I reliably count the preceding number of rows above a given row, in a given order by clause?

Tried the subquery method but it is O(n^2) and will be painfully slow when the number of rows is large.

答:
First I would suggest not to sort by one column only
try this

```<code>ORDER BY From, ID
</code>```

about your question, not sure if i understood the question correctly but in that case this script may help

```<code>SELECT COUNT(*)
FROM your_table
WHERE From > @From
ORDER BY From, ID
</code>```

Body:
I would like to know how to count preceding number of rows of a given row, in a given order by clause, in MySQL.
Also the rows may be inserted randomly, so auto_increment is unreliable.

MyAgenda - List

ID   FROM                  TO
32   2017-09-26 12:35:00   2017-09-26 13:35:00
33   2017-10-10 12:35:00   2017-10-10 13:35:00
32   2017-10-17 12:35:00   2017-10-17 13:35:00
32   2017-10-24 12:35:00   2017-10-24 13:35:00

Like in this case, The rows are sorted by the "From" column, but apparently row 34 is inserted before row 36, but after sorting 36 is above 34, and if another row 37 is inserted it maybe above or below any row, or even at the top. So how can I reliably count the preceding number of rows above a given row, in a given order by clause?

Tried the subquery method but it is O(n^2) and will be painfully slow when the number of rows is large.

Body:
First I would suggest not to sort by one column only
try this

ORDER BY From, ID

about your question, not sure if i understood the question correctly but in that case this script may help

SELECT COUNT(*)
FROM your_table
WHERE From > @From
ORDER BY From, ID


问:
vue-cli + webpack: where to include npm package js and css files?
I'm trying to import an npm package into my vue-cli dev site. Here are the instructions provided by the package website:

It says that it needs the css and js files to be included somewhere in the code. How would I go about doing this?

I'm guessing the css file is included by putting this in App.vue:

```<code><style>
  @import '../node_modules/swiper/dist/css/swiper.min.css';
....
</style>
</code>```

Is that right? How would I include the .js file? Inside App.vue, or main.js? I'm honestly not sure how the syntax for that would go either.

Here is my index.html file:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="build/swiper.min.css">
  </head>
  <body>
    <div id="app"></div>
    <script src="build/swiper.min.js"></script>
  </body>
</html>
</code>```

答:
This seems to be working - in my main.js file, I've included the js and css files like this:

```<code>import Swiper from 'swiper'
import 'swiper/dist/css/swiper.min.css'
</code>```

As far as I can tell, this is correctly importing the npm package into the project for use in development and production.

Body:
I'm trying to import an npm package into my vue-cli dev site. Here are the instructions provided by the package website:

It says that it needs the css and js files to be included somewhere in the code. How would I go about doing this?

I'm guessing the css file is included by putting this in App.vue:

Is that right? How would I include the .js file? Inside App.vue, or main.js? I'm honestly not sure how the syntax for that would go either.

Here is my index.html file:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="build/swiper.min.css">

Body:
This seems to be working - in my main.js file, I've included the js and css files like this:

import Swiper from 'swiper'
import 'swiper/dist/css/swiper.min.css'

As far as I can tell, this is correctly importing the npm package into the project for use in development and production.


问:
Change standard authorization in VF04
I need to change the authorization for billing type in transaction VF04, to be editable for all users.

Is there some user exit for this?

Thanks.

答:
The authorization object for billing types is V_VBRK_FKA, and its check is located in program SAPLV05H include LV05HFBE, and technically you can make a modification (strongly discouraged!) to remove this check but why? It is is weird to try to suppress standard checks.

Why not to add this type to authorization profiles of all users in order this check to be passed? If you want to allow certain billing type for all users, just create the role and assign it to all users.

Title: Change standard authorization in VF04


问:
Create web service using Eclipse
I am trying to create my first webservice using eclipse javaEE under Axis2,
i am following this turorial eclipse tutorial
 to learn how to make it.I make the webservice but when i want to assure that the ws has been deployed through viewing it through URL, an HTTP status 400 occure. How can I know what is the error??
here what i make exactly:

i make the settings in preferences [ ant , axis2, tomcat and java ].

New -> New dynamic web page

new ->java (I create the class i want to convert to ws)

new ->web service (i want to create  bottom up ws).

type http://localhost:8080/Axis2/services/listservices in the url of browser

this what return HTTP Status 404 - /services/listservices

can some one tell me how can i know what is the error? or how can i define it?

EDIT:
an exception happen in the console of eclipse which is :

```<code>org.apache.axis2.transport.http.AxisAdminServlet java.lang.ClassNotFoundException: org.apache.axis2.transport.http.AxisAdminServlet
</code>```

what should I do ,in the configuration i specify where is axis2 and eclipse shows

```<code>Axis2 runtime loaded successfully
</code>```

after creating new work space and create webservice again, this is the output appears in console

```<code> Dec 20, 2010 8:32:04 PM org.apache.catalina.core.AprLifecycleListener init
 INFO: The APR based Apache Tomcat Native library which allows optimal performance in
production environments was not found on the java.library.path: C:\Program
 Files\Java\jdk1.6.0_18\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;F:/alaa college/year 4/1st
 semester/Advance sw/Libraries/eclipse/jre/bin/client;F:/alaa college/year 4/1st
semester/Advance sw/Libraries/eclipse/jre/bin;D:\app\AloOoSh\product\11.1.0\db_1\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jdk1.6.0_18\bin;%ANT_HOME%\bin;%AXIS2_HOME%\bin;%CATALINA_HOME%\bin;C:\Program Files\MATLAB\R2008a\bin;C:\Program Files\MATLAB\R2008a\bin\win32;
Dec 20, 2010 8:32:05 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source'
to 'org.eclipse.jst.jee.server:testFirst' did not find a matching property.
 Dec 20, 2010 8:32:05 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Dec 20, 2010 8:32:05 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 401 ms
Dec 20, 2010 8:32:05 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina

Dec 20, 2010 8:32:05 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.29
[INFO] Deploying module: addressing-1.4 -     file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testF
 irst/WEB-INF/modules/addressing-1.4.mar
[INFO] Deploying module: metadataExchange-1.4 -
 file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/mex-1.4.mar
 [INFO] Deploying module: ping-1.4 -
 file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/ping-1.4.mar
 [INFO] Deploying module: script-1.4 -  file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/scripting-1.4.mar
 [INFO] Deploying module: smtpfault - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/smtpfault.mar
[INFO] Deploying module: soapmonitor-1.4 - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/soapmonitor-1.4.mar
 [INFO] Deploying Web service: Converter - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/services/Converter/
[INFO] Deploying Web service: version.aar - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/services/version.aar
 Dec 20, 2010 8:32:06 PM org.apache.coyote.http11.Http11Protocol start
 INFO: Starting Coyote HTTP/1.1 on http-8080
 Dec 20, 2010 8:32:06 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Dec 20, 2010 8:32:06 PM org.apache.jk.server.JkMain start
 INFO: Jk running ID=0 time=0/19  config=null
Dec 20, 2010 8:32:06 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1383 ms
</code>```

答:
These is my own post to creating webservice and use that service in android. its
work properly.

Try this once below link

http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/#comment-179

Title: Create web service using Eclipse

Body:
I am trying to create my first webservice using eclipse javaEE under Axis2,
i am following this turorial eclipse tutorial
 to learn how to make it.I make the webservice but when i want to assure that the ws has been deployed through viewing it through URL, an HTTP status 400 occure. How can I know what is the error??
here what i make exactly:

i make the settings in preferences [ ant , axis2, tomcat and java ].

New -> New dynamic web page

new ->java (I create the class i want to convert to ws)

new ->web service (i want to create  bottom up ws).

type http://localhost:8080/Axis2/services/listservices in the url of browser

this what return HTTP Status 404 - /services/listservices

can some one tell me how can i know what is the error? or how can i define it?

EDIT:
an exception happen in the console of eclipse which is :

org.apache.axis2.transport.http.AxisAdminServlet java.lang.ClassNotFoundException: org.apache.axis2.transport.http.AxisAdminServlet

what should I do ,in the configuration i specify where is axis2 and eclipse shows

Axis2 runtime loaded successfully

after creating new work space and create webservice again, this is the output appears in console

 Dec 20, 2010 8:32:04 PM org.apache.catalina.core.AprLifecycleListener init
 INFO: The APR based Apache Tomcat Native library which allows optimal performance in
production environments was not found on the java.library.path: C:\Program
 Files\Java\jdk1.6.0_18\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;F:/alaa college/year 4/1st
 semester/Advance sw/Libraries/eclipse/jre/bin/client;F:/alaa college/year 4/1st
semester/Advance sw/Libraries/eclipse/jre/bin;D:\app\AloOoSh\product\11.1.0\db_1\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jdk1.6.0_18\bin;%ANT_HOME%\bin;%AXIS2_HOME%\bin;%CATALINA_HOME%\bin;C:\Program Files\MATLAB\R2008a\bin;C:\Program Files\MATLAB\R2008a\bin\win32;
Dec 20, 2010 8:32:05 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source'
to 'org.eclipse.jst.jee.server:testFirst' did not find a matching property.
 Dec 20, 2010 8:32:05 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Dec 20, 2010 8:32:05 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 401 ms
Dec 20, 2010 8:32:05 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina

Dec 20, 2010 8:32:05 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.29
[INFO] Deploying module: addressing-1.4 -     file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testF
 irst/WEB-INF/modules/addressing-1.4.mar
[INFO] Deploying module: metadataExchange-1.4 -
 file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/mex-1.4.mar
 [INFO] Deploying module: ping-1.4 -
 file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/ping-1.4.mar
 [INFO] Deploying module: script-1.4 -  file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/scripting-1.4.mar
 [INFO] Deploying module: smtpfault - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/smtpfault.mar
[INFO] Deploying module: soapmonitor-1.4 - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/soapmonitor-1.4.mar
 [INFO] Deploying Web service: Converter - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/services/Converter/
[INFO] Deploying Web service: version.aar - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/services/version.aar
 Dec 20, 2010 8:32:06 PM org.apache.coyote.http11.Http11Protocol start
 INFO: Starting Coyote HTTP/1.1 on http-8080
 Dec 20, 2010 8:32:06 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Dec 20, 2010 8:32:06 PM org.apache.jk.server.JkMain start
 INFO: Jk running ID=0 time=0/19  config=null
Dec 20, 2010 8:32:06 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1383 ms


问:
How do you reverse a string in-place in JavaScript?
How do you reverse a string in-place in JavaScript when it is passed to a function with a return statement, without using built-in functions (.reverse(), .charAt() etc.)?

答:
Keep it DRY and simple silly!!</p>

```<code>function reverse(s){
let str = s;
var reverse = '';
for (var i=str.length;i>0;i--){

    var newstr = str.substring(0,i)
    reverse += newstr.substr(-1,1)
}
return reverse;
}
</code>```

OwnerDisplayName: Jake

Body:
Keep it DRY and simple silly!!

function reverse(s){
let str = s;
var reverse = '';
for (var i=str.length;i>0;i--){

    var newstr = str.substring(0,i)
    reverse += newstr.substr(-1,1)
}
return reverse;
}


问:
MPI_Barrier - Only some processes passes the barrier
I'm facing a situation where only some processes bypass the MPI_Barrier function.

The problem appears in this fragment of code:

```<code>printf("[%d] Before barrier\n", mpi_rank);
fflush(stdout);
MPI_Barrier(MPI_COMM_WORLD);
printf("[%d] After barrier\n", mpi_rank);
fflush(stdout);
sleep(1);
</code>```

After running it with 4 processes, I have the following output:

```<code>[3] Before barrier
[2] Before barrier
[0] Before barrier
[1] Before barrier
[1] After barrier
</code>```

And the application freezes.

I was expecting that all processes were able to print the message [id] After barrier, but only process 1 printed it.

Why are not all processes passing the barrier?

I was expecting an output like:

```<code>[3] Before barrier
[2] Before barrier
[0] Before barrier
[1] Before barrier
[1] After barrier
[0] After barrier
[2] After barrier
[3] After barrier
</code>```

I'm using openmpi with centos inside docker. The application starts several threads, but the fragment showed is not inside any of it.

答:
I've been experiencing similar problems, began searching the web. I found - as far as I understand it - that the implementation of MPI_Barrier in OpenMPI might be buggy, depending on the specific version.

https://github.com/open-mpi/ompi/issues/3042

MPI_Barrier doesn't function properly

Body:
I'm facing a situation where only some processes bypass the MPI_Barrier function.

The problem appears in this fragment of code:

printf("[%d] Before barrier\n", mpi_rank);
fflush(stdout);
MPI_Barrier(MPI_COMM_WORLD);
printf("[%d] After barrier\n", mpi_rank);
fflush(stdout);
sleep(1);

After running it with 4 processes, I have the following output:

[3] Before barrier
[2] Before barrier
[0] Before barrier
[1] Before barrier
[1] After barrier

And the application freezes.

I was expecting that all processes were able to print the message [id] After barrier, but only process 1 printed it.

Why are not all processes passing the barrier?

I was expecting an output like:

[3] Before barrier
[2] Before barrier
[0] Before barrier
[1] Before barrier
[1] After barrier
[0] After barrier
[2] After barrier
[3] After barrier

I'm using openmpi with centos inside docker. The application starts several threads, but the fragment showed is not inside any of it.


问:
filesize() expects parameter 1 to be a valid path - PHP
I am tryig to read an entire file in PHP, but I have this issue with filesize function. Here is the code:</p>

```<code><?php
 $file = fopen("file.txt", "r");
 echo $file;

 $fsize = filesize($file);
 //$ftext = fread($file, $fsize);
 //echo $ftext;
?>
</code>```

答:
The answer is right there in the question title: you need to pass filesize a path, not the $file object you get from fopen:

```<code>$fsize = filesize("file.txt");
</code>```

Body:
I am tryig to read an entire file in PHP, but I have this issue with filesize function. Here is the code:

<?php
 $file = fopen("file.txt", "r");
 echo $file;

 $fsize = filesize($file);
 //$ftext = fread($file, $fsize);
 //echo $ftext;
?>

Body:
The answer is right there in the question title: you need to pass filesize a path, not the $file object you get from fopen:

$fsize = filesize("file.txt");