问:
Building wxWidgets 3.1.0 on CLion (Ubuntu)
I am currently trying to build wxWidgets-3.1.0 on a CLion 1.3 project. I use Ubuntu 16.04 (64 bit). Basically, I edited the CMakeLists.txt file like this:

```<code>cmake_minimum_required(VERSION 3.5)
project(WxProva)

set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules"
${CMAKE_MODULE_PATH})

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

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

find_package(wxWidgets)
include_directories(${wxWidgets_INCLUDE_DIRS})
target_link_libraries(WxProva ${wxWidgets_LIBRARIES})
</code>```

The "External Libraries" section also shows me wxWidgets, but when it comes to write some lines on my main.cpp, everything related with the library seems to be unreachable by the compiler (it's all written in red, like an error). Anyway, if I try to compile, that's the result:

```<code>/home/federico/ClionProjects/WxProva/main.cpp:2:35: fatal error: wxWidgets-3.1.0/include: File o directory non esistente
compilation terminated.
</code>```

Which is like "File or directory doesn't exists."
How can I fix this?

答:
After some experiments here solution. You can just copy it and change some information and ready to build and run.

```<code>cmake_minimum_required(VERSION 3.7)
project(Your_Project_Name) //any name for your project

set(CMAKE_CXX_STANDARD 11)

set(wxWidgets_ROOT_DIR </usr/include/wx-3.0-unofficial>) // here I am  giving where to search for wxwidgets library. it can be different for you
set(wxWidgets_CONFIGURATION mswu)
find_package(wxWidgets COMPONENTS core base REQUIRED)
include(${wxWidgets_USE_FILE})

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

target_link_libraries(FirstC ${wxWidgets_LIBRARIES})
</code>```

For more Information read https://wiki.wxwidgets.org/CMake

Edit 1
Here you shouldn't even add some compile and link config (wx-config --cxxflags and wx-config --libs) as it is necessary in NetBeans

Body:
I am currently trying to build wxWidgets-3.1.0 on a CLion 1.3 project. I use Ubuntu 16.04 (64 bit). Basically, I edited the CMakeLists.txt file like this:

cmake_minimum_required(VERSION 3.5)
project(WxProva)

set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules"
${CMAKE_MODULE_PATH})

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

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

find_package(wxWidgets)
include_directories(${wxWidgets_INCLUDE_DIRS})
target_link_libraries(WxProva ${wxWidgets_LIBRARIES})

The "External Libraries" section also shows me wxWidgets, but when it comes to write some lines on my main.cpp, everything related with the library seems to be unreachable by the compiler (it's all written in red, like an error). Anyway, if I try to compile, that's the result:

/home/federico/ClionProjects/WxProva/main.cpp:2:35: fatal error: wxWidgets-3.1.0/include: File o directory non esistente
compilation terminated.

Which is like "File or directory doesn't exists."
How can I fix this?

Body:
After some experiments here solution. You can just copy it and change some information and ready to build and run.

cmake_minimum_required(VERSION 3.7)
project(Your_Project_Name) //any name for your project

set(CMAKE_CXX_STANDARD 11)

set(wxWidgets_ROOT_DIR </usr/include/wx-3.0-unofficial>) // here I am  giving where to search for wxwidgets library. it can be different for you
set(wxWidgets_CONFIGURATION mswu)
find_package(wxWidgets COMPONENTS core base REQUIRED)
include(${wxWidgets_USE_FILE})

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

target_link_libraries(FirstC ${wxWidgets_LIBRARIES})

For more Information read https://wiki.wxwidgets.org/CMake

Edit 1
Here you shouldn't even add some compile and link config (wx-config --cxxflags and wx-config --libs) as it is necessary in NetBeans


来源: stackexchange

问:
Find a pair in a vector by its first value
I have a vector which contains several pairs(INT,INT).
I want to search for a particular but I only have one key of that pair.
How should I search for the second key?</p>

答:
You can use the following algorithm (pseudo code):

```<code>let vec be the input vector
let key be the value that you are searching
for each pair p in vec
    let p_1 be p.first
    if p_1 == key
        return you have found the key
</code>```

Here is a functional approach to extract re-usable components:

```<code>find_if(beg, end, predicate):
    let beg be an iterator to the beginning of a sequence
    let end be an iterator to the end of a sequence
    let predicate be a function from container element to boolean
    for each iterator in beg...end
        let element be what the iterator points to
        if predicate(element)
            return iterator
</code>```

Now, you can define a custom predicate function:

```<code>my_predicate(p):
    let p be a pair
    let p_1 be p.first
    let key be the value that you are searching
    return p_1 == key
</code>```

And use find_if:

```<code>let vec be the input vector
found_iterator = find_if(begin(vec), end(vec), my_predicate)
</code>```

It just so happens that the C++ standard library contains std::find_if with pretty much identical interface to my pseudo code.

ContentLicense: CC BY-SA 3.0

Body:
You can use the following algorithm (pseudo code):

let vec be the input vector
let key be the value that you are searching
for each pair p in vec
    let p_1 be p.first
    if p_1 == key
        return you have found the key

Here is a functional approach to extract re-usable components:

find_if(beg, end, predicate):
    let beg be an iterator to the beginning of a sequence
    let end be an iterator to the end of a sequence
    let predicate be a function from container element to boolean
    for each iterator in beg...end
        let element be what the iterator points to
        if predicate(element)
            return iterator

Now, you can define a custom predicate function:

my_predicate(p):
    let p be a pair
    let p_1 be p.first
    let key be the value that you are searching
    return p_1 == key

And use find_if:

let vec be the input vector
found_iterator = find_if(begin(vec), end(vec), my_predicate)

It just so happens that the C++ standard library contains std::find_if with pretty much identical interface to my pseudo code.


问:
Express: How to pass app-instance to routes from a different file?
I want to split up my routes into different files, where one file contains all routes and the other one the corresponding actions. I currently have a solution to achieve this, however I need to make the app-instance global to be able to access it in the actions.
My current setup looks like this:

app.js:

```<code>var express   = require('express');
var app       = express.createServer();
var routes    = require('./routes');

var controllers = require('./controllers');
routes.setup(app, controllers);

app.listen(3000, function() {
  console.log('Application is listening on port 3000');
});
</code>```

routes.js:

```<code>exports.setup = function(app, controllers) {

  app.get('/', controllers.index);
  app.get('/posts', controllers.posts.index);
  app.get('/posts/:post', controllers.posts.show);
  // etc.

};
</code>```

controllers/index.js:

```<code>exports.posts = require('./posts');

exports.index = function(req, res) {
  // code
};
</code>```

controllers/posts.js:

```<code>exports.index = function(req, res) {
  // code
};

exports.show = function(req, res) {
  // code
};
</code>```

However, this setup has a big issue: I have a database- and an app-instance I need to pass to the actions (controllers/*.js). The only option I could think of, is making both variables global which isn't really a solution. I want to separate routes from the actions because I have a lot of routes and want them in a central place.

What's the best way to pass variables to the actions but separate the actions from the routes?

答:
Or just do that:

```<code>var app = req.app
</code>```

inside the Middleware you are using for these routes. Like that:

```<code>router.use( (req,res,next) => {
    app = req.app;
    next();
});
</code>```

Body:
I want to split up my routes into different files, where one file contains all routes and the other one the corresponding actions. I currently have a solution to achieve this, however I need to make the app-instance global to be able to access it in the actions.
My current setup looks like this:

app.js:

var express   = require('express');
var app       = express.createServer();
var routes    = require('./routes');

var controllers = require('./controllers');
routes.setup(app, controllers);

app.listen(3000, function() {
  console.log('Application is listening on port 3000');
});

routes.js:

exports.setup = function(app, controllers) {

  app.get('/', controllers.index);
  app.get('/posts', controllers.posts.index);
  app.get('/posts/:post', controllers.posts.show);
  // etc.

};

controllers/index.js:

exports.posts = require('./posts');

exports.index = function(req, res) {
  // code
};

controllers/posts.js:

exports.index = function(req, res) {
  // code
};

exports.show = function(req, res) {
  // code
};

However, this setup has a big issue: I have a database- and an app-instance I need to pass to the actions (controllers/*.js). The only option I could think of, is making both variables global which isn't really a solution. I want to separate routes from the actions because I have a lot of routes and want them in a central place.

What's the best way to pass variables to the actions but separate the actions from the routes?

Body:
Or just do that:

var app = req.app

inside the Middleware you are using for these routes. Like that:

router.use( (req,res,next) => {
    app = req.app;
    next();
});


问:
NFC Tags not detected | CoreNFC
I created an app using CoreNFC to read NFC tags, I managed to get the app run without any errors, but it doesn't seem to recognise my tags, I've tried it with two tags of same type and brand which I got it from Amazon for few a bucks, and I tried my local train card(NFC Card) which has no effect too... What might be the problem? I've attached the screenshot of the app, please take a look! Screenshot of my App, nothing happens beyond this point, and nothing on the console too.

Thanks,

Hari

```<code>func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
    print("ERROR")

}

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
    print(messages)
}

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let session = NFCNDEFReaderSession(delegate: self as NFCNDEFReaderSessionDelegate, queue: nil, invalidateAfterFirstRead: false)
    session.begin()

    return true
}
</code>```

答:
At the moment, CoreNFC only supports NFC tags in NDEF format. Therefore, most of your NFC cards (credit card, id card, members cards, etc.) won't work as they most probably do not comply to this format. If you want to test CoreNFC you need to use dedicated NDEF tags.

From the CoreNFC documentation:

Using Core NFC, you can read Near Field Communication (NFC) tags of types 1 through 5 that contain data in the NFC Data Exchange Format (NDEF).

Title: NFC Tags not detected | CoreNFC

Body:
I created an app using CoreNFC to read NFC tags, I managed to get the app run without any errors, but it doesn't seem to recognise my tags, I've tried it with two tags of same type and brand which I got it from Amazon for few a bucks, and I tried my local train card(NFC Card) which has no effect too... What might be the problem? I've attached the screenshot of the app, please take a look! Screenshot of my App, nothing happens beyond this point, and nothing on the console too.

Thanks,

Hari

func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
    print("ERROR")

}

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
    print(messages)
}

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let session = NFCNDEFReaderSession(delegate: self as NFCNDEFReaderSessionDelegate, queue: nil, invalidateAfterFirstRead: false)
    session.begin()

    return true
}


问:
unity3d - android file reading error
I have a problem with reading files on aandroid after building apk file. When I try to read data form:

*jar:file:///data/app/appname/base.apk!/assets/Levels/level0.xml,*

game will crush with error message: URI scheme must start with a letter and must consist of one of alphabet, digits, '+', '-' or '.' character.

Here is part of code that throws an exception:

```<code>void start()
{
        //some part of code
        level = Level.loadLevel(Path.Combine(Application.streamingAssetsPath , Path.Combine("Levels", "level0.xml")));
        //some part of code
}
public static Level loadLevel(string filePath)
{
        Level result = new Level();
        XmlDocument doc = new XmlDocument();
        doc.Load(filePath);
        //some part of code
}
</code>```

答:
Since files are contained inside a compressed .jar file, you have to use Unity WWW class to read them. It should look like this:

```<code>public IEnumerator loadLevel(string filePath)
{
    WWW www = new WWW(filePath);
    yield return www;
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(www.text);
    [...]
}
</code>```

Hope this helps,

Title: unity3d - android file reading error

Body:
I have a problem with reading files on aandroid after building apk file. When I try to read data form:

*jar:file:///data/app/appname/base.apk!/assets/Levels/level0.xml,*

game will crush with error message: URI scheme must start with a letter and must consist of one of alphabet, digits, '+', '-' or '.' character.

Here is part of code that throws an exception:

void start()
{
        //some part of code
        level = Level.loadLevel(Path.Combine(Application.streamingAssetsPath , Path.Combine("Levels", "level0.xml")));
        //some part of code
}
public static Level loadLevel(string filePath)
{
        Level result = new Level();
        XmlDocument doc = new XmlDocument();
        doc.Load(filePath);
        //some part of code
}

Body:
Since files are contained inside a compressed .jar file, you have to use Unity WWW class to read them. It should look like this:

public IEnumerator loadLevel(string filePath)
{
    WWW www = new WWW(filePath);
    yield return www;
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(www.text);
    [...]
}

Hope this helps,


问:
Laravel form not sending request of dynamically generated content
I have a form like this:

```<code><form class="form-horizontal" role="form" method="POST" name="myform" id="myform" action="{{ url('/mypage/') }}">
        {{ csrf_field() }}
<div id="somecontent">
</div>
<div id="abutton">
</div>
</form>
</code>```

Then some Jquery like this:

```<code> $('#somecontent').html('<select class="form-control" id="myselect"  form="my"><option value="1">Hello</option><option value="2">World</option></select>');
</code>```

And then I add a button like this:

```<code>button = $('<button type="submit" form="myform" class="btn btn-theme">Send</button>');

$('#abutton').html(button);
</code>```

And I also change the action dynamically:

```<code> $("#myform").attr("action","/mypage/" + item_id);
</code>```

Then I got this in the web file:

```<code>Route::post('/mypage/{item_id}','mycontroller@do_something');
</code>```

And then do this in the controller:

```<code>public function do_something($item_id,Request $request){
dd($request);
}
</code>```

But the $request is empty, it does not contain the value selected in the dynamically generated select.

Any ideas why?

答:
you haven't added name attribute of select, add name attribute and see it will populate into $request.

Try below code.

```<code> $('#somecontent').html('<select name="select_name" class="form-control" id="myselect"  form="my"><option value="1">Hello</option><option value="2">World</option></select>');
</code>```

Body:
I have a form like this:

<form class="form-horizontal" role="form" method="POST" name="myform" id="myform" action="{{ url('/mypage/') }}">
        {{ csrf_field() }}

</form>

Then some Jquery like this:

 $('#somecontent').html('<select class="form-control" id="myselect"  form="my"><option value="1">Hello</option><option value="2">World</option></select>');

And then I add a button like this:

button = $('<button type="submit" form="myform" class="btn btn-theme">Send</button>');

$('#abutton').html(button);

And I also change the action dynamically:

 $("#myform").attr("action","/mypage/" + item_id);

Then I got this in the web file:

Route::post('/mypage/{item_id}','mycontroller@do_something');

And then do this in the controller:

public function do_something($item_id,Request $request){
dd($request);
}

But the $request is empty, it does not contain the value selected in the dynamically generated select.

Any ideas why?

Body:
you haven't added name attribute of select, add name attribute and see it will populate into $request.

Try below code.

 $('#somecontent').html('<select name="select_name" class="form-control" id="myselect"  form="my"><option value="1">Hello</option><option value="2">World</option></select>');


问:
Load html template script on button click
I have a template
```

Here is an example of an external script file loading on a click event: Jquery load script on click event.

Is there a way to load the template script in my html on a click event?

答:
If you want to run a whole javascript file do this

```<code>var script = document.createElement("script");
script.src = "url"; // replace url with actual url of script
document.head.appendChild(script);
</code>```

To add a small script from string form

```<code>var script = document.createElement("script");
script.innerHtml = "script"; // replace script with actual script
document.head.appendChild(script);
</code>```

You could also just create a function

```<code>function onClick() {
    // insert your code
}
</code>```

And you can call it by doing onClick(); using JavaScript

You can also call it from a button by doing <button onclick="onClick()">Click Me</button>

Finally you can also call it from a anchor element by doing Click Me

Body:
I have a template

Here is an example of an external script file loading on a click event: Jquery load script on click event.

Is there a way to load the template script in my html on a click event?

Body:
If you want to run a whole javascript file do this

var script = document.createElement("script");
script.src = "url"; // replace url with actual url of script
document.head.appendChild(script);

To add a small script from string form

var script = document.createElement("script");
script.innerHtml = "script"; // replace script with actual script
document.head.appendChild(script);

You could also just create a function

function onClick() {
    // insert your code
}

And you can call it by doing onClick(); using JavaScript

You can also call it from a button by doing <button onclick="onClick()">Click Me</button>

Finally you can also call it from a anchor element by doing <a href="javascript:onClick()">Click Me</a>


问:
a-entity text only showing when created by the Inspector
I've been trying to do something super simple, such as displaying some text. It was working a couple of hours back, but now it its not. This is the exact code:

```<code>    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
     <script src="https://aframe.io/releases/0.5.0/aframe.min.js" async></script>
    <meta name="description" content="Science Labs for Homeschoolers in Virtual Reality">

</head>
<body>

<a-scene>
  <a-assets>
    <img id="groundTexture" src="https://cdn.aframe.io/a-painter/images/floor.jpg">
    <img id="skyTexture" src="https://cdn.aframe.io/a-painter/images/sky.jpg">
  </a-assets>
  <a-cylinder id="ground" src="#groundTexture" radius="30" height="0.1"></a-cylinder>
  <a-sky id="background" src="#skyTexture" theta-length="90" radius="30"></a-sky>
<a-entity position="0.768 1.04 -3.442" rotation="0 0 0" scale="10 10 2" visible="true" text="value:Hello Berry Berry;"></a-entity>
</a-scene>
<script type="text/javascript" src="build/client/bundle.js"></script></body>

</html>
</code>```

It's just a testing project. Currently using nodejs v7.10.0 with express 4.15.3 with webpack. Using Google Chrome 58.0.3 and Edge 15.

Nothing fancy, just serving the index.html file (what you're seeing above).

No matter what, I can't see the text (Only from this file). I've also tried:

Looking around the scene.

Setting the text double sided to spot it.

Copying the exact asset from the inspector to my code.

Changing the position

Changing the text scale.

This is what's resulting:

As you can see, there's no sign of the text (when it should look big due to the scale settings).
Any ideas? Thank you very much!

Edit:
Here is with 0.5 0.5 0.5

Side note: I'm having problems uploading images to StackOverflow: http://i66.tinypic.com/a47l2b.jpg

Here's with 10 10 10:
http://i67.tinypic.com/npfd50.jpg

In addition, I can't move the a-entity "graphically" (With the red, black, yellow arrows), but I can if I change them in the properties panel.

Edit 2:
Here is a code share in Glitch:
https://glitch.com/edit/#!/nebulous-pail?path=index.html:1:0

答:
Well. It seems that the problem, so far, was loading A-Frame asynchronously:

```<code><script src="https://aframe.io/releases/0.5.0/aframe.min.js" async></script>
</code>```

We need to omit the "async" attribute for it to work:

```<code> <script src="https://aframe.io/releases/0.5.0/aframe.min.js"></script>
</code>```

My theory would be that it is not gracefully upgrading the element after it has been loaded.

I even tried adding the text as a mixin, but it will not work unless A-Frame has been loaded first.

Body:
I've been trying to do something super simple, such as displaying some text. It was working a couple of hours back, but now it its not. This is the exact code:

    <!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <meta name="description" content="Science Labs for Homeschoolers in Virtual Reality">

It's just a testing project. Currently using nodejs v7.10.0 with express 4.15.3 with webpack. Using Google Chrome 58.0.3 and Edge 15.

Nothing fancy, just serving the index.html file (what you're seeing above).

No matter what, I can't see the text (Only from this file). I've also tried:

Looking around the scene.

Setting the text double sided to spot it.

Copying the exact asset from the inspector to my code.

Changing the position

Changing the text scale.

This is what's resulting:

As you can see, there's no sign of the text (when it should look big due to the scale settings).
Any ideas? Thank you very much!

Edit:
Here is with 0.5 0.5 0.5

Side note: I'm having problems uploading images to StackOverflow: http://i66.tinypic.com/a47l2b.jpg

Here's with 10 10 10:
http://i67.tinypic.com/npfd50.jpg

In addition, I can't move the a-entity "graphically" (With the red, black, yellow arrows), but I can if I change them in the properties panel.

Edit 2:
Here is a code share in Glitch:
https://glitch.com/edit/#!/nebulous-pail?path=index.html:1:0

Body:
Well. It seems that the problem, so far, was loading A-Frame asynchronously:

<script src="https://aframe.io/releases/0.5.0/aframe.min.js" async></script>

We need to omit the "async" attribute for it to work:

 <script src="https://aframe.io/releases/0.5.0/aframe.min.js"></script>

My theory would be that it is not gracefully upgrading the element after it has been loaded.

I even tried adding the text as a mixin, but it will not work unless A-Frame has been loaded first.


问:
How to store p12 file in Git repository using Fastlane?
I'm using Fastlane Match to manage my certificates and provisionings on iOS.
This tool is so cool that I would like to inspire me to manage my push notification certicates and p12.

I'm using pem to create the p12 file, and I would like to store it, in my git repo, with the others certificates.

I have no idea how to do :

create my own fastfile?

create my own fastlane plugin?

答:
In order to create a Fastfile, you can run fastlane init from your project directory. To create a fastlane plug_in, you can run fastlane new_plugin from your project directory.

Here are instructions to create a new plugin.

Here are instructions to set up your project for fastlane.

ContentLicense: CC BY-SA 4.0


问:
SQL - string combine based on id
Need suggestion to split string in table 1, match its Ids with table 2 and concatenate the values.

Table - 1

```<code>Id  Tbl1Col
1   2
2   2,4
3
4   6
5   3
</code>```

Table - 2

```<code>Id  Tbl2Col
1   E
2   F
3   M
4   U
5   P
6   C
7   N
8   G
</code>```

Query -

```<code>SELECT T2.Tbl2Col
FROM Table1 AS T1
LEFT JOIN Table2 AS T2 WHERE T1.Tbl1Col= T2.Id
WHERE T1.Id = @Id
</code>```

Now If @Id = 1, Output is F -- works fine

Now If @Id = 2, Output should be FU -- should not be F,U

答:
```<code>create table dbo.Table01 (
Id int
, Col varchar(100)
);

create table dbo.Table02 (
Id int
, Col varchar(100)
);

insert into dbo.Table01 (Id, Col)
values (1, '2'), (2, '2, 4');

insert into dbo.Table02 (Id, Col)
values (1, 'E'), (2, 'F'), (4, 'U');

select
t.Id
, replace(STRING_AGG (t02.Col, ','), ',', '') as StringAgg
from dbo.Table01 t
cross apply string_split (t.Col, ',') as ss
inner join dbo.Table02 t02 on ss.value = t02.Id
group by t.id
</code>```

Title: SQL - string combine based on id

Body:
Need suggestion to split string in table 1, match its Ids with table 2 and concatenate the values.

Table - 1

Id  Tbl1Col
1   2
2   2,4
3
4   6
5   3

Table - 2

Id  Tbl2Col
1   E
2   F
3   M
4   U
5   P
6   C
7   N
8   G

Query -

SELECT T2.Tbl2Col
FROM Table1 AS T1
LEFT JOIN Table2 AS T2 WHERE T1.Tbl1Col= T2.Id
WHERE T1.Id = @Id

Now If @Id = 1, Output is F -- works fine

Now If @Id = 2, Output should be FU -- should not be F,U


问:
Monitor a rake task in rails 5
I have a requirement wherein I have to constantly fetch messages from AWS-SQS(simple queue service) and update the related records of a model. The message contains data that needs to be displayed to the related users as notifications as soon as they are fetched. This has been successfully managed by using Action Cable. I have created a rake task that fetches the messages from the queue and does the required processing. This task is supposed to run in an infinite loop. I have 2 questions regarding it?

```<code>namespace :sqs_consumer do
  desc 'Get data from the AWS-SQS and process it.'
  task start: :environment do
    # initialize the sqs client
    loop do
      #read the queue for messages and process them in batches(if any)
    end
  end
end
</code>```

1) Is it right to create a rake task for the above requirement? A rake task that runs infinitely is the right way? If not, what is the right approach. I cant run the task periodically since i need data in real time.

2) I want to monitor the task. I am using monit for the same. Unfortunately, Monit conf for the same doesn't seem to work. What am I doing wrong or missing?

```<code>check process aws_sqs_consumer with pidfile /var/www/myproject/shared/pids/sqs_consumer.pid
  start program = "/bin/sh -c 'cd /var/www/myproject/current; nohup bundle exec rake sqs_consumer:start RAILS_ENV=staging -i 0 -P /var/www/myproject/shared/pids/sqs_consumer.pid >> log/sqs_consumer.log 2>&1 &'" as uid ubuntu and gid ubuntu
  stop program = "/bin/sh -c 'kill $(cat /var/www/myproject/shared/pids/sqs_consumer.pid)'" as uid ubuntu and gid ubuntu
</code>```

答:
This monit configuration worked for me</p>

```<code>check process aws_sqs_consumer with pidfile /var/www/myproject/shared/tmp/pids/sqs_consumer.pid
  start program = "/bin/sh -c 'cd /var/www/myproject/current && BACKGROUND=y PIDFILE=/var/www/myproject/shared/tmp/pids/sqs_consumer.pid LOG_LEVEL=info bundle exec rake sqs_consumer:start RAILS_ENV=staging'"
  stop program = "/bin/sh -c 'kill $(cat /var/www/myproject/shared/tmp/pids/sqs_consumer.pid)'" as uid ubuntu and gid ubuntu with timeout 90 seconds
</code>```

Title: Monitor a rake task in rails 5

Body:
I have a requirement wherein I have to constantly fetch messages from AWS-SQS(simple queue service) and update the related records of a model. The message contains data that needs to be displayed to the related users as notifications as soon as they are fetched. This has been successfully managed by using Action Cable. I have created a rake task that fetches the messages from the queue and does the required processing. This task is supposed to run in an infinite loop. I have 2 questions regarding it?

namespace :sqs_consumer do
  desc 'Get data from the AWS-SQS and process it.'
  task start: :environment do
    # initialize the sqs client
    loop do
      #read the queue for messages and process them in batches(if any)
    end
  end
end

1) Is it right to create a rake task for the above requirement? A rake task that runs infinitely is the right way? If not, what is the right approach. I cant run the task periodically since i need data in real time.

2) I want to monitor the task. I am using monit for the same. Unfortunately, Monit conf for the same doesn't seem to work. What am I doing wrong or missing?

check process aws_sqs_consumer with pidfile /var/www/myproject/shared/pids/sqs_consumer.pid
  start program = "/bin/sh -c 'cd /var/www/myproject/current; nohup bundle exec rake sqs_consumer:start RAILS_ENV=staging -i 0 -P /var/www/myproject/shared/pids/sqs_consumer.pid >> log/sqs_consumer.log 2>&1 &'" as uid ubuntu and gid ubuntu
  stop program = "/bin/sh -c 'kill $(cat /var/www/myproject/shared/pids/sqs_consumer.pid)'" as uid ubuntu and gid ubuntu

Body:
This monit configuration worked for me

check process aws_sqs_consumer with pidfile /var/www/myproject/shared/tmp/pids/sqs_consumer.pid
  start program = "/bin/sh -c 'cd /var/www/myproject/current && BACKGROUND=y PIDFILE=/var/www/myproject/shared/tmp/pids/sqs_consumer.pid LOG_LEVEL=info bundle exec rake sqs_consumer:start RAILS_ENV=staging'"
  stop program = "/bin/sh -c 'kill $(cat /var/www/myproject/shared/tmp/pids/sqs_consumer.pid)'" as uid ubuntu and gid ubuntu with timeout 90 seconds


问:
sed / awk - remove all but a specific matching pattern from a file
I want to convert a makefile like this:

```<code>test.o: var_one.h var_two.h

test2.o: another_header.h var_three.h archive/something_random.h
</code>```

to this:

```<code>test.o: var_one.h var_two.h

test2.o: var_three.h
</code>```

ie, I want to remove any filename that doesn't start with the search string "var_"

I can't seem to find a lot of information for sed about pattern matching when not wanting the search string?

答:
You really need awk for this type of job. With sed, attempting to remove words that don't match a string would be a painful (and probably ugly) script to write.

```<code>awk '{for(i=2;i<=NF;i++)$i !~ /var_.*\.h/ && $i=""}1' Makefile
</code>```

Input

```<code>$ cat Makefile
test.o: var_one.h var_two.h

test2.o: another_header.h var_three.h archive/something_random.h
</code>```

Output

```<code>$ awk '{for(i=2;i<=NF;i++)$i !~ /var_.*\.h/ && $i=""}1' Makefile
test.o: var_one.h var_two.h

test2.o:  var_three.h
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to convert a makefile like this:

test.o: var_one.h var_two.h

test2.o: another_header.h var_three.h archive/something_random.h

to this:

test.o: var_one.h var_two.h

test2.o: var_three.h

ie, I want to remove any filename that doesn't start with the search string "var_"

I can't seem to find a lot of information for sed about pattern matching when not wanting the search string?

Body:
You really need awk for this type of job. With sed, attempting to remove words that don't match a string would be a painful (and probably ugly) script to write.

awk '{for(i=2;i<=NF;i++)$i !~ /var_.*\.h/ && $i=""}1' Makefile

Input

$ cat Makefile
test.o: var_one.h var_two.h

test2.o: another_header.h var_three.h archive/something_random.h

Output

$ awk '{for(i=2;i<=NF;i++)$i !~ /var_.*\.h/ && $i=""}1' Makefile
test.o: var_one.h var_two.h

test2.o:  var_three.h


问:
Docker composed services can't communicate by service name
tldr: I can't communicate with a docker composed service by its service name in order to make requests to an api running in networked containers.

I have a single page application that makes requests to a json api. Its Dockerfile looks like this:

```<code>FROM nginx:alpine
COPY dist /usr/share/nginx/html
EXPOSE 80
</code>```

A build process does it's thing and puts all the static assets in a dist directory which is then copied to the html directory of the nginx web server.

I have a mock json api powered by json-server. Its Dockerfile looks like this:

```<code>FROM node:7.10.0-alpine

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json /usr/src/app/
RUN npm install

COPY . /usr/src/app

EXPOSE 3000

CMD [ "npm", "start" ]
</code>```

I have a docker-compose file that looks like this:

```<code>version: '2'

services:
  badass-ui:
    image: mydocker-hub/badass-ui
    container_name: badass-ui
    ports:
      - "80:80"

  badderer-api:
    image: mydocker-hub/badderer-api
    container_name: badderer-api
    ports:
      - "3000:3000"
</code>```

I'm able to build both containers successfully, and am able to run "docker-compose up" with both containers running smoothly. Fetch requests from badass-ui to badderer-api:3000/users returns "net::ERR_NAME_NOT_RESOLVED". Fetch requests to http://192.168.99.100:3000/users (or whatever the container IP may be) work fine. I thought by using docker compose I would be able to reference the name of a service defined in docker-compose.yml as a domain name, and that would enable communication between the containers via domain name. This doesn't seem to work. Is there something wrong with my docker-compose.yml? I'm on Windows 10 Home edition, using the tools that come with the Docker Quickstart terminal for Windows. I'm using docker-compose version 1.13.0, docker version 17.05.0-ce, docker-machine version 0.11.0 and VirtualBox 5.1.20.

答:
Since you are using docker-compose.yml version 2, links should not be necessary. Containers within a compose network should be able to resolve other compose containers by service name.

Reading the comments on your question it seems like the networking and host name resolution works, so it seems like the problem is in your web UI. I don't see you passing any type of configuration to the UI application saying where to find the api. Maybe there is a hard coded url to the api in your UI causing the error?

Edit:

Is your UI a client side/javascript app? Are you sure the app isn't actually making the call from your browser? Your browser running on your local machine and not in docker will not be able resolve the badderrer-api hostname.

Body:
tldr: I can't communicate with a docker composed service by its service name in order to make requests to an api running in networked containers.

I have a single page application that makes requests to a json api. Its Dockerfile looks like this:

FROM nginx:alpine
COPY dist /usr/share/nginx/html
EXPOSE 80

A build process does it's thing and puts all the static assets in a dist directory which is then copied to the html directory of the nginx web server.

I have a mock json api powered by json-server. Its Dockerfile looks like this:

FROM node:7.10.0-alpine

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json /usr/src/app/
RUN npm install

COPY . /usr/src/app

EXPOSE 3000

CMD [ "npm", "start" ]

I have a docker-compose file that looks like this:

version: '2'

services:
  badass-ui:
    image: mydocker-hub/badass-ui
    container_name: badass-ui
    ports:
      - "80:80"

  badderer-api:
    image: mydocker-hub/badderer-api
    container_name: badderer-api
    ports:
      - "3000:3000"

I'm able to build both containers successfully, and am able to run "docker-compose up" with both containers running smoothly. Fetch requests from badass-ui to badderer-api:3000/users returns "net::ERR_NAME_NOT_RESOLVED". Fetch requests to http://192.168.99.100:3000/users (or whatever the container IP may be) work fine. I thought by using docker compose I would be able to reference the name of a service defined in docker-compose.yml as a domain name, and that would enable communication between the containers via domain name. This doesn't seem to work. Is there something wrong with my docker-compose.yml? I'm on Windows 10 Home edition, using the tools that come with the Docker Quickstart terminal for Windows. I'm using docker-compose version 1.13.0, docker version 17.05.0-ce, docker-machine version 0.11.0 and VirtualBox 5.1.20.


问:
A special switch statement in C
I am reading CSAPP, the chapter about setjmp and longjmp, and encounter the following code snippets:

```<code>int rc;
switch(setjmp(buf));
if (rc == 0)
    foo();
else if (rc == 1)
    printf("sth.");
else if (rc == 2)
    printf("sth. other");
...
</code>```

The switch statement really confused me, could someone explain this usage of switch statement in C for me?

PS: This is actually an error of CSAPP(the second edition), and the author fixes this by using normal switch-case statement in the third edition. Thanks for all.

答:
First of all, please note that setjmp and longjmp are considered incredible poor practice to use, the worst kind of spaghetti programming. Any source of learning teaching you to use these functions should be regarded with great scepticism.

As for the reason why the weird switch statement is there, it is because of a number of artificial requirements placed on the setjmp function by the standard. C11 7.13.1.1

Environmental limits  An invocation of the setjmp macro shall appear
  only in one of the following contexts:

  — the entire controlling
  expression of a selection or iteration statement;

  — one operand of a
  relational or equality operator with the other operand an integer
  constant expression, with the resulting expression being the entire
  controlling expression of a selection or iteration statement;

  — the operand of a unary ! operator with the resulting expression being the entire
  controlling expression of a selection or iteration statement; or

  — the entire expression of an expression statement (possibly cast to void).

Please note that the last point above allows code such as (void) setjmp(env);, so the switch statement in the question is mostly obfuscation.

The C standard rationale 7.13.1 provides an explanation of why this "function" has such artificial requirements, namely because it must be implemented as a macro:

7.13.1.1 The setjmp macro

  One proposed requirement on setjmp is that it be usable like any other function, that is, that it be callable
  in any expression context, and that the expression evaluate correctly
  whether the return from setjmp is direct or via a call to longjmp.
  Unfortunately, any implementation of setjmp as a conventional called
  function cannot know enough about the calling environment to save any
  temporary registers or dynamic stack locations used part way through
  an expression evaluation. (A setjmp macro seems to help only if it expands to inline assembly code or a call
  to a special built-in function.) The temporaries may be correct on the initial call to setjmp, but
  are not likely to be on any return initiated by a corresponding call to longjmp. These
  considerations dictated the constraint that setjmp be called only from within fairly simple expressions, ones not likely to need temporary storage.

To put it plainly: if you would call a function instead of a macro, then the CPU/OS might stack away various registers that you actually want setjmp to preserve, most notably the program counter. (setjmp was specified long before the C language supported inline functions.)

Title: A special switch statement in C

Body:
I am reading CSAPP, the chapter about setjmp and longjmp, and encounter the following code snippets:

int rc;
switch(setjmp(buf));
if (rc == 0)
    foo();
else if (rc == 1)
    printf("sth.");
else if (rc == 2)
    printf("sth. other");
...

The switch statement really confused me, could someone explain this usage of switch statement in C for me?

PS: This is actually an error of CSAPP(the second edition), and the author fixes this by using normal switch-case statement in the third edition. Thanks for all.


答:
Create a script element and append it into your head tag like the following

function addVals() {
  var sc = document.createElement("script");
  sc.innerHTML = "window.daySelected = window.currentdate; window.monthSelected = window.currentmonth; window.yearSelected = window.currentyear;";
  document.head.appendChild(sc);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" onclick="addVals()" value="click me" /></code>```

Title: Load html template script on button click

Body:
Create a script element and append it into your head tag like the following

function addVals() {
  var sc = document.createElement("script");
  sc.innerHTML = "window.daySelected = window.currentdate; window.monthSelected = window.currentmonth; window.yearSelected = window.currentyear;";
  document.head.appendChild(sc);
}

<input type="button" onclick="addVals()" value="click me" />


问:
How do I provide files for download?
I have written a post and would like to provide a file as attachment for download.

So far I have

created a link [Download files][download-file]

declared the link as [download-file]: download.zip

put download.zip in the _posts folder

However, the file does not get copied to the correct location.

I have

read about data files

read about directory structure

read about static files, which IMHO was the closest hit. Unfortunately, no example is provided.

So neither page gave me an answer on how to provide files for download.

I don't know where to put static files in the directory structure. Once I knew that, it seems I could use some Liquid like {{ site.static_files }}, but even then I'd still need to specify a file name.

答:
You can place your download.zip file in the root of your project, and it will get copied over to {{ site.url }}/download.zip. If you'd like it contained in a folder, you can create any folder, eg download/, and any file will be able to accessed via {{ site.url }}/download/*.

Every other directory and file except for [the Jekyll files]—such as css and images folders,  favicon.ico files, and so forth—will be copied verbatim to the generated site.

from the Jekyll Docs

Title: How do I provide files for download?


问:
Creating arrays on condition in javascript
This has been eating me away. Check CodePen here. I have a function that adds elements to a ruler. Call expose.init(lengthOfPeriod) with an integer to set the length of each period in the ruler. Call expose.addAction(time, team) with an integer and a string == 'HOME' || 'AWAY' to place an action in the ruler.

When the screen is resized, I want something to happen to the elements in the ruler that touch each other (basically collapse into a group).

I have a function 'detectOverlap' that takes 2 params and determines if they are touching or not. I also have a function in the resize event handler that populates an array 'allTouching' with all the elements in the ruler that are touching each other at each resize.

```<code>if (actionArray.length > 1) { //don't run if there's only one element in the page
actionArray.reduce(function (prev, next) {
    if (detectOverlap(prev, next)) {
        if (allTouching.indexOf(prev, next) === -1) allTouching.push(prev, next);
    }
    return next;
});
</code>```

If actions are touching each other, I need them to collapse into groups. In order to do this, I need to create an array for each group of actions touching each other. However, I haven't been able to make this happen so far.
Here's some pseudo code:

```<code>for (i = 0; i < allTouching.length; i++) {
  if (detectOverlap(allTouching[0], alltouching) {
    touchingGroup[i] = new Array(allTouching[0], all other elements touched by 0);
    do not include any element more than once in touchingGroup[i];
    do not include any similar arrays (same elements) in allGroups;
    allGroups.push(touchingGroup[i]);
  }
}
</code>```

In short, this would need to loop for all the elements in the allTouching array, and create a new touchingGroup[n] for each new group of actions that touch each other.

This sounds simple in my head, and I'm sure there must be a way to do it without code getting overly complex, but I haven't found it yet.
Any feedback would be appreciated.

答:
It seems your question is only about the grouping, so I will ignore the visualisation aspect and assume that the function detectOverlap is correct.

Then you could create the groups in one for loop. In this snippet I have added simplistic sample data and a mock detectOverlap function that will return true when its two arguments are the same (just for the purpose of the snippet):

// Simplistic mock data and function, just to make the snippet work
var actionArray = [1, 1, 3, 3, 3, 8, 9];
function detectOverlap(a, b) { return a === b; }

// Actual code:
var allGroups = [];
var start = 0;
for (var i = 1; i <= actionArray.length; i++) {
    if (i >= actionArray.length || !detectOverlap(actionArray[i-1], actionArray[i])) {
        if (i - start > 1) // Remove this condition if you want singletons as well
            allGroups.push(actionArray.slice(start, i));
        start = i;
    }
}
console.log(JSON.stringify(allGroups));```

Explanation

The variable start is used as an index in the array, from where the most recently found group should start. That group is not yet actually created, since we do not know where it ends, and so I will call this the "undecided" group. start is initialised at 0 to indicate that the first group will start there.

The loop iterates over the array, but starting at 1. In each iteration it decides whether the "undecided" group (started at start) is complete. The group is considered complete when there is no overlap between the previous and the current element of the array. In that case the previous element is the last element of the "undecided" group. The elements for that group are copied from the array with slice. Note that the second argument of slice is the index of the first element that should not be part of the group. Now that group is stored, and start is put at the current index, where the next (and only) "undecided" group should start.

But as long as the two elements do overlap, no new group should be created (that is why the condition has a !). Instead start remains unchanged, and so this "undecided", "unclosed" group is getting bigger in size.

There is an if just before that slice, which prevents the creation of groups that only contain one element. If you remove that if, then also single elements will be isolated in their own "singleton" groups.

The loop will go up to and including arrayAction.length: this is unusual, since that makes the last i an invalid index. But it is useful, since in that case we still want to finish up the last group that is still "ongoing". So in that case i >= arrayAction.length will be true, and so the detectOverlap function will not be called (because the if condition is already known to be true). The if block will be entered and the final group will be created.

Body:
This has been eating me away. Check CodePen here. I have a function that adds elements to a ruler. Call expose.init(lengthOfPeriod) with an integer to set the length of each period in the ruler. Call expose.addAction(time, team) with an integer and a string == 'HOME' || 'AWAY' to place an action in the ruler.

When the screen is resized, I want something to happen to the elements in the ruler that touch each other (basically collapse into a group).

I have a function 'detectOverlap' that takes 2 params and determines if they are touching or not. I also have a function in the resize event handler that populates an array 'allTouching' with all the elements in the ruler that are touching each other at each resize.

if (actionArray.length > 1) { //don't run if there's only one element in the page
actionArray.reduce(function (prev, next) {
    if (detectOverlap(prev, next)) {
        if (allTouching.indexOf(prev, next) === -1) allTouching.push(prev, next);
    }
    return next;
});

If actions are touching each other, I need them to collapse into groups. In order to do this, I need to create an array for each group of actions touching each other. However, I haven't been able to make this happen so far.
Here's some pseudo code:

for (i = 0; i < allTouching.length; i++) {
  if (detectOverlap(allTouching[0], alltouching) {
    touchingGroup[i] = new Array(allTouching[0], all other elements touched by 0);
    do not include any element more than once in touchingGroup[i];
    do not include any similar arrays (same elements) in allGroups;
    allGroups.push(touchingGroup[i]);
  }
}

In short, this would need to loop for all the elements in the allTouching array, and create a new touchingGroup[n] for each new group of actions that touch each other.

This sounds simple in my head, and I'm sure there must be a way to do it without code getting overly complex, but I haven't found it yet.
Any feedback would be appreciated.

Body:
It seems your question is only about the grouping, so I will ignore the visualisation aspect and assume that the function detectOverlap is correct.

Then you could create the groups in one for loop. In this snippet I have added simplistic sample data and a mock detectOverlap function that will return true when its two arguments are the same (just for the purpose of the snippet):

// Simplistic mock data and function, just to make the snippet work
var actionArray = [1, 1, 3, 3, 3, 8, 9];
function detectOverlap(a, b) { return a === b; }

// Actual code:
var allGroups = [];
var start = 0;
for (var i = 1; i <= actionArray.length; i++) {
    if (i >= actionArray.length || !detectOverlap(actionArray[i-1], actionArray[i])) {
        if (i - start > 1) // Remove this condition if you want singletons as well
            allGroups.push(actionArray.slice(start, i));
        start = i;
    }
}
console.log(JSON.stringify(allGroups));

Explanation

The variable start is used as an index in the array, from where the most recently found group should start. That group is not yet actually created, since we do not know where it ends, and so I will call this the "undecided" group. start is initialised at 0 to indicate that the first group will start there.

The loop iterates over the array, but starting at 1. In each iteration it decides whether the "undecided" group (started at start) is complete. The group is considered complete when there is no overlap between the previous and the current element of the array. In that case the previous element is the last element of the "undecided" group. The elements for that group are copied from the array with slice. Note that the second argument of slice is the index of the first element that should not be part of the group. Now that group is stored, and start is put at the current index, where the next (and only) "undecided" group should start.

But as long as the two elements do overlap, no new group should be created (that is why the condition has a !). Instead start remains unchanged, and so this "undecided", "unclosed" group is getting bigger in size.

There is an if just before that slice, which prevents the creation of groups that only contain one element. If you remove that if, then also single elements will be isolated in their own "singleton" groups.

The loop will go up to and including arrayAction.length: this is unusual, since that makes the last i an invalid index. But it is useful, since in that case we still want to finish up the last group that is still "ongoing". So in that case i >= arrayAction.length will be true, and so the detectOverlap function will not be called (because the if condition is already known to be true). The if block will be entered and the final group will be created.


问:
Printing the 3 highest integers from an array without sorting
I am trying to create a program that prints the highest integers from a collection of student's grades array, but the code keeps returning me the same values each time it returns me a value.

So far this is the code:

```<code>class BestGrades {
public static void main(String args[]){
            Scanner sc = new Scanner(System.in);

            int grade[] = new int[6];
            int best[] = new int[3];

            System.out.println("Enter the student's grade...");

            for(int i = 0; i < grade.length; i++){

                    grade[i] = sc.nextInt();

                    for(int a = 0; a < best.length; a++){
                            if(grade[i] > best[a]){
                                    best[a] = grade[i];
                            }
                    }
            }

            for(int i = 0; i < best.length; i++){
                    System.out.println("Best degrees are: "+best[i]);
            }
    }
</code>```

}

As I said, the code will always return me the same highest value 3x.
Pardon me for any mistakes, first time asking here.

答:
```<code>for(int a = 0; a < best.length; a++){
    if(grade[i] > best[a]){
        for(int b = a + 1; b < best.length; b++){
            best[b] = best[b - 1];
        }
        best[a] = grade[i];
        break;
    }
}
</code>```

Body:
I am trying to create a program that prints the highest integers from a collection of student's grades array, but the code keeps returning me the same values each time it returns me a value.

So far this is the code:

class BestGrades {
public static void main(String args[]){
            Scanner sc = new Scanner(System.in);

            int grade[] = new int[6];
            int best[] = new int[3];

            System.out.println("Enter the student's grade...");

            for(int i = 0; i < grade.length; i++){

                    grade[i] = sc.nextInt();

                    for(int a = 0; a < best.length; a++){
                            if(grade[i] > best[a]){
                                    best[a] = grade[i];
                            }
                    }
            }

            for(int i = 0; i < best.length; i++){
                    System.out.println("Best degrees are: "+best[i]);
            }
    }

}

As I said, the code will always return me the same highest value 3x.
Pardon me for any mistakes, first time asking here.


问:
Empty response when trying retrieve a user's followers
Request (with my actual access token in place of UserAccessToken):

```<code>https://api.instagram.com/v1/users/self/follows?access_token=UserAccessToken
</code>```

Response:

```<code>{
  "pagination": {},
  "data": [],
  "meta": { "code": 200 }
}
</code>```

Sandbox: YES

Invite to user: accepted

Has anyone had this problem? Please help!

答:
beacuse your app in in sanbox mode .

it just show users insert in sanbox mode.(just 3 people can inserted to this mode.)

follow this link to see more deatails :

https://www.instagram.com/developer/sandbox/

if it will be in live mode it will work(need to accept instagram company.).

Body:
Request (with my actual access token in place of UserAccessToken):

https://api.instagram.com/v1/users/self/follows?access_token=UserAccessToken

Response:

{
  "pagination": {},
  "data": [],
  "meta": { "code": 200 }
}

Sandbox: YES

Invite to user: accepted

Has anyone had this problem? Please help!


问:
How to create a custom home page in XMLUI mirage 2 theme?
all I am working on DSpace 1.6 with XML UI mirage 2 theme, the default installation work fine,  I also know about the overlaying the styles in Mirage 2 theme by placing files in

dspace/modules/xmlui-mirage2 themes.

Generally, What I need is to modify a homepage, so that I can put latest and trending items in a homepage as a banner as shown in world bank home page as shown below.

答:
@psycho3
The basis for this can be found in later versions of DSpace, starting from version DSpace 4 I believe.
Check out a class called "SiteRecentSubmissions". https://github.com/DSpace/DSpace/blob/dspace-4_x/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/SiteRecentSubmissions.java

What this class does is add the latest submitted items to the frontpage.
You could create a new kind of class that finds the top downloaded items and adds them to the body of that new class.

But, that being said, this might be more difficult since you are using a Dspace 1.6 and there might be some serious limitations involved in terms of querying solr on the fly etc.

(Also, how did you manage to set up a DSpace 1.6 with a functional Mirage2 if I might ask?)


问:
tinyMCE only displays in dialog box if initialized on page load
I created an application that uses a bunch of AJAX requests. It displays a table of products, and from there you can click the name of a product which will open a dialog box (box1). Within box1, there is another list of links you can click. When clicked, it will open another dialog box (box2).

In box2, I have a textarea field which is initialized as a tinyMCE. For some reason, initializing the textarea as a tinyMCE editor was not working. So, I created a separate textarea field, initialized as a tinyMCE on page load, in a stand alone div, which worked fine. So I navigated to the textarea within box 2, and surprisingly, it initialized itself as a tinyMCE. So, I simply set that stand alone div to display none. How does that make any sense?

For the time being, I will leave it this way because it works. However, I highly doubt that is the correct way to do this. Has anyone else ever experienced something similar?

Let me know if I should post some code.

Thanks.

EDIT: As requested, here is some code. Keep in mind that the initTinyMCE function was written by someone else a long time ago from a classic ASP file. My job is to convert it to an aspx file.

Backend file creating the textarea and calling the initTinyMCE() javascript function...

```<code>htmlString.Append("<p><span class=\"regTextBld\"><strong>Scenario Text</strong></span>");
            htmlString.Append("<script type=\"text/javascript\">initTinyMCE();</script>");
            htmlString.Append("<textarea class=\"TinyMCEeditor\" name=\"txtEntry\" id=\"txtEntry\" style=\"height:400px; width: 99%;\">" + reader["assumptions"] + "</textarea></p>");
</code>```

And here is the initTinyMCE function...

```<code>function initTinyMCE() {
        //alert("x");
        initPlugins();
        tinyMCE.init({
            mode: "specific_textareas",
            editor_selector: "TinyMCEeditor",
            theme: "advanced",
            //plugins : "economy,safari,style,table,advhr,advimage,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,visualchars,nonbreaking,template",
            plugins: "economy,safari,style,table,inlinepopups,searchreplace,print,contextmenu,paste,fullscreen,visualchars,medclink",
            theme_advanced_buttons1: "cut,copy,paste,pastetext,replace,print,|,undo,redo,|,rspell,|,link,unlink,|,hr,image,table,|,code",
            theme_advanced_buttons2: "bold,italic,underline,removeformat,|,numlist, bullist,outdent,indent,|,justifyleft,justifycenter,justifyright,justifyfull,|,nonbreaking,charmap",
            theme_advanced_buttons3: "",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            content_css: "/style/intranet.css?" + new Date().getTime(),
            paste_preprocess: function(pl, o) {
                o.content = o.content.replace(/\u2019/gi, "'"); // â€™
                o.content = o.content.replace(/\u201C/gi, "\""); // â€œ
                o.content = o.content.replace(/\u201D/gi, "\""); // â€
            },
            cleanup: false,
            encoding: "html",
            entity_encoding: "named",
            verify_html: true
        });
    }
</code>```

答:
I am using jquery tinymce

```<code>$('#textareaid').tinymce().show();
</code>```

Use this code when u click on textarea to activate tinymce.

Body:
I created an application that uses a bunch of AJAX requests. It displays a table of products, and from there you can click the name of a product which will open a dialog box (box1). Within box1, there is another list of links you can click. When clicked, it will open another dialog box (box2).

In box2, I have a textarea field which is initialized as a tinyMCE. For some reason, initializing the textarea as a tinyMCE editor was not working. So, I created a separate textarea field, initialized as a tinyMCE on page load, in a stand alone div, which worked fine. So I navigated to the textarea within box 2, and surprisingly, it initialized itself as a tinyMCE. So, I simply set that stand alone div to display none. How does that make any sense?

For the time being, I will leave it this way because it works. However, I highly doubt that is the correct way to do this. Has anyone else ever experienced something similar?

Let me know if I should post some code.

Thanks.

EDIT: As requested, here is some code. Keep in mind that the initTinyMCE function was written by someone else a long time ago from a classic ASP file. My job is to convert it to an aspx file.

Backend file creating the textarea and calling the initTinyMCE() javascript function...

htmlString.Append("
Scenario Text");
            htmlString.Append("");
            htmlString.Append("<textarea class=\"TinyMCEeditor\" name=\"txtEntry\" id=\"txtEntry\" style=\"height:400px; width: 99%;\">" + reader["assumptions"] + "</textarea>
");

And here is the initTinyMCE function...

function initTinyMCE() {
        //alert("x");
        initPlugins();
        tinyMCE.init({
            mode: "specific_textareas",
            editor_selector: "TinyMCEeditor",
            theme: "advanced",
            //plugins : "economy,safari,style,table,advhr,advimage,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,visualchars,nonbreaking,template",
            plugins: "economy,safari,style,table,inlinepopups,searchreplace,print,contextmenu,paste,fullscreen,visualchars,medclink",
            theme_advanced_buttons1: "cut,copy,paste,pastetext,replace,print,|,undo,redo,|,rspell,|,link,unlink,|,hr,image,table,|,code",
            theme_advanced_buttons2: "bold,italic,underline,removeformat,|,numlist, bullist,outdent,indent,|,justifyleft,justifycenter,justifyright,justifyfull,|,nonbreaking,charmap",
            theme_advanced_buttons3: "",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            content_css: "/style/intranet.css?" + new Date().getTime(),
            paste_preprocess: function(pl, o) {
                o.content = o.content.replace(/\u2019/gi, "'"); // â€™
                o.content = o.content.replace(/\u201C/gi, "\""); // â€œ
                o.content = o.content.replace(/\u201D/gi, "\""); // â€
            },
            cleanup: false,
            encoding: "html",
            entity_encoding: "named",
            verify_html: true
        });
    }

Body:
I am using jquery tinymce

$('#textareaid').tinymce().show();

Use this code when u click on textarea to activate tinymce.