问:
Multifile shiny dashboard
I try to rebuild my application as in the link. I have a multitematic dashboard and I would like to have each topic in separate ui and server files to have better control of the code.

The main file (app.R) is contacting with other files eg UI using source(file.path("ui", "tab1.R"),  local = TRUE)$value
tab1.R looks like:

tabPanel("Tab 1", uiOutput("content1")) (content1 is in server file).

I would like to have possibility to put more then on tabPanel in one file. I thought that i can do something like that:
tab1.R looks like:

```<code>aaa <- tabPanel("Tab 2", uiOutput("content2"))
bbb <- tabPanel("Tab 1", uiOutput("content1"))
</code>```

And then contact with them using:

```<code>source(file.path("ui", "tab1.R"),  local = TRUE)$aaa
source(file.path("ui", "tab1.R"),  local = TRUE)$bbb
</code>```

But i get ERROR:

```<code>Error in attr(x, "selected") <- TRUE :
  attempt to set an attribute on NULL
</code>```

I could not find answer for that anywhere so I disated to write here for help

答:
I found imo the best way, I just used the functions:

```<code>aaa <- function(){tabPanel("Tab 2", uiOutput("content2"))}
bbb <- function(){tabPanel("Tab 1", uiOutput("content1"))}
</code>```

And then on the top on file I upload source:

```<code>source(file.path("ui", "tab1.R"),  local = TRUE)
</code>```

Now I can normally use functions in code:

```<code>aaa()
bbb()
</code>```

Title: Multifile shiny dashboard

Body:
I try to rebuild my application as in the link. I have a multitematic dashboard and I would like to have each topic in separate ui and server files to have better control of the code.

The main file (app.R) is contacting with other files eg UI using source(file.path("ui", "tab1.R"),  local = TRUE)$value
tab1.R looks like:

tabPanel("Tab 1", uiOutput("content1")) (content1 is in server file).

I would like to have possibility to put more then on tabPanel in one file. I thought that i can do something like that:
tab1.R looks like:

aaa <- tabPanel("Tab 2", uiOutput("content2"))
bbb <- tabPanel("Tab 1", uiOutput("content1"))

And then contact with them using:

source(file.path("ui", "tab1.R"),  local = TRUE)$aaa
source(file.path("ui", "tab1.R"),  local = TRUE)$bbb

But i get ERROR:

Error in attr(x, "selected") <- TRUE :
  attempt to set an attribute on NULL

I could not find answer for that anywhere so I disated to write here for help

Body:
I found imo the best way, I just used the functions:

aaa <- function(){tabPanel("Tab 2", uiOutput("content2"))}
bbb <- function(){tabPanel("Tab 1", uiOutput("content1"))}

And then on the top on file I upload source:

source(file.path("ui", "tab1.R"),  local = TRUE)

Now I can normally use functions in code:

aaa()
bbb()


来源: stackexchange

问:
Excel Sum by Month
Hi have the following scenario:

Items in Column A, Total Time in Column B, then I have 365 dates in columns.

I want to summarise the column dates by month.

I want, for example, for Item A, in March, total Times taken.
How to do it?
Thanks

答:
So, somewhat overkill but was interested in how to do it with power query and was interested in building a custom function for the MonthNumber.

Powerquery is free add-in for pre 2016 and is inbuilt for 2016

STEPS:

1) Data tab (2016) or powerquery tab (2010 to 2016) => Select query from table and ensure your source data is selected and appears in pop-up

2) Select the first date column, hold shift down and select last date, then select unpivot columns

3) Make sure column Attribute (your pivoted dates) is formatted as a date column

4) Open the advanced query editor window

and paste the following between let and source

```<code>fnMonthNum = (input) => let
values = {
{"January", "1"},
{"February", "2"},
{"March", "3"},
{"April","4"},
{"May", "5"},
{"June", "6"},
{"July", "7"},
{"August", "8"},
{"September", "9"},
{"October", "10"},
{"November", "11"},
{"December", "12"},
{input, "Undefined"}

},
Result = List.First(List.Select(values, each _{0}=input)){1}
in
Result,
</code>```

This is M code for creating a custom function that returns month numbers from month names.

5) Add column tab => Add custom column, rename it MonthName and insert the following text

```<code>=Date.ToText([Attribute],"MMMM")
</code>```

6) Add another custom column, rename it MonthNum and use our new function here:

```<code>= fnMonthNum([MonthName])
</code>```

7) Remove the now unnecessary Attribute column; select column => right click => remove

8) Transform tab => Group by and enter the following:

9) Make sure MonthNum column is numeric.

10)  Close and load to => Only create connection,
     Tick checkbox for Add to data model, and then Load

11) As per instructions here: CREATE A PIVOT TABLE USING EXCEL’S INTERNAL DATA MODEL

Choose Insert→PivotTable from the Ribbon. The Create PivotTable dialog box opens.

Select the Use an External Data Source option, as shown, and then click the Choose Connection button. You see the Existing Connections dialog box, as shown.

Select the query you just created for Table1 and a destination for the pivottable

12) Arrange the fields as required and sort ascending on the MonthNum rowfield

13) Insert slicer

Note: You could introduce a custom sort to avoid having to use the MonthNum column for sorting.

ContentLicense: CC BY-SA 3.0

Title: Excel Sum by Month

Body:
So, somewhat overkill but was interested in how to do it with power query and was interested in building a custom function for the MonthNumber.

Powerquery is free add-in for pre 2016 and is inbuilt for 2016

STEPS:

1) Data tab (2016) or powerquery tab (2010 to 2016) => Select query from table and ensure your source data is selected and appears in pop-up

2) Select the first date column, hold shift down and select last date, then select unpivot columns

3) Make sure column Attribute (your pivoted dates) is formatted as a date column

4) Open the advanced query editor window

and paste the following between let and source

fnMonthNum = (input) => let
values = {
{"January", "1"},
{"February", "2"},
{"March", "3"},
{"April","4"},
{"May", "5"},
{"June", "6"},
{"July", "7"},
{"August", "8"},
{"September", "9"},
{"October", "10"},
{"November", "11"},
{"December", "12"},
{input, "Undefined"}

},
Result = List.First(List.Select(values, each _{0}=input)){1}
in
Result,

This is M code for creating a custom function that returns month numbers from month names.

5) Add column tab => Add custom column, rename it MonthName and insert the following text

=Date.ToText([Attribute],"MMMM")

6) Add another custom column, rename it MonthNum and use our new function here:

= fnMonthNum([MonthName])

7) Remove the now unnecessary Attribute column; select column => right click => remove

8) Transform tab => Group by and enter the following:

9) Make sure MonthNum column is numeric.

10)  Close and load to => Only create connection,
     Tick checkbox for Add to data model, and then Load

11) As per instructions here: CREATE A PIVOT TABLE USING EXCEL’S INTERNAL DATA MODEL

Choose Insert→PivotTable from the Ribbon. The Create PivotTable dialog box opens.

Select the Use an External Data Source option, as shown, and then click the Choose Connection button. You see the Existing Connections dialog box, as shown.

Select the query you just created for Table1 and a destination for the pivottable

12) Arrange the fields as required and sort ascending on the MonthNum rowfield

13) Insert slicer

Note: You could introduce a custom sort to avoid having to use the MonthNum column for sorting.


问:
Business Layer in 3 tier Architecture
I went for an interview, and was asked to show up my Business layer architecture. I have some idea about 3 tier architecture but really no idea, to what to write in front of interviewer.
So suppose my project deals with Employees of an organization, then what would i have written there. Will it be any kind of diagrams i should have made or some coding part. I worked in C# framework 3.5. I really don't understand what else to mention in this question, so please let me know if something is required.Thanks.

Edit
I worked in winforms.
I know what Business layer is, but was not sure what to tell the interviewer as business layer has codes and obviously my project was a bit big, so there were huge numbers of codes. So what i should have written there??

答:
Business logic is defined as any application logic that is concerned with the retrieval, processing, transformation, and management of application data; application of business rules and policies; and ensuring data consistency and validity. To maximize reuse opportunities, business logic components should not contain any behavior or application logic that is specific to a use case or user story. Business logic can be further subdivided into the following two categories:

Business Workflow. After the UI components collect the required data from the user and pass it to the business layer, the application can use this data to perform a business process. Many business processes involve multiple steps that must be performed in the correct order, and may interact with each other through an orchestration. Business workflow define and coordinate long running, multi step business processes, and can be implemented using business process management tools. They work with business process components that instantiate and perform operations on workflow components.

Business Entity Business Entity entities, or—more generally—business objects, encapsulate the business logic and data necessary to represent real world elements, such as Customers or Orders, within your application. They store data values and expose them through properties; contain and manage business data used by the application; and provide stateful programmatic access to the business data and related functionality. Business entities also validate the data contained within the entity and encapsulate business logic to ensure consistency and to implement business rules and behavior.

Title: Business Layer in 3 tier Architecture


问:
Creating screen and execute command in it without actually open that screen
Is it possible to create a screen and execute a command in it without actually open it?

What I need to perform is the following:

Open a screen (screen -S screen_name)

Execute command in that screen

At the moment I need to manually create the screen, then enter it, and then execute the desired command.

Is it possible to do that only via 1 bash command?

答:
Create a screen with in detached mode:

```<code>screen -S "scr1" -d -m
</code>```

Send the command to be executed on your screen:

```<code>screen -r "scr1" -X stuff $'ls -lrt \n'
</code>```

The $ before the command is to make the shell parse the \n inside the quotes, and the newline is required to execute the command (like when you press enter).

Body:
Create a screen with in detached mode:

screen -S "scr1" -d -m

Send the command to be executed on your screen:

screen -r "scr1" -X stuff $'ls -lrt \n'

The $ before the command is to make the shell parse the \n inside the quotes, and the newline is required to execute the command (like when you press enter).


问:
"Arithmetic overflow error converting expression to data type datetime" SQL SERVER
I am currently getting this error and i am completely lost as to what the issue is. I tracked the error down to a view and completed a select * statement from it and i get that message. Now, the weird thing is is that this error has never appeared on this view before. It has always ran without any issues and nothings been changed so i am unsure as to what the issue is.

I cant show the data for security reasons but it holds 2 date fields that are

```<code> datetime, not null
</code>```

but i am not trying to change this data in anyway, i am simply just trying to select it.

The only other fields i thought it might concern are

```<code>decimal (38,20)
</code>```

could this be the issue?

Sorry for the lack of information regarding the tables but i have literally tried everything from casting the fields to larger decimals, floats etc and still nothing.

It would be great if there was any small advice anyone could give that would possibly point me in the right direction?

UPDATE

If i do a

```<code>select top (1000)
</code>```

query it works but any larger and i get that error

答:
If using sql server version 2012 or higher, try use TRY_CONVERT function.
It goes like

```<code>SELECT TRY_CONVERT(datetime, ColumnName).
</code>```

NOTE: It will return a NULL if ColumnName contains data which can't be converted to a datetime.

Body:
I am currently getting this error and i am completely lost as to what the issue is. I tracked the error down to a view and completed a select * statement from it and i get that message. Now, the weird thing is is that this error has never appeared on this view before. It has always ran without any issues and nothings been changed so i am unsure as to what the issue is.

I cant show the data for security reasons but it holds 2 date fields that are

 datetime, not null

but i am not trying to change this data in anyway, i am simply just trying to select it.

The only other fields i thought it might concern are

decimal (38,20)

could this be the issue?

Sorry for the lack of information regarding the tables but i have literally tried everything from casting the fields to larger decimals, floats etc and still nothing.

It would be great if there was any small advice anyone could give that would possibly point me in the right direction?

UPDATE

If i do a

select top (1000)

query it works but any larger and i get that error

Body:
If using sql server version 2012 or higher, try use TRY_CONVERT function.
It goes like

SELECT TRY_CONVERT(datetime, ColumnName).

NOTE: It will return a NULL if ColumnName contains data which can't be converted to a datetime.


问:
Disable SonarLint analysis during Debug build
Is it possible (in Visual Studio using SonarLint extension) to disable Sonar Analyzers during Debug build, but keep them enabled in Release build? The reason is that connecting the solution to SonarQube has drastically increased the build time.</p>

答: The only way I can think of is to duplicate your rulesets and lower (disable) rules for the Debug mode but keep the original ruleset for release mode. Note that this is going to be painful because SonarLint will them complain that you have lower strength of the ruletset compared to the Quality Profile on SonarQube. Besides, every time you will update it will probably break this manual tweak.</p>


问:
Getting the field of an object
I have objects like below

```<code>{
"user": "58a9bf92e0f78000055dd932",
"type": "template_created",
"count": 2
}
</code>```

I need to get 'user' field, ..->type returns "template_created" and ..->count gives its value but ..->user returns null. These objects come from mongodb aggregation framework by the way.

答:
You can resolve with two ways :-

```<code>$data = '{
    "user": "58a9bf92e0f78000055dd932",
    "type": "template_created",
    "count": 2
    }';
$objectdata = json_decode($data); //stclassobject
echo $objectdata->count;
  --------OR-------
$arraydata= json_decode($data,true); //convert to array
echo $arraydata['count'];
</code>```

Hope it hepls!

Title: Getting the field of an object

Body:
I have objects like below

{
"user": "58a9bf92e0f78000055dd932",
"type": "template_created",
"count": 2
}

I need to get 'user' field, ..->type returns "template_created" and ..->count gives its value but ..->user returns null. These objects come from mongodb aggregation framework by the way.

Body:
You can resolve with two ways :-

$data = '{
    "user": "58a9bf92e0f78000055dd932",
    "type": "template_created",
    "count": 2
    }';
$objectdata = json_decode($data); //stclassobject
echo $objectdata->count;
  --------OR-------
$arraydata= json_decode($data,true); //convert to array
echo $arraydata['count'];

Hope it hepls!


问:
How to use the Developer Tools in IE 7?
could any one tell me how to use the Developer Tools in IE 7?I am using the .Net programming language .Wanna to debug the javascript and jquery.</p>

答:
When debugging within the browser, it really doesn't matter what kind of server-side language or frameworks you are using (java, .net, php, whatever) all you are really debugging is the javascript on the pages, and javascript is javascript no matter where it came from.

IMO you are MUCH better off if you use chrome's developer mode (activate by right clicking and choosing inspect for instance) or the firefox-plugin called firebug for debugging javascript, but sometimes you get bugs which are only present on IE, in which case you need to check them out using tools for IE,

AFAIK there is no built-in tool for IE7, but here are some tools which work with IE7 to make debugging easier: http://www.ehow.com/list_7148039_developer-tools-ie7.html

ContentLicense: CC BY-SA 2.5

Title: How to use the Developer Tools in IE 7?


问:
Migration to Tomcat 8: InstanceAlreadyExistsException datasource
I have a question about context config in Tomcat 8. I migrating project from Tomcat 7 to 8 and have unusual problem: if nothing change in config I caught an error:

```<code>    "2015-02-03 12:05:48,310 FIRST_ADMIN ERROR web.context.ContextLoader:331
-> Context initialization failed org.springframework.jmx.export.UnableToRegisterMBeanException:
    Unable to register MBean [org.apache.tomcat.dbcp.dbcp2.BasicDataSource@434990dd]
     with key 'dataSource'; nested exception is
    javax.management.InstanceAlreadyExistsException:
    Catalina:type=DataSource,host=localhost,context=/first-
    admin,class=javax.sql.DataSource,name="jdbc/datasource/first"
</code>```

Part of context:

```<code><Resource name="jdbc/datasource/first"
              auth="Container"
              type="javax.sql.DataSource"
              poolPreparedStatements="true"
              initialSize="25"
              maxActive="100"
              maxIdle="100"
              minIdle="25"
              username="us"
              password="pa"
              driverClassName="com.mysql.jdbc.Driver"
              validationQuery="select 1"
              testOnBorrow="true"
          url="jdbc:mysql://localhost:3306/firstproject?useUnicode=true&characterEncoding=UTF-8&profileSQL=false&autoSlowLog=false&slowQueryThresholdMillis=100&autoReconnect=true"/>
</code>```

So, it's works in tomcat 7 without any problem. In Tomcat 8 I can solve this problem in 2 ways:

By adding to resource: singleton = "false";

By adding to resource: factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"

If I clearly understand tomcat creates datasource for my app and for jmx, but in Tomcat 7 it was single object, in Tomcat 8 it must be different. So my question is why that situation has happened? I couldn't find any information of this change in documentation. And I'm interesting what is better: create single datasource (I think so) or create several by factory.

答:
If you want the solution using annotations
Spring boot already defines MBeanExporter bean so you can auto-wire on it

```<code>@Autowired
MBeanExporter mBeanExporter ;
</code>```

Then change the registration policy

```<code>mBeanExporter.setRegistrationPolicy(RegistrationPolicy.IGNORE_EXISTING);
</code>```

Body:
I have a question about context config in Tomcat 8. I migrating project from Tomcat 7 to 8 and have unusual problem: if nothing change in config I caught an error:

    "2015-02-03 12:05:48,310 FIRST_ADMIN ERROR web.context.ContextLoader:331
-> Context initialization failed org.springframework.jmx.export.UnableToRegisterMBeanException:
    Unable to register MBean [org.apache.tomcat.dbcp.dbcp2.BasicDataSource@434990dd]
     with key 'dataSource'; nested exception is
    javax.management.InstanceAlreadyExistsException:
    Catalina:type=DataSource,host=localhost,context=/first-
    admin,class=javax.sql.DataSource,name="jdbc/datasource/first"

Part of context:

<Resource name="jdbc/datasource/first"
              auth="Container"
              type="javax.sql.DataSource"
              poolPreparedStatements="true"
              initialSize="25"
              maxActive="100"
              maxIdle="100"
              minIdle="25"
              username="us"
              password="pa"
              driverClassName="com.mysql.jdbc.Driver"
              validationQuery="select 1"
              testOnBorrow="true"
          url="jdbc:mysql://localhost:3306/firstproject?useUnicode=true&characterEncoding=UTF-8&profileSQL=false&autoSlowLog=false&slowQueryThresholdMillis=100&autoReconnect=true"/>

So, it's works in tomcat 7 without any problem. In Tomcat 8 I can solve this problem in 2 ways:

By adding to resource: singleton = "false";

By adding to resource: factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"

If I clearly understand tomcat creates datasource for my app and for jmx, but in Tomcat 7 it was single object, in Tomcat 8 it must be different. So my question is why that situation has happened? I couldn't find any information of this change in documentation. And I'm interesting what is better: create single datasource (I think so) or create several by factory.

Body:
If you want the solution using annotations
Spring boot already defines MBeanExporter bean so you can auto-wire on it

@Autowired
MBeanExporter mBeanExporter ;

Then change the registration policy

mBeanExporter.setRegistrationPolicy(RegistrationPolicy.IGNORE_EXISTING);


问:
Display the Pixels of Bayer Format Image
I have just started using OpenCv-Python.
I want to see the pixel values of an image which is in Bayer format. Using OpenCv-Python, I have written the following code to display the pixel values :

```<code>import numpy as np
import cv2
image = cv2.imread("bayer_small.png")
image_data = np.array(image)
print(image_data[50][50])

#Output is printed as " [ 0 0 102]
</code>```

My expectation is single pixel value : 102

Why is this happening? Since the image is only in Bayer format, I am expecting one component only per pixel.

I understand that output is showing zero for other two components. But I am expecting the data in the bayer format only, for example : BGBGBGBG for first line.

My goal is to implement an algorithm. Hence trying to do step by step.

Edit 1: Is there any in-built function where I can convert a normal image to Bayer format?

答:
While your picure probably contains the data from the Bayer matrix, it obiously still uses the RGB format for containing it. You can probably assume that two channels contain 0 for each pixel; thus you should apply a vectorized sum to the whole picture along the third axis with:

```<code>data = np.sum(image_data, axis=2)
</code>```

in order to normalize it.

By the way, you can access data in a Numpy array with the more concise syntax: data[50, 50] instead of data[50][50].

Body:
I have just started using OpenCv-Python.
I want to see the pixel values of an image which is in Bayer format. Using OpenCv-Python, I have written the following code to display the pixel values :

import numpy as np
import cv2
image = cv2.imread("bayer_small.png")
image_data = np.array(image)
print(image_data[50][50])

#Output is printed as " [ 0 0 102]

My expectation is single pixel value : 102

Why is this happening? Since the image is only in Bayer format, I am expecting one component only per pixel.

I understand that output is showing zero for other two components. But I am expecting the data in the bayer format only, for example : BGBGBGBG for first line.

My goal is to implement an algorithm. Hence trying to do step by step.

Edit 1: Is there any in-built function where I can convert a normal image to Bayer format?

Body:
While your picure probably contains the data from the Bayer matrix, it obiously still uses the RGB format for containing it. You can probably assume that two channels contain 0 for each pixel; thus you should apply a vectorized sum to the whole picture along the third axis with:

data = np.sum(image_data, axis=2)

in order to normalize it.

By the way, you can access data in a Numpy array with the more concise syntax: data[50, 50] instead of data[50][50].


问:
Call a function in another function
I have a function publicRooms to display public discussions that are on the server. I want to use this data for another function I created addNewMessageNewThread:

```<code>matrixClient.publicRooms(function(err, data) {
  console.log("Public Rooms: %s", JSON.stringify(data));
  console.log("data", data.chunk[0].aliases[0]);

  this.addNewMessageNewThread({
    'id': 'paul',
    'author': 'Paul Manip',
    'body': '  ?'
  });
});
</code>```

Off when I do that, he tells me he does not know this function :

ERROR TypeError: Cannot read property 'addNewMessageNewThread' of
  undefined

And when I test this function outside the function, it works

///////////EDIT//////////////

This is my function addNewMessageNewThread() :

```<code>addNewMessageNewThread(objMessage: any): void {

    const newUser: User      = new User(objMessage.author, objMessage.site);
    const newThread: Thread = new Thread(objMessage.id, [newUser],objMessage.title);
    const newMessage = new Message(objMessage);

    objMessage.date = moment().toDate();

    newThread.arrayMessages.push(newMessage);
    newThread.messages = Observable.of(newThread.arrayMessages);

    newThread.lastMessage = newMessage;

    objMessage.thread = newThread;
    this.addThread(newThread);
}
</code>```

答:
You should pass the context this:

```<code>matrixClient.publicRooms(function(err, data) {
  console.log("Public Rooms: %s", JSON.stringify(data));
  console.log("data", data.chunk[0].aliases[0]);

  this.addNewMessageNewThread({
    'id': 'paul',
    'author': 'Paul Manip',
    'body': '  ?'
  });
}, this);
</code>```

Or use arrow function to use the parent context:

```<code>matrixClient.publicRooms((err, data) => {
  console.log("Public Rooms: %s", JSON.stringify(data));
  console.log("data", data.chunk[0].aliases[0]);

  this.addNewMessageNewThread({
    'id': 'paul',
    'author': 'Paul Manip',
    'body': '  ?'
  });
});
</code>```

Title: Call a function in another function

Body:
I have a function publicRooms to display public discussions that are on the server. I want to use this data for another function I created addNewMessageNewThread:

matrixClient.publicRooms(function(err, data) {
  console.log("Public Rooms: %s", JSON.stringify(data));
  console.log("data", data.chunk[0].aliases[0]);

  this.addNewMessageNewThread({
    'id': 'paul',
    'author': 'Paul Manip',
    'body': '  ?'
  });
});

Off when I do that, he tells me he does not know this function :

ERROR TypeError: Cannot read property 'addNewMessageNewThread' of
  undefined

And when I test this function outside the function, it works

///////////EDIT//////////////

This is my function addNewMessageNewThread() :

addNewMessageNewThread(objMessage: any): void {

    const newUser: User      = new User(objMessage.author, objMessage.site);
    const newThread: Thread = new Thread(objMessage.id, [newUser],objMessage.title);
    const newMessage = new Message(objMessage);

    objMessage.date = moment().toDate();

    newThread.arrayMessages.push(newMessage);
    newThread.messages = Observable.of(newThread.arrayMessages);

    newThread.lastMessage = newMessage;

    objMessage.thread = newThread;
    this.addThread(newThread);
}

Body:
You should pass the context this:

matrixClient.publicRooms(function(err, data) {
  console.log("Public Rooms: %s", JSON.stringify(data));
  console.log("data", data.chunk[0].aliases[0]);

  this.addNewMessageNewThread({
    'id': 'paul',
    'author': 'Paul Manip',
    'body': '  ?'
  });
}, this);

Or use arrow function to use the parent context:

matrixClient.publicRooms((err, data) => {
  console.log("Public Rooms: %s", JSON.stringify(data));
  console.log("data", data.chunk[0].aliases[0]);

  this.addNewMessageNewThread({
    'id': 'paul',
    'author': 'Paul Manip',
    'body': '  ?'
  });
});


问:
How is local function in C#7.0 different from a foreach or a loop?
This is more of a why question. Here it goes.

C# 7.0 added a new feature called "Local Function". Below is a code snippet.

```<code>public int Fibonacci(int x)
{
    if (x < 0) throw new ArgumentException("Less negativity please!", nameof(x));
    return Fib(x).current;

    (int current, int previous) Fib(int i)
    {
        if (i == 0) return (1, 0);
        var (p, pp) = Fib(i - 1);
        return (p + pp, p);
    }
}
</code>```

What I dont understand is, its doing a recursive call to the same method. We can easily achieve this with a normal foreach. Then why a local function.

MSDN says

methods implemented as iterators commonly need a non-iterator wrapper
  method for eagerly checking the arguments at the time of the call.
  (The iterator itself doesn’t start running until MoveNext is called).

Need some help in understanding the concept that it.

答:
its doing a recursive call to the same method. We can easily achieve this with a normal foreach

That are two different things: tail recursion (method calling itself at the end of the method itself) or iterating over a collection. They are not always exchangeable, but they can be used to achieve the same end result.

The local function is nothing more that a class method, with a scope limited to the method body it is declared in.

Local functions are useful for many more than recursion. It is an easy way to prevent repeating code in several blocks.

Body:
This is more of a why question. Here it goes.

C# 7.0 added a new feature called "Local Function". Below is a code snippet.

public int Fibonacci(int x)
{
    if (x < 0) throw new ArgumentException("Less negativity please!", nameof(x));
    return Fib(x).current;

    (int current, int previous) Fib(int i)
    {
        if (i == 0) return (1, 0);
        var (p, pp) = Fib(i - 1);
        return (p + pp, p);
    }
}

What I dont understand is, its doing a recursive call to the same method. We can easily achieve this with a normal foreach. Then why a local function.

MSDN says

methods implemented as iterators commonly need a non-iterator wrapper
  method for eagerly checking the arguments at the time of the call.
  (The iterator itself doesn’t start running until MoveNext is called).

Need some help in understanding the concept that it.


问:
How to process images of a video, frame by frame, in video streaming using OpenCV and Python
I am a beginner in OpenCV. I want to do some image processing on the frames of a video which is being uploaded to my server. I just want to read the available frames and write them in a directory. Then, wait for the other part of the video to be uploaded and write the frames to the directory. And , I should wait for each frame to be completely uploaded then write it to a file.

Can you tell me how can I do it with OpenCV (Python)?

Edit 1:
I wrote this code for capturing the video from a file, while new data are being appended at the end of the file. In other words, the out.mp4 file is not a complete video and another program is writing new frames on it. What I'm going to do is, wait for the other program to write new frames then read them and display them.

Here is my code:

import cv2
cap = cv2.VideoCapture("./out.mp4")

while True:
    if cap.grab():
        flag, frame = cap.retrieve()
        if not flag:
            continue
        else:
            cv2.imshow('video', frame)
    if cv2.waitKey(10) == 27:
        break
```

So the problem is the cap.grab() call! When there is no frame, it will return False! And it won't capture frames anymore, even if I wait for a long time.

答:
The only solution I have found is not to set the index to a previous frame and wait (then OpenCV stops reading frames, anyway), but to initialize the capture one more time. So, it looks like this:

```<code>cap = cv2.VideoCapture(camera_url)
while True:
    ret, frame = cap.read()

    if not ret:
        cap = cv.VideoCapture(camera_url)
        continue

    # do your processing here
</code>```

And it works perfectly!

ContentLicense: CC BY-SA 4.0

Body:
I am a beginner in OpenCV. I want to do some image processing on the frames of a video which is being uploaded to my server. I just want to read the available frames and write them in a directory. Then, wait for the other part of the video to be uploaded and write the frames to the directory. And , I should wait for each frame to be completely uploaded then write it to a file.

Can you tell me how can I do it with OpenCV (Python)?

Edit 1:
I wrote this code for capturing the video from a file, while new data are being appended at the end of the file. In other words, the out.mp4 file is not a complete video and another program is writing new frames on it. What I'm going to do is, wait for the other program to write new frames then read them and display them.

Here is my code:

import cv2
cap = cv2.VideoCapture("./out.mp4")

while True:
    if cap.grab():
        flag, frame = cap.retrieve()
        if not flag:
            continue
        else:
            cv2.imshow('video', frame)
    if cv2.waitKey(10) == 27:
        break

So the problem is the cap.grab() call! When there is no frame, it will return False! And it won't capture frames anymore, even if I wait for a long time.

Body:
The only solution I have found is not to set the index to a previous frame and wait (then OpenCV stops reading frames, anyway), but to initialize the capture one more time. So, it looks like this:

cap = cv2.VideoCapture(camera_url)
while True:
    ret, frame = cap.read()

    if not ret:
        cap = cv.VideoCapture(camera_url)
        continue

    # do your processing here

And it works perfectly!


问:
S_ISDIR returning different value for directory
I'm currently trying to do some kind of recursive find where I need to distinguish regular files with directory.
I made a loop to check with S_ISDIR if a given file is a directory but when applied to /home, I don't get the expected result.
I only have a pome directory in /home so expected result would be :

```<code>/home/.
/home/..
/home/pome
</code>```

but it doesn't detect pome as a directory, S_ISDIR() returns 0 for pome and 1 for . and ..

Code :

```<code>DIR * dir = opendir("/home");
if(dir==NULL){
    puts("Unknown directory");
    return 1;
}
char path[SIZE_PATH];
memset(path,'\0',sizeof(path));
strcpy(path,"/home");
struct dirent * trucdir;
char filename[SIZE_PATH];
memset(filename,'\0',sizeof(filename));
struct stat * filestat=malloc(sizeof(struct stat));
while((trucdir=readdir(dir))!=NULL){
    memset(filename,'\0',sizeof(filename));
    strcpy(filename,trucdir->d_name);
    stat(filename,filestat);
    if(S_ISDIR(filestat->st_mode)!=0){
        puts(filename);
    }
}
</code>```

Isn't S_ISDIR supposed to return a non-zero value if the file is a directory ?

答:
You have to check, that your stat()-call actually succeeds  by checking its return value. In your case, the call to stat is:

```<code>stat("pome", filestat);
</code>```

but your current working directory (cwd) is not /home!

Hence, the call to stat fails with -1 and errno ENOENT and the IS_DIR-macro is meaningless. The stat-calls to . and .. of course succeed, since they are present in all directories (although other information like inode number etc. doesn't match then)

You have to make sure that you either provide the full path in filename (i.e. /home/pome) or you set the cwd to /home before (with chdir("/home");); this should solve your issue!

Body:
I'm currently trying to do some kind of recursive find where I need to distinguish regular files with directory.
I made a loop to check with S_ISDIR if a given file is a directory but when applied to /home, I don't get the expected result.
I only have a pome directory in /home so expected result would be :

/home/.
/home/..
/home/pome

but it doesn't detect pome as a directory, S_ISDIR() returns 0 for pome and 1 for . and ..

Code :

DIR * dir = opendir("/home");
if(dir==NULL){
    puts("Unknown directory");
    return 1;
}
char path[SIZE_PATH];
memset(path,'\0',sizeof(path));
strcpy(path,"/home");
struct dirent * trucdir;
char filename[SIZE_PATH];
memset(filename,'\0',sizeof(filename));
struct stat * filestat=malloc(sizeof(struct stat));
while((trucdir=readdir(dir))!=NULL){
    memset(filename,'\0',sizeof(filename));
    strcpy(filename,trucdir->d_name);
    stat(filename,filestat);
    if(S_ISDIR(filestat->st_mode)!=0){
        puts(filename);
    }
}

Isn't S_ISDIR supposed to return a non-zero value if the file is a directory ?

Body:
You have to check, that your stat()-call actually succeeds  by checking its return value. In your case, the call to stat is:

stat("pome", filestat);

but your current working directory (cwd) is not /home!

Hence, the call to stat fails with -1 and errno ENOENT and the IS_DIR-macro is meaningless. The stat-calls to . and .. of course succeed, since they are present in all directories (although other information like inode number etc. doesn't match then)

You have to make sure that you either provide the full path in filename (i.e. /home/pome) or you set the cwd to /home before (with chdir("/home");); this should solve your issue!


问:
DataFrame.lookup for a value in multi-index DataFrame
I'm struggling to replicate this
solution for a multiindex columns
DataFrame.

Given this df:

```<code>>>> import pandas as pd
>>> import numpy as np
>>>
>>> # given dataframe
>>> arrays = [np.array(['REF',  'A1', 'A1', 'A2', 'A2']),
>>>           np.array(['absmax', 'min', 'max', 'min', 'max'])]
>>> values = np.array([[-0.1, -0.11, 0.8, -0.7, 0.8],
>>>           [0.05, -0.2, 0.01, -0.23, 0.07],
>>>           [-0.07, -0.15, 0.23, -0.09, 0.01]])
>>> df = pd.DataFrame(values, columns=arrays).sort_index(axis=1)
>>> print(df)

     A1          A2          REF
    max   min   max   min absmax
0  0.80 -0.11  0.80 -0.70  -0.10
1  0.01 -0.20  0.07 -0.23   0.05
2  0.23 -0.15  0.01 -0.09  -0.07
</code>```

I need to create for all columns Ai a sub-column absmax that would duplicate
('Ai', 'min') or ('Ai', 'max') depending on the sign of ('REF', 'absmax').
Provided the previous DataFrame, I would expect:

```<code>      A1                 A2                REF
  absmax   max   min absmax   max   min absmax
0  -0.11  0.80 -0.11  -0.70  0.80 -0.70  -0.10
1   0.01  0.01 -0.20   0.07  0.07 -0.23   0.05
2  -0.15  0.23 -0.15  -0.09  0.01 -0.09  -0.07
</code>```

To achieve this, I first create a vec column retrieving the relevant
sub-column name:

```<code>>>> # retrieve value to read based on REF/absmax sign
>>> df[('REF', 'vec')] = np.where(df['REF', 'absmax']<0, 'min', 'max')
>>> print(df.sort_index(axis=1))
     A1          A2          REF
    max   min   max   min absmax  vec
0  0.80 -0.11  0.80 -0.70  -0.10  min
1  0.01 -0.20  0.07 -0.23   0.05  max
2  0.23 -0.15  0.01 -0.09  -0.07  min
</code>```

And trying to assign the relevant value for 'A1' (knowing I can have a bunch of 'Ai' columns):

```<code>>>> # assign value
>>> df[('A1', 'absmax')] = df.lookup(df.index, df[('A1', df[('REF', 'vec')])])
>>> df.sort_index(axis=1, inplace=True)
>>> print(df)
---------------------------------------------------------------------
TypeError                           Traceback (most recent call last)
[...]
TypeError: '('A1', 0    min
1    max
2    min
Name: (REF, vec), dtype: object)' is an invalid key
</code>```

Which makes sense. Any idea how to solve this?

PS:

```<code>>>> print('pandas %s' % pd.__version__)
>>> print('numpy %s' % np.__version__)
pandas 0.20.3
numpy 1.13.1
</code>```

答:
One way to do it

```<code>ref = df[('REF', 'absmax')]

vec = np.array(['min', 'max'])[ref.ge(0).astype(int)]

lu = lambda d, vec: d.assign(absmax=d.lookup(d.index, vec))
df.filter(like='A').stack(0).groupby(level=1).apply(lu, vec=vec) \
  .unstack().swaplevel(0, 1, 1).sort_index(1).join(ref)

      A1                 A2                REF
  absmax   max   min absmax   max   min absmax
0  -0.11  0.80 -0.11  -0.70  0.80 -0.70  -0.10
1   0.01  0.01 -0.20   0.07  0.07 -0.23   0.05
2  -0.15  0.23 -0.15  -0.09  0.01 -0.09  -0.07
</code>```

I could be more explicit by using drop instead of filter

```<code>ref = df[('REF', 'absmax')]

vec = np.array(['min', 'max'])[ref.ge(0).astype(int)]

lu = lambda d, vec: d.assign(absmax=d.lookup(d.index, vec))
df.drop(('REF', 'absmax'), 1).stack(0).groupby(level=1).apply(lu, vec=vec) \
  .unstack().swaplevel(0, 1, 1).sort_index(1).join(ref)
</code>```

Body:
I'm struggling to replicate this
solution for a multiindex columns
DataFrame.

Given this df:

>>> import pandas as pd
>>> import numpy as np
>>>
>>> # given dataframe
>>> arrays = [np.array(['REF',  'A1', 'A1', 'A2', 'A2']),
>>>           np.array(['absmax', 'min', 'max', 'min', 'max'])]
>>> values = np.array([[-0.1, -0.11, 0.8, -0.7, 0.8],
>>>           [0.05, -0.2, 0.01, -0.23, 0.07],
>>>           [-0.07, -0.15, 0.23, -0.09, 0.01]])
>>> df = pd.DataFrame(values, columns=arrays).sort_index(axis=1)
>>> print(df)

     A1          A2          REF
    max   min   max   min absmax
0  0.80 -0.11  0.80 -0.70  -0.10
1  0.01 -0.20  0.07 -0.23   0.05
2  0.23 -0.15  0.01 -0.09  -0.07

I need to create for all columns Ai a sub-column absmax that would duplicate
('Ai', 'min') or ('Ai', 'max') depending on the sign of ('REF', 'absmax').
Provided the previous DataFrame, I would expect:

      A1                 A2                REF
  absmax   max   min absmax   max   min absmax
0  -0.11  0.80 -0.11  -0.70  0.80 -0.70  -0.10
1   0.01  0.01 -0.20   0.07  0.07 -0.23   0.05
2  -0.15  0.23 -0.15  -0.09  0.01 -0.09  -0.07

To achieve this, I first create a vec column retrieving the relevant
sub-column name:

>>> # retrieve value to read based on REF/absmax sign
>>> df[('REF', 'vec')] = np.where(df['REF', 'absmax']<0, 'min', 'max')
>>> print(df.sort_index(axis=1))
     A1          A2          REF
    max   min   max   min absmax  vec
0  0.80 -0.11  0.80 -0.70  -0.10  min
1  0.01 -0.20  0.07 -0.23   0.05  max
2  0.23 -0.15  0.01 -0.09  -0.07  min

And trying to assign the relevant value for 'A1' (knowing I can have a bunch of 'Ai' columns):

>>> # assign value
>>> df[('A1', 'absmax')] = df.lookup(df.index, df[('A1', df[('REF', 'vec')])])
>>> df.sort_index(axis=1, inplace=True)
>>> print(df)
---------------------------------------------------------------------
TypeError                           Traceback (most recent call last)
[...]
TypeError: '('A1', 0    min
1    max
2    min
Name: (REF, vec), dtype: object)' is an invalid key

Which makes sense. Any idea how to solve this?

PS:

>>> print('pandas %s' % pd.__version__)
>>> print('numpy %s' % np.__version__)
pandas 0.20.3
numpy 1.13.1

Body:
One way to do it

ref = df[('REF', 'absmax')]

vec = np.array(['min', 'max'])[ref.ge(0).astype(int)]

lu = lambda d, vec: d.assign(absmax=d.lookup(d.index, vec))
df.filter(like='A').stack(0).groupby(level=1).apply(lu, vec=vec) \
  .unstack().swaplevel(0, 1, 1).sort_index(1).join(ref)

      A1                 A2                REF
  absmax   max   min absmax   max   min absmax
0  -0.11  0.80 -0.11  -0.70  0.80 -0.70  -0.10
1   0.01  0.01 -0.20   0.07  0.07 -0.23   0.05
2  -0.15  0.23 -0.15  -0.09  0.01 -0.09  -0.07

I could be more explicit by using drop instead of filter

ref = df[('REF', 'absmax')]

vec = np.array(['min', 'max'])[ref.ge(0).astype(int)]

lu = lambda d, vec: d.assign(absmax=d.lookup(d.index, vec))
df.drop(('REF', 'absmax'), 1).stack(0).groupby(level=1).apply(lu, vec=vec) \
  .unstack().swaplevel(0, 1, 1).sort_index(1).join(ref)


问:
c# console application backup mysql
I try to use this code as a console application so that I can back up mydatabase automatics
I am not sure what wrong with it</p>

```<code>static void Main(string[] args)
{
    try
    {
        DateTime backupTime = DateTime.Now;
        int year = backupTime.Year;
        int month = backupTime.Month;
        int day = backupTime.Day;
        int hour = backupTime.Hour;
        int minute = backupTime.Minute;
        int second = backupTime.Second;
        int ms = backupTime.Millisecond;

        String tmestr = backupTime.ToString();
        tmestr = "C:\\" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + ".sql";
        StreamWriter file = new StreamWriter(tmestr);
        ProcessStartInfo proc = new ProcessStartInfo();
        string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql");
        proc.FileName = "mysqldump";
        proc.RedirectStandardInput = false;
        proc.RedirectStandardOutput = true;
        proc.Arguments = cmd;//"-u root -p smartdb > testdb.sql";
        proc.UseShellExecute = false;
        Process p = Process.Start(proc);
        string res;
        res = p.StandardOutput.ReadToEnd();
        file.WriteLine(res);
        p.WaitForExit();
        file.Close();

    }

    catch (IOException ex)
    {
        MessageBox.Show("Disk full or other IO error , unable to backup!");
    }
}
</code>```

答:
for starters i would change how you're outputting the information. You're essentially opening a file so you can redirect the backup utility's output to that file. The > in your process call is for that very purpose. Just change your "backup.sql" parameter to tmestr.

Also, because the output is already being redirected to a file, your process won't have anything to return. But because we're now having it dump to the correct path, this should be irrelevant.

One final change, add a space between your -u{0} so it's -u {0}. And the same with -h{2}.

In summary:

remove StreamWriter and all variables associated to it

modify the String.Format in your process arguments to use `tmestr

add spaces in your cmd variable for -u&-h

And you should be good-to-go (assuming it's not a problem with locating the mysqldump executable.

Title: c# console application backup mysql

Body:
I try to use this code as a console application so that I can back up mydatabase automatics
I am not sure what wrong with it

static void Main(string[] args)
{
    try
    {
        DateTime backupTime = DateTime.Now;
        int year = backupTime.Year;
        int month = backupTime.Month;
        int day = backupTime.Day;
        int hour = backupTime.Hour;
        int minute = backupTime.Minute;
        int second = backupTime.Second;
        int ms = backupTime.Millisecond;

        String tmestr = backupTime.ToString();
        tmestr = "C:\\" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + ".sql";
        StreamWriter file = new StreamWriter(tmestr);
        ProcessStartInfo proc = new ProcessStartInfo();
        string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql");
        proc.FileName = "mysqldump";
        proc.RedirectStandardInput = false;
        proc.RedirectStandardOutput = true;
        proc.Arguments = cmd;//"-u root -p smartdb > testdb.sql";
        proc.UseShellExecute = false;
        Process p = Process.Start(proc);
        string res;
        res = p.StandardOutput.ReadToEnd();
        file.WriteLine(res);
        p.WaitForExit();
        file.Close();

    }

    catch (IOException ex)
    {
        MessageBox.Show("Disk full or other IO error , unable to backup!");
    }
}


问:
Selecting arrays with specific element values
This is driving me nuts, I've been trying to figure out how to do this one thing for hours now.

What I want to do is select all array items that have a specific value. This is easiest to explain by example:

I have an array, called media[]. It holds ALL of the media in my media gallery. It has two properties of note: path and gallery, or media[x][0] and media[x][1].

I want to select all media objects that belong in a certain gallery, and then add them to that gallery. That's where I'm struggling and it's driving me mad.

Here are my fumbled attempts at trying to do this... this is some seriously messy code (and mostly pointless), I'm just providing it so you can get a sense of how clueless I am about this. Please note that NONE of the code I have right now actually tries to do anything; everything I've done so far ends up as a broken for or while loop that either does nothing or crashes Chrome.

```<code>// this function is meant to return an array of all media items
// that belong in a certain gallery... didn't get that far because
// the loops tripped me up
function getTheMedia (galNum) {
    var output = [];
    for (var i = 0; i < media.length; ++i) {
        // I tried using an if statement here to check if the
        // media[i][1] == galNum, and if so, add it to the output
        // but that didn't work
        output.push(media[i]);
    }
    return output;
}

// this function was actually my first attempt but I kept running into
// the same issue as above
function fillGal () {
    /*
    var output = [];
    for (var i = 0; i < Gallery.length; ++i) {
        output.push(Gallery[i]);
    }
    */
    var output = [];
    var i = 0;
    while (i < media.length) {
        output.push(i);
        i++;
    }
    console.log(output);
}
</code>```

Seeing as I'm kind of burnt out and frustrating with running in circles (...loops? aha...), all I'm really looking for is a way to select only those specific array items as specified above. Everything else (adding them to the Gallery, etc) I can figure out myself.

Otherwise I'm just going to have to go back to the old way: define separate media[]arrays for each "gallery" (mediaThisGallery, mediaThatGallery, etc), and then combine them all at the end to get "allMedia". Only reason I don't want to do that is because I want to be able to change which gallery a media item belongs to... this HAS to be possible, right?

Thanks in advance! Sorry for the scatter-brainedness. I also apologize if the title is a bit off.

EDIT:

```<code>var media = [];

media[0] = ['0.png', 0, 'index'];
media[1] = ['0.png', 0];

media[2] = ['new/316.png', 1, "316"];
media[3] = ['new/kitties.jpg', 1, "D'aww kitties!!"];
media[4] = ['new/home.jpg', 1, "\"I'm Going Home\""];
media[5] = ['new/3.mp4', 1, "Crucible Carnage"];
media[6] = ['new/942.jpg', 1, "this is straight for testing purposes like omg long ass title lol"];
media[7] = ['new/boom.mp4', 1, "Maximum Efficiency"];
media[8] = ['new/42.jpg', 1, "Moo"];

// this is only included as a quick fix so my working code doesn't break
// as my "production" code is using multiple arrays; Media is used
// to store only the selected array (current Gallery)
// in other words, ignore this
var Media = [];
Media = media;

var Gallery = [];
Gallery[0] = [mediaRoot, "index", media ];
Gallery[1] = [mediaRoot, "new", Media ];
</code>```

It's pretty arbitrary atm.

Note that the main reason I'm converting from multiple arrays to a single array is that eventually, I plan to expand this app and I thought it made more sense to store ALL media in a single "database".

答:
Well you can simply use .filter() method like this:

```<code>var output = media.filter(function(m) {
  return m[1] == galNum;
});
</code>```

Body:
This is driving me nuts, I've been trying to figure out how to do this one thing for hours now.

What I want to do is select all array items that have a specific value. This is easiest to explain by example:

I have an array, called media[]. It holds ALL of the media in my media gallery. It has two properties of note: path and gallery, or media[x][0] and media[x][1].

I want to select all media objects that belong in a certain gallery, and then add them to that gallery. That's where I'm struggling and it's driving me mad.

Here are my fumbled attempts at trying to do this... this is some seriously messy code (and mostly pointless), I'm just providing it so you can get a sense of how clueless I am about this. Please note that NONE of the code I have right now actually tries to do anything; everything I've done so far ends up as a broken for or while loop that either does nothing or crashes Chrome.

// this function is meant to return an array of all media items
// that belong in a certain gallery... didn't get that far because
// the loops tripped me up
function getTheMedia (galNum) {
    var output = [];
    for (var i = 0; i < media.length; ++i) {
        // I tried using an if statement here to check if the
        // media[i][1] == galNum, and if so, add it to the output
        // but that didn't work
        output.push(media[i]);
    }
    return output;
}

// this function was actually my first attempt but I kept running into
// the same issue as above
function fillGal () {
    /*
    var output = [];
    for (var i = 0; i < Gallery.length; ++i) {
        output.push(Gallery[i]);
    }
    */
    var output = [];
    var i = 0;
    while (i < media.length) {
        output.push(i);
        i++;
    }
    console.log(output);
}

Seeing as I'm kind of burnt out and frustrating with running in circles (...loops? aha...), all I'm really looking for is a way to select only those specific array items as specified above. Everything else (adding them to the Gallery, etc) I can figure out myself.

Otherwise I'm just going to have to go back to the old way: define separate media[]arrays for each "gallery" (mediaThisGallery, mediaThatGallery, etc), and then combine them all at the end to get "allMedia". Only reason I don't want to do that is because I want to be able to change which gallery a media item belongs to... this HAS to be possible, right?

Thanks in advance! Sorry for the scatter-brainedness. I also apologize if the title is a bit off.

EDIT:

var media = [];

media[0] = ['0.png', 0, 'index'];
media[1] = ['0.png', 0];

media[2] = ['new/316.png', 1, "316"];
media[3] = ['new/kitties.jpg', 1, "D'aww kitties!!"];
media[4] = ['new/home.jpg', 1, "\"I'm Going Home\""];
media[5] = ['new/3.mp4', 1, "Crucible Carnage"];
media[6] = ['new/942.jpg', 1, "this is straight for testing purposes like omg long ass title lol"];
media[7] = ['new/boom.mp4', 1, "Maximum Efficiency"];
media[8] = ['new/42.jpg', 1, "Moo"];

// this is only included as a quick fix so my working code doesn't break
// as my "production" code is using multiple arrays; Media is used
// to store only the selected array (current Gallery)
// in other words, ignore this
var Media = [];
Media = media;

var Gallery = [];
Gallery[0] = [mediaRoot, "index", media ];
Gallery[1] = [mediaRoot, "new", Media ];

It's pretty arbitrary atm.

Note that the main reason I'm converting from multiple arrays to a single array is that eventually, I plan to expand this app and I thought it made more sense to store ALL media in a single "database".

Body:
Well you can simply use .filter() method like this:

var output = media.filter(function(m) {
  return m[1] == galNum;
});


问:
how fix encoding on java
Good afternoon,

I'm trying resolve the classic encoding error in java, but I don't know what to do...

I try:

```<code>add on jsp: <%@page contentType="text/html"pageEncoding="UTF-8"%>

use "SQL_Latin1_General_CP1_CI_AS" no select(sqlserver)

add "CharacterSet=UTF-8" on String conection of jdbc

add response.setContentType("application/json"); and response.setCharacterEncoding("utf-8");  on servlet
</code>```

but nothing works!!!!

SGBD: SQL Server
Server: GlassFish

Exemple record of database "EstÃƒÂ¡"

what can I do?

答:
Seems that you have jtds parameter sendStringParametersAsUnicode=false

One solution is to change it to true. If not then:

SQL_Latin1_General_CP1_CI_AS is CP-1252 (Windows-1252) encoding, so to search in database you need to encode your Unicode string to Windows-1252:

```<code>new String(value.getBytes("UTF-8"), "Windows-1252")
</code>```

Vice versa after read from database:

```<code>new String(value.getBytes("Windows-1252"), "UTF-8")
</code>```

Title: how fix encoding on java

Body:
Good afternoon,

I'm trying resolve the classic encoding error in java, but I don't know what to do...

I try:

add on jsp: <%@page contentType="text/html"pageEncoding="UTF-8"%>

use "SQL_Latin1_General_CP1_CI_AS" no select(sqlserver)

add "CharacterSet=UTF-8" on String conection of jdbc

add response.setContentType("application/json"); and response.setCharacterEncoding("utf-8");  on servlet

but nothing works!!!!

SGBD: SQL Server
Server: GlassFish

Exemple record of database "EstÃƒÂ¡"

what can I do?

Body:
Seems that you have jtds parameter sendStringParametersAsUnicode=false

One solution is to change it to true. If not then:

SQL_Latin1_General_CP1_CI_AS is CP-1252 (Windows-1252) encoding, so to search in database you need to encode your Unicode string to Windows-1252:

new String(value.getBytes("UTF-8"), "Windows-1252")

Vice versa after read from database:

new String(value.getBytes("Windows-1252"), "UTF-8")


问:
MFC Classes and C++ style casts
I'm wondering if I haven't fully understood C++ casts versus old C-Style cast. In MFC I have this method:

```<code>CWnd * GetDlgItem(UINT uResId);
</code>```

I'm expecting that a CComboBox (or CEdit), which is derived from CWnd, requires this kind of cast:

```<code>dynamic_cast<CComboBox *>(GetDlgItem(IDC_COMBO1));
// for CEdit:
dynamic_cast<CEdit *>(GetDlgItem(IDC_EDIT1));
</code>```

but this operation causes a crash for using null pointer, that means that cast have failed. Using:

```<code>reinterpret_cast<CComboBox *>(GetDlgItem(IDC_COMBO1));
// for CEdit:
reinterpret_cast<CEdit *>(GetDlgItem(IDC_EDIT1));
</code>```

fixes the problem, but I'm disappointed.
What am I missing?

答:
```<code>class A {
public:
    A() {};

    virtual ~A(){}
};

class B : public A {
public:
    B() {};
    virtual ~B() {}
};

int main()
{

    A* a = new A();
    B* b = dynamic_cast<B*>(a);
    // b is 0
    return 0;
}
</code>```

As in winocc.cpp

```<code>CWnd* CWnd::GetDlgItem(int nID) const
{
    ASSERT(::IsWindow(m_hWnd));

    if (m_pCtrlCont == NULL)
        return CWnd::FromHandle(::GetDlgItem(m_hWnd, nID));
    else
        return m_pCtrlCont->GetDlgItem(nID);
}
</code>```

and wincore.cpp

```<code>CWnd* PASCAL CWnd::FromHandle(HWND hWnd)
{
    CHandleMap* pMap = afxMapHWND(TRUE); //create map if not exist
    ASSERT(pMap != NULL);
    CWnd* pWnd = (CWnd*)pMap->FromHandle(hWnd);

    pWnd->AttachControlSite(pMap);

    ASSERT(pWnd == NULL || pWnd->m_hWnd == hWnd);
    return pWnd;
}
</code>```

When CHandleMap contains the object is CWnd not a CComboBox or any other derived class type, it will not ok by using dynamic_cast to cast down.

Title: MFC Classes and C++ style casts

Body:
I'm wondering if I haven't fully understood C++ casts versus old C-Style cast. In MFC I have this method:

CWnd * GetDlgItem(UINT uResId);

I'm expecting that a CComboBox (or CEdit), which is derived from CWnd, requires this kind of cast:

dynamic_cast<CComboBox *>(GetDlgItem(IDC_COMBO1));
// for CEdit:
dynamic_cast<CEdit *>(GetDlgItem(IDC_EDIT1));

but this operation causes a crash for using null pointer, that means that cast have failed. Using:

reinterpret_cast<CComboBox *>(GetDlgItem(IDC_COMBO1));
// for CEdit:
reinterpret_cast<CEdit *>(GetDlgItem(IDC_EDIT1));

fixes the problem, but I'm disappointed.
What am I missing?

Body:
class A {
public:
    A() {};

    virtual ~A(){}
};

class B : public A {
public:
    B() {};
    virtual ~B() {}
};

int main()
{

    A* a = new A();
    B* b = dynamic_cast<B*>(a);
    // b is 0
    return 0;
}

As in winocc.cpp

CWnd* CWnd::GetDlgItem(int nID) const
{
    ASSERT(::IsWindow(m_hWnd));

    if (m_pCtrlCont == NULL)
        return CWnd::FromHandle(::GetDlgItem(m_hWnd, nID));
    else
        return m_pCtrlCont->GetDlgItem(nID);
}

and wincore.cpp

CWnd* PASCAL CWnd::FromHandle(HWND hWnd)
{
    CHandleMap* pMap = afxMapHWND(TRUE); //create map if not exist
    ASSERT(pMap != NULL);
    CWnd* pWnd = (CWnd*)pMap->FromHandle(hWnd);

    pWnd->AttachControlSite(pMap);

    ASSERT(pWnd == NULL || pWnd->m_hWnd == hWnd);
    return pWnd;
}

When CHandleMap contains the object is CWnd not a CComboBox or any other derived class type, it will not ok by using dynamic_cast to cast down.


问:
Check for value definedness in C++
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

```<code>class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}
</code>```

Is it possible in C++?

Thanks

答: As others pointed out, there is nothing like an "undefined" state.  But you may want to look into boost.optional</p>

OwnerDisplayName: Tunnuz

Title: Check for value definedness in C++

Body:
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}

Is it possible in C++?

Thanks

OwnerDisplayName: gimpf


问:
Halide Func reshape
I want to convert the dimensions of a Halide Func. For example consider the following,

func1(x, y, z) = some operation

I know the range of each dimension of the function. Lets assume they are

x = [0, 3], y = [0, 3], z = [0, 15]
Now if I want to convert the func to 1 dimension, something like this

flatten(z * 16 + y * 4 + x) = func1(x, y, z)

But the above definition is not valid as the function definition does not have a pure Var. Is there anyway I can do this in Halide?

答:
You'll need to express it as a pure function of one variable, e.g.:

```<code>flatten(x) = func1(x % 4, (x % 16) / 4, x / 16);
</code>```

You can simplify away much of this added addressing arithmetic by scheduling flatten appropriately, for example:

```<code>// Require the bounds realized to be a multiple of 16.
flatten.align_bounds(x, 16);

// Split the loops at the "critical points" of the addressing arithmetic.
flatten
    .unroll(x, 4, TailStrategy::RoundUp)
    .split(x, xo, xi, 4, TailStrategy::RoundUp);
</code>```

Title: Halide Func reshape

Body:
You'll need to express it as a pure function of one variable, e.g.:

flatten(x) = func1(x % 4, (x % 16) / 4, x / 16);

You can simplify away much of this added addressing arithmetic by scheduling flatten appropriately, for example:

// Require the bounds realized to be a multiple of 16.
flatten.align_bounds(x, 16);

// Split the loops at the "critical points" of the addressing arithmetic.
flatten
    .unroll(x, 4, TailStrategy::RoundUp)
    .split(x, xo, xi, 4, TailStrategy::RoundUp);


问:
Create Series of Families On a Selected Path In Revit Using Dynamo
I’ve started exploring dynamo for a while now and quite enjoying its power. I’ve started work on a project, I’m wondering if someone would like to share their expert views on how do I create series of families from one starting point to other. See the following image to understand it visually. I’m sure we can achieve such functionality via Dynamo. Appreciate any help. Thank you.

答: Here is a discussion of using a dynamic model updater DMU in conjunction with the Idling event to achieve a couple of complex synchronisation tasks, including a video of almost exactly what you are asking for: Updater Queues Multi-Transaction Operation for Idling.


问:
Pass variable from custom Laravel Helpers to Blade file
I'm trying to create a helper to centralize a complicated Form::select.

My helper:

```<code>namespace App\Helpers;
use Log;
use App\Countries;

class Address {
    public static function country() {
        $countries = Countries::orderby('name_zh','asc');
        $form = "Form::select('countries', \$countries);";
        return $form;
    }
}
</code>```

My View:

```<code>{!! Address::country() !!}
</code>```

I would like to have this select form with $countries variable from this helper and show a Dropdown list on my view. How do I do it?

答:
In your helper create the select using the Laravel Collective helper the return it t the view, do it like this:

```<code>public static function country() {
    $countries = Countries::orderby('name_zh','asc')
                            ->pluck('name', 'id');
    return Form::select('countries', $countries);
}
</code>```

In the view just call the method :

```<code>{{ Address::country() }}
</code>```

Or if you want the $countries variable as well you can send it to the view from the controller then send it to the helper as well :

```<code>public function controllerFunction() {
    $countries = Countries::orderby('name_zh','asc')
                            ->get();
    return view('yourView')->withCountries($countries);
}
</code>```

And in the view you have access to this $countries then pass it to the helper :

```<code>{{ Address::country($countries->pluck('name', 'id')) }}
</code>```

And the helper this time should look like this :

```<code>public static function country($countries) {
    return Form::select('countries', $countries);
}
</code>```

Body:
I'm trying to create a helper to centralize a complicated Form::select.

My helper:

namespace App\Helpers;
use Log;
use App\Countries;

class Address {
    public static function country() {
        $countries = Countries::orderby('name_zh','asc');
        $form = "Form::select('countries', \$countries);";
        return $form;
    }
}

My View:

{!! Address::country() !!}

I would like to have this select form with $countries variable from this helper and show a Dropdown list on my view. How do I do it?

Body:
In your helper create the select using the Laravel Collective helper the return it t the view, do it like this:

public static function country() {
    $countries = Countries::orderby('name_zh','asc')
                            ->pluck('name', 'id');
    return Form::select('countries', $countries);
}

In the view just call the method :

{{ Address::country() }}

Or if you want the $countries variable as well you can send it to the view from the controller then send it to the helper as well :

public function controllerFunction() {
    $countries = Countries::orderby('name_zh','asc')
                            ->get();
    return view('yourView')->withCountries($countries);
}

And in the view you have access to this $countries then pass it to the helper :

{{ Address::country($countries->pluck('name', 'id')) }}

And the helper this time should look like this :

public static function country($countries) {
    return Form::select('countries', $countries);
}


问:
Angular throwing exception 'module cant be loaded'!
I was trying to clean my angular app code up. So I moved all the controllers in their own files. But when I moved the controllers, my main app stoped working and started throwing the exception below -

Error: $injector:modulerr
  Module Error

Then I tried searching for the why the module won't load but with no luck.

```<code>main.js /*File where app module is declared*/

var app = angular.module('app', ['ngRoute','thatisuday.dropzone','UserController','LinkController','articleController']);
</code>```

I tried injecting the dependency for the controller files.

Controllers:

Link Controller

```<code>var app = angular.module('app');

app.controller('LinkController', ['$scope','$http','$sce',function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
    return $sce.trustAsHtml(html_code);
};

$scope.trustSrc = function (src) {
    return $sce.trustAsResourceUrl(src);
};

/*First AJAX request which gets all the links and categories for the user*/

$http({
    method: 'GET',
    url: '/users'
}).then(function successCallback(response) {

    $scope.user = response.data;

}, function errorCallback(response) {

});

$scope.getUser = function () {
    $http({
        method: 'GET',
        url: '/users'
    }).then(function successCallback(response) {

        $scope.user = response.data;

    }, function errorCallback(response) {

    });
};

$http({
    method: 'GET',
    url: '/links'
}).then(function successCallback(response) {

    this.orderProp = 'age';

    /*the response is saved in scope variables*/
    $scope.links = response.data[0];
    $scope.categories = response.data[1];
    $scope.categorytolink = response.data[2];

}, function errorCallback(response) {
    console.log('There was a problem! Refresh!');
});

/*AJAX request for getting the recommendations according to the most viewed stars*/

$http({
    method: 'GET',
    url: '/recommendations/top'
}).then(function successCallback(response) {

    $scope.recommendations = response.data;

}, function errorCallback(response) {

});

/*AJAX request when a user clicks a link retrieves the link data*/
$scope.getLinkData = function (link) {
    $http({
        method: 'GET',
        url: "/proxy",
        headers: {
            "X-Proxy-To": link.rss_link
        }
    }).then(function successCallback(response) {

        /*AJAX request: add a star to the link*/

        $http.post('/links/' + link.id + '/views/add', {'link': link}).then(function successCallback(data, status, headers, config) {

            // Manually increment star for link just clicked

            var $data;

            $data = data.data;

            $scope.link = $data;

            console.log('200 OK! Star added');

        }, function errorCallback() {

            console.log('Error!');

        });

        /*The data will be retrieved and will be sorted according to the requirements of welcome.blade*/

        $myXml = response.data;

        $xmlObj = $.parseXML($myXml);

        $newsItems = [];

        $channelImage = $($xmlObj).find("channel>image");

        /*the information of the link is sorted */

        $linkData = {
            "title": $channelImage.find("title").text(),
            "link": $channelImage.find("link").text(),
            "imgurl": $channelImage.find("url").text()

        };

        /*the data is sorted below*/

        $.each($($xmlObj).find("item"), function (index, value) {
            $newsItems.push({
                "title": $(value).find("title").text(),
                "description": $(value).find("description").text(),
                "link": $(value).find("link").text(),
                "date_published": moment($(value).find("pubDate").text()).format('MMMM Do YYYY'),
                "time_published": moment($(value).find("pubDate").text()).format('h:mm:ss a'),
                "guid": $(value).find("guid").text()
            })
        });

        $scope.newsItems = $newsItems;

        $scope.linkData = $linkData;

    }, function errorCallback(response) {

    });
};

/*Create a category private to the user*/

$scope.create_category = function (category) {

    /*AJAX request: adds a new category*/
    $http.post('/categories/new', {'category': category}).then(function successCallback(response) {

        /*AJAX request: Updates the categories for the use of new category*/

        $http({
            method: 'GET',
            url: '/categories'
        }).then(function successCallback(response) {

            $scope.categories = response.data;

        }, function errorCallback(response) {

        });
    }, function errorCallback(response) {

    });

};
}]);
</code>```

User Controller

```<code>    var app = angular.module('app');

app.controller("UserController", ['$scope','$http','$sce', function ($scope, $http, $sce) {

/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
    return $sce.trustAsHtml(html_code);
};

$scope.trustSrc = function (src) {
    return $sce.trustAsResourceUrl(src);
};

$scope.dzOptions = {
    paramName: "file",
    dictDefaultMessage: "<h4><i class='fa fa-camera'></i> <b>Upload</b></h4>",
    createImageThumbnails: false,
    autoDiscover: false
};

$scope.dzCallbacks = {
    'sending': function (file, xhr, formData) {
        formData.append('_token', $('#csrf-token').val());
    },
    'success': function (file, response) {
        $scope.user = response;
        $.notify("Profile photo changed!", "success", {autoHide: true, autoHideDelay: 500});
    }
};

/*Update user info*/
$scope.updateUser = function () {
    /*AJAX request: update user info*/
    $http.post('/users/update', {
        'name': $scope.user.name,
        'username': $scope.user.username,
        'email': $scope.user.email
    }).then(
        function successCallback(data) {
            $scope.user = data;
            $.notify("User updated!", "success", {autoHide: true, autoHideDelay: 500});
            console.log('200 OK! User updated');
        }, function errorCallback() {
            console.log('Error!');
        });
};

}]);
</code>```

Article Controller

```<code>    var app = angular.module('app');

app.controller("articleController", ['$scope','$http','$sce', function ($scope, $http, $sce) {

/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
    return $sce.trustAsHtml(html_code);
};

$scope.trustSrc = function (src) {
    return $sce.trustAsResourceUrl(src);
};

/*Populates the comments for particular
 * */
$scope.populatecomments = function (newsItem) {
    $http({
        method: 'GET',
        url: '/articles/' + newsItem.guid + '/comments'
    }).then(function successCallback(response) {

        $scope.comments = response.data;

    }, function errorCallback(response) {

    });
};

$scope.data = [];
$scope.comment = [];
$scope.btn_add = function (newsItem) {
    if ($scope.txtcomment != '') {
        $scope.data.push({
            "comment": $scope.txtcomment,
            "guid": newsItem.guid
        });
        $http.post('/comments/new', {
            "comment": $scope.txtcomment,
            "guid": newsItem.guid
        }).then(function successCallback() {

            var encodedURI = encodeURIComponent(newsItem.guid);

            $http({
                method: 'GET',
                url: '/articles/' + encodedURI + '/comments'
            }).then(function successCallback(response) {

                $scope.comments = response.data;

                $scope.txtcomment = "";

            }, function errorCallback(response) {

            });
        }, function errorCallback() {

            console.log('Error comment!');
        });

    }
};

$scope.savearticle = function (newsItem) {
    $http.post('/saved-articles/save', newsItem).then(function successCallback(response) {
        /*console.log(document.getElementById("save/"+newsItem.guid).className="disabled");*/
    }, function errorCallback(response) {

    });
}

/**
 * The saved articles by the user will be retrieved when a button clicked
 */

$scope.getSavedArticles = function () {

    /*AJAX request: retreive the saved the saved articles for the user*/

    $http({
        method: 'GET',
        url: '/saved-articles'
    }).then(function successCallback(response) {

        $scope.linkData = null;

        $scope.newsItems = response.data;

    }, function errorCallback(response) {

    });
};
}]);
</code>```

HELP needed!

答:
You are injecting controller in you module like dependency.

Change your main.js file to this:

```<code>var app = angular.module('app', ['ngRoute','thatisuday.dropzone']);
</code>```

@Sajeetharan is right you do not need module declaration in all controllers.

Since you are using laravel according to your comment. ( It will conflict with your blade template because both use same {{ }} for variables )

There are two ways to do this:

Change the Angular Tags

```<code>var app = angular.module('app', [], function($interpolateProvider) {
        $interpolateProvider.startSymbol('<%');
        $interpolateProvider.endSymbol('%>');
    });
</code>```

Now Laravel will use the {{ variableName }} and Angular will use <%
  variableName %>.

Change the Laravel Blade Tags

```<code> Blade::setContentTags('<%', '%>');// for variables and all things Blade
 Blade::setEscapedContentTags('<%%', '%%>');// for escaped data
</code>```

Variables will be: <% $variable %>. Comments will be: <%-- $variable
  --%>. Escaped data will look like: <%% $variable %%>.

You can check this Tutorial for more info.

Body:
I was trying to clean my angular app code up. So I moved all the controllers in their own files. But when I moved the controllers, my main app stoped working and started throwing the exception below -

Error: $injector:modulerr
  Module Error

Then I tried searching for the why the module won't load but with no luck.

main.js /*File where app module is declared*/

var app = angular.module('app', ['ngRoute','thatisuday.dropzone','UserController','LinkController','articleController']);

I tried injecting the dependency for the controller files.

Controllers:

Link Controller

var app = angular.module('app');

app.controller('LinkController', ['$scope','$http','$sce',function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
    return $sce.trustAsHtml(html_code);
};

$scope.trustSrc = function (src) {
    return $sce.trustAsResourceUrl(src);
};

/*First AJAX request which gets all the links and categories for the user*/

$http({
    method: 'GET',
    url: '/users'
}).then(function successCallback(response) {

    $scope.user = response.data;

}, function errorCallback(response) {

});

$scope.getUser = function () {
    $http({
        method: 'GET',
        url: '/users'
    }).then(function successCallback(response) {

        $scope.user = response.data;

    }, function errorCallback(response) {

    });
};

$http({
    method: 'GET',
    url: '/links'
}).then(function successCallback(response) {

    this.orderProp = 'age';

    /*the response is saved in scope variables*/
    $scope.links = response.data[0];
    $scope.categories = response.data[1];
    $scope.categorytolink = response.data[2];

}, function errorCallback(response) {
    console.log('There was a problem! Refresh!');
});

/*AJAX request for getting the recommendations according to the most viewed stars*/

$http({
    method: 'GET',
    url: '/recommendations/top'
}).then(function successCallback(response) {

    $scope.recommendations = response.data;

}, function errorCallback(response) {

});

/*AJAX request when a user clicks a link retrieves the link data*/
$scope.getLinkData = function (link) {
    $http({
        method: 'GET',
        url: "/proxy",
        headers: {
            "X-Proxy-To": link.rss_link
        }
    }).then(function successCallback(response) {

        /*AJAX request: add a star to the link*/

        $http.post('/links/' + link.id + '/views/add', {'link': link}).then(function successCallback(data, status, headers, config) {

            // Manually increment star for link just clicked

            var $data;

            $data = data.data;

            $scope.link = $data;

            console.log('200 OK! Star added');

        }, function errorCallback() {

            console.log('Error!');

        });

        /*The data will be retrieved and will be sorted according to the requirements of welcome.blade*/

        $myXml = response.data;

        $xmlObj = $.parseXML($myXml);

        $newsItems = [];

        $channelImage = $($xmlObj).find("channel>image");

        /*the information of the link is sorted */

        $linkData = {
            "title": $channelImage.find("title").text(),
            "link": $channelImage.find("link").text(),
            "imgurl": $channelImage.find("url").text()

        };

        /*the data is sorted below*/

        $.each($($xmlObj).find("item"), function (index, value) {
            $newsItems.push({
                "title": $(value).find("title").text(),
                "description": $(value).find("description").text(),
                "link": $(value).find("link").text(),
                "date_published": moment($(value).find("pubDate").text()).format('MMMM Do YYYY'),
                "time_published": moment($(value).find("pubDate").text()).format('h:mm:ss a'),
                "guid": $(value).find("guid").text()
            })
        });

        $scope.newsItems = $newsItems;

        $scope.linkData = $linkData;

    }, function errorCallback(response) {

    });
};

/*Create a category private to the user*/

$scope.create_category = function (category) {

    /*AJAX request: adds a new category*/
    $http.post('/categories/new', {'category': category}).then(function successCallback(response) {

        /*AJAX request: Updates the categories for the use of new category*/

        $http({
            method: 'GET',
            url: '/categories'
        }).then(function successCallback(response) {

            $scope.categories = response.data;

        }, function errorCallback(response) {

        });
    }, function errorCallback(response) {

    });

};
}]);

User Controller

    var app = angular.module('app');

app.controller("UserController", ['$scope','$http','$sce', function ($scope, $http, $sce) {

/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
    return $sce.trustAsHtml(html_code);
};

$scope.trustSrc = function (src) {
    return $sce.trustAsResourceUrl(src);
};

$scope.dzOptions = {
    paramName: "file",
    dictDefaultMessage: "
 Upload
",
    createImageThumbnails: false,
    autoDiscover: false
};

$scope.dzCallbacks = {
    'sending': function (file, xhr, formData) {
        formData.append('_token', $('#csrf-token').val());
    },
    'success': function (file, response) {
        $scope.user = response;
        $.notify("Profile photo changed!", "success", {autoHide: true, autoHideDelay: 500});
    }
};

/*Update user info*/
$scope.updateUser = function () {
    /*AJAX request: update user info*/
    $http.post('/users/update', {
        'name': $scope.user.name,
        'username': $scope.user.username,
        'email': $scope.user.email
    }).then(
        function successCallback(data) {
            $scope.user = data;
            $.notify("User updated!", "success", {autoHide: true, autoHideDelay: 500});
            console.log('200 OK! User updated');
        }, function errorCallback() {
            console.log('Error!');
        });
};

}]);

Article Controller

    var app = angular.module('app');

app.controller("articleController", ['$scope','$http','$sce', function ($scope, $http, $sce) {

/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
    return $sce.trustAsHtml(html_code);
};

$scope.trustSrc = function (src) {
    return $sce.trustAsResourceUrl(src);
};

/*Populates the comments for particular
 * */
$scope.populatecomments = function (newsItem) {
    $http({
        method: 'GET',
        url: '/articles/' + newsItem.guid + '/comments'
    }).then(function successCallback(response) {

        $scope.comments = response.data;

    }, function errorCallback(response) {

    });
};

$scope.data = [];
$scope.comment = [];
$scope.btn_add = function (newsItem) {
    if ($scope.txtcomment != '') {
        $scope.data.push({
            "comment": $scope.txtcomment,
            "guid": newsItem.guid
        });
        $http.post('/comments/new', {
            "comment": $scope.txtcomment,
            "guid": newsItem.guid
        }).then(function successCallback() {

            var encodedURI = encodeURIComponent(newsItem.guid);

            $http({
                method: 'GET',
                url: '/articles/' + encodedURI + '/comments'
            }).then(function successCallback(response) {

                $scope.comments = response.data;

                $scope.txtcomment = "";

            }, function errorCallback(response) {

            });
        }, function errorCallback() {

            console.log('Error comment!');
        });

    }
};

$scope.savearticle = function (newsItem) {
    $http.post('/saved-articles/save', newsItem).then(function successCallback(response) {
        /*console.log(document.getElementById("save/"+newsItem.guid).className="disabled");*/
    }, function errorCallback(response) {

    });
}

/**
 * The saved articles by the user will be retrieved when a button clicked
 */

$scope.getSavedArticles = function () {

    /*AJAX request: retreive the saved the saved articles for the user*/

    $http({
        method: 'GET',
        url: '/saved-articles'
    }).then(function successCallback(response) {

        $scope.linkData = null;

        $scope.newsItems = response.data;

    }, function errorCallback(response) {

    });
};
}]);

HELP needed!

Body:
You are injecting controller in you module like dependency.

Change your main.js file to this:

var app = angular.module('app', ['ngRoute','thatisuday.dropzone']);

@Sajeetharan is right you do not need module declaration in all controllers.

Since you are using laravel according to your comment. ( It will conflict with your blade template because both use same {{ }} for variables )

There are two ways to do this:

Change the Angular Tags

var app = angular.module('app', [], function($interpolateProvider) {
        $interpolateProvider.startSymbol('<%');
        $interpolateProvider.endSymbol('%>');
    });

Now Laravel will use the {{ variableName }} and Angular will use <%
  variableName %>.

Change the Laravel Blade Tags

 Blade::setContentTags('<%', '%>');// for variables and all things Blade
 Blade::setEscapedContentTags('<%%', '%%>');// for escaped data

Variables will be: <% $variable %>. Comments will be: <%-- $variable
  --%>. Escaped data will look like: <%% $variable %%>.

You can check this Tutorial for more info.


问:
Disable spell checking on IntelliJ IDEA
I'm trying to disable spell checking in MacOS's IntelliJ IDEA version 8.1.

How can I disable it?

答:
If you want to suppress in a file, you can use comment in file
like  in html.

Title: Disable spell checking on IntelliJ IDEA

Body:
If you want to suppress in a file, you can use comment in file
like <!--suppress SpellCheckingInspection --> in html.


问:
NotificationCompat.Builder deprecated in Android O
After upgrading my project to Android O

```<code>buildToolsVersion "26.0.1"
</code>```

Lint in Android Studio is showing a deprecated warning for the follow notification builder method:

```<code>new NotificationCompat.Builder(context)
</code>```

The problem is: Android Developers update their Documentation describing NotificationChannel to support notifications in Android O, and provide us with a snippet, yet with the same deprecated warning:

```<code>Notification notification = new Notification.Builder(MainActivity.this)
        .setContentTitle("New Message")
        .setContentText("You've received new messages.")
        .setSmallIcon(R.drawable.ic_notify_status)
        .setChannelId(CHANNEL_ID)
        .build();
</code>```

Notifications Overview

My question: Is there is any other solution for building notification, and still support Android O?

A solution I found is to pass the channel ID as a parameter in Notification.Builder constructor. But this solution is not exactly reusable.

```<code>new Notification.Builder(MainActivity.this, "channel_id")
</code>```

答:
Here is the sample code, which is working in Android Oreo and less than Oreo.</p>

```<code>  NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
                notificationManager.createNotificationChannel(notificationChannel);
                builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
            } else {
                builder = new NotificationCompat.Builder(getApplicationContext());
            }

            builder = builder
                    .setSmallIcon(R.drawable.ic_notification_icon)
                    .setColor(ContextCompat.getColor(context, R.color.color))
                    .setContentTitle(context.getString(R.string.getTitel))
                    .setTicker(context.getString(R.string.text))
                    .setContentText(message)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true);
            notificationManager.notify(requestCode, builder.build());
</code>```

Body:
After upgrading my project to Android O

buildToolsVersion "26.0.1"

Lint in Android Studio is showing a deprecated warning for the follow notification builder method:

new NotificationCompat.Builder(context)

The problem is: Android Developers update their Documentation describing NotificationChannel to support notifications in Android O, and provide us with a snippet, yet with the same deprecated warning:

Notification notification = new Notification.Builder(MainActivity.this)
        .setContentTitle("New Message")
        .setContentText("You've received new messages.")
        .setSmallIcon(R.drawable.ic_notify_status)
        .setChannelId(CHANNEL_ID)
        .build();

Notifications Overview

My question: Is there is any other solution for building notification, and still support Android O?

A solution I found is to pass the channel ID as a parameter in Notification.Builder constructor. But this solution is not exactly reusable.

new Notification.Builder(MainActivity.this, "channel_id")

Body:
Here is the sample code, which is working in Android Oreo and less than Oreo.

  NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
                notificationManager.createNotificationChannel(notificationChannel);
                builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
            } else {
                builder = new NotificationCompat.Builder(getApplicationContext());
            }

            builder = builder
                    .setSmallIcon(R.drawable.ic_notification_icon)
                    .setColor(ContextCompat.getColor(context, R.color.color))
                    .setContentTitle(context.getString(R.string.getTitel))
                    .setTicker(context.getString(R.string.text))
                    .setContentText(message)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true);
            notificationManager.notify(requestCode, builder.build());


问:
IBM Bluemix Zero-downtime deployment capability for cloud applications
We have a NodeJS Cloud Foundry application with a DevOps Delivery Pipeline enabled.

Initially we set up the pipeline to use the Active Deploy extension to the Delivery Pipeline in Bluemix to deploy app updates without any downtime. Also called: Rolling deployments, Blue-Green deployments, Red-Black deployments.
https://www.ibm.com/developerworks/cloud/library/cl-bluemix-rollingpipeline/cl-bluemix-rollingpipeline-pdf.pdf

Unfortunately, the Active Deploy service was retired swiftly as of June 23, 2017 as we are inhabiting downtime upon deployment.
https://www.ibm.com/blogs/bluemix/2017/05/retirement-ibm-active-deploy-beta-service/

How do we go back to the process by which a new version of an application is deployed into an environment with no disruption in service for the consumer? UrbanCode? Other options?

答:
A good way of doing this is to use the IBM Cloud Garage's blue-green-deploy cf plugin. In your deploy script, add:

```<code>cf add-plugin-repo CF-Community https://plugins.cloudfoundry.org
cf install-plugin blue-green-deploy -f -r CF-Community
</code>```

Then, instead of doing cf push <app_name>, do:

```<code>cf blue-green-deploy <app_name>
</code>```

You can also specify a manifest, or specify a smoke test (if the smoke test fails, the build will be marked as failed and the original version will continue running).

Body:
A good way of doing this is to use the IBM Cloud Garage's blue-green-deploy cf plugin. In your deploy script, add:

cf add-plugin-repo CF-Community https://plugins.cloudfoundry.org
cf install-plugin blue-green-deploy -f -r CF-Community

Then, instead of doing cf push <app_name>, do:

cf blue-green-deploy <app_name>

You can also specify a manifest, or specify a smoke test (if the smoke test fails, the build will be marked as failed and the original version will continue running).


问:
Angular2 Pipes: output raw HTML
I'm trying to create an Angular2 custom pipe that outputs raw html. I want it to simply convert newlines in the input into HTML line breaks. How do I output raw HTML from an angular2 pipe?

The following is my current pipe definition, but it escapes the HTML which I don't want:

```<code>import {Pipe, PipeTransform} from '@angular/core';
/*
 * Converts newlines into html breaks
*/
@Pipe({ name: 'newline' })
export class NewlinePipe implements PipeTransform {
    transform(value: string, args: string[]): any {
        return value.replace(/(?:\r\n|\r|\n)/g, '<br />');
    }
}
</code>```

EDIT: Just a quick note since this question seems to get a number of views and activity that I'm leaving my accepted answer as is, even though for my specific example use-case css probably would have been a better option and was in fact what I changed to. But my actual question was "how do I output raw html from an angular 2 pipe", not "what's the best way to render line breaks" which is what the accepted answer shows.

Beware though, as mentioned in comments below, if you do use the method in the accepted answer you need to ensure that you're not rendering unchecked user input as this could open you up to XSS vulnerabilities.

答:
What about:

```<code>```{{text}}```
</code>```

Or for html:

```<code><pre [innerHtml]="text">```
```

<p>I often use the HTML pre element that represents preformatted text.</p>

<p>Another trick I often use to format Json is:</p>

``````{{jsonString | json}}```
```

Title: Angular2 Pipes: output raw HTML

Body:
I'm trying to create an Angular2 custom pipe that outputs raw html. I want it to simply convert newlines in the input into HTML line breaks. How do I output raw HTML from an angular2 pipe?

The following is my current pipe definition, but it escapes the HTML which I don't want:

import {Pipe, PipeTransform} from '@angular/core';
/*
 * Converts newlines into html breaks
*/
@Pipe({ name: 'newline' })
export class NewlinePipe implements PipeTransform {
    transform(value: string, args: string[]): any {
        return value.replace(/(?:\r\n|\r|\n)/g, '
');
    }
}

EDIT: Just a quick note since this question seems to get a number of views and activity that I'm leaving my accepted answer as is, even though for my specific example use-case css probably would have been a better option and was in fact what I changed to. But my actual question was "how do I output raw html from an angular 2 pipe", not "what's the best way to render line breaks" which is what the accepted answer shows.

Beware though, as mentioned in comments below, if you do use the method in the accepted answer you need to ensure that you're not rendering unchecked user input as this could open you up to XSS vulnerabilities.

Body:
What about:

<pre>{{text}}</pre>

Or for html:

<pre [innerHtml]="text"></pre>

I often use the HTML pre element that represents preformatted text.

Another trick I often use to format Json is:

<pre>{{jsonString | json}}</pre>


问:
wpml languages redirecting to default
I'm not too familiar with WPML and I site I am working on is using it. Everything was working fine, but now it has been noticed that when you go to a different language domain (e.g. www.domain.com/es/pagename) the site seems to rewrite the address to (www.domain.com/pagename) removing the language directory from the web address making some language pages unaccessable.
This is not occurring on all pages though.

I checked the htaccess file and the rewrite are their.

Any help or information on this would be great.

答: Try check settings of WPML plugin http://take.ms/hFuqg</p>

Title: wpml languages redirecting to default