问:
Generate reports from CosmosDB using Data warehouse
I am using COSMOSDB for my application with SQL API.I need to generate the tabular and visualization reports from Azure COSMOSDB. What is the standard approach or any guidelines I need to refer.I guess directly connecting it with tool like Power BI or SSRS leads to certain hiccups. I need to analyse the data and accordingly generate the reports.Creating Data Warehouse is the best approach to generate such kind of reports but how to transfer data from NoSQL COSMOSDB to Azure SQL Datawarehouse.

Can anyone help me to clarify my doubts.

Thanks in Advance.

答:
Power BI works fine on Cosmos DB.
https://learn.microsoft.com/en-us/azure/cosmos-db/powerbi-visualize

That said, Cosmos DB is not an analytics data store. It is designed for operational workloads. Customers looking to do analytics on top of data in Cosmos typically do one of the following.

Use Change Feed to build "materalized views" of aggregates, https://learn.microsoft.com/en-us/azure/cosmos-db/change-feed or use Change Feed to write data into some other cold store for analytics including Spark.

Use Spark for analytics, https://learn.microsoft.com/en-us/azure/cosmos-db/spark-connector which can also include using Change Feed depending on whether you are looking to do Spark streaming.

Update: Building analytics on top of Cosmos DB today is most easily done using Synapse Link and either SQL or Spark for queryies, then connect Power BI to that for visualization.


来源: stackexchange

问:
Filling struct's array crashes with Segmentation Fault

Just for the record: I spent a while already checking similar
  questions and trying their proposed answers without success

I am facing a "Segmentation fault" error in runtime with the following C code:

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

#define ROW_NUM     8
#define COL_NUM     7

typedef struct {
    int matrix[ROW_NUM][COL_NUM];
} screen_type;

typedef struct {
    screen_type *p_screen;
} snake_type;

void fillSnake(snake_type *p_snake);

int main(void) {
    snake_type snake;
    fillSnake(&snake);
    return 0;
}

void fillSnake(snake_type *p_snake) {
    fillWithPointer((screen_type*)p_snake->p_screen);
}

void fillWithPointer(screen_type *p_screen) { //segmentation fault in this method
    for (int col = 0; col < COL_NUM; col++) {
        for (int row = 0; row < ROW_NUM; row++) {
            p_screen->matrix[row][col] = 0;
        }
    }
}
</code>```

The problem is while filling the array with the method fillWithPointer.
Any hints will be more than welcome.

答:
In your main function, snake is never initialized, and so its p_snake member is left as a pointer to some arbitrary location in memory.  You then attempt to write to this memory within fillWithPointer, which you are not allowed to do, hence the segmentation fault.

To correct this error, allocate some memory for the snake, either on the stack or the heap. One way to accomplish this would be the following:

```<code>int main(void) {
    screen_type screen = {{{0}}};
    snake_type snake = {&screen};
    fillSnake(&snake);
    return 0;
}

</code>```

Note that since the screen is already zero-initialized, your fillWithPointer functions becomes superfluous.

ContentLicense: CC BY-SA 4.0

Body:
Just for the record: I spent a while already checking similar
  questions and trying their proposed answers without success

I am facing a "Segmentation fault" error in runtime with the following C code:

#include <stdio.h>
#include <stdlib.h>

#define ROW_NUM     8
#define COL_NUM     7

typedef struct {
    int matrix[ROW_NUM][COL_NUM];
} screen_type;

typedef struct {
    screen_type *p_screen;
} snake_type;

void fillSnake(snake_type *p_snake);

int main(void) {
    snake_type snake;
    fillSnake(&snake);
    return 0;
}

void fillSnake(snake_type *p_snake) {
    fillWithPointer((screen_type*)p_snake->p_screen);
}

void fillWithPointer(screen_type *p_screen) { //segmentation fault in this method
    for (int col = 0; col < COL_NUM; col++) {
        for (int row = 0; row < ROW_NUM; row++) {
            p_screen->matrix[row][col] = 0;
        }
    }
}

The problem is while filling the array with the method fillWithPointer.
Any hints will be more than welcome.

Body:
In your main function, snake is never initialized, and so its p_snake member is left as a pointer to some arbitrary location in memory.  You then attempt to write to this memory within fillWithPointer, which you are not allowed to do, hence the segmentation fault.

To correct this error, allocate some memory for the snake, either on the stack or the heap. One way to accomplish this would be the following:

int main(void) {
    screen_type screen = {{{0}}};
    snake_type snake = {&screen};
    fillSnake(&snake);
    return 0;
}

Note that since the screen is already zero-initialized, your fillWithPointer functions becomes superfluous.


问:
Undefined symbol error when use inline methods in C++
When I make method as inline, compilation fails with this error:

Undefined symbol: 'int CPositionRequestor::State(void) const (?State@CPositionRequestor@@QBEHXZ)'

Header file:

```<code>class CPositionRequestor : public CActive
    {
    // ...

private:
    TInt iState;

public:
    inline TInt State() const;
    }
</code>```

CPP file:

```<code>inline TInt CPositionRequestor::State() const
    {
    return iState;
    }
</code>```

答:
An inline function needs it's definition to be available in the file that is calling that function.

So if You define it in one cpp file and try to call it in a second cpp file, then it will not be found.

What You need to do is move this definition into the h file. (just cut & paste it after the class definition).

Or as @einpoklum has noticed, if You don't need it, remove the inline from all the definitions.

Body:
When I make method as inline, compilation fails with this error:

Undefined symbol: 'int CPositionRequestor::State(void) const (?State@CPositionRequestor@@QBEHXZ)'

Header file:

class CPositionRequestor : public CActive
    {
    // ...

private:
    TInt iState;

public:
    inline TInt State() const;
    }

CPP file:

inline TInt CPositionRequestor::State() const
    {
    return iState;
    }


问:
How to type react-redux's useSelector?
Component, where do i call my LoaderStore:

```<code>const loaderStore = useSelector((state: any) => state.loader);
</code>```

Loader reducer:

```<code>interface IState {
  isLoading: boolean;
  state: States;
  error: string | null;
}

const initialState: IState = {
  isLoading: false,
  state: States.init,
  error: null
};
</code>```

But if export my IState interface in a component, then use it as:

```<code>const loaderStore = useSelector((state: IState) => state.loader);
</code>```

Then i'm getting a following error:

```<code>TS2339: Property 'loader' does not exist on type 'IState'.
</code>```

I want to point const loaderStore to a Loader main initialState, how can i type it correctly?

答:
Just needed to create a root interface for the root state:

```<code>export interface RootState {
  user: UserState;
  loader: LoaderState;
}
</code>```

Where UserState and LoaderState are the actual interfaces for the state.

Title: How to type react-redux's useSelector?

Body:
Component, where do i call my LoaderStore:

const loaderStore = useSelector((state: any) => state.loader);

Loader reducer:

interface IState {
  isLoading: boolean;
  state: States;
  error: string | null;
}

const initialState: IState = {
  isLoading: false,
  state: States.init,
  error: null
};

But if export my IState interface in a component, then use it as:

const loaderStore = useSelector((state: IState) => state.loader);

Then i'm getting a following error:

TS2339: Property 'loader' does not exist on type 'IState'.

I want to point const loaderStore to a Loader main initialState, how can i type it correctly?

Body:
Just needed to create a root interface for the root state:

export interface RootState {
  user: UserState;
  loader: LoaderState;
}

Where UserState and LoaderState are the actual interfaces for the state.


问:
Name Of Generic "Pipe" Concept for Physical Communication?
I currently have an idea rolling around in my head about how to abstract away (to some degree) common data transfer mechanisms of embedded systems such as CAN, UART, SPI, I2C, Ethernet, etc. Ideally I would want to have something like the concept of a Pipe, but that the interface doesn't really care about what physical medium/protocol the data is flowing over. If I say "transfer this data through the pipe", it just works. Obviously there would have to be some protocol specific details in the construction of this pipe object but outside of that it shouldn't matter.

Is there an industry accepted name for what I'm trying to do?

Is this concept even a good idea? I feel like it will be useful for my purposes but I don't know if it's pointless in the grand scheme of the embedded engineering world.

答:
Pipes are commonly used for IPC (inter process communication) or redirecting output to a file or ... For all this exists remote technologies, 'remote' means over the network or over an interface or bus like RS232, SPI, ... The name for remote IPC is remote procedure calls (RPC), see https://os.mbed.com/cookbook/Interfacing-Using-RPC and https://github.com/EmbeddedRPC/erpc . Like with all IPC, security is a major problem, especially over a network.

I.e. writing a remote file (over TCP/IP) can be done like in https://askubuntu.com/questions/917200/how-to-redirect-command-output-from-remote-machine-to-local-file-via-ssh

The SSH login you can wrap into a function and this function to get the commands shorter (macros can also be used for wrapping a function Wrap function call with macro)

There are also various implementations of communication protocols over each other i.e. Ethernet over USB (https://en.wikipedia.org/wiki/Ethernet_over_USB)


问:
Angular7 multiple child routes with empty path
Hi StackOverflow

I am new to Angular, and currently developing an application for learning purposes.

I have one root module (app), and two child modules (quiz and question).

Expected behavior

If I surf to / => I want to show the QuestionListComponent in the QuestionModule

If I surf to /question => I want to show the QuestionListComponent in the QuestionModule

If I surf to /quiz => I want to show the QuizComponent in the QuizModule

Current behavior

If I surf to / => QuestionListComponent is loaded

If I surf to /question => QuestionListComponent is loaded

If I surf to /quiz => QuestionListComponent is loaded instead of QuizComponent

AppModule routes

```<code>RouterModule.forRoot([
  { path: '', pathMatch: 'full', redirectTo: 'questions' },
  { path: 'quiz', loadChildren: './quiz/quiz.module#QuizModule' },
  { path: 'questions', loadChildren: './question/question.module#QuestionModule'}
]);
</code>```

QuestionModule routes

```<code>RouterModule.forChild([
      { path: '', component: QuestionListComponent },
      { path: 'new', component: QuestionFormComponent, canDeactivate: [UnsavedChangesGuard] },
      { path: 'edit/:id', component: QuestionFormComponent, canDeactivate: [UnsavedChangesGuard] },
    ]),
</code>```

QuizModule routes

```<code>RouterModule.forChild([
      { path: '', component: QuizComponent }
    ])
</code>```

Question

Obviously, the problem is that when surfing to /quiz, angular finds the '' path in the QuestionModule first and loads the corresponding content.

But, how would I fix this, so that when surfing to /quiz, the QuizComponent is loaded?

Router tree
For some reason, the Question components falls under the quiz node

答:
I was able to solve the issue.

I included the QuestionModule in the QuizModule, causing Angular to merge the forChild routes. I removed it.

Now my router tree is looking good.

Body:
Hi StackOverflow

I am new to Angular, and currently developing an application for learning purposes.

I have one root module (app), and two child modules (quiz and question).

Expected behavior

If I surf to / => I want to show the QuestionListComponent in the QuestionModule

If I surf to /question => I want to show the QuestionListComponent in the QuestionModule

If I surf to /quiz => I want to show the QuizComponent in the QuizModule

Current behavior

If I surf to / => QuestionListComponent is loaded

If I surf to /question => QuestionListComponent is loaded

If I surf to /quiz => QuestionListComponent is loaded instead of QuizComponent

AppModule routes

RouterModule.forRoot([
  { path: '', pathMatch: 'full', redirectTo: 'questions' },
  { path: 'quiz', loadChildren: './quiz/quiz.module#QuizModule' },
  { path: 'questions', loadChildren: './question/question.module#QuestionModule'}
]);

QuestionModule routes

RouterModule.forChild([
      { path: '', component: QuestionListComponent },
      { path: 'new', component: QuestionFormComponent, canDeactivate: [UnsavedChangesGuard] },
      { path: 'edit/:id', component: QuestionFormComponent, canDeactivate: [UnsavedChangesGuard] },
    ]),

QuizModule routes

RouterModule.forChild([
      { path: '', component: QuizComponent }
    ])

Question

Obviously, the problem is that when surfing to /quiz, angular finds the '' path in the QuestionModule first and loads the corresponding content.

But, how would I fix this, so that when surfing to /quiz, the QuizComponent is loaded?

Router tree
For some reason, the Question components falls under the quiz node


问:
How to use Python type hints with Django QuerySet?
Is it possible to specify type of records in Django QuerySet with Python type hints? Something like QuerySet[SomeModel]?

For example, we have model:

```<code>class SomeModel(models.Model):
    smth = models.IntegerField()
</code>```

And we want to pass QuerySet of that model as param in func:

```<code>def somefunc(rows: QuerySet):
    pass
</code>```

But how to specify type of records in QuerySet, like with List[SomeModel]:

```<code>def somefunc(rows: List[SomeModel]):
    pass
</code>```

but with QuerySet?

答:
I've found myself that using typing.Sequence to solve a similar issue:

```<code>from typing import Sequence

def print_emails(users: Sequence[User]):
    for user in users:
        print(user.email)

users = User.objects.all()

print_emails(users=users)
</code>```

As far as I know from docs:

A Sequence is anything that supports len() and .getitem(), independent of its actual type.

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to specify type of records in Django QuerySet with Python type hints? Something like QuerySet[SomeModel]?

For example, we have model:

class SomeModel(models.Model):
    smth = models.IntegerField()

And we want to pass QuerySet of that model as param in func:

def somefunc(rows: QuerySet):
    pass

But how to specify type of records in QuerySet, like with List[SomeModel]:

def somefunc(rows: List[SomeModel]):
    pass

but with QuerySet?

Body:
I've found myself that using typing.Sequence to solve a similar issue:

from typing import Sequence

def print_emails(users: Sequence[User]):
    for user in users:
        print(user.email)

users = User.objects.all()

print_emails(users=users)

As far as I know from docs:

A Sequence is anything that supports len() and .getitem(), independent of its actual type.


问:
Deprecated: Function ereg()

Possible Duplicate:

  Function ereg() is deprecated

I understand that in the new version of PHP ereg is deprecated:

Deprecated: Function ereg() is deprecated

The code below worked fine in the old PHP. So I replaced ereg with preg_match and I am now getting the following error:

Warning: preg_match() [function.preg-match]: Unknown modifier '{' in

Here is my code...

```<code>if (!empty($searchval))
{
    if(ereg("[0-9]{5}", $searchval)) {
        $zip = $searchval;
    }
    else {
        $city = $searchval;
    }
} else
{
    $error .= "<div id='Error'>Please enter zip</div>";
    $zip = false;
}
</code>```

答:
You need to surround the regular expression with a delimiter like:</p>

```<code>if(preg_match("/[0-9]{5}/", $searchval)) {
</code>```

Title: Deprecated: Function ereg()

Body:
Possible Duplicate:

  Function ereg() is deprecated

I understand that in the new version of PHP ereg is deprecated:

Deprecated: Function ereg() is deprecated

The code below worked fine in the old PHP. So I replaced ereg with preg_match and I am now getting the following error:

Warning: preg_match() [function.preg-match]: Unknown modifier '{' in

Here is my code...

if (!empty($searchval))
{
    if(ereg("[0-9]{5}", $searchval)) {
        $zip = $searchval;
    }
    else {
        $city = $searchval;
    }
} else
{
    $error .= "
Please enter zip
";
    $zip = false;
}

Body:
You need to surround the regular expression with a delimiter like:

if(preg_match("/[0-9]{5}/", $searchval)) {


问:
Access EC2 instance from internet?
I have an EC2 instance running Apex Oracle.

On the virtual machine I can access Apex by typing : localhost:8080/apex

I'm trying to access the same URL but from internet.

I use : ec2-xx-xx-xx-xx.us-east-2.compute.amazonaws.com:8080/apex but it's not working.

In my security attributes I have the following inbound rule :

Customized TCP Rule

Protocol : TCP

Ports : 8080

Source : MyIP address

My virtual machine's firewall doesn't block any connexion on this port.

What am I doing wrong ?

Thanks.
Cheers,

答:
Make sure your instance is in a public subnet and not in a private subnet. An easy way to tell is whether or not your instance has a public IP, though this could also be incorrectly configured during the EC2 instance creation.

To verify connectivity, you could assign an Elastic IP to that instance then try connecting to it using the IP instead of the hostname. If that works then you know it's an issue with the hostname.

If you want to check your NACLs:

VPC

Route Tables

Routes

The default VPC settings should work fine, it's only if you start using private subnets that things get tricky and you need a NAT Gateway.

Title: Access EC2 instance from internet?


问:
Take a full screenshot for all webview in swift
Does anyone know how can I take a full screenshot for all my web view using code in swift ( not the screen ! because the webview is long and we must scroll to view the all content ) and share it via UIActivityViewController?

答:
Solution with WKWebView in Swift 5

```<code>extension ViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView,didFinish navigation: WKNavigation!) {

        let configuration = WKSnapshotConfiguration()
        configuration.rect = CGRect(origin: .zero, size: (self.webView.scrollView.contentSize))

        webView.takeSnapshot(with: configuration) {image, error in
            if let image = image {
                self.saveImage(imageName: "snapshot.jpg", image: image)
            }
        }
    }
}
</code>```

Body:
Solution with WKWebView in Swift 5

extension ViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView,didFinish navigation: WKNavigation!) {

        let configuration = WKSnapshotConfiguration()
        configuration.rect = CGRect(origin: .zero, size: (self.webView.scrollView.contentSize))

        webView.takeSnapshot(with: configuration) {image, error in
            if let image = image {
                self.saveImage(imageName: "snapshot.jpg", image: image)
            }
        }
    }
}


答:
As my understanding according to your code you have to do malloc struct snake_type before passing into method in main method.
snake_type* snake = (snake_type*)malloc(sizeof(snake_type));

Fillsnake(snake);

Title: Filling struct's array crashes with Segmentation Fault


答:
You haven't included a delimiter in your regular expression.  Try this:</p>

```<code>if (!empty($searchval))
{
    if(ereg("/[0-9]{5}/", $searchval)) {
    $zip = $searchval;
    }
    else {
    $city = $searchval;
    }
} else
{
    $error .= "<div id='Error'>Please enter zip</div>";
    $zip = false;
}
</code>```

Title: Deprecated: Function ereg()

Body:
You haven't included a delimiter in your regular expression.  Try this:

if (!empty($searchval))
{
    if(ereg("/[0-9]{5}/", $searchval)) {
    $zip = $searchval;
    }
    else {
    $city = $searchval;
    }
} else
{
    $error .= "<div id='Error'>Please enter zip</div>";
    $zip = false;
}


问:
Unsupported Uri in ContentResolver when passing Uri returned by Intent
I have an app where the user can add music files by selecting a file or adding all the files in a selected directory into a ListView. When adding a single file, everything is fine, but for directories I'm getting Unsupported Uri. Problem is not related to permissions:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.dibo.testapp, PID: 12226
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65579, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/tree/raw:/storage/emulated/0/Download/2006 A Good Year flg=0xc3 }} to activity {com.example.dibo.testapp/com.example.dibo.testapp.MainActivity}: java.lang.UnsupportedOperationException: Unsupported Uri content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2F2006%20A%20Good%20Year
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4360)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4402)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.UnsupportedOperationException: Unsupported Uri content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2F2006%20A%20Good%20Year
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
        at android.content.ContentProviderProxy.query(ContentProviderNative.java:418)
        at android.content.ContentResolver.query(ContentResolver.java:802)
        at android.content.ContentResolver.query(ContentResolver.java:752)
        at android.content.ContentResolver.query(ContentResolver.java:710)
        at com.example.dibo.testapp.PlaylistFragment.addFolder(PlaylistFragment.java:380)
        at com.example.dibo.testapp.PlaylistFragment.onActivityResult(PlaylistFragment.java:346)
        at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:160)
        at com.example.dibo.testapp.MainActivity.onActivityResult(MainActivity.java:152)
        at android.app.Activity.dispatchActivityResult(Activity.java:7454)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4353)
</code>```

This is intent request:*

```<code>private void selectDirectory() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);

    startActivityForResult(intent, REQUEST_FOLDER);
}
</code>```

Result handler:

```<code>@Override
public void onActivityResult(int requestCode, int resultCode,
                             Intent resultData) {

    if (requestCode == REQUEST_FILE && resultCode == Activity.RESULT_OK) {
        if (resultData != null) {
            addFile(resultData.getData());
        }
    }

    if (requestCode == REQUEST_FOLDER && resultCode == Activity.RESULT_OK) {

        if (resultData != null) {
            addFolder(resultData.getData());
        }
    }
}

private void addFolder(Uri uri) {

    ContentResolver contentResolver = getActivity().getContentResolver();

    if (contentResolver==null) {
        return;
    }

    Cursor cursor = contentResolver.query(
            uri, // Uri
            null,
            null,
            null,
            null
    );

    if (cursor != null &&  cursor.moveToFirst()) {
        int Title = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);

        do {

            String SongTitle = cursor.getString(Title);
            Log.d("addFolder", SongTitle);

        } while (cursor.moveToNext());
    }

    if (cursor != null) {
        cursor.close();
    }

}
</code>```

Exception is raised in contentResolver.query. Note that everything is in Fragment Class, not in Activity.

答:
You need first do magic thing:

```<code>Uri docUriTree = DocumentsContract.buildDocumentUriUsingTree(treeUri, DocumentsContract.getTreeDocumentId(treeUri));
</code>```

Then you can read DocumentsContract.Document values from your Uri.

Body:
I have an app where the user can add music files by selecting a file or adding all the files in a selected directory into a ListView. When adding a single file, everything is fine, but for directories I'm getting Unsupported Uri. Problem is not related to permissions:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.dibo.testapp, PID: 12226
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65579, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/tree/raw:/storage/emulated/0/Download/2006 A Good Year flg=0xc3 }} to activity {com.example.dibo.testapp/com.example.dibo.testapp.MainActivity}: java.lang.UnsupportedOperationException: Unsupported Uri content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2F2006%20A%20Good%20Year
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4360)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4402)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.UnsupportedOperationException: Unsupported Uri content://com.android.providers.downloads.documents/tree/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2F2006%20A%20Good%20Year
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
        at android.content.ContentProviderProxy.query(ContentProviderNative.java:418)
        at android.content.ContentResolver.query(ContentResolver.java:802)
        at android.content.ContentResolver.query(ContentResolver.java:752)
        at android.content.ContentResolver.query(ContentResolver.java:710)
        at com.example.dibo.testapp.PlaylistFragment.addFolder(PlaylistFragment.java:380)
        at com.example.dibo.testapp.PlaylistFragment.onActivityResult(PlaylistFragment.java:346)
        at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:160)
        at com.example.dibo.testapp.MainActivity.onActivityResult(MainActivity.java:152)
        at android.app.Activity.dispatchActivityResult(Activity.java:7454)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4353)

This is intent request:*

private void selectDirectory() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);

    startActivityForResult(intent, REQUEST_FOLDER);
}

Result handler:

@Override
public void onActivityResult(int requestCode, int resultCode,
                             Intent resultData) {

    if (requestCode == REQUEST_FILE && resultCode == Activity.RESULT_OK) {
        if (resultData != null) {
            addFile(resultData.getData());
        }
    }

    if (requestCode == REQUEST_FOLDER && resultCode == Activity.RESULT_OK) {

        if (resultData != null) {
            addFolder(resultData.getData());
        }
    }
}

private void addFolder(Uri uri) {

    ContentResolver contentResolver = getActivity().getContentResolver();

    if (contentResolver==null) {
        return;
    }

    Cursor cursor = contentResolver.query(
            uri, // Uri
            null,
            null,
            null,
            null
    );

    if (cursor != null &&  cursor.moveToFirst()) {
        int Title = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);

        do {

            String SongTitle = cursor.getString(Title);
            Log.d("addFolder", SongTitle);

        } while (cursor.moveToNext());
    }

    if (cursor != null) {
        cursor.close();
    }

}

Exception is raised in contentResolver.query. Note that everything is in Fragment Class, not in Activity.

Body:
You need first do magic thing:

Uri docUriTree = DocumentsContract.buildDocumentUriUsingTree(treeUri, DocumentsContract.getTreeDocumentId(treeUri));

Then you can read DocumentsContract.Document values from your Uri.


问:
alert dialog written in non activity class not showing alert dialog when dismissed from calling activity
I crate a class called "Dailog" for building alert dialog which has its own dismiss() method to dismiss the dialog. and then use it's Object in many screens where I need to show alert dialog.

In my calling Activity class I create instance of Dailog class, and then call up method which does some network operation(which is not async task) and then when network task is finished I dismis the dialog object. I need wait on the same screen untill networks operation finishes but with dialog showing something is happening.

While debugging I do see that that dialog object is not null. No exception throughout this execution but alert dialog never shows up

```<code>
public class Dialog  {

    private AlertDialog dialog  ;
    private AlertDialog.Builder builder;

    public Dialog(Activity activity , String Message , String titleMsg) {
        builder = new AlertDialog.Builder(activity);
        builder.setMessage(Message);
        builder.setTitle(titleMsg);
        builder.setCancelable(false);
        builder.setIcon(R.drawable.logoxl);
        dialog = builder.create();
        dialog.show();
    }
 public void dismiss(){
        this.dialog.dismiss();
    }

}

// my activity method(openMenu) on button click where I am calling this

public void OpenMenu(View view){
 Dialog progress = new Dialog(this , "We are fetching today's menu...Please Wait" , "Biji's Kitchen");
        try {
            Data fetcheddata = new Data(this);
            fetcheddata.getMenu();
        }catch(Exception e){
            e.printStackTrace();

        }
 progress.dismiss();
}
</code>```

答:
Data.getMenu() is network operation and should be executed in the separate thread. Dialog.dismiss(), on the other hand, is UI operation and should be executed in main thread.

So, in Data thread you should wait for network request completion and then post message to UI thread to dismiss the dialog after that.

P.S. To be more clear: your current implementation does show dialog - and immediately dismisses it as show and dismiss are called one after another in UI thread but data is still loading in another thread.

Body:
I crate a class called "Dailog" for building alert dialog which has its own dismiss() method to dismiss the dialog. and then use it's Object in many screens where I need to show alert dialog.

In my calling Activity class I create instance of Dailog class, and then call up method which does some network operation(which is not async task) and then when network task is finished I dismis the dialog object. I need wait on the same screen untill networks operation finishes but with dialog showing something is happening.

While debugging I do see that that dialog object is not null. No exception throughout this execution but alert dialog never shows up

public class Dialog  {

    private AlertDialog dialog  ;
    private AlertDialog.Builder builder;

    public Dialog(Activity activity , String Message , String titleMsg) {
        builder = new AlertDialog.Builder(activity);
        builder.setMessage(Message);
        builder.setTitle(titleMsg);
        builder.setCancelable(false);
        builder.setIcon(R.drawable.logoxl);
        dialog = builder.create();
        dialog.show();
    }
 public void dismiss(){
        this.dialog.dismiss();
    }

}

// my activity method(openMenu) on button click where I am calling this

public void OpenMenu(View view){
 Dialog progress = new Dialog(this , "We are fetching today's menu...Please Wait" , "Biji's Kitchen");
        try {
            Data fetcheddata = new Data(this);
            fetcheddata.getMenu();
        }catch(Exception e){
            e.printStackTrace();

        }
 progress.dismiss();
}


答:
Try commenting this Line. I hope it should work.</p>

```<code>//progress.dismiss();
</code>```

Title: alert dialog written in non activity class not showing alert dialog when dismissed from calling activity

Body:
Try commenting this Line. I hope it should work.

//progress.dismiss();


答:
You can use melt with set_index. By adding C and D as id_vars, the columns will keep the same structure, then you can just set the columns of interest as index to get a MultiIndex dataframe:

```<code>df.melt(id_vars=['Date', 'C', 'D']).set_index(['variable', 'Date'])

               C  D  value
variable Date
A        2000  5  4      1
         2001  7  4      2
         2002  7  7      3
         2003  5  7      4
B        2000  5  4      2
         2001  7  4      2
         2002  7  7      1
         2003  5  7      1
</code>```

Title: How can I turn the following dataframe into a multi-index dataframe?

Body:
How can I achieve the following:
I have a table like so

|----------------------|
| Date | A | B | C | D |
|------+---+---+---+---|
| 2000 | 1 | 2 | 5 | 4 |
|------+---+---+---+---|
| 2001 | 2 | 2 | 7 | 4 |
|------+---+---+---+---|
| 2002 | 3 | 1 | 7 | 7 |
|------+---+---+---+---|
| 2003 | 4 | 1 | 5 | 7 |
|----------------------|

and turn it into a multi-index type dataframe:

|------------------------------------|
| Column Name | Date | Value | C | D |
|-------------+------+-------+---+---|
|      A      | 2000 |   1   | 5 | 4 |
|             |------+-------+---+---|
|             | 2001 |   2   | 7 | 4 |
|             |------+-------+---+---|
|             | 2002 |   3   | 7 | 7 |
|             |------+-------+---+---|
|             | 2003 |   4   | 5 | 7 |
|-------------+------+-------+---+---|
|      B      | 2000 |   2   | 5 | 4 |
|             |------+-------+---+---|
|             | 2001 |   2   | 7 | 4 |
|             |------+-------+---+---|
|             | 2002 |   1   | 7 | 7 |
|             |------+-------+---+---|
|             | 2003 |   1   | 5 | 7 |
|------------------------------------|

I have tried using the Melt function on a dataframe but could not figure out how to achieve this desired look. I think I would also then have to apply a groupby function to the melted dataframe.

Body:
You can use melt with set_index. By adding C and D as id_vars, the columns will keep the same structure, then you can just set the columns of interest as index to get a MultiIndex dataframe:

df.melt(id_vars=['Date', 'C', 'D']).set_index(['variable', 'Date'])

               C  D  value
variable Date
A        2000  5  4      1
         2001  7  4      2
         2002  7  7      3
         2003  5  7      4
B        2000  5  4      2
         2001  7  4      2
         2002  7  7      1
         2003  5  7      1


问:
flex - Methods of creating pivot or tabular reports?
Looking for some ideas, strategies, tools, etc. on creating reports from Flash Builder / Flex 4.

I have a flex application that allows create/read/update/delete of client information from a back-end database.  It uses web services (zend amf -> mongo db or mysql).  I already have the client data IN flex via the web service as a collection for example.

A user requests the ability to generate a report - to display a list of clients under a certain age in a tabular excel style grid (datagrid most likely).   It will be sorted and subtotaled by a demographic such as "insurance type".  Ideally the user would like to be able to select the insurance types allowed on the report (or in the datagrid/pivot table).

I know one option would be to present the user with a series of check boxes or a multi-select list to choose the insurance types.   Then, present them with a data grid or advanced data grid component to display the 'report'.

What other techniques, options or components are available / have people used?

答:
You won't be able to avoid the fact that you're going to have to do some work on your own.  Your solution will be way too custom for a commercial options since only you know the data to display.

You need to create some kind of interface that the user can say what he wants in the report, while Flex queries the services, gets the data it needs to display and knows how to display it properly.  You need to figure out each part for this to work.


问:
Undefined index: code use Export to Excel in Laravel 5.8
I'm executing  Export, Import to Excel in Laravel. But I have an error

Undefined index: code

in a file  AlumniImport.php.
Thank you for help!

AlumniImport.php

namespace App\Imports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Illuminate\Support\Facades\Hash;

class AlumniImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new User([
            'code'          => $row["code"],
            'first_name'    => $row["first_name"],
            'last_name'     => $row["last_name"],
            'username'      => $row["username"],
            'password'      => Hash::make($row["password"]),
            'tel'           => $row["tel"],
            'email'         => $row["email"],
            'gender'        => $row["gender"],
            'birthday'      => $row["birthday"],
            'address'       => $row["address"],
            'status_id'     => $row["status_id"],
        ]);
    }
}
```

<p><strong>AlumniController.php</strong></p>

<pre class="lang-php prettyprint-override"><code>// Excel
use App\Imports\AlumniImport;
use App\Exports\AlumniExport;
use Excel;
class AlumniController extends Controller
{
 public function import()
    {
        Excel::import(new AlumniImport,request()->file('file'));
        return back();
    }
}
</code>```

Example of data in Excel:

```<code>code    first_name  last_name   username    password    tel     email      gender birthday  address status_id
B8888   John        Smith       johnsmith   123456    123456    johnsmith@gmail.com Male 4/9/1998   USA 1
B7777   Tom         Cruise      tomcruise   123456    123456    tomcruies@gmail.com Male    4/5/1998 Canada 1
B6666   Lena        Do          lenado      123456    123456    lenado@gmail.com    Male    9/4/1997    USA 2
</code>```

答:
Add this line in your AlumniImport class:

```<code>use Maatwebsite\Excel\Concerns\WithHeadingRow;
</code>```

After this, include WithHeadingRow in your AlumniImport class like this:

```<code>class AlumniImport implements ToModel,WithHeadingRow
</code>```

Body:
I'm executing  Export, Import to Excel in Laravel. But I have an error

Undefined index: code

in a file  AlumniImport.php.
Thank you for help!

AlumniImport.php

namespace App\Imports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Illuminate\Support\Facades\Hash;

class AlumniImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new User([
            'code'          => $row["code"],
            'first_name'    => $row["first_name"],
            'last_name'     => $row["last_name"],
            'username'      => $row["username"],
            'password'      => Hash::make($row["password"]),
            'tel'           => $row["tel"],
            'email'         => $row["email"],
            'gender'        => $row["gender"],
            'birthday'      => $row["birthday"],
            'address'       => $row["address"],
            'status_id'     => $row["status_id"],
        ]);
    }
}

AlumniController.php

// Excel
use App\Imports\AlumniImport;
use App\Exports\AlumniExport;
use Excel;
class AlumniController extends Controller
{
 public function import()
    {
        Excel::import(new AlumniImport,request()->file('file'));
        return back();
    }
}

Example of data in Excel:

code    first_name  last_name   username    password    tel     email      gender birthday  address status_id
B8888   John        Smith       johnsmith   123456    123456    johnsmith@gmail.com Male 4/9/1998   USA 1
B7777   Tom         Cruise      tomcruise   123456    123456    tomcruies@gmail.com Male    4/5/1998 Canada 1
B6666   Lena        Do          lenado      123456    123456    lenado@gmail.com    Male    9/4/1997    USA 2

Body:
Add this line in your AlumniImport class:

use Maatwebsite\Excel\Concerns\WithHeadingRow;

After this, include WithHeadingRow in your AlumniImport class like this:

class AlumniImport implements ToModel,WithHeadingRow


问:
Compare string of unknown length against string of known length
I want to compare a null-terminated string of an unknown length (s1) with an unterminated string of a known length (s2).

!strncmp(s1, s2, s2_len) is close to correct, but also becomes evaluates to true if s2 is a prefix of s1.

strlen(s1) == s2_len && !strcmp(s1, s2) is correct, but scans s1 twice.

Obviously, manually comparing the strings also works, but loses me all the shiny optimizations the C library has picked up in the last forty years.

Is there a good way to achieve this with C library functions?

答:
If strncmp(s1, s2, s2_len) returns 0 you know that s1 is at least as long as s2, so you can just do a check for the terminator to exclude the possibility that s2 is a prefix of s1:

```<code>if (!strncmp(s1, s2, s2_len) && s1[s2_len] == '\0') {
    // ...
}
</code>```

Body:
If strncmp(s1, s2, s2_len) returns 0 you know that s1 is at least as long as s2, so you can just do a check for the terminator to exclude the possibility that s2 is a prefix of s1:

if (!strncmp(s1, s2, s2_len) && s1[s2_len] == '\0') {
    // ...
}


问:
Maximum Likelihood Estimation of a Poisson Distribution?
I have a table with observations (x, y) and need to estimate the mean of the Poisson distribution that more closely resembles them. It seems R and Octave can both do this on Linux, but I was wondering if there is a multiplatform way to do it. I can bundle anything with the program but I can't ask to install anything for it to run.

I tried searching for an algorithm to do it myself and couldn't find one, so I don't know what to do.

For the record, I did find a simple algorithm to do it that was basically summing all the values and dividing by the number of examples, but it fails for even a trivial example taken directly from a book.

Example:

```<code>requisitions per day : absolute frequency (days) : relative frequency
 8 :  2 : 0.016
 9 :  4 : 0.033
10 :  6 : 0.050
11 :  8 : 0.066
12 : 10 : 0.083
13 : 12 : 0.100
14 : 13 : 0.108
15 : 14 : 0.116
16 : 12 : 0.100
17 : 10 : 0.083
18 :  9 : 0.075
19 :  7 : 0.058
20 :  5 : 0.041
21 :  3 : 0.025
22 :  2 : 0.016
23 :  2 : 0.016
24 :  1 : 0.008
</code>```

The mean for the Poisson distribution should be 15 (according to the book where I got the example). The method that I said above and is in one of the answers gives me 16. Using the sum of the squared euclidean distances I also find that the Poisson with mean 15 is closer to the data than the one with mean 16.

答:
The MLE of the mean is just the sample mean. See Wikipedia:

http://en.wikipedia.org/wiki/Poisson_distribution#Maximum_likelihood

Just average your vector of data.

Update: I'm extending this answer now, based on the sample data just added to the question.

My interpretation of the sample data is that

```<code>reqs-per-day   frequency
 8             2
 9             4
10             6
</code>```

means that there were two days where the requisition count on each day was 8. And four days where the requisition count was 9. Therefore, I will assume that the data is equivalent to:

```<code>8,8,9,9,9,9,10,10,10,10,10,10,...
</code>```

where each entry in this list corresponds to one day. The order of this list doesn't matter. I think you should average this list.

The total of your frequency field is 120. I take this to mean there were 120 days altogether in the experiment.

Body:
I have a table with observations (x, y) and need to estimate the mean of the Poisson distribution that more closely resembles them. It seems R and Octave can both do this on Linux, but I was wondering if there is a multiplatform way to do it. I can bundle anything with the program but I can't ask to install anything for it to run.

I tried searching for an algorithm to do it myself and couldn't find one, so I don't know what to do.

For the record, I did find a simple algorithm to do it that was basically summing all the values and dividing by the number of examples, but it fails for even a trivial example taken directly from a book.

Example:

requisitions per day : absolute frequency (days) : relative frequency
 8 :  2 : 0.016
 9 :  4 : 0.033
10 :  6 : 0.050
11 :  8 : 0.066
12 : 10 : 0.083
13 : 12 : 0.100
14 : 13 : 0.108
15 : 14 : 0.116
16 : 12 : 0.100
17 : 10 : 0.083
18 :  9 : 0.075
19 :  7 : 0.058
20 :  5 : 0.041
21 :  3 : 0.025
22 :  2 : 0.016
23 :  2 : 0.016
24 :  1 : 0.008

The mean for the Poisson distribution should be 15 (according to the book where I got the example). The method that I said above and is in one of the answers gives me 16. Using the sum of the squared euclidean distances I also find that the Poisson with mean 15 is closer to the data than the one with mean 16.

Body:
The MLE of the mean is just the sample mean. See Wikipedia:

http://en.wikipedia.org/wiki/Poisson_distribution#Maximum_likelihood

Just average your vector of data.

Update: I'm extending this answer now, based on the sample data just added to the question.

My interpretation of the sample data is that

reqs-per-day   frequency
 8             2
 9             4
10             6

means that there were two days where the requisition count on each day was 8. And four days where the requisition count was 9. Therefore, I will assume that the data is equivalent to:

8,8,9,9,9,9,10,10,10,10,10,10,...

where each entry in this list corresponds to one day. The order of this list doesn't matter. I think you should average this list.

The total of your frequency field is 120. I take this to mean there were 120 days altogether in the experiment.


问:
Why are additional query constraints in a "unique validation rule" built with a closure in Laravel Documentation?
I am referring to https://laravel.com/docs/6.x/validation#rule-unique, section Adding Additional Where Clauses.

In the example of the documentation, the additional query is returned within a closure:

```<code>'email' => Rule::unique('users')->where(function ($query) {
    return $query->where('account_id', 1);
})
</code>```

In my application I validate my request like this:

```<code>$request->validate([
    'display_name' => [
        'required',
        'string',
        'between:3,32',
        Rule::unique('devices')->where(function ($query) {
            return $query->where('user_id', auth()->id());
        })
    ],
    // ...
]);
</code>```

If I omit the closure, my code still seems to work as expected:

```<code>$request->validate([
    'display_name' => [
        'required',
        'string',
        'between:3,32',
        Rule::unique('devices')->where('user_id', auth()->id())
    ],
    // ...
]);
</code>```

Is there a special reason for using a closure, like in the example?

答:
I highly doubt it makes a difference.  It looks like the Rule::unique() method is returning a Query\Builder object (the foundation for Eloquent) with a pre-generated base query of SELECT DISTINCT ? FROM devices. At that point, you're interacting with it as just a normal Builder object.  And Builder::where() offers either syntax you're using there.

When you supply a closure instead of field/(operator)/value arguments, the resulting query conditions get placed in parentheses.  So you can do things like SELECT DISTINCT ? FROM devices WHERE ? OR (? AND ?).

Body:
I am referring to https://laravel.com/docs/6.x/validation#rule-unique, section Adding Additional Where Clauses.

In the example of the documentation, the additional query is returned within a closure:

'email' => Rule::unique('users')->where(function ($query) {
    return $query->where('account_id', 1);
})

In my application I validate my request like this:

$request->validate([
    'display_name' => [
        'required',
        'string',
        'between:3,32',
        Rule::unique('devices')->where(function ($query) {
            return $query->where('user_id', auth()->id());
        })
    ],
    // ...
]);

If I omit the closure, my code still seems to work as expected:

$request->validate([
    'display_name' => [
        'required',
        'string',
        'between:3,32',
        Rule::unique('devices')->where('user_id', auth()->id())
    ],
    // ...
]);

Is there a special reason for using a closure, like in the example?


答:
```<code>if (!strncmp(s1, s2, s2_len) && s1[s2_len] == 0) {...}
</code>```

If the strncmp() returns zero, then s2 is a prefix of s1.

if s1[s2_len] is NUL, then the strings are equal

when not: then strlen(s1) > s2_len

if the strncmp() returns nonzero, the second test is skipped (short-cicuit evaluation)

Title: Compare string of unknown length against string of known length

Body:
I want to compare a null-terminated string of an unknown length (s1) with an unterminated string of a known length (s2).

!strncmp(s1, s2, s2_len) is close to correct, but also becomes evaluates to true if s2 is a prefix of s1.

strlen(s1) == s2_len && !strcmp(s1, s2) is correct, but scans s1 twice.

Obviously, manually comparing the strings also works, but loses me all the shiny optimizations the C library has picked up in the last forty years.

Is there a good way to achieve this with C library functions?

Body:
if (!strncmp(s1, s2, s2_len) && s1[s2_len] == 0) {...}

If the strncmp() returns zero, then s2 is a prefix of s1.

if s1[s2_len] is NUL, then the strings are equal

when not: then strlen(s1) > s2_len

if the strncmp() returns nonzero, the second test is skipped (short-cicuit evaluation)


问:
Run a LLVM Pass without using opt tool
I am a beginner in writing LLVM Pass, and I was going through the documentation about writing my own LLVM pass and then run it with opt tool, i.e

```<code>/llvm/bin/opt -load /llvm/lib/LLVMHello.so  -hello input.ll
</code>```

Here, my pass is Hello.cpp and a C function is in input.c which is converted to input.ll by Clang.

My question is can we run our pass without using opt tool i.e.

```<code>./hello input.ll
</code>```

Is there any method to run a pass like above such method?

答:
After attaining a valid Module, for example, via llvm::parseBitcodeFile, all actions you need are just creating llvm::legacy::Passmanager, invoking llvm::legacy::Passmanager::add to add passes and finally invoking llvm::legacy::Passmanager::run on your module.

opt use a class derived from llvm::legacy::Passmanager but actually call methods in the base class to cope with modules.

Title: Run a LLVM Pass without using opt tool

Body:
I am a beginner in writing LLVM Pass, and I was going through the documentation about writing my own LLVM pass and then run it with opt tool, i.e

/llvm/bin/opt -load /llvm/lib/LLVMHello.so  -hello input.ll

Here, my pass is Hello.cpp and a C function is in input.c which is converted to input.ll by Clang.

My question is can we run our pass without using opt tool i.e.

./hello input.ll

Is there any method to run a pass like above such method?


问:
Attempt to insert record on page where this table is not allowed
I get the message above (Attempt to insert record on page where this table is not allowed) when trying to create a new record from an extension.

The "page" i try to create the record in is a sysfolder and not a page

t3lib_extMgm::allowTableOnStandardPages('user_myext_categories'); is set

there are already records of categories on this page

there is no 'type' => definition in TCA, but the table itself is registered in TCA like the other tables from this extension (and they work)

Any hints on this?

答: in the ext_table you need this: \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::allowTableOnStandardPages('XXXXXX');


问:
error `require' /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot
I installed ubuntu and want to install Ruby on Rails. But tried few times and see same error after I run 'rails new app' I see error </p>

```<code>from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
/usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file -- bundler/setup (LoadError)
</code>```

<p>The server also doesn't run because of it. </p>

答:
You need to install Bundler first.

```<code>gem install bundler
</code>```

Bundler is a Ruby gem. It's a Ruby gem used to manage other Ruby gems (often called dependencies).

Body:
I installed ubuntu and want to install Ruby on Rails. But tried few times and see same error after I run 'rails new app' I see error

from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
/usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file -- bundler/setup (LoadError)

The server also doesn't run because of it.

Body:
You need to install Bundler first.

gem install bundler

Bundler is a Ruby gem. It's a Ruby gem used to manage other Ruby gems (often called dependencies).


问:
Unicode CSS Font Awesome Icons Rendering as Boxes in React
I am using the jPlayer example in a create-react-app. Here is a CodeSandbox showing the issue of font-awesome icon's rendering as boxes.

The icons render via css rules specifying content as unicode for  tags with the fa class.

I installed the font-awesome dependency which was in the jPlayer example's package.json. Then, I implemented an AudioPlayer component and used the skins provided by jPlayer. The component renders but the icons are all boxes, and I can see the unicode content in the source.

Here's an example of the project architecture. This is the play button in /src/AudioPlayer/AudioPlayer.jsx.

<Play>{/* Icon set in css */}</Play>

Then, the AudioPlayer is imported into App.jsx. App.jsx imports a stylesheet which has this relevant rule:

```<code>.fa, .fas, .far {
    font-family: FontAwesome !important;
}
</code>```

App.jsx is then rendered by index.js. Inside index.js, we import the audio player's stylesheets:

```<code>// Styles the jPlayer to look nice
import 'react-jplayer/dist/css/skins/sleek.min.css';
// Styles Play/Pause/Mute etc when icons (<i />) are used for them
import 'react-jplayer/dist/css/controls/iconControls.min.css';
</code>```

The rule for the play button in iconControls.css looks like this:

```<code>.jp-jplayer .jp-icon-controls .jp-play i:before {
  content: "\F04B";
  font-family: 'Font Awesome\ 5 Free';
  font-weight: 900;
}
</code>```

then within index.html's head I include the font-awesome CDN as a final attempt at fixing the boxes being rendered instead of font-awesome icons.

答:
I think in the styles.css there is FontAwesome !important as shown below which is overriding the FontAwesome 5 Free font. You could remove this style to see the fonts coming up.

fa, .fas, .far {
    font-family: FontAwesome !important;
}```

Body:
I am using the jPlayer example in a create-react-app. Here is a CodeSandbox showing the issue of font-awesome icon's rendering as boxes.

The icons render via css rules specifying content as unicode for  tags with the fa class.

I installed the font-awesome dependency which was in the jPlayer example's package.json. Then, I implemented an AudioPlayer component and used the skins provided by jPlayer. The component renders but the icons are all boxes, and I can see the unicode content in the source.

Here's an example of the project architecture. This is the play button in /src/AudioPlayer/AudioPlayer.jsx.

<Play>{/* Icon set in css */}</Play>

Then, the AudioPlayer is imported into App.jsx. App.jsx imports a stylesheet which has this relevant rule:

.fa, .fas, .far {
    font-family: FontAwesome !important;
}

App.jsx is then rendered by index.js. Inside index.js, we import the audio player's stylesheets:

// Styles the jPlayer to look nice
import 'react-jplayer/dist/css/skins/sleek.min.css';
// Styles Play/Pause/Mute etc when icons () are used for them
import 'react-jplayer/dist/css/controls/iconControls.min.css';

The rule for the play button in iconControls.css looks like this:

.jp-jplayer .jp-icon-controls .jp-play i:before {
  content: "\F04B";
  font-family: 'Font Awesome\ 5 Free';
  font-weight: 900;
}

then within index.html's head I include the font-awesome CDN as a final attempt at fixing the boxes being rendered instead of font-awesome icons.


问:
remotely determine using ssh IF a machine needs to be rebooted
There are plenty of examples of HOW to reboot a linux machine via SSH. However, in my case I want to check IF a linux machine needs to be rebooted via SSH. I have an agent that checks a machine for various metrics and reports that back to a central alarm console. I want to add the ability to check if a machine requires a reboot since some of them have security updates automatically installing.

I don't want to have to enable something on each machine as I prefer to run one script from one location preferably with a single command to check remotely.

EDIT: To clarify, I was looking for a file on a machine that would indicate whether a machine requires a reboot. I then wanted to check for the existence of that file (or something else) remotely using SSH where I am already doing other checks on a group of machines on a nightly basis. I didn't necessarily want to trigger a reboot if it was determined a reboot is required.

The answer I was looking for is below that's referencing /var/run/reboot-required which lead me to to this link.

答:
You can check if the file /var/run/reboot-required exists.

In a bash script, you can use:

```<code>#!/bin/bash
if [ -f /var/run/reboot-required ]; then
  echo 'A reboot is required'
  restart -r now
fi
</code>```

That way, the script will reboot your machine if a required reboot is pending.

Body:
You can check if the file /var/run/reboot-required exists.

In a bash script, you can use:

#!/bin/bash
if [ -f /var/run/reboot-required ]; then
  echo 'A reboot is required'
  restart -r now
fi

That way, the script will reboot your machine if a required reboot is pending.


问:
how to use retrofit 2 to send file and other params together
I am looking for an example how could I send file and other params together to server.

I have to send server JSON which

```<code>{
    "title": "title",
    "file": "uploaded file instance",
    "location": {
        "lat": 48.8583,
        "lng": 2.29232,
        "place": "Eiffel Tower"
    }
}
</code>```

How could I create Retrofit to handle this case?

If file is a string I know how to handle this. If file is File object I have no idea how to do this.

答:
As of 02.2020 @Abtin Gramian's answer is great, except RequestBody.create() and MediaType.parse() are deprecated in Kotlin, so you have to use:

```<code>file.asRequestBody("image".toMediaTypeOrNull())
</code>```

instead of:

```<code>RequestBody.create(MediaType.parse("image"), file)
</code>```

Also, I had to write the following manually:

```<code>import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.asRequestBody
</code>```

Body:
I am looking for an example how could I send file and other params together to server.

I have to send server JSON which

{
    "title": "title",
    "file": "uploaded file instance",
    "location": {
        "lat": 48.8583,
        "lng": 2.29232,
        "place": "Eiffel Tower"
    }
}

How could I create Retrofit to handle this case?

If file is a string I know how to handle this. If file is File object I have no idea how to do this.

Body:
As of 02.2020 @Abtin Gramian's answer is great, except RequestBody.create() and MediaType.parse() are deprecated in Kotlin, so you have to use:

file.asRequestBody("image".toMediaTypeOrNull())

instead of:

RequestBody.create(MediaType.parse("image"), file)

Also, I had to write the following manually:

import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.asRequestBody


问:
How can i edit jupyter notebook from terminal without opening web browser?
How can I edit my jupyter notebook in terminal.
I just don't like to open jupyter notebook in web browser.
I google out but every answer is related to how can we open notebook from terminal directly.</p>

答:
I'd suggest looking at Jupytext's ability to do command line conversions back-and-forth from the notebook json structure to a python script (or markdown). If you already have the backbone of a notebook (.ipynb) file, you can convert it to .py script using jupytext --to py notebook.ipynb. That makes a text file that is easy to edit in your favorite terminal based text editor. The json in the .ipynb files is not as easy to edit directly.

Then when you are done editing, you can convert the .py script form back to a notebook with something like jupytext --to notebook notebook.py. Optionally, you can even execute it without opening a browser by adding --execute. I have an example conversion-and-execution command in use here.


问:
@Around aspect and Kotlin suspended function
I try to understand how to create an @Around aspect for a Kotlin’s suspended function (for example, to measure time spent in this function, or for a custom @Transactional aspect):

```<code>@Timed("my-timer")
suspend fun test() {
    println("before")
    delay(50) // invokes ProceedingJoinPoint#proceed() before this line
    println("after")
}
</code>```

Since this function has a suspend function call, the @Around aspect’s proceed function will be invoked right before delay() call. But obviously I’d like to measure full time spent in the function.

What is the right way to solve it? Maybe I can somehow subscribe on the last continuation in the method, or smth like that?

答:
This is tracked by https://github.com/spring-projects/spring-framework/issues/22462 and will most likely be fixed in 5.3

The same issue happens for @Transactional.

Body:
I try to understand how to create an @Around aspect for a Kotlin’s suspended function (for example, to measure time spent in this function, or for a custom @Transactional aspect):

@Timed("my-timer")
suspend fun test() {
    println("before")
    delay(50) // invokes ProceedingJoinPoint#proceed() before this line
    println("after")
}

Since this function has a suspend function call, the @Around aspect’s proceed function will be invoked right before delay() call. But obviously I’d like to measure full time spent in the function.

What is the right way to solve it? Maybe I can somehow subscribe on the last continuation in the method, or smth like that?


问:
React-DOM: Unable to append Trading-view canvas from 'lightweight-charts' to body
Trading-view for react comes with document.body and I want to impend the canvas within the parent div. But it gets append to the end of the body. Tried quite a few possible solutions, but nothing has worked.

Elements

The Graph code is as follows:

```<code>import { createChart } from "lightweight-charts";

function Graph() {
      var chart = createChart(document.body, {
        width: 600,
        height: 300,
        crosshair: {
          mode: "normal"
        }
      });

      var candleSeries = chart.addCandlestickSeries();

      var data = [
        { time: "2018-10-19", open: 54.62, high: 55.5, low: 54.52, close: 54.9 },
        { time: "2018-10-22", open: 55.08, high: 55.27, low: 54.61, close: 54.98 },
        { time: "2018-10-23", open: 56.09, high: 57.47, low: 56.09, close: 57.21 },
        { time: "2018-10-24", open: 57.0, high: 58.44, low: 56.41, close: 57.42 },
        { time: "2018-10-25", open: 57.46, high: 57.63, low: 56.17, close: 56.43 },
        { time: "2018-10-26", open: 56.26, high: 56.62, low: 55.19, close: 55.51 },
        { time: "2018-10-29", open: 55.81, high: 57.15, low: 55.72, close: 56.48 },
        { time: "2018-10-30", open: 56.92, high: 58.8, low: 56.92, close: 58.18 },
        { time: "2018-10-31", open: 58.32, high: 58.32, low: 56.76, close: 57.09 },
        { time: "2018-11-01", open: 56.98, high: 57.28, low: 55.55, close: 56.05 },
        { time: "2018-11-02", open: 56.34, high: 57.08, low: 55.92, close: 56.63 },
        { time: "2018-11-05", open: 56.51, high: 57.45, low: 56.51, close: 57.21 },
        { time: "2018-11-06", open: 57.02, high: 57.35, low: 56.65, close: 57.21 },
        { time: "2018-11-07", open: 57.55, high: 57.78, low: 57.03, close: 57.65 },
        { time: "2018-11-08", open: 57.7, high: 58.44, low: 57.66, close: 58.27 },
      ];

      candleSeries.setData(data);

      var lastClose = data[data.length - 1].close;
      var lastIndex = data.length - 1;

      var targetIndex = lastIndex + 105 + Math.round(Math.random() + 30);
      var targetPrice = getRandomPrice();

      var currentIndex = lastIndex + 1;
      var currentBusinessDay = { day: 29, month: 5, year: 2019 };
      var ticksInCurrentBar = 0;
      var currentBar = {
        open: null,
        high: null,
        low: null,
        close: null,
        time: currentBusinessDay
      };

    function mergeTickToBar(price) {
        if (currentBar.open === null) {
          currentBar.open = price;
          currentBar.high = price;
          currentBar.low = price;
          currentBar.close = price;
        } else {
          currentBar.close = price;
          currentBar.high = Math.max(currentBar.high, price);
          currentBar.low = Math.min(currentBar.low, price);
        }
        candleSeries.update(currentBar);
      }

      function reset() {
        candleSeries.setData(data);
        lastClose = data[data.length - 1].close;
        lastIndex = data.length - 1;

        targetIndex = lastIndex + 5 + Math.round(Math.random() + 30);
        targetPrice = getRandomPrice();

        currentIndex = lastIndex + 1;
        currentBusinessDay = { day: 29, month: 5, year: 2019 };
        ticksInCurrentBar = 0;
      }

      function getRandomPrice() {
        return 10 + Math.round(Math.random() * 10000) / 100;
      }

      function nextBusinessDay(time) {
        var d = new Date();
        d.setUTCFullYear(time.year);
        d.setUTCMonth(time.month - 1);
        d.setUTCDate(time.day + 1);
        d.setUTCHours(0, 0, 0, 0);
        return {
          year: d.getUTCFullYear(),
          month: d.getUTCMonth() + 1,
          day: d.getUTCDate()
        };
      }

      setInterval(function() {
        var deltaY = targetPrice - lastClose;
        var deltaX = targetIndex - lastIndex;
        var angle = deltaY / deltaX;
        var basePrice = lastClose + (currentIndex - lastIndex) * angle;
        var noise = 0.1 - Math.random() * 0.2 + 1.0;
        var noisedPrice = basePrice * noise;
        mergeTickToBar(noisedPrice);
        if (++ticksInCurrentBar === 5) {
          // move to next bar
          currentIndex++;
          currentBusinessDay = nextBusinessDay(currentBusinessDay);
          currentBar = {
            open: null,
            high: null,
            low: null,
            close: null,
            time: currentBusinessDay
          };
          ticksInCurrentBar = 0;
          if (currentIndex === 5000) {
            reset();
            return;
          }
          if (currentIndex === targetIndex) {
            // change trend
            lastClose = noisedPrice;
            lastIndex = currentIndex;
            targetIndex = lastIndex + 5 + Math.round(Math.random() + 30);
            targetPrice = getRandomPrice();
          }
        }
      }, 200);
      return null;
    }

    export default Graph;
</code>```

The parent component:

```<code>import React from "react";
import Graph from "./Graph";

function App() {
  return (
    <div
      style={{
        flex: 1,
        flexDirection: "column",
        background: "orange",
        justifyContent: "center",
        alignItems: "center"
      }}
    >
      <Graph />
      <h1>It is to append graph into body</h1>
    </div>
  );
}

export default App;
</code>```

I have tried refs, different DOM manipulation methods, but nothing has worked. It would be great if someone can help me get to the solution.

答:
I was using useRef with wrong logic and got it working with these changes, for someone who might run into same kind of problem: </p>

```<code>import { createChart } from "lightweight-charts";
import React from 'react';

const  Graph = () => {
  const chartRef = React.useRef(null);

  React.useEffect(()=> {
    if(chartRef.current){
      const chart = createChart(chartRef.current, {
        width: 600,
        height: 300,
        crosshair: {
          mode: "normal"
        }
      });

      prepareChart(chart);
    }
  }, [])

  function prepareChart(chart) {

  var candleSeries = chart.addCandlestickSeries();

  var data = [
    { time: "2018-10-19", open: 54.62, high: 55.5, low: 54.52, close: 54.9 },
    { time: "2018-10-22", open: 55.08, high: 55.27, low: 54.61, close: 54.98 },
    { time: "2018-10-23", open: 56.09, high: 57.47, low: 56.09, close: 57.21 },
    { time: "2018-10-24", open: 57.0, high: 58.44, low: 56.41, close: 57.42 },
    { time: "2018-10-25", open: 57.46, high: 57.63, low: 56.17, close: 56.43 },
  ];

  candleSeries.setData(data);

  var lastClose = data[data.length - 1].close;
  var lastIndex = data.length - 1;

  var targetIndex = lastIndex + 105 + Math.round(Math.random() + 30);
  var targetPrice = getRandomPrice();

  var currentIndex = lastIndex + 1;
  var currentBusinessDay = { day: 29, month: 5, year: 2019 };
  var ticksInCurrentBar = 0;
  var currentBar = {
    open: null,
    high: null,
    low: null,
    close: null,
    time: currentBusinessDay
  };

  function mergeTickToBar(price) {
    if (currentBar.open === null) {
      currentBar.open = price;
      currentBar.high = price;
      currentBar.low = price;
      currentBar.close = price;
    } else {
      currentBar.close = price;
      currentBar.high = Math.max(currentBar.high, price);
      currentBar.low = Math.min(currentBar.low, price);
    }
    candleSeries.update(currentBar);
  }

  function reset() {
    candleSeries.setData(data);
    lastClose = data[data.length - 1].close;
    lastIndex = data.length - 1;

    targetIndex = lastIndex + 5 + Math.round(Math.random() + 30);
    targetPrice = getRandomPrice();

    currentIndex = lastIndex + 1;
    currentBusinessDay = { day: 29, month: 5, year: 2019 };
    ticksInCurrentBar = 0;
  }

  function getRandomPrice() {
    return 10 + Math.round(Math.random() * 10000) / 100;
  }

  function nextBusinessDay(time) {
    var d = new Date();
    d.setUTCFullYear(time.year);
    d.setUTCMonth(time.month - 1);
    d.setUTCDate(time.day + 1);
    d.setUTCHours(0, 0, 0, 0);
    return {
      year: d.getUTCFullYear(),
      month: d.getUTCMonth() + 1,
      day: d.getUTCDate()
    };
  }

  setInterval(function() {
    var deltaY = targetPrice - lastClose;
    var deltaX = targetIndex - lastIndex;
    var angle = deltaY / deltaX;
    var basePrice = lastClose + (currentIndex - lastIndex) * angle;
    var noise = 0.1 - Math.random() * 0.2 + 1.0;
    var noisedPrice = basePrice * noise;
    mergeTickToBar(noisedPrice);
    if (++ticksInCurrentBar === 5) {
      // move to next bar
      currentIndex++;
      currentBusinessDay = nextBusinessDay(currentBusinessDay);
      currentBar = {
        open: null,
        high: null,
        low: null,
        close: null,
        time: currentBusinessDay
      };
      ticksInCurrentBar = 0;
      if (currentIndex === 5000) {
        reset();
        return;
      }
      if (currentIndex === targetIndex) {
        // change trend
        lastClose = noisedPrice;
        lastIndex = currentIndex;
        targetIndex = lastIndex + 5 + Math.round(Math.random() + 30);
        targetPrice = getRandomPrice();
      }
    }
  }, 200);

}
  return <div ref={chartRef} />;
}

export default Graph;
</code>```

Body:
Trading-view for react comes with document.body and I want to impend the canvas within the parent div. But it gets append to the end of the body. Tried quite a few possible solutions, but nothing has worked.

Elements

The Graph code is as follows:

import { createChart } from "lightweight-charts";

function Graph() {
      var chart = createChart(document.body, {
        width: 600,
        height: 300,
        crosshair: {
          mode: "normal"
        }
      });

      var candleSeries = chart.addCandlestickSeries();

      var data = [
        { time: "2018-10-19", open: 54.62, high: 55.5, low: 54.52, close: 54.9 },
        { time: "2018-10-22", open: 55.08, high: 55.27, low: 54.61, close: 54.98 },
        { time: "2018-10-23", open: 56.09, high: 57.47, low: 56.09, close: 57.21 },
        { time: "2018-10-24", open: 57.0, high: 58.44, low: 56.41, close: 57.42 },
        { time: "2018-10-25", open: 57.46, high: 57.63, low: 56.17, close: 56.43 },
        { time: "2018-10-26", open: 56.26, high: 56.62, low: 55.19, close: 55.51 },
        { time: "2018-10-29", open: 55.81, high: 57.15, low: 55.72, close: 56.48 },
        { time: "2018-10-30", open: 56.92, high: 58.8, low: 56.92, close: 58.18 },
        { time: "2018-10-31", open: 58.32, high: 58.32, low: 56.76, close: 57.09 },
        { time: "2018-11-01", open: 56.98, high: 57.28, low: 55.55, close: 56.05 },
        { time: "2018-11-02", open: 56.34, high: 57.08, low: 55.92, close: 56.63 },
        { time: "2018-11-05", open: 56.51, high: 57.45, low: 56.51, close: 57.21 },
        { time: "2018-11-06", open: 57.02, high: 57.35, low: 56.65, close: 57.21 },
        { time: "2018-11-07", open: 57.55, high: 57.78, low: 57.03, close: 57.65 },
        { time: "2018-11-08", open: 57.7, high: 58.44, low: 57.66, close: 58.27 },
      ];

      candleSeries.setData(data);

      var lastClose = data[data.length - 1].close;
      var lastIndex = data.length - 1;

      var targetIndex = lastIndex + 105 + Math.round(Math.random() + 30);
      var targetPrice = getRandomPrice();

      var currentIndex = lastIndex + 1;
      var currentBusinessDay = { day: 29, month: 5, year: 2019 };
      var ticksInCurrentBar = 0;
      var currentBar = {
        open: null,
        high: null,
        low: null,
        close: null,
        time: currentBusinessDay
      };

    function mergeTickToBar(price) {
        if (currentBar.open === null) {
          currentBar.open = price;
          currentBar.high = price;
          currentBar.low = price;
          currentBar.close = price;
        } else {
          currentBar.close = price;
          currentBar.high = Math.max(currentBar.high, price);
          currentBar.low = Math.min(currentBar.low, price);
        }
        candleSeries.update(currentBar);
      }

      function reset() {
        candleSeries.setData(data);
        lastClose = data[data.length - 1].close;
        lastIndex = data.length - 1;

        targetIndex = lastIndex + 5 + Math.round(Math.random() + 30);
        targetPrice = getRandomPrice();

        currentIndex = lastIndex + 1;
        currentBusinessDay = { day: 29, month: 5, year: 2019 };
        ticksInCurrentBar = 0;
      }

      function getRandomPrice() {
        return 10 + Math.round(Math.random() * 10000) / 100;
      }

      function nextBusinessDay(time) {
        var d = new Date();
        d.setUTCFullYear(time.year);
        d.setUTCMonth(time.month - 1);
        d.setUTCDate(time.day + 1);
        d.setUTCHours(0, 0, 0, 0);
        return {
          year: d.getUTCFullYear(),
          month: d.getUTCMonth() + 1,
          day: d.getUTCDate()
        };
      }

      setInterval(function() {
        var deltaY = targetPrice - lastClose;
        var deltaX = targetIndex - lastIndex;
        var angle = deltaY / deltaX;
        var basePrice = lastClose + (currentIndex - lastIndex) * angle;
        var noise = 0.1 - Math.random() * 0.2 + 1.0;
        var noisedPrice = basePrice * noise;
        mergeTickToBar(noisedPrice);
        if (++ticksInCurrentBar === 5) {
          // move to next bar
          currentIndex++;
          currentBusinessDay = nextBusinessDay(currentBusinessDay);
          currentBar = {
            open: null,
            high: null,
            low: null,
            close: null,
            time: currentBusinessDay
          };
          ticksInCurrentBar = 0;
          if (currentIndex === 5000) {
            reset();
            return;
          }
          if (currentIndex === targetIndex) {
            // change trend
            lastClose = noisedPrice;
            lastIndex = currentIndex;
            targetIndex = lastIndex + 5 + Math.round(Math.random() + 30);
            targetPrice = getRandomPrice();
          }
        }
      }, 200);
      return null;
    }

    export default Graph;

The parent component:

import React from "react";
import Graph from "./Graph";

function App() {
  return (

      <Graph />

It is to append graph into body

  );
}

export default App;

I have tried refs, different DOM manipulation methods, but nothing has worked. It would be great if someone can help me get to the solution.

Body:
I was using useRef with wrong logic and got it working with these changes, for someone who might run into same kind of problem:

import { createChart } from "lightweight-charts";
import React from 'react';

const  Graph = () => {
  const chartRef = React.useRef(null);

  React.useEffect(()=> {
    if(chartRef.current){
      const chart = createChart(chartRef.current, {
        width: 600,
        height: 300,
        crosshair: {
          mode: "normal"
        }
      });

      prepareChart(chart);
    }
  }, [])

  function prepareChart(chart) {

  var candleSeries = chart.addCandlestickSeries();

  var data = [
    { time: "2018-10-19", open: 54.62, high: 55.5, low: 54.52, close: 54.9 },
    { time: "2018-10-22", open: 55.08, high: 55.27, low: 54.61, close: 54.98 },
    { time: "2018-10-23", open: 56.09, high: 57.47, low: 56.09, close: 57.21 },
    { time: "2018-10-24", open: 57.0, high: 58.44, low: 56.41, close: 57.42 },
    { time: "2018-10-25", open: 57.46, high: 57.63, low: 56.17, close: 56.43 },
  ];

  candleSeries.setData(data);

  var lastClose = data[data.length - 1].close;
  var lastIndex = data.length - 1;

  var targetIndex = lastIndex + 105 + Math.round(Math.random() + 30);
  var targetPrice = getRandomPrice();

  var currentIndex = lastIndex + 1;
  var currentBusinessDay = { day: 29, month: 5, year: 2019 };
  var ticksInCurrentBar = 0;
  var currentBar = {
    open: null,
    high: null,
    low: null,
    close: null,
    time: currentBusinessDay
  };

  function mergeTickToBar(price) {
    if (currentBar.open === null) {
      currentBar.open = price;
      currentBar.high = price;
      currentBar.low = price;
      currentBar.close = price;
    } else {
      currentBar.close = price;
      currentBar.high = Math.max(currentBar.high, price);
      currentBar.low = Math.min(currentBar.low, price);
    }
    candleSeries.update(currentBar);
  }

  function reset() {
    candleSeries.setData(data);
    lastClose = data[data.length - 1].close;
    lastIndex = data.length - 1;

    targetIndex = lastIndex + 5 + Math.round(Math.random() + 30);
    targetPrice = getRandomPrice();

    currentIndex = lastIndex + 1;
    currentBusinessDay = { day: 29, month: 5, year: 2019 };
    ticksInCurrentBar = 0;
  }

  function getRandomPrice() {
    return 10 + Math.round(Math.random() * 10000) / 100;
  }

  function nextBusinessDay(time) {
    var d = new Date();
    d.setUTCFullYear(time.year);
    d.setUTCMonth(time.month - 1);
    d.setUTCDate(time.day + 1);
    d.setUTCHours(0, 0, 0, 0);
    return {
      year: d.getUTCFullYear(),
      month: d.getUTCMonth() + 1,
      day: d.getUTCDate()
    };
  }

  setInterval(function() {
    var deltaY = targetPrice - lastClose;
    var deltaX = targetIndex - lastIndex;
    var angle = deltaY / deltaX;
    var basePrice = lastClose + (currentIndex - lastIndex) * angle;
    var noise = 0.1 - Math.random() * 0.2 + 1.0;
    var noisedPrice = basePrice * noise;
    mergeTickToBar(noisedPrice);
    if (++ticksInCurrentBar === 5) {
      // move to next bar
      currentIndex++;
      currentBusinessDay = nextBusinessDay(currentBusinessDay);
      currentBar = {
        open: null,
        high: null,
        low: null,
        close: null,
        time: currentBusinessDay
      };
      ticksInCurrentBar = 0;
      if (currentIndex === 5000) {
        reset();
        return;
      }
      if (currentIndex === targetIndex) {
        // change trend
        lastClose = noisedPrice;
        lastIndex = currentIndex;
        targetIndex = lastIndex + 5 + Math.round(Math.random() + 30);
        targetPrice = getRandomPrice();
      }
    }
  }, 200);

}
  return <div ref={chartRef} />;
}

export default Graph;


问:
Ionic start <Project> <Template> Freezes
I am trying to start a new project in the ionic framework with the following command

```<code>ionic start MyFirstIonic blank
</code>```

However, no matter what I try the command prompt just sits there and blinks and eventually goes unresponsive.

I had downloaded everything I needed to run an application about a month ago and everything seemed to work just fine. However, now when I try to create a new project it just freezes.

I have a school project I need to get done and this is really stressing me out. I have tried the following solutions but to no avail.

Cleaning the cache

uninstalling and reinstalling ionic and cordova

uninstalling and reinstalling node

installing an earlier version of node (V8.11)

Going to my app roaming and deleting npm and npm cache

None of these proposed solutions I found online seem to work.

These are my current versions

Here is the infinite loop error:

If anyone has any ideas on how to get my programming environment up and running I would greatly appreciate it! I am already running behind on my assignments and really do not wish to fall even further behind.

答:
I had the same problem. Uninstalling the old CLI and installing the new CLI (with a different name) fixed the problem for me:</p>

```<code>npm uninstall -g ionic
npm install -g @ionic/cli
</code>```

Body:
I am trying to start a new project in the ionic framework with the following command

ionic start MyFirstIonic blank

However, no matter what I try the command prompt just sits there and blinks and eventually goes unresponsive.

I had downloaded everything I needed to run an application about a month ago and everything seemed to work just fine. However, now when I try to create a new project it just freezes.

I have a school project I need to get done and this is really stressing me out. I have tried the following solutions but to no avail.

Cleaning the cache

uninstalling and reinstalling ionic and cordova

uninstalling and reinstalling node

installing an earlier version of node (V8.11)

Going to my app roaming and deleting npm and npm cache

None of these proposed solutions I found online seem to work.

These are my current versions

Here is the infinite loop error:

If anyone has any ideas on how to get my programming environment up and running I would greatly appreciate it! I am already running behind on my assignments and really do not wish to fall even further behind.

Body:
I had the same problem. Uninstalling the old CLI and installing the new CLI (with a different name) fixed the problem for me:

npm uninstall -g ionic
npm install -g @ionic/cli


问:
Set a title programmatically
Here is my storyboard. My TabBarController references to the NavigationController (which has a own class) in the second picture.

I am not able to set a title via code. I tried every piece of code inside my MapsViewController & MapsNavigationViewController I found on Google & co.

viewController.title = "some title" <- not working

self.title = "some title" <- not working

navigationBar.topItem.title = "some title" <- not working

self.navigationItem.title = "Your Title" <- not working

self.parent?.title = "some title" <- not working

navigationItem.title = "What ever you want" <- not working

How can I set a title to my Navigation programmatically...?

1)

2)

3)

Edit: View Hierachy:

答:
Insert navigation controller in between the view controller and tabbarController .Set viewcontrollers as rootviewcontroller from navigation controller.OR you can embed also. Then set in Perticular viewController class ViewDidLoad()

```<code>self.title = "some title"
</code>```

OR

```<code>self.navigationItem.title = "Your Title"
</code>```

Title: Set a title programmatically

Body:
Insert navigation controller in between the view controller and tabbarController .Set viewcontrollers as rootviewcontroller from navigation controller.OR you can embed also. Then set in Perticular viewController class ViewDidLoad()

self.title = "some title"

OR

self.navigationItem.title = "Your Title"


问:
Create new user tool  to paste text with EditPlus
I use EditPlus 3.30 as my code editor, but this question also applies to earlier versions.  I would like to create a new user tool item on the user tool bar. The default set-up allows you to open a template when you click on an icon. I would like to create an item that instead pastes code from a libray file  (*.ctl) or any other text file. In the end, the new user tool item would function just like one of the icons on the hml tool bar.

I don't have extensive programming experience.

答:
EditPlus text editor: How to create a toolbar user tool icon to paste custom code snippets.

Configure the Preference/Tools dialog like this:

```
Command        CScript.exe C:\Your Path\Pastetext.js
Argument         //NoLogo $(CurRow)
leave initial directory blank
Action         Run as text (Insert)
```

Save the flowing five lines as  Pastetext.js

```
 var cArgs =                  WScript.Arguments;
var rStr =                  cArgs(0);
var rStr ="<item id='file1' media-type='application/xhtml+xml' href='aSample.html'/>";
// Print filler string
WScript.StdOut.Write(rStr);
```

//The rStr variable will print where your cursor is in an open document.

Body:
EditPlus text editor: How to create a toolbar user tool icon to paste custom code snippets.

Configure the Preference/Tools dialog like this:

Command        CScript.exe C:\Your Path\Pastetext.js
Argument         //NoLogo $(CurRow)
leave initial directory blank
Action         Run as text (Insert)

Save the flowing five lines as  Pastetext.js

 var cArgs =                  WScript.Arguments;
var rStr =                  cArgs(0);
var rStr ="<item id='file1' media-type='application/xhtml+xml' href='aSample.html'/>";
// Print filler string
WScript.StdOut.Write(rStr);

//The rStr variable will print where your cursor is in an open document.


问:
What should I know about C# before walking into an interview for a .NET job?
Sure, we all have written tons of C# code. So walking into an interview for a .NET job should be a no-brainer, right? And then you read some stackoverflow posts and it hits you: You don't know squat!

Remember that site with the cram sessions to go through, before taking an exam? I think stackoverflow could be used to make a sorted (voting) list of topics to know about.

Please only put one topic per post.
Please also add some information about the topic. Links, reference material etc.

EDIT: I guess some of you misunderstood the reason for the post - I'm hoping to generate a list of stuff to know about .NET, a sort of cram session that can be reviewed by everyone on the planet to regularly review. This should help us all remember arcane stuff we never really use.

答: I hope the job interview is about coding itself. c# is just a syntax of programming.  To be sure read about some specific C# things like reference vs value types</p>

OwnerDisplayName: Daren Thomas

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Daren Thomas

OwnerDisplayName: PoweRoy


问:
Dynamic State Machine in Ruby? Do State Machines Have to be Classes?
Question is, are state machines always defined statically (on classes)?  Or is there a way for me to have it so each instance of the class with has it's own set of states?

I'm checking out Stonepath for implementing a Task Engine.  I don't really see the distinction between "states" and "tasks" in there, so I'm thinking I could just map a Task directly to a state.  This would allow me to be able to define task-lists (or workflows) dynamically, without having to do things like:

```<code>aasm_event :evaluate do
  transitions :to => :in_evaluation, :from => :pending
end

aasm_event :accept do
  transitions :to => :accepted, :from => :pending
end

aasm_event :reject do
  transitions :to => :rejected, :from => :pending
end
</code>```

Instead, a WorkItem (the main workflow/task manager model), would just have many tasks.  Then the tasks would work like states, so I could do something like this:

```<code>aasm_initial_state :initial

tasks.each do |task|
  aasm_state task.name.to_sym
end

previous_state = nil
tasks.each do |tasks|
  aasm_event task.name.to_sym do
    transitions :to => "#{task.name}_phase".to_sym, :from => previous_state ? "#{task.name}_phase" : "initial"
  end
  previous_state = state
end
</code>```

However, I can't do that with the aasm gem because those methods (aasm_state and aasm_event) are class methods, so every instance of the class with that state machine has the same states.  I want it so a "WorkItem" or "TaskList" dynmically creates a sequence of states and transitions based on the tasks it has.

This would allow me to dynamically define workflows and just have states map to tasks.

Are state machines ever used like this?  It seems that this ruby workflow gem is similar to what I'm describing.

Update:  I can see doing something like the following, but it seems sort of hackish:

```<code>@implementation_state_machine = Class::new do
  include AASM
  aasm_initial_state :initial

  tasks.each { |state| aasm_state :"#{task.name}"}
  # ...
end
</code>```

... where a property on my model would be implementation_state_machine.  I'd have to override method_missing to delegate state-related methods (accepted_phase?) to the implementation anonymous class.

答:
In my implementation state machine is a hash https://github.com/mpapis/state_attr

```<code>state_attr :state, {
  nil => :first,
  :first => [:second, :third],
  :second => :last,
  :third => nil,
}
</code>```

you can define as many state attributes as you like

BTW: in the background there is still a class but only as a proxy to attribute

Body:
Question is, are state machines always defined statically (on classes)?  Or is there a way for me to have it so each instance of the class with has it's own set of states?

I'm checking out Stonepath for implementing a Task Engine.  I don't really see the distinction between "states" and "tasks" in there, so I'm thinking I could just map a Task directly to a state.  This would allow me to be able to define task-lists (or workflows) dynamically, without having to do things like:

aasm_event :evaluate do
  transitions :to => :in_evaluation, :from => :pending
end

aasm_event :accept do
  transitions :to => :accepted, :from => :pending
end

aasm_event :reject do
  transitions :to => :rejected, :from => :pending
end

Instead, a WorkItem (the main workflow/task manager model), would just have many tasks.  Then the tasks would work like states, so I could do something like this:

aasm_initial_state :initial

tasks.each do |task|
  aasm_state task.name.to_sym
end

previous_state = nil
tasks.each do |tasks|
  aasm_event task.name.to_sym do
    transitions :to => "#{task.name}_phase".to_sym, :from => previous_state ? "#{task.name}_phase" : "initial"
  end
  previous_state = state
end

However, I can't do that with the aasm gem because those methods (aasm_state and aasm_event) are class methods, so every instance of the class with that state machine has the same states.  I want it so a "WorkItem" or "TaskList" dynmically creates a sequence of states and transitions based on the tasks it has.

This would allow me to dynamically define workflows and just have states map to tasks.

Are state machines ever used like this?  It seems that this ruby workflow gem is similar to what I'm describing.

Update:  I can see doing something like the following, but it seems sort of hackish:

@implementation_state_machine = Class::new do
  include AASM
  aasm_initial_state :initial

  tasks.each { |state| aasm_state :"#{task.name}"}
  # ...
end

... where a property on my model would be implementation_state_machine.  I'd have to override method_missing to delegate state-related methods (accepted_phase?) to the implementation anonymous class.

Body:
In my implementation state machine is a hash https://github.com/mpapis/state_attr

state_attr :state, {
  nil => :first,
  :first => [:second, :third],
  :second => :last,
  :third => nil,
}

you can define as many state attributes as you like

BTW: in the background there is still a class but only as a proxy to attribute


问:
Select and display an image from the filesystem with electron
I'm developing a little app in Electron from which I can upload an image to Instagram and I'm stuck at one of the first steps :/

I want to select an image from the filesystem and display it in my app.

This is the code I've got so far:

CODE:

```<code>remote.dialog.showOpenDialog((filenames) => {
    fs.readFile(filepath, 'utf-8', (err, data) => {

        if(err){
            alert("An error ocurred reading the file :" + err.message);
            return;
        }
    });
});
</code>```

答:
Here is a solution with more information on separation of main process and renderer and usage of es6

main process

```<code>import { ipcMain, dialog } from "electron";
import fs from 'fs';

ipcMain.on("chooseFile", (event, arg) => {
  const result = dialog.showOpenDialog({
    properties: ["openFile"],
    filters: [{ name: "Images", extensions: ["png","jpg","jpeg"] }]
  });

  result.then(({canceled, filePaths, bookmarks}) => {
    const base64 = fs.readFileSync(filePaths[0]).toString('base64');
    event.reply("chosenFile", base64);
  });
});
</code>```

renderer process

```<code>import electron from 'electron';

// trigger file prompt
electron.ipcRenderer.send('chooseFile');

// handle response
electron.ipcRenderer.on('chosenFile', (event, base64) => {
  const src = `data:image/jpg;base64,${base64}`
})
</code>```

Body:
I'm developing a little app in Electron from which I can upload an image to Instagram and I'm stuck at one of the first steps :/

I want to select an image from the filesystem and display it in my app.

This is the code I've got so far:

CODE:

remote.dialog.showOpenDialog((filenames) => {
    fs.readFile(filepath, 'utf-8', (err, data) => {

        if(err){
            alert("An error ocurred reading the file :" + err.message);
            return;
        }
    });
});

Body:
Here is a solution with more information on separation of main process and renderer and usage of es6

main process

import { ipcMain, dialog } from "electron";
import fs from 'fs';

ipcMain.on("chooseFile", (event, arg) => {
  const result = dialog.showOpenDialog({
    properties: ["openFile"],
    filters: [{ name: "Images", extensions: ["png","jpg","jpeg"] }]
  });

  result.then(({canceled, filePaths, bookmarks}) => {
    const base64 = fs.readFileSync(filePaths[0]).toString('base64');
    event.reply("chosenFile", base64);
  });
});

renderer process

import electron from 'electron';

// trigger file prompt
electron.ipcRenderer.send('chooseFile');

// handle response
electron.ipcRenderer.on('chosenFile', (event, base64) => {
  const src = `data:image/jpg;base64,${base64}`
})


问:
XCBUtil.PropertyListConversionError in Xcode
When I try to run my project, I get this error, pointing to my localized .strings file:

read failed: The operation couldn’t be completed. (XCBUtil.PropertyListConversionError error 1.)

What can I do to fix this issue?

答: This quite common when you have info.plist file with wrong structure.</p>


问:
Passing subarray of 2-dimensional array in FORTRAN-77
I have 2-dimensional array

```<code>real triangle(0:2, 0:1)
</code>```

where "triangle" is an array of vectors (1-dim arrays)
also i have subroutine

```<code>subroutine vecSub(lhs, rhs, result)
real lhs(0:1), rhs(0:1), result(0:1)
    result(0) = lhs(0) - rhs(0)
    result(1) = lhs(1) - rhs(1)
    return
end
</code>```

is there any way to pass one of the vectors from "triangle" variable to this subroutine? Fortran-90 can do this: triangle(0, :) which gives first array of triangle, but i'm allowed to use only FORTRAN-77, so this won't do, any suggestions?

答:
@Javier Martin wrote "not with the current layout of your array", but missed the opportunity to suggest an alternative.

If instead you declared the variable as follows:

real triangle(0:1, 0:2)

reversing the order of the bounds, you could then pass triangle(0,0), triangle(0,1) or triangle(0,2) to the subroutine and get exactly the behavior you want, due to a Fortran feature called "sequence association". When you pass a single array element to a dummy argument that is an array, you are implicitly passing that and following elements, in array element order. This is about the only allowed violation of the normal Fortran shape-matching rules, and was part of FORTRAN 77.

Body:
I have 2-dimensional array

real triangle(0:2, 0:1)

where "triangle" is an array of vectors (1-dim arrays)
also i have subroutine

subroutine vecSub(lhs, rhs, result)
real lhs(0:1), rhs(0:1), result(0:1)
    result(0) = lhs(0) - rhs(0)
    result(1) = lhs(1) - rhs(1)
    return
end

is there any way to pass one of the vectors from "triangle" variable to this subroutine? Fortran-90 can do this: triangle(0, :) which gives first array of triangle, but i'm allowed to use only FORTRAN-77, so this won't do, any suggestions?