问:
Compile Single file in a project in netbeans
I am using NetBeans Ide 8.2 on ubuntu 16

I am learning C and C++ programming hence the program i make are not related and when I try to create multiple file in a project the include multiple main() function which return error

error: multiple main function found

I want to create separate file for each program but I don't want to create separate project for all the program.

please suggest me a way & I am sorry for my language , I hope i am able to make you understand my problem.

答:
To have multiple main files in a single Netbeans project:

Under the Projects tab in the left, double-click on your project to show its contents.

Double-click on the Source Files folder to show its contents

Right-click on the earlier main file (most-likely main.cpp) and select Properties.

Under the Item Configuration tab, check the Excluded from build option and click on Ok.

Right-click on the Source Files folder, select New and click on C++ Main File. This will create a new main file in the same project.

Now, when you build and run your project, it will compile the new main file, and the old one will be ignored.

Tip: It is a good idea to give unique names to the main files, to avoid name clashes.


来源: stackexchange

问:
Could proc get executed without using call method?
I am bringing out a separate question from here. It really confused me. Here is the definition of add_mapping method:

```<code>def add_mapping(regexp, &proc)
  @test_mappings << [regexp, proc]
end
</code>```

How could proc here get executed and return result without using call method?

答:
Eric, what add_mapping does is just adding a regular expresion + proc tuple to an array called @test_mappings.

add_mappings does not execute the proc. I don't know how ZenTest works but it should be executing the procs after reading all add_mapping calls.

Check out the code for ZenTest and look out for @test_mappings, that could reveal you where  (and when) the proc is executed.

ContentLicense: CC BY-SA 3.0

Body:
I am bringing out a separate question from here. It really confused me. Here is the definition of add_mapping method:

def add_mapping(regexp, &proc)
  @test_mappings << [regexp, proc]
end

How could proc here get executed and return result without using call method?

ContentLicense: CC BY-SA 2.5


问:
SAPUI5 - GET request
How can I display a JSON data using an url in SAPUI5.
I use SAPUI5 for frontend dev.

This is my controller function:

```<code>initThingsModel:function () {

    var oMenuModel = new sap.ui.model.json.JSONModel();

    oMenuModel.loadData("http://localhost:8085/things");

    sap.ui.getCore().setModel(oMenuModel);
}
</code>```

But I don't know how should my view.xml look.

答:
```<code>oMenuModel.attachRequestCompleted(function() {
    var data = oMenuModel.getData();
    console.log(data);
});
</code>```

Title: SAPUI5 - GET request

Body:
How can I display a JSON data using an url in SAPUI5.
I use SAPUI5 for frontend dev.

This is my controller function:

initThingsModel:function () {

    var oMenuModel = new sap.ui.model.json.JSONModel();

    oMenuModel.loadData("http://localhost:8085/things");

    sap.ui.getCore().setModel(oMenuModel);
}

But I don't know how should my view.xml look.


问:
How to load javascript file1 first before javascript file2
I have two javascript file one with the functions and another with the eventlistener. This is how I declare them

```<code><body>
    <script src="../script/Main%20Functions.js"></script>
    <script src="../script/Main-events.js"></script>
</body>
</code>```

Main Functions.js

```<code>checklike(userId,postId);
function checkLike(userId, postId) {
    $.ajax({

        type: "POST",
        url: "../Main.asmx/get_liked",
        data: "{'userID':'" + userId + "', 'postID':'" + postId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var result = response.d;
            console.log('ok');
            $.each(result, function (index, data) {
                var liked = data.liked;
                if (liked == true) {
                    $("#" + postId).prev().parent("button").css("background", "#ccc");
                }
                else {
                    $("#" + postId).prev().parent("button").css("background", "white");
                }
            });

        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('Function Error "checkLike"');
        }

    });
}
</code>```

Main-events.js

```<code>const d = document.querySelector.bind(document);
const D = document.querySelectorAll.bind(document);
const logOut = d('.lOut h3');
const iFrame = d('#if1');
const alias = d('.codename-label h2');
const monito = d('.monito-label');
const monitoChecklists = D('.monito-checklist');
const displayPicture = d('#displayPic');
const btnReveal = d('.btn-reveal');
const btnSubmit = d('.btn-submit');
const btnLike = D('.buttonLike');
console.log('ok2');
btnLike.forEach(function (like) {
    like.addEventListener('click', function (e) {
        console.log(this);
    })
});
</code>```

but when I open the html the console.log('ok2'); executes first not the console.log('ok') . Is there a way on telling the javascript to load specific file first before executing the file for eventlistener?

EDIT 1: The adding of eventlistener for the btnLike loads first before the javascript added the elemet on the page.

EDIT 2: Okay upon investigation

Before trying eventlistener I use this jquery code

```<code>$(document).on('click', '.buttonLike', function () {
    var color = $(this).css("background-color");
    var id = $(this).find(".postID").attr("id");
    if (color == "rgb(204, 204, 204)") {
        $(this).css("background-color", "white");
        var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) - 1;
        if (number > 1) {
            number = number + " Likes";
        }
        else {
            number = number + " Like";
        }
        $("#" + id).html(number);
        Remove_Like(id);
    }
    else {
        $(this).css("background-color", "#ccc");
        var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) + 1;
        if (number > 1) {
            number = number + " Likes";
        }
        else {
            number = number + " Like";
        }
        $("#" + id).html(number);
        Add_Like(id);
    }
});
</code>```

it works fine and I found out that it uses the document and check if the target has class name .buttonLike am i right?

答:
ajax is Asynchronous Javascript and XML.

So, being asynchronous, the console.log are not being called in order. And as ajax might be taking a while to get called, the 'ok2' is getting called first.

The solution to this is to call the 'ok2' inside the success or done method of $.ajax

Body:
I have two javascript file one with the functions and another with the eventlistener. This is how I declare them

Main Functions.js

checklike(userId,postId);
function checkLike(userId, postId) {
    $.ajax({

        type: "POST",
        url: "../Main.asmx/get_liked",
        data: "{'userID':'" + userId + "', 'postID':'" + postId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var result = response.d;
            console.log('ok');
            $.each(result, function (index, data) {
                var liked = data.liked;
                if (liked == true) {
                    $("#" + postId).prev().parent("button").css("background", "#ccc");
                }
                else {
                    $("#" + postId).prev().parent("button").css("background", "white");
                }
            });

        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('Function Error "checkLike"');
        }

    });
}

Main-events.js

const d = document.querySelector.bind(document);
const D = document.querySelectorAll.bind(document);
const logOut = d('.lOut h3');
const iFrame = d('#if1');
const alias = d('.codename-label h2');
const monito = d('.monito-label');
const monitoChecklists = D('.monito-checklist');
const displayPicture = d('#displayPic');
const btnReveal = d('.btn-reveal');
const btnSubmit = d('.btn-submit');
const btnLike = D('.buttonLike');
console.log('ok2');
btnLike.forEach(function (like) {
    like.addEventListener('click', function (e) {
        console.log(this);
    })
});

but when I open the html the console.log('ok2'); executes first not the console.log('ok') . Is there a way on telling the javascript to load specific file first before executing the file for eventlistener?

EDIT 1: The adding of eventlistener for the btnLike loads first before the javascript added the elemet on the page.

EDIT 2: Okay upon investigation

Before trying eventlistener I use this jquery code

$(document).on('click', '.buttonLike', function () {
    var color = $(this).css("background-color");
    var id = $(this).find(".postID").attr("id");
    if (color == "rgb(204, 204, 204)") {
        $(this).css("background-color", "white");
        var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) - 1;
        if (number > 1) {
            number = number + " Likes";
        }
        else {
            number = number + " Like";
        }
        $("#" + id).html(number);
        Remove_Like(id);
    }
    else {
        $(this).css("background-color", "#ccc");
        var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) + 1;
        if (number > 1) {
            number = number + " Likes";
        }
        else {
            number = number + " Like";
        }
        $("#" + id).html(number);
        Add_Like(id);
    }
});

it works fine and I found out that it uses the document and check if the target has class name .buttonLike am i right?


问:
Jquery sortable drag and drop not showing 'move' cursor
Im using this .sortable function on my list. My problem is that I want it to show the move cursor when the drag and drop is being used, and the pointer cursor only on hover. I have my css calling the cursor:pointer on hover, but it does not seem to show the move cursor at all. Everything else works fine. Code below.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/themes/base/jquery-ui.css" type="text/css"/>
    <link rel="stylesheet" href="blah.css" type="text/css" />
    <script type="text/javascript" charset="UTF-8">
    $(document).ready(function()
    {
    $("#sortable").sortable({
        /*helper: 'clone', Tried this =(*/
        distance: 5,
        delay: 300,
        opacity: 0.6,
        cursor: 'move',
        update: function() {}
    });
    });
    </script>
    </head>
    <body>
    <ul id="sortable">
        <li class="ui-state-default">Item 1</li>
        <li class="ui-state-default">Item 2</li>
        <li class="ui-state-default">Item 3</li>
    </ul>
    </body>
    </html>
</code>```

Seperate css doc contains:

```<code>#sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.1em; line-height: 18px; height: 18px; }
#sortable li span { position: absolute; margin-left: -1.3em; }

/* HERE'S THE IMPORTANT STUFF! */
#sortable li:hover {
    cursor: pointer;
}

#sortable li.ui-sortable-helper {
    cursor: move;
}
</code>```

Any help would be greatly appreciated. Thanks in advance. =)

Perhaps a little more information. Its a db populated list from a while statement. each list item is a link, so I want it to display the {cursor: Pointer;} option. But when it is dragged i need it to display the {cursor: move;}. I would have thought that the code above would do it but its not working. I confused myself with the first post so thought i would clarify this a little better.

答:
Try this:

```<code>$element.droppable({
  over: function() {
    $('body').css('cursor','copy');
  },
  out: function() {
    $('body').css('cursor','no-drop');
  },
});
</code>```

It will indicate the user if the draggable if over a droppable.

Body:
Im using this .sortable function on my list. My problem is that I want it to show the move cursor when the drag and drop is being used, and the pointer cursor only on hover. I have my css calling the cursor:pointer on hover, but it does not seem to show the move cursor at all. Everything else works fine. Code below.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/themes/base/jquery-ui.css" type="text/css"/>
    <link rel="stylesheet" href="blah.css" type="text/css" />

Item 1

Item 2

Item 3

Seperate css doc contains:

#sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.1em; line-height: 18px; height: 18px; }
#sortable li span { position: absolute; margin-left: -1.3em; }

/* HERE'S THE IMPORTANT STUFF! */
#sortable li:hover {
    cursor: pointer;
}

#sortable li.ui-sortable-helper {
    cursor: move;
}

Any help would be greatly appreciated. Thanks in advance. =)

Perhaps a little more information. Its a db populated list from a while statement. each list item is a link, so I want it to display the {cursor: Pointer;} option. But when it is dragged i need it to display the {cursor: move;}. I would have thought that the code above would do it but its not working. I confused myself with the first post so thought i would clarify this a little better.

Body:
Try this:

$element.droppable({
  over: function() {
    $('body').css('cursor','copy');
  },
  out: function() {
    $('body').css('cursor','no-drop');
  },
});

It will indicate the user if the draggable if over a droppable.


问:
Storing Images in Azure and Accessing it in Code
Before I published the website I've been working on to Azure, I kept all the images inside a local "Catalog" folder which was referenced in the program like;

image src='/Catalog/Images/Thumbs/<%#:Item.ImagePath%

Now it is deployed on Azure, I believe I need to turn to something called "Unstructured Blob Storage" to store and retrieve the images on the website.

This is my first time using Azure, I am wondering if it is as easy as storing the images in an unstructured blob storage on Azure, then just changing the "Catalog/Images/Thumbs" to the file path on Azure.

Does anybody know exactly how this works?

Thanks!

答:
AFAIK, after deployed your web application to Azure, you could still store your resources (e.g. image, doc, excel, etc.) within your web application. In order to better manage your resources and reduce the pressure for your application when serving the static resources, you could store your resources in a central data store.

This is my first time using Azure, I am wondering if it is as easy as storing the images in an unstructured blob storage on Azure, then just changing the "Catalog/Images/Thumbs" to the file path on Azure.

Based on your requirement, you could create a blob container named catalog and upload your images to the virtual directory Images/Thumbs, and set anonymous read access to your container and blobs. For a simple way, you could leverage Azure Storage Explorer to upload your images and set access level for your container as follows:

And you image would look like this:

```<code><img src="https://brucchstorage.blob.core.windows.net/catalog/Images/Thumbs/lake.jpeg">
</code>```

Moreover, you could leverage AzCopy to copy data to Azure Blob storage using simple commands with optimal performance. Additionally, you could leverage Azure Storage client library to manage your storage resources, details you could follow here.

Body:
AFAIK, after deployed your web application to Azure, you could still store your resources (e.g. image, doc, excel, etc.) within your web application. In order to better manage your resources and reduce the pressure for your application when serving the static resources, you could store your resources in a central data store.

This is my first time using Azure, I am wondering if it is as easy as storing the images in an unstructured blob storage on Azure, then just changing the "Catalog/Images/Thumbs" to the file path on Azure.

Based on your requirement, you could create a blob container named catalog and upload your images to the virtual directory Images/Thumbs, and set anonymous read access to your container and blobs. For a simple way, you could leverage Azure Storage Explorer to upload your images and set access level for your container as follows:

And you image would look like this:

<img src="https://brucchstorage.blob.core.windows.net/catalog/Images/Thumbs/lake.jpeg">

Moreover, you could leverage AzCopy to copy data to Azure Blob storage using simple commands with optimal performance. Additionally, you could leverage Azure Storage client library to manage your storage resources, details you could follow here.


问:
How to resolve this error Ora-25137 "Data Value Out of range" in oracle
How to resolve this error

ORA-25137: Data Value out of range

Cause: value from CAST operand is larger than CAST target size

Action: Increase size of CAST target.

Inside CAST I used one column value having datatype length 18 and then after compute again I used another CAST to convert its Datatype having same length 18 but after execute I got an error as I mentioned above. Here is the code:

CAST((CAST(col1 as number(18,0)) * 100)/col2 as varchar(18))

How to resolve this error?

答:
try

```<code>as varchar2(18 char)
</code>```

because varchar(18) means 18 bytes.

ContentLicense: CC BY-SA 4.0

Body:
try

as varchar2(18 char)

because varchar(18) means 18 bytes.


问:
Java: How can I compile an entire directory structure of code ?
The use case is simple. I got the source files that were created using Eclipse. So, there is a deep directory structure, where any Java class could be referring to another Java class in the same, child, sibling or parent folder.

How do I compile this whole thing from the terminal using javac ?

答:
You'd have to use something like Ant to do this hierarchically:

http://ant.apache.org/manual/Tasks/javac.html

You'll need to create a build script with a target called compile containing the following:

```<code><javac sourcepath="" srcdir="${src}"
         destdir="${build}" >
    <include name="**/*.java"/>
</javac>
</code>```

Then you''ll be able to compile all files by running:

```<code> ant compile
</code>```

Alternatively, import your project into Eclipse and it will automatically compile all the source files for that project.

Body:
You'd have to use something like Ant to do this hierarchically:

http://ant.apache.org/manual/Tasks/javac.html

You'll need to create a build script with a target called compile containing the following:

<javac sourcepath="" srcdir="${src}"
         destdir="${build}" >
    <include name="**/*.java"/>
</javac>

Then you''ll be able to compile all files by running:

 ant compile

Alternatively, import your project into Eclipse and it will automatically compile all the source files for that project.


问:
RCTBatchedBridge is deprecated and will be removed in a future React Native release
I am facing this warning in my react Native App, How to solve this any suggestion would be helpful.</p>

答:
I had the same problem with my existing native app. I followed the Integrating with Existing Apps guide and solved it.

Simply change Podfile

```<code>target 'MyApp' do
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    ...
    'BatchedBridge'
  ]
end
</code>```

to

```<code>target 'MyApp' do
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    ...
    'CxxBridge'
  ]

  # Third party deps podspec link
  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'GLog', :podspec => '../node_modules/react-native/third-party-podspecs/GLog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
end
</code>```

Body:
I had the same problem with my existing native app. I followed the Integrating with Existing Apps guide and solved it.

Simply change Podfile

target 'MyApp' do
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    ...
    'BatchedBridge'
  ]
end

to

target 'MyApp' do
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    ...
    'CxxBridge'
  ]

  # Third party deps podspec link
  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'GLog', :podspec => '../node_modules/react-native/third-party-podspecs/GLog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
end


问:
Angular 2 routing to specific part of a webpage from one component link to another component
I have a link in footer that takes to the terms page but I want that link to take to a specific part of the terms webpage (3rd paragraph in terms).

Here is the code for footer.component.html

```<code><a routerLink="terms">Terms & conditions</a> |
<a routerLink="terms">Privacy policy</a> |
<a routerLink="terms">Cancellation policy</a>
</code>```

In terms.component.html is the place where i want the privacy policy link in the footer to be opened when clicked.

```<code><ol start="3">
    <li>INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES</li>
</ol>
</code>```

What do we need to use for these to work? Any help is appreciated. Thanks.

答:
To add to @Rahul VV's answer i have edited component with event scrollIntoView below like this

footer.component.ts

```<code>import { Router, NavigationEnd } from '@angular/router';

constructor(router: Router) {
    router.events.subscribe(s => {
      if (s instanceof NavigationEnd) {
        const tree = router.parseUrl(router.url);
        if (tree.fragment) {
          const element = document.querySelector("#" + tree.fragment);
          if (element) { element.scrollIntoView(); }
        }
      }
    });
   }
</code>```

Body:
I have a link in footer that takes to the terms page but I want that link to take to a specific part of the terms webpage (3rd paragraph in terms).

Here is the code for footer.component.html

Terms & conditions |
Privacy policy |
Cancellation policy

In terms.component.html is the place where i want the privacy policy link in the footer to be opened when clicked.

INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES

What do we need to use for these to work? Any help is appreciated. Thanks.

Body:
To add to @Rahul VV's answer i have edited component with event scrollIntoView below like this

footer.component.ts

import { Router, NavigationEnd } from '@angular/router';

constructor(router: Router) {
    router.events.subscribe(s => {
      if (s instanceof NavigationEnd) {
        const tree = router.parseUrl(router.url);
        if (tree.fragment) {
          const element = document.querySelector("#" + tree.fragment);
          if (element) { element.scrollIntoView(); }
        }
      }
    });
   }


问:
Excon::Error::Socket: SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A (OpenSSL::SSL::SSLError)
I'm attempting to use fog-google to upload images to my google cloud storage.
My code looks like this:

```<code>config.paperclip_defaults = {
  storage: :fog,
  fog_host: "https://#{ENV.fetch('GOOGLE_STORAGE_BUCKET')}.storage.googleapis.com",
  fog_credentials: {
      google_storage_access_key_id: ENV.fetch('GOOGLE_STORAGE_ID'),
      google_storage_secret_access_key: ENV.fetch('GOOGLE_STORAGE_SECRET'),
      provider: 'Google' },
  fog_directory: ENV.fetch('GOOGLE_STORAGE_BUCKET') }
</code>```

However, I always get this error:
Excon::Error::Socket: SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A (OpenSSL::SSL::SSLError)

Seems like the connection is not established successfully.

Here is the error log:

```<code>C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/ssl_socket.rb:117:in `connect_nonblock'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/ssl_socket.rb:117:in `initialize'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:404:in `new'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:404:in `socket'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:101:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/mock.rb:48:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/instrumentor.rb:26:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/base.rb:16:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/base.rb:16:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/base.rb:16:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:250:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-core-1.45.0/lib/fog/core/connection.rb:81:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-xml-0.1.3/lib/fog/xml/connection.rb:9:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-google-0.6.0/lib/fog/storage/google_xml/real.rb:103:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-google-0.6.0/lib/fog/storage/google_xml/requests/head_object.rb:36:in `head_object'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-google-0.6.0/lib/fog/storage/google_xml/models/files.rb:81:in `head'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/paperclip-5.1.0/lib/paperclip/storage/fog.rb:65:in `exists?'
</code>```

答: It works when I switch from windows to Linux. </p>

Body:
I'm attempting to use fog-google to upload images to my google cloud storage.
My code looks like this:

config.paperclip_defaults = {
  storage: :fog,
  fog_host: "https://#{ENV.fetch('GOOGLE_STORAGE_BUCKET')}.storage.googleapis.com",
  fog_credentials: {
      google_storage_access_key_id: ENV.fetch('GOOGLE_STORAGE_ID'),
      google_storage_secret_access_key: ENV.fetch('GOOGLE_STORAGE_SECRET'),
      provider: 'Google' },
  fog_directory: ENV.fetch('GOOGLE_STORAGE_BUCKET') }

However, I always get this error:
Excon::Error::Socket: SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A (OpenSSL::SSL::SSLError)

Seems like the connection is not established successfully.

Here is the error log:

C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/ssl_socket.rb:117:in `connect_nonblock'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/ssl_socket.rb:117:in `initialize'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:404:in `new'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:404:in `socket'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:101:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/mock.rb:48:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/instrumentor.rb:26:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/base.rb:16:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/base.rb:16:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/base.rb:16:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:250:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-core-1.45.0/lib/fog/core/connection.rb:81:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-xml-0.1.3/lib/fog/xml/connection.rb:9:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-google-0.6.0/lib/fog/storage/google_xml/real.rb:103:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-google-0.6.0/lib/fog/storage/google_xml/requests/head_object.rb:36:in `head_object'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-google-0.6.0/lib/fog/storage/google_xml/models/files.rb:81:in `head'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/paperclip-5.1.0/lib/paperclip/storage/fog.rb:65:in `exists?'


问:
Is it possible to get an rss feed using javascript client side scripting only?
If I can't do this would the process for getting the data be:
1) Have my server get the rss data from the desired rss feed.
2) Have the server parse the data.  I don't know what rss looks like but I assume some parsing     is needed to display it for a user to read.
3) Send the data to the javascript client.</p>

答: I don't think it is. A JavaScript script can't retrieve files from domains other than the one it was served from, be they RSS or anything else.</p>


问:
How to get each pattern from regex
```<code>var patterns = new string[] { @"Regex 1 Pattern", @"Regex 2 Pattern", @"Regex 3 Pattern" };

var rx = new Regex(string.Join("|", patterns), RegexOptions.IgnoreCase);
</code>```

In the above code how to get rx value to display.

答:
According to the docs, you can call toString on a Regex object and it will:

Returns the regular expression pattern that was passed into the Regex constructor.

Which in this case is your concatenated string!

```<code>rx.toString()
</code>```

Alternatively, why don't you put the string into a variable first, then pass it into the regex constructor:

```<code>var regexString = string.Join("|", patterns);
Console.WriteLine(regexString); // Here you can print the regex out now!
var rx = new Regex(regexString, RegexOptions.IgnoreCase);
</code>```

If you want to get the patterns one by one, simply use a foreach loop:

```<code>foreach(var pattern in patterns) {
    Console.WriteLine(pattern);
}
</code>```

Title: How to get each pattern from regex

Body:
var patterns = new string[] { @"Regex 1 Pattern", @"Regex 2 Pattern", @"Regex 3 Pattern" };

var rx = new Regex(string.Join("|", patterns), RegexOptions.IgnoreCase);

In the above code how to get rx value to display.

Body:
According to the docs, you can call toString on a Regex object and it will:

Returns the regular expression pattern that was passed into the Regex constructor.

Which in this case is your concatenated string!

rx.toString()

Alternatively, why don't you put the string into a variable first, then pass it into the regex constructor:

var regexString = string.Join("|", patterns);
Console.WriteLine(regexString); // Here you can print the regex out now!
var rx = new Regex(regexString, RegexOptions.IgnoreCase);

If you want to get the patterns one by one, simply use a foreach loop:

foreach(var pattern in patterns) {
    Console.WriteLine(pattern);
}


问:
Easiest way to print 64 bit hex data splitted by 16 bits
I want to print 64 bits hex data in following format:

```<code>0x1111_2222_3333_4444
</code>```

I can think of following:

```<code>#define FIRST_MASK  0xFFFF000000000000
#define SECOND_MASK 0x0000FFFF00000000
#define THIRD_MASK  0x00000000FFFF0000
#define FOURTH_MASK 0x000000000000FFFF

val = 0x1111222233334444
printf("0x%04x_%04x_%04x_%04x\n", \
       (unsigned int)((val & FIRST_MASK)  >> 48),
       (unsigned int)((val & SECOND_MASK) >> 32),
       (unsigned int)((val & THIRD_MASK)  >> 16),
       (unsigned int)(val & FOURTH_MASK)
);
</code>```

Is there a simple (or maybe more clean) way to achieve this?

答:
Bit shifts are always the best method, because they are both fast and platform-independent. However, your code is needlessly complex: you can mask after shifting instead of before.</p>

```<code>#include <stdint.h>
#include <stdio.h>

int main (void)
{
  uint64_t val = 0x1111222233334444;
  printf("0x%04x_%04x_%04x_%04x\n",
         (unsigned int)(val>>48 & 0xFFFF),
         (unsigned int)(val>>32 & 0xFFFF),
         (unsigned int)(val>>16 & 0xFFFF),
         (unsigned int)(val>> 0 & 0xFFFF) );
}
</code>```

Body:
I want to print 64 bits hex data in following format:

0x1111_2222_3333_4444

I can think of following:

#define FIRST_MASK  0xFFFF000000000000
#define SECOND_MASK 0x0000FFFF00000000
#define THIRD_MASK  0x00000000FFFF0000
#define FOURTH_MASK 0x000000000000FFFF

val = 0x1111222233334444
printf("0x%04x_%04x_%04x_%04x\n", \
       (unsigned int)((val & FIRST_MASK)  >> 48),
       (unsigned int)((val & SECOND_MASK) >> 32),
       (unsigned int)((val & THIRD_MASK)  >> 16),
       (unsigned int)(val & FOURTH_MASK)
);

Is there a simple (or maybe more clean) way to achieve this?

Body:
Bit shifts are always the best method, because they are both fast and platform-independent. However, your code is needlessly complex: you can mask after shifting instead of before.

#include <stdint.h>
#include <stdio.h>

int main (void)
{
  uint64_t val = 0x1111222233334444;
  printf("0x%04x_%04x_%04x_%04x\n",
         (unsigned int)(val>>48 & 0xFFFF),
         (unsigned int)(val>>32 & 0xFFFF),
         (unsigned int)(val>>16 & 0xFFFF),
         (unsigned int)(val>> 0 & 0xFFFF) );
}


问:
MySQL query to get post_id and feature image URL
WordPress considers both a post and the post's featured image as two separate posts, which seems to make it impossible to create a SELECT query putting the post and post's image URL into the same row, like this:

```<code>post_id  imageURL
100      [URL]
</code>```

How do you merge two rows in a MySQL table which have no column with a common value? The value in one column is associated with the value in a different column.

```<code>meta_id   post_id    meta_key          meta_value
100       250        _thumbnail_id     101
101       255       _wp_attached_file  [URL]
</code>```

...to get a result like this

```<code>post_id  imageURL
100      [URL]
</code>```

WordPress seems to have changed it database structure since this question was answered on this site.

I am trying to understand the principle in MySQL of taking the value from one row and showing it in another row, when "Group by" is not available.

Many hours later of watching videos, trial and error, reading answers here, this query gets me only half-way to solving it, but either the Post ID or the Image URL are always missing. I cannot merge two rows to unite the Post with its image URL.

```<code>SELECT * FROM `wp_postmeta`
INNER JOIN wp_posts on wp_posts.id = wp_postmeta.post_id
WHERE wp_postmeta.meta_key = "_wp_attached_file"
ORDER BY `wp_postmeta`.`post_id` DESC
</code>```

Please help. There may be a simple bit of syntax to achieve this, which I am missing. The query is coming in via the WP API, so using raw SQL queries, not the functions available inside WordPress.

答:
You are trying to get the data based on the value of post_id and meta_value, so this can be achieved by using Self JOIN

Here is the sample working MySQL query

```<code>SELECT p.id AS post_id, pm2.meta_value AS URL
FROM `wp_posts` AS p
INNER JOIN `wp_postmeta` AS pm1 ON p.id = pm1.post_id
INNER JOIN `wp_postmeta` AS pm2 ON pm1.meta_value = pm2.post_id
AND pm2.meta_key = '_wp_attached_file'
AND pm1.meta_key = '_thumbnail_id'
ORDER BY p.id DESC;
</code>```

Hope this helps!

Body:
WordPress considers both a post and the post's featured image as two separate posts, which seems to make it impossible to create a SELECT query putting the post and post's image URL into the same row, like this:

post_id  imageURL
100      [URL]

How do you merge two rows in a MySQL table which have no column with a common value? The value in one column is associated with the value in a different column.

meta_id   post_id    meta_key          meta_value
100       250        _thumbnail_id     101
101       255       _wp_attached_file  [URL]

...to get a result like this

post_id  imageURL
100      [URL]

WordPress seems to have changed it database structure since this question was answered on this site.

I am trying to understand the principle in MySQL of taking the value from one row and showing it in another row, when "Group by" is not available.

Many hours later of watching videos, trial and error, reading answers here, this query gets me only half-way to solving it, but either the Post ID or the Image URL are always missing. I cannot merge two rows to unite the Post with its image URL.

SELECT * FROM `wp_postmeta`
INNER JOIN wp_posts on wp_posts.id = wp_postmeta.post_id
WHERE wp_postmeta.meta_key = "_wp_attached_file"
ORDER BY `wp_postmeta`.`post_id` DESC

Please help. There may be a simple bit of syntax to achieve this, which I am missing. The query is coming in via the WP API, so using raw SQL queries, not the functions available inside WordPress.

Body:
You are trying to get the data based on the value of post_id and meta_value, so this can be achieved by using Self JOIN

Here is the sample working MySQL query

SELECT p.id AS post_id, pm2.meta_value AS URL
FROM `wp_posts` AS p
INNER JOIN `wp_postmeta` AS pm1 ON p.id = pm1.post_id
INNER JOIN `wp_postmeta` AS pm2 ON pm1.meta_value = pm2.post_id
AND pm2.meta_key = '_wp_attached_file'
AND pm1.meta_key = '_thumbnail_id'
ORDER BY p.id DESC;

Hope this helps!


问:
How to make 2 layouts sliding on button click in xamarin/android?
I'm begining with xamarin and android, and I'm not sure to understand the good way to do.
Then I created a main activity and a second activity with their respective layouts.
In the first I put a button with that code:

```<code>button.Click += (sender, e) =>
{
var intent = new Android.Content.Intent(this, typeof(Activity1));
StartActivity(intent);
OverridePendingTransition(Android.Resource.Animation.SlideInleft, Android.Resource.Animation.SlideInleft);
};
</code>```

And in the second:

```<code>button.Click += (sender, e) =>
{
Finish();
};
</code>```

But this doesn't do what I want, I would like the two layouts two slide as if there were side by side, but here the second layout just slides on the first. Also it comes from the left were I would like it to come from the right and there's no SlideInright.
Also is it the right way to do using two activities, mustn't I have only one activity and two layouts (views?).

答:
First, you could use one activity which contains two ViewGroup. As for your question, you can use Animation and FrameLayout which contains two RelativeLayout to complete what you want, like this:

MainActivity.axml:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:a="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout
        android:id="@+id/rl2"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:background="@android:color/holo_green_dark">
        <Button
            android:id="@+id/bt2"
            android:text="page2"
            android:layout_height="100dp"
            android:layout_width="100dp" />
    </RelativeLayout>
    <RelativeLayout
        android:id="@+id/rl1"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:background="@android:color/holo_red_dark">
        <Button
            android:id="@+id/bt1"
            android:text="page1"
            android:layout_height="100dp"
            android:layout_width="100dp" />
    </RelativeLayout>
</FrameLayout>
</code>```

MainActivity:

```<code>        [Activity(Label = "Aniamtion", MainLauncher = true)]
        public class MainActivity : Activity
        {
            Button bt1,bt2;
            RelativeLayout rl1, rl2;
            int width;
            protected override void OnCreate(Bundle savedInstanceState)
        {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        getScreenWidth();//get the screen's width, so we can define how much the animation can translate
        initView();
        initListener();
        }

        private void getScreenWidth()
        {
            DisplayMetrics dm = new DisplayMetrics();
            WindowManager.DefaultDisplay.GetMetrics(dm);
            width = dm.WidthPixels;
        }

        private void initListener()
        {
            bt1.Click += toPage1;
            bt2.Click += toPage2;
        }

        private void toPage1(object sender, EventArgs e)
        {
            //use ObjectAnimator to complete it
            ObjectAnimator objectAnimator = ObjectAnimator.OfFloat(rl1, "translationX", 0, -width);
            objectAnimator.SetDuration(500);
            objectAnimator.Start();
            ObjectAnimator objectAnimator1 = ObjectAnimator.OfFloat(rl2, "translationX", width, 0);
            objectAnimator1.SetDuration(500);
            objectAnimator1.Start();
        }

        private void toPage2(object sender, EventArgs e)
        {
            ObjectAnimator objectAnimator = ObjectAnimator.OfFloat(rl1, "translationX", -width, 0);
            objectAnimator.SetDuration(500);
            objectAnimator.Start();
            ObjectAnimator objectAnimator1 = ObjectAnimator.OfFloat(rl2, "translationX", 0, width);
            objectAnimator1.SetDuration(500);
            objectAnimator1.Start();
        }

        private void initView()
        {
            bt1 = FindViewById<Button>(Resource.Id.bt1);
            bt2 = FindViewById<Button>(Resource.Id.bt2);
            rl1 = FindViewById<RelativeLayout>(Resource.Id.rl1);
            rl2 = FindViewById<RelativeLayout>(Resource.Id.rl2);
        }
        }
</code>```

Second, about this OverridePendingTransition(Android.Resource.Animation.SlideInleft, Android.Resource.Animation.SlideInleft) method, the parameter you can use System resource, or you can custom it .

Update:

put this into your Resource->anim->SlideInRight, this is about customing animation in Xamarin.Android, it is same as Android, and this is document  which you can refer to

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
  <translate android:fromXDelta="50%p"
             android:toXDelta="0"
            android:duration="300"/>
</set>
</code>```

Body:
I'm begining with xamarin and android, and I'm not sure to understand the good way to do.
Then I created a main activity and a second activity with their respective layouts.
In the first I put a button with that code:

button.Click += (sender, e) =>
{
var intent = new Android.Content.Intent(this, typeof(Activity1));
StartActivity(intent);
OverridePendingTransition(Android.Resource.Animation.SlideInleft, Android.Resource.Animation.SlideInleft);
};

And in the second:

button.Click += (sender, e) =>
{
Finish();
};

But this doesn't do what I want, I would like the two layouts two slide as if there were side by side, but here the second layout just slides on the first. Also it comes from the left were I would like it to come from the right and there's no SlideInright.
Also is it the right way to do using two activities, mustn't I have only one activity and two layouts (views?).

Body:
First, you could use one activity which contains two ViewGroup. As for your question, you can use Animation and FrameLayout which contains two RelativeLayout to complete what you want, like this:

MainActivity.axml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:a="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout
        android:id="@+id/rl2"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:background="@android:color/holo_green_dark">
        <Button
            android:id="@+id/bt2"
            android:text="page2"
            android:layout_height="100dp"
            android:layout_width="100dp" />
    </RelativeLayout>
    <RelativeLayout
        android:id="@+id/rl1"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:background="@android:color/holo_red_dark">
        <Button
            android:id="@+id/bt1"
            android:text="page1"
            android:layout_height="100dp"
            android:layout_width="100dp" />
    </RelativeLayout>
</FrameLayout>

MainActivity:

        [Activity(Label = "Aniamtion", MainLauncher = true)]
        public class MainActivity : Activity
        {
            Button bt1,bt2;
            RelativeLayout rl1, rl2;
            int width;
            protected override void OnCreate(Bundle savedInstanceState)
        {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        getScreenWidth();//get the screen's width, so we can define how much the animation can translate
        initView();
        initListener();
        }

        private void getScreenWidth()
        {
            DisplayMetrics dm = new DisplayMetrics();
            WindowManager.DefaultDisplay.GetMetrics(dm);
            width = dm.WidthPixels;
        }

        private void initListener()
        {
            bt1.Click += toPage1;
            bt2.Click += toPage2;
        }

        private void toPage1(object sender, EventArgs e)
        {
            //use ObjectAnimator to complete it
            ObjectAnimator objectAnimator = ObjectAnimator.OfFloat(rl1, "translationX", 0, -width);
            objectAnimator.SetDuration(500);
            objectAnimator.Start();
            ObjectAnimator objectAnimator1 = ObjectAnimator.OfFloat(rl2, "translationX", width, 0);
            objectAnimator1.SetDuration(500);
            objectAnimator1.Start();
        }

        private void toPage2(object sender, EventArgs e)
        {
            ObjectAnimator objectAnimator = ObjectAnimator.OfFloat(rl1, "translationX", -width, 0);
            objectAnimator.SetDuration(500);
            objectAnimator.Start();
            ObjectAnimator objectAnimator1 = ObjectAnimator.OfFloat(rl2, "translationX", 0, width);
            objectAnimator1.SetDuration(500);
            objectAnimator1.Start();
        }

        private void initView()
        {
            bt1 = FindViewById<Button>(Resource.Id.bt1);
            bt2 = FindViewById<Button>(Resource.Id.bt2);
            rl1 = FindViewById<RelativeLayout>(Resource.Id.rl1);
            rl2 = FindViewById<RelativeLayout>(Resource.Id.rl2);
        }
        }

Second, about this OverridePendingTransition(Android.Resource.Animation.SlideInleft, Android.Resource.Animation.SlideInleft) method, the parameter you can use System resource, or you can custom it .

Update:

put this into your Resource->anim->SlideInRight, this is about customing animation in Xamarin.Android, it is same as Android, and this is document  which you can refer to

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
  <translate android:fromXDelta="50%p"
             android:toXDelta="0"
            android:duration="300"/>
</set>


问:
Segmentation fault in linux driver
I'm trying to write a linux driver. The kernel version is 2.4.18 and the distribution is Red Hat linux 8.0.

The code of my driver is:

```<code>#define LINUX

#include <linux/kernel.h> /* We're doing kernel work */
#include <linux/module.h> /* Specifically, a module */
#include <linux/fs.h>
#include <asm-i386/semaphore.h>
#include "rng.h"
#include <linux/random.h>
#include <linux/slab.h>

#define DEVICE_NAME "rng"
#define BUF_LEN 80

static int major;
int init_module();
void cleanup_module();
static int device_open(struct inode *, struct file *);
static int device_release(struct inode *, struct file *);

struct file_operations my_fops = {
  open: device_open,
  release: device_release,
};

/* Init and Cleanup */

int init_module() {
   SET_MODULE_OWNER(&my_fops);
   major = register_chrdev(0, DEVICE_NAME, &my_fops);
   return 0;
}

void cleanup_module() {

   int ret = unregister_chrdev(major, DEVICE_NAME);
   if (ret < 0)
       printk("Error in unregister_chrdev: %d\n", ret);

}

static int device_open(struct inode *inode, struct file *file) {
   file->f_op=&my_fops;
   return 1;
}

static int device_release(struct inode *inode, struct file *file) {
   return 0;
}
</code>```

And the code I'm using in order to test my driver is:

```<code>#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

int openTest() {
    int game1 = open("/dev/game1", O_RDONLY); // SEGMENTATION FAULT
    int retValue=1;

    close(game1);
    return retValue;
}

int main() {
    int res;
    if (openTest() < 1) {
       fprintf(stderr, "open didnt work\n");
    return -1;
    }
    fprintf(stderr, "everything works :)\n");
    return 0;
}
</code>```

In the code above, I'm getting a segmentation fault when I'm trying to open the device. Can somebody explain to me why I'm getting this segmentation fault? I really don't understand.

Thanks a lot!

答:
This line seems to be wrong file->f_op=&my_fops;

Basically when writing a linux driver operations are setup at build time itself.

Title: Segmentation fault in linux driver

Body:
I'm trying to write a linux driver. The kernel version is 2.4.18 and the distribution is Red Hat linux 8.0.

The code of my driver is:

#define LINUX

#include <linux/kernel.h> /* We're doing kernel work */
#include <linux/module.h> /* Specifically, a module */
#include <linux/fs.h>
#include <asm-i386/semaphore.h>
#include "rng.h"
#include <linux/random.h>
#include <linux/slab.h>

#define DEVICE_NAME "rng"
#define BUF_LEN 80

static int major;
int init_module();
void cleanup_module();
static int device_open(struct inode *, struct file *);
static int device_release(struct inode *, struct file *);

struct file_operations my_fops = {
  open: device_open,
  release: device_release,
};

/* Init and Cleanup */

int init_module() {
   SET_MODULE_OWNER(&my_fops);
   major = register_chrdev(0, DEVICE_NAME, &my_fops);
   return 0;
}

void cleanup_module() {

   int ret = unregister_chrdev(major, DEVICE_NAME);
   if (ret < 0)
       printk("Error in unregister_chrdev: %d\n", ret);

}

static int device_open(struct inode *inode, struct file *file) {
   file->f_op=&my_fops;
   return 1;
}

static int device_release(struct inode *inode, struct file *file) {
   return 0;
}

And the code I'm using in order to test my driver is:

#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

int openTest() {
    int game1 = open("/dev/game1", O_RDONLY); // SEGMENTATION FAULT
    int retValue=1;

    close(game1);
    return retValue;
}

int main() {
    int res;
    if (openTest() < 1) {
       fprintf(stderr, "open didnt work\n");
    return -1;
    }
    fprintf(stderr, "everything works :)\n");
    return 0;
}

In the code above, I'm getting a segmentation fault when I'm trying to open the device. Can somebody explain to me why I'm getting this segmentation fault? I really don't understand.

Thanks a lot!


问:
Specifying which activity to launch dynamically
I am developing a chat application.

Once logged in, the user should be navigated into the main page next time when he start the app. Like WhatsApp, it does not have a splash screen. So, Where do I do the check if the user has logged in or not next time ? I don't want to launch the login screen again if the user is already logged in.

Can I launch a service or something on the first time in which I can check which activity is shown next?

答:
Always open LoginActivity first. When the user logs in, store the unique token that determines the user’s current login session in shared preferences. And remove the token when user logs out.
So whenever user opens the app, check in login activity, if token exists, take the user to main activity and if it doesn’t, stay in login activity.</p>


问:
Window form execute a batch file
I am new to C# programming. I would like to have an application contains 1 text box and 1 submit button to exec a batch file.

The file is d:\XMLupdate.bat, but the program appends a number on the command line to the file
for example d:\XMLupdate.bat 10 or d:\XMLupdate.bat 15

Another thing is that the submission has to be validated to either 1 -999 or ALL

In Java way:

```<code> Runtime rt = Runtime.getRuntime();
                            Process pr = rt.exec(command);
                        }
                else{
                try{
int boxNumber = Integer.parseInt(jTextField1.getText());
                        if((boxNumber > 0) && boxNumber < 1000)
                            {
                                String arguments = jTextField1.getText();
                                String command = "CMD /C start d:/XMLupdate.bat " + arguments;
                                Runtime rt = Runtime.getRuntime();

rt.exec(command);

                            }
                         else{
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                            }
 }catch(Exception e)
                        {
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                        }
                    }
</code>```

However, the machine can not install JVM. Therefore, i have to build it in exe. My programming language is C#:

Here is the source code:

```<code>public partial class Form1 : Form
    {

        //private System.Windows.Forms.TextBox textBox1;  //Input text
        //private System.Windows.Forms.Button button1;   //Sumbit button

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //get text
           // string str_inputText = textBox1.Text;
            if (!(textBox1.Text.Equals("")))
            {
                  if (textBox1.Text.Equals("ALL"))
                      {
                          try
                          {

                              Process p = new Process();
                              p.StartInfo.FileName = "CMD.exe"; //Execute command
                              p.StartInfo.WorkingDirectory = "c:\temp"; //Diretory
                              p.StartInfo.Arguments = "xmlupdate.bat" + int.Parse(textBox1.Text);
                              p.Start();

                              p.WaitForExit();

                          }

                          catch (Exception ex)
                          {

                              Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
                              MessageBox.Show("Invalid value entered");

                          }
                      }

            }

        }

        private void textBox1_TextChanged(object sender, CancelEventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //Check the input number, only allow from 0 until 1000
            try
            {
                int numberEntered = int.Parse(textBox1.Text);
                if (numberEntered < 1 || numberEntered > 10)
                {
                   // e.Cancel = true;

                }
            }
            catch (FormatException)
            {
               // e.Cancel = true;
                MessageBox.Show("You need to enter a number between 1 and 999");
            }
        }

    }
</code>```

My main question is about process method,  can i execute it like that?  thanks

答:
You'll probably want to hook standard output and error for the process as well, redirecting them so you get notified of any output produced. It's useful to log it.

You also might want to hook standard input as well, but only if you know what input its expecting (you don't get an event fired when the process wants input: you have preemptively provide it.)

So if your batch file/child process wants input and you can't provide it, the child process will hang forever.

Title: Window form execute a batch file

Body:
I am new to C# programming. I would like to have an application contains 1 text box and 1 submit button to exec a batch file.

The file is d:\XMLupdate.bat, but the program appends a number on the command line to the file
for example d:\XMLupdate.bat 10 or d:\XMLupdate.bat 15

Another thing is that the submission has to be validated to either 1 -999 or ALL

In Java way:

 Runtime rt = Runtime.getRuntime();
                            Process pr = rt.exec(command);
                        }
                else{
                try{
int boxNumber = Integer.parseInt(jTextField1.getText());
                        if((boxNumber > 0) && boxNumber < 1000)
                            {
                                String arguments = jTextField1.getText();
                                String command = "CMD /C start d:/XMLupdate.bat " + arguments;
                                Runtime rt = Runtime.getRuntime();

rt.exec(command);

                            }
                         else{
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                            }
 }catch(Exception e)
                        {
                            JOptionPane.showMessageDialog(null, "Invalid value entered.");
                        }
                    }

However, the machine can not install JVM. Therefore, i have to build it in exe. My programming language is C#:

Here is the source code:

public partial class Form1 : Form
    {

        //private System.Windows.Forms.TextBox textBox1;  //Input text
        //private System.Windows.Forms.Button button1;   //Sumbit button

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //get text
           // string str_inputText = textBox1.Text;
            if (!(textBox1.Text.Equals("")))
            {
                  if (textBox1.Text.Equals("ALL"))
                      {
                          try
                          {

                              Process p = new Process();
                              p.StartInfo.FileName = "CMD.exe"; //Execute command
                              p.StartInfo.WorkingDirectory = "c:\temp"; //Diretory
                              p.StartInfo.Arguments = "xmlupdate.bat" + int.Parse(textBox1.Text);
                              p.Start();

                              p.WaitForExit();

                          }

                          catch (Exception ex)
                          {

                              Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
                              MessageBox.Show("Invalid value entered");

                          }
                      }

            }

        }

        private void textBox1_TextChanged(object sender, CancelEventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //Check the input number, only allow from 0 until 1000
            try
            {
                int numberEntered = int.Parse(textBox1.Text);
                if (numberEntered < 1 || numberEntered > 10)
                {
                   // e.Cancel = true;

                }
            }
            catch (FormatException)
            {
               // e.Cancel = true;
                MessageBox.Show("You need to enter a number between 1 and 999");
            }
        }

    }

My main question is about process method,  can i execute it like that?  thanks


问:
KeyboardAvoidingView with ScrollView
I am sort of new to react native and have one question that I did not find in react native documentation.

I am looking into this component KeyboardAvoidingView:
https://facebook.github.io/react-native/docs/keyboardavoidingview.html

Question is simple - has anyone to get KeyboardAvoidingView to work nicely with ScrollView? I have many TextInputs in one component (sum of TextInputs height is bigger then device height), and once the keyboard appears, I have various issues..

If I use View instead of ScrollView then everything is fine, but I can't use it, since I need more space than the device height..
I Couldn't find anything about Scroll in the KeyboardAvoidingView documentation.

Thanks.

答:
I also tried to find the solution on the internet, but I figured it out myself. I was able to make keyboardAvoidingView to work with ScrollView on the iPhone SE simulator.

I used padding type position, with keyboardVerticalOffset set to some higher value.  I hope this helps everybody who is trapped in this situation.

```<code>render() {
  return (
    <View style={...}>
      <ScrollView>
        <KeyboardAvoidingView
          style={{ flex: 1 }}
          keyboardVerticalOffset={100}
          behavior={"position"}
        >
          <TextInput style={styles.editInput} ... />
        </KeyboardAvoidingView>
      </ScrollView>
    </View>
  );
}
</code>```

Title: KeyboardAvoidingView with ScrollView

Body:
I also tried to find the solution on the internet, but I figured it out myself. I was able to make keyboardAvoidingView to work with ScrollView on the iPhone SE simulator.

I used padding type position, with keyboardVerticalOffset set to some higher value.  I hope this helps everybody who is trapped in this situation.

render() {
  return (
    <View style={...}>
      <ScrollView>
        <KeyboardAvoidingView
          style={{ flex: 1 }}
          keyboardVerticalOffset={100}
          behavior={"position"}
        >
          <TextInput style={styles.editInput} ... />
        </KeyboardAvoidingView>
      </ScrollView>
    </View>
  );
}


问:
Get containing path of lua file
I am wondering if there is a way of getting the path to the currently executing lua script file?

This is specifically not the current working directory, which could be entirely different. I know luafilesystem will let me get the current working directory, but it doesn't seem to be able to tell the current executing script file.

Thanks

EDIT:
I'm not running from the standard command line interpreter, I am executing the scripts from a C++ binary via luabind.

答:
I have written a function getScriptDir which uses the debug information like a few other people have suggested, but this one is going to work everytime (at least in Windows). But the thing is there are quite a few lines of code as it uses another function string.cut which i have created, which separates a string every given pattern, and puts it into a table.

```<code>function string.cut(s,pattern)
  if pattern == nil then pattern = " " end
  local cutstring = {}
  local i1 = 0
  repeat
    i2 = nil
    local i2 = string.find(s,pattern,i1+1)
    if i2 == nil then i2 = string.len(s)+1 end
    table.insert(cutstring,string.sub(s,i1+1,i2-1))
    i1 = i2
  until i2 == string.len(s)+1
  return cutstring
end

function getScriptDir(source)
  if source == nil then
    source = debug.getinfo(1).source
  end
  local pwd1 = (io.popen("echo %cd%"):read("*l")):gsub("\\","/")
  local pwd2 = source:sub(2):gsub("\\","/")
  local pwd = ""
  if pwd2:sub(2,3) == ":/" then
    pwd = pwd2:sub(1,pwd2:find("[^/]*%.lua")-1)
  else
    local path1 = string.cut(pwd1:sub(4),"/")
    local path2 = string.cut(pwd2,"/")
    for i = 1,#path2-1 do
      if path2[i] == ".." then
        table.remove(path1)
      else
        table.insert(path1,path2[i])
      end
    end
    pwd = pwd1:sub(1,3)
    for i = 1,#path1 do
      pwd = pwd..path1[i].."/"
    end
  end
  return pwd
end
</code>```

Note: if you want to use this function in another OS than Windows, you have to change the io.popen("echo %cd%") in the line 15 to whatever command gives you present working directory in your OS, e.g. io.popen("pwd") for Linux, and the pwd2:sub(2,3) == ":/" in the line 18 to whatever represents the root directory in your OS, e.g. pwd2:sub(1,1) == "/" for Linux.

Note2: if you don't provide the source variable to the function via debug.getinfo(1).source when calling it, then it will return the path to the directory of the file containing this function. Therefore, if you want to get the directory of a file which you called via dofile or loadfile, you will have to give it the source, like this: getScriptDir(debug.getinfo(1).source).

Title: Get containing path of lua file

Body:
I have written a function getScriptDir which uses the debug information like a few other people have suggested, but this one is going to work everytime (at least in Windows). But the thing is there are quite a few lines of code as it uses another function string.cut which i have created, which separates a string every given pattern, and puts it into a table.

function string.cut(s,pattern)
  if pattern == nil then pattern = " " end
  local cutstring = {}
  local i1 = 0
  repeat
    i2 = nil
    local i2 = string.find(s,pattern,i1+1)
    if i2 == nil then i2 = string.len(s)+1 end
    table.insert(cutstring,string.sub(s,i1+1,i2-1))
    i1 = i2
  until i2 == string.len(s)+1
  return cutstring
end

function getScriptDir(source)
  if source == nil then
    source = debug.getinfo(1).source
  end
  local pwd1 = (io.popen("echo %cd%"):read("*l")):gsub("\\","/")
  local pwd2 = source:sub(2):gsub("\\","/")
  local pwd = ""
  if pwd2:sub(2,3) == ":/" then
    pwd = pwd2:sub(1,pwd2:find("[^/]*%.lua")-1)
  else
    local path1 = string.cut(pwd1:sub(4),"/")
    local path2 = string.cut(pwd2,"/")
    for i = 1,#path2-1 do
      if path2[i] == ".." then
        table.remove(path1)
      else
        table.insert(path1,path2[i])
      end
    end
    pwd = pwd1:sub(1,3)
    for i = 1,#path1 do
      pwd = pwd..path1[i].."/"
    end
  end
  return pwd
end

Note: if you want to use this function in another OS than Windows, you have to change the io.popen("echo %cd%") in the line 15 to whatever command gives you present working directory in your OS, e.g. io.popen("pwd") for Linux, and the pwd2:sub(2,3) == ":/" in the line 18 to whatever represents the root directory in your OS, e.g. pwd2:sub(1,1) == "/" for Linux.

Note2: if you don't provide the source variable to the function via debug.getinfo(1).source when calling it, then it will return the path to the directory of the file containing this function. Therefore, if you want to get the directory of a file which you called via dofile or loadfile, you will have to give it the source, like this: getScriptDir(debug.getinfo(1).source).


问:
getting 400 null as error message for calling get method API with query parameters using rest template
I am trying to call one get method API by passing query parameters using rest template. I am passing the request in the proper format only, but I am getting the
 error as message as "400 null".

Following is the curl command which is working properly with POSTMAN:

```<code>curl -X GET \
  'http://localhost:8086/uaa/Groups?filter=identity_zone_id%20eq%20%22uaa%22' \
  -H 'authorization: Bearer eyJhbGciOiJIUzI1NiIsImtpZCI6ImxlZ2FjeS10b2tlbi1rZXkiLCJ0eXAiOiJKV1QifQ.eyJqdGkiOiJlMmEwYzgwN2M4ZDQ0YzhiYTE1ZmUwNGJmZjFmNzNlYyIsInN1YiI6IjBkZTZlZDhkLWU1OGMtNGExNC1iNTdmLWM5Mjk2Y2JlYjM3NSIsInNjb3BlIjpbImFwaXMucmVhZCIsIm9wZW5pZCIsImFwaXMud3JpdGUiLCJ1YWEuYWRtaW4iLCJzY2ltLndyaXRlIiwic2NpbS5yZWFkIiwidWFhLnVzZXIiXSwiY2xpZW50X2lkIjoiY2xpZW50IiwiY2lkIjoiY2xpZW50IiwiYXpwIjoiY2xpZW50IiwiZ3JhbnRfdHlwZSI6ImF1dGhvcml6YXRpb25fY29kZSIsInVzZXJfaWQiOiIwZGU2ZWQ4ZC1lNThjLTRhMTQtYjU3Zi1jOTI5NmNiZWIzNzUiLCJvcmlnaW4iOiJ1YWEiLCJ1c2VyX25hbWUiOiJtYXJpc3NhIiwiZW1haWwiOiJtYXJpc3NhQHRlc3Qub3JnIiwiYXV0aF90aW1lIjoxNTEyNDU1NzU4LCJyZXZfc2lnIjoiMWE5MzYzNWYiLCJpYXQiOjE1MTI0NTU3NTksImV4cCI6MTUxMjQ5ODk1OSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3VhYS9vYXV0aC90b2tlbiIsInppZCI6InVhYSIsImF1ZCI6WyJzY2ltIiwiYXBpcyIsInVhYSIsIm9wZW5pZCIsImNsaWVudCJdfQ.LbVu7inr5htyOHPyoN_KzIyFRZZiiiCV4xZHTCJZR30'
</code>```

Same format only I am passing the request through rest template. Following is the code which I am trying:

public String listGroup(String accessToken){

```<code>    String transactionUrl = "http://localhost:8086/uaa/Groups";
</code>```

HttpHeaders headers = new HttpHeaders();

```<code>    headers.set("Authorization", "Bearer "+accessToken);
       HttpEntity<String> entity = new HttpEntity<String>(headers);

    UriComponentsBuilder builder = UriComponentsBuilder
        .fromUriString(transactionUrl)
        // Add query parameter
        .queryParam("filter", "identity_zone_id+eq+%22uaa%22");

    RestTemplate restTemplate = new RestTemplate();
    //String response = restTemplate.getForObject(builder.toUriString(), String.class);
    System.out.println("URL===="+builder.toUriString());
    try {
        String param= URLDecoder.decode("filter=identity_zone_id%2Beq%2B%2522uaa%2522", "UTF-8");
        System.out.println("param=="+param+"\n");

        String decodedURL = URLDecoder.decode(builder.toUriString(), "UTF-8");
        System.out.println("decodedURL=="+decodedURL+"\n");
        System.out.println("----------------------------------------------------");

        System.out.println(URLDecoder.decode(builder.toUriString(), "UTF-8"));
        System.out.println("entity=="+entity);

    //String decodedURL = java.net.URLDecoder.decode(builder.toUriString(), "UTF-8");

    ResponseEntity<String> response =
            restTemplate.exchange(decodedURL,
                                  HttpMethod.GET, entity, String.class, param);
    return "Success-"+response;
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }

    return "error";
}
</code>```

Can anyone help me out in resolving this issue.

Thanks & Regards,

Shilpa Kulkarni

答:
Instead of mentioning the port in the url pass it using the URIComponentsBuilder</p>

```<code>String transactionUrl = "http://localhost/uaa/Groups";
UriComponentsBuilder builder = UriComponentsBuilder
        .fromUriString(transactionUrl)
        .port(8086)
        // Add query parameter
        .queryParam("filter", "identity_zone_id+eq+%22uaa%22");
</code>```

Body:
I am trying to call one get method API by passing query parameters using rest template. I am passing the request in the proper format only, but I am getting the
 error as message as "400 null".

Following is the curl command which is working properly with POSTMAN:

curl -X GET \
  'http://localhost:8086/uaa/Groups?filter=identity_zone_id%20eq%20%22uaa%22' \
  -H 'authorization: Bearer eyJhbGciOiJIUzI1NiIsImtpZCI6ImxlZ2FjeS10b2tlbi1rZXkiLCJ0eXAiOiJKV1QifQ.eyJqdGkiOiJlMmEwYzgwN2M4ZDQ0YzhiYTE1ZmUwNGJmZjFmNzNlYyIsInN1YiI6IjBkZTZlZDhkLWU1OGMtNGExNC1iNTdmLWM5Mjk2Y2JlYjM3NSIsInNjb3BlIjpbImFwaXMucmVhZCIsIm9wZW5pZCIsImFwaXMud3JpdGUiLCJ1YWEuYWRtaW4iLCJzY2ltLndyaXRlIiwic2NpbS5yZWFkIiwidWFhLnVzZXIiXSwiY2xpZW50X2lkIjoiY2xpZW50IiwiY2lkIjoiY2xpZW50IiwiYXpwIjoiY2xpZW50IiwiZ3JhbnRfdHlwZSI6ImF1dGhvcml6YXRpb25fY29kZSIsInVzZXJfaWQiOiIwZGU2ZWQ4ZC1lNThjLTRhMTQtYjU3Zi1jOTI5NmNiZWIzNzUiLCJvcmlnaW4iOiJ1YWEiLCJ1c2VyX25hbWUiOiJtYXJpc3NhIiwiZW1haWwiOiJtYXJpc3NhQHRlc3Qub3JnIiwiYXV0aF90aW1lIjoxNTEyNDU1NzU4LCJyZXZfc2lnIjoiMWE5MzYzNWYiLCJpYXQiOjE1MTI0NTU3NTksImV4cCI6MTUxMjQ5ODk1OSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3VhYS9vYXV0aC90b2tlbiIsInppZCI6InVhYSIsImF1ZCI6WyJzY2ltIiwiYXBpcyIsInVhYSIsIm9wZW5pZCIsImNsaWVudCJdfQ.LbVu7inr5htyOHPyoN_KzIyFRZZiiiCV4xZHTCJZR30'

Same format only I am passing the request through rest template. Following is the code which I am trying:

public String listGroup(String accessToken){

    String transactionUrl = "http://localhost:8086/uaa/Groups";

HttpHeaders headers = new HttpHeaders();

    headers.set("Authorization", "Bearer "+accessToken);
       HttpEntity<String> entity = new HttpEntity<String>(headers);

    UriComponentsBuilder builder = UriComponentsBuilder
        .fromUriString(transactionUrl)
        // Add query parameter
        .queryParam("filter", "identity_zone_id+eq+%22uaa%22");

    RestTemplate restTemplate = new RestTemplate();
    //String response = restTemplate.getForObject(builder.toUriString(), String.class);
    System.out.println("URL===="+builder.toUriString());
    try {
        String param= URLDecoder.decode("filter=identity_zone_id%2Beq%2B%2522uaa%2522", "UTF-8");
        System.out.println("param=="+param+"\n");

        String decodedURL = URLDecoder.decode(builder.toUriString(), "UTF-8");
        System.out.println("decodedURL=="+decodedURL+"\n");
        System.out.println("----------------------------------------------------");

        System.out.println(URLDecoder.decode(builder.toUriString(), "UTF-8"));
        System.out.println("entity=="+entity);

    //String decodedURL = java.net.URLDecoder.decode(builder.toUriString(), "UTF-8");

    ResponseEntity<String> response =
            restTemplate.exchange(decodedURL,
                                  HttpMethod.GET, entity, String.class, param);
    return "Success-"+response;
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }

    return "error";
}

Can anyone help me out in resolving this issue.

Thanks & Regards,

Shilpa Kulkarni

Body:
Instead of mentioning the port in the url pass it using the URIComponentsBuilder

String transactionUrl = "http://localhost/uaa/Groups";
UriComponentsBuilder builder = UriComponentsBuilder
        .fromUriString(transactionUrl)
        .port(8086)
        // Add query parameter
        .queryParam("filter", "identity_zone_id+eq+%22uaa%22");


问:
Bash-shell grammar issue about Ternary operator and printf function
```<code>cat file
chenghuanghuijia jidianzhong 100 E20128
pannybudaqiu gujihuihenwan -1
shuijiao buxihuan 20 E20138
huijiakan babamama 10
</code>```

I want get the result that when the line contains E2[0-9]*$ , the end of the line will be printed, if the line not contain E2[0-9]*$, the end of the line will be printed NULL or \n.

Here is my code:

```<code>awk '{printf("%s\n",($NF~/E2[0-9]*$/? "E2.*$" : NULL))}' file
</code>```

The output as below:

```<code>E2.*$

E2.*$
</code>```

but I want to print E20128 & E20138, So I verified my code with deleting " "

```<code>awk '{printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}' file
</code>```

Then it comes the error:

```<code>awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                    ^ syntax error
awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                               ^ syntax error
awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                                ^ syntax error
</code>```

So I think is the grammar issue of Ternary operator( _?x:y) or printf function.
please support me .

答:
If you just want to extract the E2..., a simple grep should be enough:

```<code>grep -o "E2[0-9]*$" file
</code>```

-o is the option for extracting the matched pattern

Body:
cat file
chenghuanghuijia jidianzhong 100 E20128
pannybudaqiu gujihuihenwan -1
shuijiao buxihuan 20 E20138
huijiakan babamama 10

I want get the result that when the line contains E2[0-9]*$ , the end of the line will be printed, if the line not contain E2[0-9]*$, the end of the line will be printed NULL or \n.

Here is my code:

awk '{printf("%s\n",($NF~/E2[0-9]*$/? "E2.*$" : NULL))}' file

The output as below:

E2.*$

E2.*$

but I want to print E20128 & E20138, So I verified my code with deleting " "

awk '{printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}' file

Then it comes the error:

awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                    ^ syntax error
awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                               ^ syntax error
awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                                ^ syntax error

So I think is the grammar issue of Ternary operator( _?x:y) or printf function.
please support me .

Body:
If you just want to extract the E2..., a simple grep should be enough:

grep -o "E2[0-9]*$" file

-o is the option for extracting the matched pattern


问:
Kibana timelion: How to add vertical line
I have a chart displayed in Kibana timelion and I want to add vertical line

For horizontal lines it can be used .value(200) or .static(200) - is there any possibility to add vertical one?

答:
I did this on 5.6.2. It's kind of hack way.

.es(q='date:[2017-12-01 TO 2017-12-02]', metric='min:Some_Test_Rate',
  timefield='date').add(10).bars(2).color(red).label('Specific Date'),

I have weekly data, so, I put the range like 2017-12-01 TO 2017-12-02. It just pick one date. (every Friday)

And display any data. Adjust with add(10) to make it looks better. (You can use max as well)

The others: .bars(2).color(red).label('Specific Date'), would be easy to understand.


问:
Does GWT have a widget which represent  HTML tag
I know that Flowpanel in GWT will be compiled into div and Horizontal/Vertical Panel will be compiled to table. Is there any widget available to represent span in GWT ?

Or

Is there a way to achieve it apart from GWT - HTML widget ?

答:
Using SpanElement you can achieve this.</p>

```<code>Element div = DOM.createDiv();

Element spanElement = DOM.createSpan();
DOM.appendChild(div, SpanElement.as(spanElement));
</code>```

Title: Does GWT have a widget which represent <span> HTML tag

Body:
Using SpanElement you can achieve this.

Element div = DOM.createDiv();

Element spanElement = DOM.createSpan();
DOM.appendChild(div, SpanElement.as(spanElement));


问:
Can cloudfront support websockets
I have my website Angular based hosted in AWS S3 bucket fronted by cloud front for SSL and caching etc.My URL's and route 53 entries point to CloudFront.
If I have to invoke a websocket [may be imagine its a publicly accessible websocket], wont it work ; i read cloud front doesn't support WebSockets?

I am invoking websockets from S3;Cloudfront is just infront of it.Does that help or this wont work at all?

答:
Amazon CloudFront doesn't support WebSockets at the moment so you cannot proxy WebSocket connections through CloudFront.

If you have EC2 instances running in your backend, use the Application Load Balancer which also allows adding AWS Issued SSL certificates and connect through WebSockets.

Title: Can cloudfront support websockets


问:
Attributed text in swift with line alignment
I have a label that has attributed text. I want to achieve something look like this image.
sample label

Subcategory and price text should be left and right alignment respectively and in a single line. There is some space before Subcategory text.
Please provide any sample code for this kind of attributed text.

答:
I think you need to use a paragraph style and add a head indent.

```<code>let style = NSMutableParagraphStyle()
style.headIndent = 100 // your value here
</code>```

Then add the paragraph style as the attribute.

```<code>[NSParagraphStyleAttributeName : style]
</code>```

Swift 4 & 5

```<code>[NSAttributedString.Key.paragraphStyle : style]
</code>```

Body:
I think you need to use a paragraph style and add a head indent.

let style = NSMutableParagraphStyle()
style.headIndent = 100 // your value here

Then add the paragraph style as the attribute.

[NSParagraphStyleAttributeName : style]

Swift 4 & 5

[NSAttributedString.Key.paragraphStyle : style]


问:
Python- Function object in class
```<code>class new:
    i=1
    def __init__(self):
        name='sakthi'

    def add(self,one,two):
         return one+two

k=new.add

print(k)
</code>```

When I execute the above program. I get function new.add at 0x0068E270 as output.

Can anyone help me to understand, what has happened and what kind of operation can I do with value k.

答:
The new.add value you're assigning to k is a function. In Python 2, it would have been a special "unbound method" object, but your output suggests you're using Python 3 (where unbound methods don't exist any more except conceptually).

Like any function, you can call k if you want, passing whatever values are appropriate for self, one and two. For instance, k("foo", 1, 2) (which will return 3).

Traditionally the self argument should be an instance of the new class, though in Python 3 that isn't enforced by anything (a check for this was the purpose of unbound method objects in Python 2). So passing a string in the example above worked fine, since self is not used in the function body for anything. (More complicated methods will usually fail if you pass an inappropriate argument as self.)

The usual way to call methods is to create an instance of a class first, then call the method on the instance. This causes the instance to be passed as the first argument automatically:

```<code>x = new()
x.add(1, 2) # returns 3, x got passed as self
</code>```

Title: Python- Function object in class

Body:
class new:
    i=1
    def __init__(self):
        name='sakthi'

    def add(self,one,two):
         return one+two

k=new.add

print(k)

When I execute the above program. I get function new.add at 0x0068E270 as output.

Can anyone help me to understand, what has happened and what kind of operation can I do with value k.

Body:
The new.add value you're assigning to k is a function. In Python 2, it would have been a special "unbound method" object, but your output suggests you're using Python 3 (where unbound methods don't exist any more except conceptually).

Like any function, you can call k if you want, passing whatever values are appropriate for self, one and two. For instance, k("foo", 1, 2) (which will return 3).

Traditionally the self argument should be an instance of the new class, though in Python 3 that isn't enforced by anything (a check for this was the purpose of unbound method objects in Python 2). So passing a string in the example above worked fine, since self is not used in the function body for anything. (More complicated methods will usually fail if you pass an inappropriate argument as self.)

The usual way to call methods is to create an instance of a class first, then call the method on the instance. This causes the instance to be passed as the first argument automatically:

x = new()
x.add(1, 2) # returns 3, x got passed as self


问:
How accurate is Android GPS?
I thought I have read somewhere that the accuracy of Android's GPS is about 10 cm?

Can anyone verify or correct this? Reason being is that my application I am trying to develop keeps track of locations a user has visited and it would help me out tremendously to know the margin of error I can expect.

答: Drop the "c" and you've got it about right.  Professional grade receivers such as Trimble's Nomad series can do 2-5m accuracy before post-processing, and 1-3m afterward, which requires downloading the points to a PC and correcting them based on satellite information received at nearby base stations, and that's with good satellite lock (perhaps 6 or more) and staying away from large vertical obstructions like trees and utility poles that deflect or block signals.  Licensed surveyors can get accuracy at the centimeter level only by using very expensive antennae (USD$10k range) and occupying the same point for hours, taking an average of thousands of readings.  And then as some posters here have said, vertical accuracy is still only about a third as good as horizontal.  I think 10m with a phone is not impossible given that it is probably indoors or in a car, or while moving, and considering satellite lock comes and goes.  The chip's primary duty is to supplement or correct info given to E911 dispatchers, and so it probably doesn't get much better than differentiating one single family home from another.</p>

Title: How accurate is Android GPS?


问:
How would I use ON DUPLICATE KEY UPDATE in my CodeIgniter model?
I have a CodeIgniter/PHP Model and I want to insert some data into the database.

However, I have this set in my 'raw' SQL query:

```<code>ON DUPLICATE KEY UPDATE duplicate=duplicate+1
</code>```

I am using CodeIgniter and am converting all my previous in-controller SQL queries to ActiveRecord. Is there any way to do this from within the ActiveRecord-based model?

Thanks!

Jack

答:
Using $this->db->query() and parameters, this is how I do it.  the first 4 parameters are for the insert part and the last three parameters are repeated for the on duplicate key update part.

```<code>$sql = "insert into application_committee ".
       "(application_id, member1_id, member2_id, member3_id) values (?, ?, ?, ?)".
       " on duplicate key update member1_id = ?, member2_id = ?, member3_id = ?";

$this->db->query($sql, array($appid, $member_1, $member_2, $member_3,
                 $member_1, $member_2, $member_3);
</code>```

Body:
I have a CodeIgniter/PHP Model and I want to insert some data into the database.

However, I have this set in my 'raw' SQL query:

ON DUPLICATE KEY UPDATE duplicate=duplicate+1

I am using CodeIgniter and am converting all my previous in-controller SQL queries to ActiveRecord. Is there any way to do this from within the ActiveRecord-based model?

Thanks!

Jack

Body:
Using $this->db->query() and parameters, this is how I do it.  the first 4 parameters are for the insert part and the last three parameters are repeated for the on duplicate key update part.

$sql = "insert into application_committee ".
       "(application_id, member1_id, member2_id, member3_id) values (?, ?, ?, ?)".
       " on duplicate key update member1_id = ?, member2_id = ?, member3_id = ?";

$this->db->query($sql, array($appid, $member_1, $member_2, $member_3,
                 $member_1, $member_2, $member_3);


问:
The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located
It's a WebApi project using VS2015.

Step to reproduce:

Create an empty WebApi project

Change Build output path from "bin\" to "bin\Debug\"

Run

Everything is working perfectly until I changed Build Output path from "bin\" to "bin\Debug\"
In fact, any Output path other than "bin\" won't work.

One little additional thing is that, having another output path to anywhere would work as long as I left a build in "bin\".

Please help providing solution to solve this.
I guess that'll cost problem on actual deployment.

答:
Here are my findings. I also faced this problem today's morning. I just added my current user to application pool on which application was running.

Steps:

Open IIS

Click on application pool

Select your application pool on which you are getting problem

Right Click -> advanced settings

Click on three dot icon beside the identiy

Now select custom account

Give your PC user name and Password

Save

Refresh your application.. and it will start working. There was some security issue for accessing dll.


问:
Hyperledger chaincode external service calls
Is it possible to make external service calls from chaincode? For example, if I need to lookup the current exchange rate or today's temperature using a public API how can I make that call from the chaincode?

If external calls are allowed then there is a chance of each node providing a different output (non-deterministic behavior). So how will consensus be reached?

答:
Yes. We can make external API calls. for ease i prefer node sdk instead of go lang for chaincode

Normally chain code is executed on one of the peers, and so is the external api call. Once the result is derived, the transaction is broadcast in the network. Other peers validate the transaction by chain of hash. So the API call is not executed on all validating peers.


问:
Is it possible to get an rss feed using javascript client side scripting only?
If I can't do this would the process for getting the data be:
1) Have my server get the rss data from the desired rss feed.
2) Have the server parse the data.  I don't know what rss looks like but I assume some parsing     is needed to display it for a user to read.
3) Send the data to the javascript client.</p>

答:
I believe u can.

Make an ajax request to php script, then that php script fetch the rss and then pass the result back to your javascript


问:
Indexing a numpy array
Consider the following scenario.

```<code>import numpy as np
x = np.random.randint(0,21,size=(10,64,64))
y = np.random.rand(10,21,64,64)

z = np.empty((10,64,64))

for i in range(10):
    for j in range(64):
        for k in range(64):
            z[i][j][k] = y[i][x[i][j][k]][j][k]
</code>```

What is the recommended (in terms of speed) way to implement this behavior using numpy indexing?

答:
It is exactly the aim of np.choose, You just need to rearange  y axis first.

```<code>In [6]: z2=np.choose(x,np.rollaxis(y,1))

In [7]: np.allclose(z,z2)
Out[7]: True
</code>```

It's 15x faster than the loop method.

Title: Indexing a numpy array

Body:
Consider the following scenario.

import numpy as np
x = np.random.randint(0,21,size=(10,64,64))
y = np.random.rand(10,21,64,64)

z = np.empty((10,64,64))

for i in range(10):
    for j in range(64):
        for k in range(64):
            z[i][j][k] = y[i][x[i][j][k]][j][k]

What is the recommended (in terms of speed) way to implement this behavior using numpy indexing?

Body:
It is exactly the aim of np.choose, You just need to rearange  y axis first.

In [6]: z2=np.choose(x,np.rollaxis(y,1))

In [7]: np.allclose(z,z2)
Out[7]: True

It's 15x faster than the loop method.


问:
How do I approach this machine learning/NLP context aware text classification project? See the description below
I am a newbie in machine learning and NLP. I need help for my college project. It's’ actually a subtask of a major project. Description is as follow:

It is a classification problem. I will be given an item and I have to predict the shop type from where the item can be bought.

Examples:

    Item       Class-label (shop-type)

    Pencil -> book store

    Beer -> bar

    Cash -> ATM

    Tube Light -> electronics store

    Medicine -> pharmacy

I am given many different class labels like stationary_shop,book_store,bakery,pharmacy etc.(around 50 labels)

Problems faced-

1. I don’t have much bigger dataset. I built a small dataset all by myself.

2. I don’t know much about machine learning and NLP techniques like how to approach this problem.

3. How to make correct prediction? For example if I have (pencil,book_store) in my dataset and it is given sharpener as input it must predict the label as book_store since sharpener is closely related to pencil.

My approaches:

I started with a small dataset and then used datamuse api for extending it by finding related words for a given word. For eg. I extracted all words related to pencil from the API and tagged them with the same label book_store. Then I used fastText for generating a prediction model but  I am not getting expected results.

Small Dataset

Dataset format : (example,class_label)

soap,department_store

pencil,book_store

pen,book_store

tea,department_store

coffee,department_store

bulb,electronics_store

battery,electronics_store

tubelight,electronics_store

medicine,pharmacy

book,book_store

money,bank

cash,atm

flowers,florist

fruits,grocery_or_supermarket

cake,bakery

clothes,clothing_store

paper,book_store

jewellery,jewelry_store

shampoo,department_store

oil,department_store

sugar,department_store

beer,bar

whisky,bar

alcohol,bar

haircut,beauty_salon

coffee,cafe

sandwich,cafe

pastry,bakery

suit,clothing_store

shoes,shoe_store

sofa,furniture_store

chair,furniture_store

bed,furniture_store

petrol,gas_station

diesel,gas_station

tools,hardware_store

pipe,hardware_store

tank,hardware_store

washing,laundry

drycleaning,laundry

necklace,jewelry_store

ring,jewelry_store

ornament,jewelry_store

dinner,restaurant

lunch,restaurant

pet,veterinary_care

chips,department_store

答:
As your problem is based on classification of text data, first you have divide training(70%) and testing data(30%) then first look for (example,class_label) your dataset format...

Step(1)---here class_label are also in text format so you have to label them numeric...for example--> department_store==1,book_store==2,
electronics_store==3,shoe_store==4....and so on, label all of them in this format...

Step(2)---after this look for your example from (example,class_label) dataset format as these examples are also in text format so we have to make them numeric as well (remember machine learning algorithm works on numeric data only so we have to convert all text data into numeric format).
here to work on text data use CountVectorizer()..give a look at these document these link will guide you how to perform feature extraction

after extracting features from text data use any algorithm for classification (remember you have to perform multi class classification as your dataset classes are multiple....all of the algorithm work on binary classification so you have to use (One Vs one) or (one vs rest)
give a look at these link

I will prefer support vector machine(SVM) for training(70% of your total data) for these as you have small dataset.
SVM
For testing perform step(2) on remaining (30% of your total data)


问:
Python: Non diagonal elements of a matrix to 0
What is the quickest way to convert the non-diagonal elements of a square symmetrical numpy ndarray to 0?</p>

答:
I'd check out the speed of saving the diagonal away, then zap the matrix, then restore the diagonal:

```<code>n = len(mat)
d = mat.ravel()[::n+1]
values = d.copy()
mat[:,:] = 0
d[:] = values
</code>```

if the matrix is not huge may be however that just allocating a new one is faster

```<code>mat = numpy.diag(numpy.diag(mat))
</code>```

Body:
I'd check out the speed of saving the diagonal away, then zap the matrix, then restore the diagonal:

n = len(mat)
d = mat.ravel()[::n+1]
values = d.copy()
mat[:,:] = 0
d[:] = values

if the matrix is not huge may be however that just allocating a new one is faster

mat = numpy.diag(numpy.diag(mat))


问:
How to get the userId of a newly registered user in ASP.NET MVC?
Im trying to get the userId stored in the AspNetUsers table and store it in my Student table during the registration process.

How do I get the userId of the newly created user (not the logged in user) from the AspnetUsers table and store it in a seperate table DURING the registration process?

My controller:

```<code>public ActionResult Create(ExpandedUserDTO paramExpandedUserDTO)
{
    try
    {
        if (paramExpandedUserDTO == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        var Email = paramExpandedUserDTO.Email.Trim();
        var UserName = paramExpandedUserDTO.Email.Trim();
        var Password = paramExpandedUserDTO.Password.Trim();

        UserName = Email.ToLower();

        // Create user

        var objNewAdminUser = new ApplicationUser { UserName = UserName, Email = Email};

        var AdminUserCreateResult = UserManager.Create(objNewAdminUser, Password);

        if (AdminUserCreateResult.Succeeded == true)
        {
            string strNewRole = Convert.ToString(Request.Form["Roles"]);

            if (strNewRole != "0")
            {
                // Put user in role
                UserManager.AddToRole(objNewAdminUser.Id, strNewRole);

                //Put user in student table
                if (strNewRole == "Student")
                {

                }
            }

            return Redirect("~/Admin");
        }
    }
    catch (Exception ex)
    {
        ViewBag.Roles = GetAllRolesAsSelectList();
        return View("Create");
    }
}
</code>```

答:
If you create the user an Id is created automatically for you.</p>

```<code> var objNewAdminUser = new ApplicationUser { UserName = UserName, Email = Email};
 var userId = objNewAdminUser.Id //18479b0a-17cd-4a76-9e9e-d90a8480617b
</code>```

Body:
Im trying to get the userId stored in the AspNetUsers table and store it in my Student table during the registration process.

How do I get the userId of the newly created user (not the logged in user) from the AspnetUsers table and store it in a seperate table DURING the registration process?

My controller:

public ActionResult Create(ExpandedUserDTO paramExpandedUserDTO)
{
    try
    {
        if (paramExpandedUserDTO == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        var Email = paramExpandedUserDTO.Email.Trim();
        var UserName = paramExpandedUserDTO.Email.Trim();
        var Password = paramExpandedUserDTO.Password.Trim();

        UserName = Email.ToLower();

        // Create user

        var objNewAdminUser = new ApplicationUser { UserName = UserName, Email = Email};

        var AdminUserCreateResult = UserManager.Create(objNewAdminUser, Password);

        if (AdminUserCreateResult.Succeeded == true)
        {
            string strNewRole = Convert.ToString(Request.Form["Roles"]);

            if (strNewRole != "0")
            {
                // Put user in role
                UserManager.AddToRole(objNewAdminUser.Id, strNewRole);

                //Put user in student table
                if (strNewRole == "Student")
                {

                }
            }

            return Redirect("~/Admin");
        }
    }
    catch (Exception ex)
    {
        ViewBag.Roles = GetAllRolesAsSelectList();
        return View("Create");
    }
}

Body:
If you create the user an Id is created automatically for you.

 var objNewAdminUser = new ApplicationUser { UserName = UserName, Email = Email};
 var userId = objNewAdminUser.Id //18479b0a-17cd-4a76-9e9e-d90a8480617b