问:
C# DLLimport with mono on ubuntu: not charging dll
Goodmorning to All
I'm developing, with Visual Studio 2017, in C# language, an executable software, myExe.exe, that will be run on a PC with ubuntu 14.04 with mono
I need to use a DLL, we can call it dll2import.dll, for work via TCP/IP with a specific device (like a driver....).
Avoiding getting boring with several useless details I write only important info (but if you need feel free to ask) and a simple example.

In C++ dll2import.dll I have the first function to create handler for working with object, called d2iCreate, I wrap it in this way:

```<code>//private const String dllPath = @"D:\ExtDll2Use\dll2import.dll";
//private const String dllPath = "/home/massi/dll2import.dll";
private const String dllPath = "dll2import.dll";
[DllImport(dllPath,EntryPoint = "d2iCreate",CallingConvention = CallingConvention.Cdecl)]
unsafe public static extern UInt32 CSd2iCreate();
</code>```

there are many other function that I wrap similar to this way, but the problem start from that, so it is not usefull write all...

When I run the .exe with my PC all works good!!! But when I put this application on my PC with ubuntu and try o running it with mono.. appears the problem!!! My code go in exception caling CSd2iCreate() !!! like it not found the library.... I try several path without success... I try to put library (and path) in my home directory, in my root, and where .exe is present.... but it is like mono not use it!
It is very strange because if I delete dll2import.dll the error not change.. so it is like mono not found the .dll .... And I can tell you that I use other .dll and they work BUT that .dll are c# project developed in visual studio and linked inside my project..
So I suppose I must configure something inside mono or install that library in other way but I not know how!

The .dll is provided "as is" and I have not the source code... I can't recompile it...

If can be relevant I write here the error, but it is not very detailed, it is a generic one.

The code is that:

```<code>private unsafe bool CreateHandler() {
      try {
        pwxHandle = d2iCreate();
        return true;
      } catch(Exception ex) {
        Log.Errore(pwxProcLog,System.Reflection.MethodBase.GetCurrentMethod().Name,"Error creating Handler",ex);
        return false;
      }
    }
</code>```

the routine for log error code is that (an extract):

```<code>public void Errore(string Proc, string Metodo, string info, Exception e)
{

        ScriviErr(Proc, Metodo, info);
        ScriviErr(Proc, "Eccezione " + e.Source, e.Message);
        ScriviErr(Proc, "Stack", Environment.NewLine + e.StackTrace + Environment.NewLine);
    }
}
</code>```

so the error logged is that:

```<code>14/11/2017-17.38.23 <WV1> - CreateHandler: [Error creating Handler]
14/11/2017-17.38.23 <WV1> - Eccezione MyProject2LinkDLL: [dll2import.dll]
14/11/2017-17.38.23 <WV1> - Stack: [
  at (wrapper managed-to-native) MyProject2LinkDLL.Perif:d2iCreate ()
  at MyProject2LinkDLL.Perif.CreateHandler () [0x00000] in <filename unknown>:0
]
</code>```

I can tell you that in this line:

```<code>14/11/2017-17.38.23 <WV1> - Eccezione MyProject2LinkDLL: [dll2import.dll]
</code>```

between [] there is the path that I write for take library... so other time was that the error

```<code>14/11/2017-14.11.37 <WV1> - Eccezione MyProject2LinkDLL: [/home/massi/dll2import.dll]
</code>```

if other details are needed feel free to ask!

Thanks,
Massimiliano

答:
Not a complete answer but I remember encountering this with a DLL I was reusing a long time ago.  Essentially you have understand the architecture you are using:

Mono native uses.Net libraries, with a façade to call *nix functions for native interactions.  Thus a P/Invoke call uses the operating system to try and load things.  This means a windows compiled dll simply won't link properly as it would try to be loaded through the *nix load library calls.

There is a project within wine to compile the mono runtime against the wine libraries (essentially as .net is actually intended to run) but with the façade provided by the wine implementation.  This means that you can invoke the executable within WINE as it will load (via wine) and link correctly against the wine libraries.  I haven't used it so I don't know it's maturity Wine - Mono

This could work provided you don't touch some part of the unimplemented/non-working parts of the system and even then, there are so many moving parts you could run into all sorts of integration problems.  Is the $100 license for XP going to break you just to run it on windows?

The article here has some highly detailed info P/Invoke Mono.

Body:
Goodmorning to All
I'm developing, with Visual Studio 2017, in C# language, an executable software, myExe.exe, that will be run on a PC with ubuntu 14.04 with mono
I need to use a DLL, we can call it dll2import.dll, for work via TCP/IP with a specific device (like a driver....).
Avoiding getting boring with several useless details I write only important info (but if you need feel free to ask) and a simple example.

In C++ dll2import.dll I have the first function to create handler for working with object, called d2iCreate, I wrap it in this way:

//private const String dllPath = @"D:\ExtDll2Use\dll2import.dll";
//private const String dllPath = "/home/massi/dll2import.dll";
private const String dllPath = "dll2import.dll";
[DllImport(dllPath,EntryPoint = "d2iCreate",CallingConvention = CallingConvention.Cdecl)]
unsafe public static extern UInt32 CSd2iCreate();

there are many other function that I wrap similar to this way, but the problem start from that, so it is not usefull write all...

When I run the .exe with my PC all works good!!! But when I put this application on my PC with ubuntu and try o running it with mono.. appears the problem!!! My code go in exception caling CSd2iCreate() !!! like it not found the library.... I try several path without success... I try to put library (and path) in my home directory, in my root, and where .exe is present.... but it is like mono not use it!
It is very strange because if I delete dll2import.dll the error not change.. so it is like mono not found the .dll .... And I can tell you that I use other .dll and they work BUT that .dll are c# project developed in visual studio and linked inside my project..
So I suppose I must configure something inside mono or install that library in other way but I not know how!

The .dll is provided "as is" and I have not the source code... I can't recompile it...

If can be relevant I write here the error, but it is not very detailed, it is a generic one.

The code is that:

private unsafe bool CreateHandler() {
      try {
        pwxHandle = d2iCreate();
        return true;
      } catch(Exception ex) {
        Log.Errore(pwxProcLog,System.Reflection.MethodBase.GetCurrentMethod().Name,"Error creating Handler",ex);
        return false;
      }
    }

the routine for log error code is that (an extract):

public void Errore(string Proc, string Metodo, string info, Exception e)
{

        ScriviErr(Proc, Metodo, info);
        ScriviErr(Proc, "Eccezione " + e.Source, e.Message);
        ScriviErr(Proc, "Stack", Environment.NewLine + e.StackTrace + Environment.NewLine);
    }
}

so the error logged is that:

14/11/2017-17.38.23 <WV1> - CreateHandler: [Error creating Handler]
14/11/2017-17.38.23 <WV1> - Eccezione MyProject2LinkDLL: [dll2import.dll]
14/11/2017-17.38.23 <WV1> - Stack: [
  at (wrapper managed-to-native) MyProject2LinkDLL.Perif:d2iCreate ()
  at MyProject2LinkDLL.Perif.CreateHandler () [0x00000] in <filename unknown>:0
]

I can tell you that in this line:

14/11/2017-17.38.23 <WV1> - Eccezione MyProject2LinkDLL: [dll2import.dll]

between [] there is the path that I write for take library... so other time was that the error

14/11/2017-14.11.37 <WV1> - Eccezione MyProject2LinkDLL: [/home/massi/dll2import.dll]

if other details are needed feel free to ask!

Thanks,
Massimiliano


来源: stackexchange

问:
ThreeJS 3D Objects quality
Somebody knows how it's possible to have so good quality for the 3D Objects like here http://showroom.littleworkshop.fr/? The objects are exported at this quality from 3DsMax or Blender or something similar, or the quality it's improved in threejs? As far I saw, the project was created with threejs. Any information regarding this project it will be helpful.

Thank you.

答:
Question of quality is subjective. A better question would be "how can I create a scene using three.js with photo-realistic lighting and materials".

So here's an answer to that. There are a few points that make the example you provided look good:

1 - lighting. The example uses a mixture of direct and ambient lighting.
It is practically impossible to generate such lighting in real time in three.js (or any other 3d package for that matter) with the current state of the art on commodity hardware. So, you need to use light-maps. Light maps are pre-rendered textures of light and shadow, they can take a long time to generate, but look incredible, as demonstrated by example you mentioned. You can use Blender's Cycles renderer to generate light maps using "Bake" feature. The topic of lightmap generation is really outside of the scope of the question.

2 - Physically based materials. This is used to refer to material models that have excellent representation of real-life materials beyond "plastic". Three.js had at least 1 such maretial: StandardMaterial which is based on Metalness/Roughness/Albedo model (https://threejs.org/examples/?q=material#webgl_materials_standard)

good luck!

ContentLicense: CC BY-SA 3.0

Title: ThreeJS 3D Objects quality


问:
RStudio 1.1.383 and rmarkdown 1.7 environment enheritance
On Windows 7 64 bits, I have recently updated to RStudio 1.1.383 and rmarkdown 1.7. As I am using render to produce a pdf from an Rmd file I have noticed a new behavior.

There is leakage between the Global Environment and the knitting environment and it goes both ways:

If I define x = 12 in the .Rmd file, I find x in the Global environment after the render is complete.

If I use an undefined variable y in the .Rmd and I set y=1000 in the global environment before using render then y is used in the knitting of the .Rmd

If I do knit from RStudio the leakage does not occur and even if y is defined in the global environment, knitting the .Rmd will give an error (y not found).

Does anyone know why is that? I believe separating the environment is very important to ensure reproducibility even though it is sometimes painful to get right.

Here is my sessionInfo():

```<code>> sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] rmarkdown_1.7

loaded via a namespace (and not attached):
 [1] compiler_3.4.2  backports_1.1.1 magrittr_1.5    rprojroot_1.2   htmltools_0.3.6 tools_3.4.2     yaml_2.1.14     Rcpp_0.12.13
 [9] stringi_1.1.5   knitr_1.17      stringr_1.2.0   digest_0.6.12   evaluate_0.10.1
</code>```

Here is the minimal "test render.R" file:

```<code>library(rmarkdown)
y=1000
render(input = "test render.Rmd")
</code>```

and Here is the minimal "test render.Rmd" file:

```<code>---
title: "test render"
author: "Courvoisier"
output: pdf_document
---

## R Markdown

```{r cars}
x = 12
print(y)
```
</code>```

and here is the pdf result:

答:
As far as I can tell, this behavior has been there since Day 1. Here is how to prove it. First install the very first version (0.3.3) of rmarkdown from the CRAN archive:

```<code>devtools::install_version('rmarkdown', '0.3.3')
</code>```

And run your example:

```<code>library(rmarkdown)
y = 1000
render(input = "test render.Rmd")
</code>```

You see y is printed (as I'd expect):

This behavior is by design and I don't know why it is surprising to you. In R, global variables are accessible from anywhere (by definition). You defined y in the global environment, and you should expect it to be accessible in the R Markdown document, too.

The R Markdown document is compiled in the environment parent.frame() of render(), and all variables will be created in this environment. In your case, parent.frame() is the global environment (i.e. globalenv()), and that explains why x was created in the global environment.

When you click the Knit button in RStudio, it is different because the document is compiled in a separate new (clean) R session. The variable y you defined in the current R session will not be available to the new R session. Similarly, x will be created in the new session and not in your current R session. Reproducibility is exactly why we chose to compile R Markdown documents in new R sessions instead of the current R session. If a document works in a new R session, it is more likely to be reproducible. If it works in your current R session (via rmarkdown::render()), it might just work by chance.

If you have to evaluate code chunks in a separate environment, you need to use the argument envir explicitly, e.g.

```<code>render(input = "test.Rmd", envir = new.env())
</code>```

This way, x will not be created in your global environment, but y will be available to the code chunk (again, by definition of global variables).

In all, if you really care about reproducibility (like we do), there is an easy way and a slightly harder way. The easy way is to click the Knit button in RStudio, and the harder way is to render the document in a separate R session by yourself, e.g., via the command line

```<code>Rscript -e "rmarkdown::render('test.Rmd')"
</code>```

Body:
On Windows 7 64 bits, I have recently updated to RStudio 1.1.383 and rmarkdown 1.7. As I am using render to produce a pdf from an Rmd file I have noticed a new behavior.

There is leakage between the Global Environment and the knitting environment and it goes both ways:

If I define x = 12 in the .Rmd file, I find x in the Global environment after the render is complete.

If I use an undefined variable y in the .Rmd and I set y=1000 in the global environment before using render then y is used in the knitting of the .Rmd

If I do knit from RStudio the leakage does not occur and even if y is defined in the global environment, knitting the .Rmd will give an error (y not found).

Does anyone know why is that? I believe separating the environment is very important to ensure reproducibility even though it is sometimes painful to get right.

Here is my sessionInfo():

> sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] rmarkdown_1.7

loaded via a namespace (and not attached):
 [1] compiler_3.4.2  backports_1.1.1 magrittr_1.5    rprojroot_1.2   htmltools_0.3.6 tools_3.4.2     yaml_2.1.14     Rcpp_0.12.13
 [9] stringi_1.1.5   knitr_1.17      stringr_1.2.0   digest_0.6.12   evaluate_0.10.1

Here is the minimal "test render.R" file:

library(rmarkdown)
y=1000
render(input = "test render.Rmd")

and Here is the minimal "test render.Rmd" file:

---
title: "test render"
author: "Courvoisier"
output: pdf_document
---

## R Markdown

```{r cars}
x = 12
print(y)
```

and here is the pdf result:

Body:
As far as I can tell, this behavior has been there since Day 1. Here is how to prove it. First install the very first version (0.3.3) of rmarkdown from the CRAN archive:

devtools::install_version('rmarkdown', '0.3.3')

And run your example:

library(rmarkdown)
y = 1000
render(input = "test render.Rmd")

You see y is printed (as I'd expect):

This behavior is by design and I don't know why it is surprising to you. In R, global variables are accessible from anywhere (by definition). You defined y in the global environment, and you should expect it to be accessible in the R Markdown document, too.

The R Markdown document is compiled in the environment parent.frame() of render(), and all variables will be created in this environment. In your case, parent.frame() is the global environment (i.e. globalenv()), and that explains why x was created in the global environment.

When you click the Knit button in RStudio, it is different because the document is compiled in a separate new (clean) R session. The variable y you defined in the current R session will not be available to the new R session. Similarly, x will be created in the new session and not in your current R session. Reproducibility is exactly why we chose to compile R Markdown documents in new R sessions instead of the current R session. If a document works in a new R session, it is more likely to be reproducible. If it works in your current R session (via rmarkdown::render()), it might just work by chance.

If you have to evaluate code chunks in a separate environment, you need to use the argument envir explicitly, e.g.

render(input = "test.Rmd", envir = new.env())

This way, x will not be created in your global environment, but y will be available to the code chunk (again, by definition of global variables).

In all, if you really care about reproducibility (like we do), there is an easy way and a slightly harder way. The easy way is to click the Knit button in RStudio, and the harder way is to render the document in a separate R session by yourself, e.g., via the command line

Rscript -e "rmarkdown::render('test.Rmd')"


问:
Check if a given key already exists in a dictionary and increment it
How do I find out if a key in a dictionary has already been set to a non-None value?

I want to increment the value if there's already one there, or set it to 1 otherwise:

```<code>my_dict = {}

if my_dict[key] is not None:
  my_dict[key] = 1
else:
  my_dict[key] += 1
</code>```

答:
You need the key in dict idiom for that.

```<code>if key in my_dict and not (my_dict[key] is None):
  # do something
else:
  # do something else
</code>```

However, you should probably consider using defaultdict (as dF suggested).

OwnerDisplayName: Ben

ContentLicense: CC BY-SA 4.0

Body:
How do I find out if a key in a dictionary has already been set to a non-None value?

I want to increment the value if there's already one there, or set it to 1 otherwise:

my_dict = {}

if my_dict[key] is not None:
  my_dict[key] = 1
else:
  my_dict[key] += 1

Body:
You need the key in dict idiom for that.

if key in my_dict and not (my_dict[key] is None):
  # do something
else:
  # do something else

However, you should probably consider using defaultdict (as dF suggested).

OwnerDisplayName: eliben

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: eliben


问:
Sending emails in test mode with ActionMailer in rails 3
I am having a slightly odd problem with sending mail in test mode with Rails 3

It seems that my mailers are not returning anything.  For example I have a mailer called UserMailer.  Users can make changes that require approval in the app so this has a method called changes_approved that should send the user an email notifying them that their changes have been approved.class

```<code>UserMailer < ActionMailer::Base

  default :from => "from@example.com"

  def changes_approved(user, page)

    @user = user
    @page = page

    mail(:to => user.email, :subject => "Your changes have been approved")

  end

end
</code>```

In my controller I have the following line

```<code>UserMailer.changes_approved(@page_revision.created_by, @page_revision.page).deliver
</code>```

However my tests fail at this point with the error:

undefined method `deliver' for nil:NilClass

When I trigger the same actions on the development site tho (http://localhost:3000 through a browser), the emails are sent out correctly and everything works quite happily

And to add further confusion, I am using devise for authentication and the emails for that seem to be working correctly both in test and development modes.  Certainly I am not getting this same error and according to my email-spec tests, everythings working

So this leads me to believe that I have a problem with my mailers rather than my test mail config per se but I have no idea what.  Any suggestions would be much appreciated

Thanks

答:
I had a similar problem - probably the UserMailer.changes_approved method is being replaced with a mock method, which returns nil (I wasn't using shoulda for that test, but that's my best guess).

My code looked like this (modified to use your example):

```<code>UserMailer.expects(:changes_approved).once
</code>```

I fixed it with an additional stub:

```<code>@mailer = stub(:deliver)
UserMailer.expects(:changes_approved).once.returns(@mailer)
</code>```

The nil is now replaced with @mailer.

Body:
I am having a slightly odd problem with sending mail in test mode with Rails 3

It seems that my mailers are not returning anything.  For example I have a mailer called UserMailer.  Users can make changes that require approval in the app so this has a method called changes_approved that should send the user an email notifying them that their changes have been approved.class

UserMailer < ActionMailer::Base

  default :from => "from@example.com"

  def changes_approved(user, page)

    @user = user
    @page = page

    mail(:to => user.email, :subject => "Your changes have been approved")

  end

end

In my controller I have the following line

UserMailer.changes_approved(@page_revision.created_by, @page_revision.page).deliver

However my tests fail at this point with the error:

undefined method `deliver' for nil:NilClass

When I trigger the same actions on the development site tho (http://localhost:3000 through a browser), the emails are sent out correctly and everything works quite happily

And to add further confusion, I am using devise for authentication and the emails for that seem to be working correctly both in test and development modes.  Certainly I am not getting this same error and according to my email-spec tests, everythings working

So this leads me to believe that I have a problem with my mailers rather than my test mail config per se but I have no idea what.  Any suggestions would be much appreciated

Thanks

Body:
I had a similar problem - probably the UserMailer.changes_approved method is being replaced with a mock method, which returns nil (I wasn't using shoulda for that test, but that's my best guess).

My code looked like this (modified to use your example):

UserMailer.expects(:changes_approved).once

I fixed it with an additional stub:

@mailer = stub(:deliver)
UserMailer.expects(:changes_approved).once.returns(@mailer)

The nil is now replaced with @mailer.


问:
Can't build React-Native app for Android
I recently started working on an existing React Native app implemented only in ios, and started the task of trying to build and develop it on Android as well. I followed all the instructions on the React Native docs, but keep getting this error and can't figure out why:

```<code>A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApk'.
   > Configuration with name 'default' not found.
</code>```

Based on research, I'm assuming that it has to be something with my settings.gradle file, but I can't figure out what. This is what that file looks like:

```<code>include ':react-native-firebase-analytics'
project(':react-native-firebase-analytics').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase-analytics/android')
include ':tipsi-stripe'
project(':tipsi-stripe').projectDir = new File(rootProject.projectDir, '../node_modules/tipsi-stripe/android')
include ':react-native-sentry'
project(':react-native-sentry').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-sentry/android')
include ':react-native-webview-bridge'
project(':react-native-webview-bridge').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-webview-bridge/android')
include ':react-native-vector-icons'
project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
include ':react-native-device-info'
project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')
include ':react-native-config'
project(':react-native-config').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-config/android')

include ':ReactAndroid'

project(':ReactAndroid').projectDir = new File(
    rootProject.projectDir, '../node_modules/react-native/ReactAndroid')

include ':app'
</code>```

Does anyone know why this is happening and how to solve it? Thanks!

答: I just solved this issue. Sometimes when you install RN packages with npm, or more specifically uninstall them, code is leftover in the Android files. Make sure you aren't including any packages you're no longer using. You can manually delete this packages in the app/build.gradle file also the settings.gradle file and that works for me.

Body:
I recently started working on an existing React Native app implemented only in ios, and started the task of trying to build and develop it on Android as well. I followed all the instructions on the React Native docs, but keep getting this error and can't figure out why:

A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApk'.
   > Configuration with name 'default' not found.

Based on research, I'm assuming that it has to be something with my settings.gradle file, but I can't figure out what. This is what that file looks like:

include ':react-native-firebase-analytics'
project(':react-native-firebase-analytics').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase-analytics/android')
include ':tipsi-stripe'
project(':tipsi-stripe').projectDir = new File(rootProject.projectDir, '../node_modules/tipsi-stripe/android')
include ':react-native-sentry'
project(':react-native-sentry').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-sentry/android')
include ':react-native-webview-bridge'
project(':react-native-webview-bridge').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-webview-bridge/android')
include ':react-native-vector-icons'
project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
include ':react-native-device-info'
project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')
include ':react-native-config'
project(':react-native-config').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-config/android')

include ':ReactAndroid'

project(':ReactAndroid').projectDir = new File(
    rootProject.projectDir, '../node_modules/react-native/ReactAndroid')

include ':app'

Does anyone know why this is happening and how to solve it? Thanks!


问:
Wrong code in implementation of Depth First Search
I was looking at a code for Depth First Search in a website (https://brilliant.org/wiki/depth-first-search-dfs/). However the implementation seems wrong.This is the code they posted

```<code>def depth_first_search(graph):
    visited, stack = set(), [root]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited
</code>```

This particular line throws an error

```<code>stack.extend(graph[vertex] - visited)
</code>```

This is my complete program

```<code>graph = {'A': ['B', 'S'], 'B': ['A'], 'C': ['S', 'F', 'D', 'E'],
     'D': ['C'], 'E': ['H', 'C'], 'F': ['C', 'G'], 'G': ['S', 'F', 'H'], 'H': ['G', 'E'], 'S': ['A', 'G', 'C']}

def depth_first_search(graph, root):
    visited, stack = set(), [root]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

print(depth_first_search(graph, 'A'))
</code>```

This is the error the program encounters

```<code>File "/home/souvik/Sublime-text programs/TestCode124.py", line 47, in
depth_first_search
    stack.extend(graph[vertex] - visited)
TypeError: unsupported operand type(s) for -: 'list' and 'set'
</code>```

What is wrong with the code?

答:
You're defining the values of graph to be lists, but the function is expecting them to be sets:

```<code>graph = {
         'A': {'B', 'S'},
         'B': {'A'},
         'C': {'S', 'F', 'D', 'E'},
         ...
        }
</code>```

Body:
I was looking at a code for Depth First Search in a website (https://brilliant.org/wiki/depth-first-search-dfs/). However the implementation seems wrong.This is the code they posted

def depth_first_search(graph):
    visited, stack = set(), [root]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

This particular line throws an error

stack.extend(graph[vertex] - visited)

This is my complete program

graph = {'A': ['B', 'S'], 'B': ['A'], 'C': ['S', 'F', 'D', 'E'],
     'D': ['C'], 'E': ['H', 'C'], 'F': ['C', 'G'], 'G': ['S', 'F', 'H'], 'H': ['G', 'E'], 'S': ['A', 'G', 'C']}

def depth_first_search(graph, root):
    visited, stack = set(), [root]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

print(depth_first_search(graph, 'A'))

This is the error the program encounters

File "/home/souvik/Sublime-text programs/TestCode124.py", line 47, in
depth_first_search
    stack.extend(graph[vertex] - visited)
TypeError: unsupported operand type(s) for -: 'list' and 'set'

What is wrong with the code?

Body:
You're defining the values of graph to be lists, but the function is expecting them to be sets:

graph = {
         'A': {'B', 'S'},
         'B': {'A'},
         'C': {'S', 'F', 'D', 'E'},
         ...
        }


问:
Power BI : Monthly averages
I know similar questions have been asked and answered previous to this, but for the life of me, cannot get any of those working with my limited knowledge on Power BI.

I have a table which contains 8 weeks worth of data which for most parts, spans 3 months. I currently calculate the daily average which is the "total" divided by the "total in". However what I need to do, is to display the average based upon the calendar month. Therefore, September will have a difference average to that of October and that of November.

Here's a sample of the data:

```<code>Date,Total In,Total Out,Daily Average,Total,Month

27 September 2017,10773,264,97.61,11037,September
28 September 2017,11198,382,96.70,11580,September
29 September 2017,17753,1122,94.06,18875,September
30 September 2017,9568,649,93.65,10217,September
28 October 2017,11434,938,92.42,12372,October
29 October 2017,1541,60,96.25,1601,October
30 October 2017,918,4,99.57,922,October
31 October 2017,8565,24,99.72,8589,October
01 November 2017,11452,635,94.75,12087,November
02 November 2017,7785,531,93.61,8316,November
</code>```

So for November I would like to have the figure as (11452 + 7785) / (12087 + 8316) * 100 = 94.29%. Obviously, that figure would be present for all dates in November as an extra column. For October it would be (11434 + 1541 + 918 + 8565) / (12372 + 1601 + 922 + 8589) * 100 = 95.63%. I would then use the extra column and plot it on a line/bar chart.

So the above data would become:

```<code>Date,Total In,Total Out,Daily Average,Total,Month,Monthly Average

27 September 2017,10773,264,97.61,11037,September,96.00
28 September 2017,11198,382,96.70,11580,September,96.00
29 September 2017,17753,1122,94.06,18875,September,96.00
30 September 2017,9568,649,93.65,10217,September,96.00
28 October 2017,11434,938,92.42,12372,October,95.63
29 October 2017,1541,60,96.25,1601,October,95.63
30 October 2017,918,4,99.57,922,October,95.63
31 October 2017,8565,24,99.72,8589,October,95.63
01 November 2017,11452,635,94.75,12087,November,94.29
02 November 2017,7785,531,93.61,8316,November,94.29
</code>```

I am having trouble getting my head around the SUMMARIZE functions etc in order to get this working without any help. So any help and explanation would be greatly appreciated.

Thanks.

答:
I see you're asking your question from a DAX perspective, but here's a Power Query based answer that's quite easy. Starting with your table in Power Query (Power BI's Query Editor):

Select the Month column, then Transform -> Group By, and set up the dialog box like this...

 and click OK.

You'll see this:

Then click the button at the top of the
AllData column to expand the nested tables, and set up the dialog box like this...

 and click OK.

You'll see this:

Now click Add Column -> Custom Column, and set up the dialog box like this...

 and click OK.

You'll see this:

Now select the first three columns (Month, Sum Total In, Sum Total) and click Home -> Remove Columns.

You'll see this:

You can double-click the Month.1 column title and rename it if you like.

Title: Power BI : Monthly averages

Body:
I know similar questions have been asked and answered previous to this, but for the life of me, cannot get any of those working with my limited knowledge on Power BI.

I have a table which contains 8 weeks worth of data which for most parts, spans 3 months. I currently calculate the daily average which is the "total" divided by the "total in". However what I need to do, is to display the average based upon the calendar month. Therefore, September will have a difference average to that of October and that of November.

Here's a sample of the data:

Date,Total In,Total Out,Daily Average,Total,Month

27 September 2017,10773,264,97.61,11037,September
28 September 2017,11198,382,96.70,11580,September
29 September 2017,17753,1122,94.06,18875,September
30 September 2017,9568,649,93.65,10217,September
28 October 2017,11434,938,92.42,12372,October
29 October 2017,1541,60,96.25,1601,October
30 October 2017,918,4,99.57,922,October
31 October 2017,8565,24,99.72,8589,October
01 November 2017,11452,635,94.75,12087,November
02 November 2017,7785,531,93.61,8316,November

So for November I would like to have the figure as (11452 + 7785) / (12087 + 8316) * 100 = 94.29%. Obviously, that figure would be present for all dates in November as an extra column. For October it would be (11434 + 1541 + 918 + 8565) / (12372 + 1601 + 922 + 8589) * 100 = 95.63%. I would then use the extra column and plot it on a line/bar chart.

So the above data would become:

Date,Total In,Total Out,Daily Average,Total,Month,Monthly Average

27 September 2017,10773,264,97.61,11037,September,96.00
28 September 2017,11198,382,96.70,11580,September,96.00
29 September 2017,17753,1122,94.06,18875,September,96.00
30 September 2017,9568,649,93.65,10217,September,96.00
28 October 2017,11434,938,92.42,12372,October,95.63
29 October 2017,1541,60,96.25,1601,October,95.63
30 October 2017,918,4,99.57,922,October,95.63
31 October 2017,8565,24,99.72,8589,October,95.63
01 November 2017,11452,635,94.75,12087,November,94.29
02 November 2017,7785,531,93.61,8316,November,94.29

I am having trouble getting my head around the SUMMARIZE functions etc in order to get this working without any help. So any help and explanation would be greatly appreciated.

Thanks.


问:
Method error - missing return statement in Java
I am trying to finish a linked list activity but I'm having an error message saying "missing return statement" right after the very last curly brace of this code. What's wrong with this?</p>

```<code>public boolean insertNode(DataElement insertItem)
{
    LinkedListNode current;
    LinkedListNode trailCurrent;
    LinkedListNode newNode;

    boolean found;

    newNode = new LinkedListNode();
    newNode.info = insertItem.getCopy();

    newNode.link = null;

    if(first == null)
    {
        first = newNode;
        count++;
    }
    else
    {
        trailCurrent = first;
        current = first;
        found = false;

        while(current !=null && !found)
            if(current.info.compareTo(insertItem) >= 0)
                found = true;
            else
            {
                trailCurrent = current;
                current = current.link;
            }
        if(current == first)
        {
            newNode.link = first;
            first = newNode;
            count++;
        }
        else
        {
            trailCurrent.link = newNode;
            newNode.link = current;
            count++;
        }
    }
}
</code>```

答:
```<code>public boolean insertNode
</code>```

Three parts in that declaration:

public -- Tells about the accessibility of this method. Public means that any class can access it.

boolean -- The method should return a boolean value to the caller. You can use void if you dont want to return anything.

insertNode -- name of the method.

So a method is constructed in the following way:

Accesscontrol returnType methodName

Can have following values:

```<code>AccessControl: private, public, protected
returnType: int, boolean, String, void, List etc etc -- Limited just by imagination.
methodName - should be meaningful verb.
</code>```

So when you ask your method to return a boolean, you call it the following way:

```<code>boolean insertSuccessful = insertNode(dataElement);
</code>```

now insertSuccessful will contain a true or false value, depending if the insert was successful.

If your method was void, it would return nothing and the caller wouldn't expect a value to be returned and hence no insertSuccessful variable.

Body:
I am trying to finish a linked list activity but I'm having an error message saying "missing return statement" right after the very last curly brace of this code. What's wrong with this?

public boolean insertNode(DataElement insertItem)
{
    LinkedListNode current;
    LinkedListNode trailCurrent;
    LinkedListNode newNode;

    boolean found;

    newNode = new LinkedListNode();
    newNode.info = insertItem.getCopy();

    newNode.link = null;

    if(first == null)
    {
        first = newNode;
        count++;
    }
    else
    {
        trailCurrent = first;
        current = first;
        found = false;

        while(current !=null && !found)
            if(current.info.compareTo(insertItem) >= 0)
                found = true;
            else
            {
                trailCurrent = current;
                current = current.link;
            }
        if(current == first)
        {
            newNode.link = first;
            first = newNode;
            count++;
        }
        else
        {
            trailCurrent.link = newNode;
            newNode.link = current;
            count++;
        }
    }
}

Body:
public boolean insertNode

Three parts in that declaration:

public -- Tells about the accessibility of this method. Public means that any class can access it.

boolean -- The method should return a boolean value to the caller. You can use void if you dont want to return anything.

insertNode -- name of the method.

So a method is constructed in the following way:

Accesscontrol returnType methodName

Can have following values:

AccessControl: private, public, protected
returnType: int, boolean, String, void, List etc etc -- Limited just by imagination.
methodName - should be meaningful verb.

So when you ask your method to return a boolean, you call it the following way:

boolean insertSuccessful = insertNode(dataElement);

now insertSuccessful will contain a true or false value, depending if the insert was successful.

If your method was void, it would return nothing and the caller wouldn't expect a value to be returned and hence no insertSuccessful variable.


问:
Android (Xamarin) stream Video from IP Cam via rtsp://
UPDATE: I solved it by using vlc-sdk for android.

So i'm facing this problem where i have a URL which provides a stream from an IP camera.

It's something like

rtsp://192.168.x.xxx:8554/BWC

Note: there is no extension like .mp4 or .mov

I tried the URL in VLC player on my Computer and with the Android application "rtsp player" and both work. They both show me the stream from the cam.

Now i need to write an Application, which also displays the stream from the cam and i have to write it with Xamarin.

I have the following code:

```<code>[Activity(Label = "StreamActivity", ScreenOrientation = ScreenOrientation.Portrait, HardwareAccelerated = true, Theme = "@style/Theme.AppCompat.Light.NoActionBar")]
public class StreamActivity : AppCompatActivity
{
    String urlPrefix = "rtsp://";
    String urlSuffix = ":8554/BWC";

    VideoView streamView { get; set; }

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.StreamView);

        var ipAddress = Intent.GetStringExtra("ip");
        var url = urlPrefix + ipAddress + urlSuffix;
        var vidUri = Android.Net.Uri.Parse(url);

        streamView = FindViewById<VideoView>(Resource.Id.view_stream);
        streamView.SetMediaController(new MediaController(this));
        streamView.SetVideoURI(vidUri);
        streamView.RequestFocus();
        streamView.Start();
    }
}
</code>```

In the main activity i just enter the IP and hit a button then the StreamActivity is starting, but after i hit the button the new activity starts and i get an error message:

Can't play this video

In the LogCat i get the following Warnings and Errors:

11-11 18:14:56.594: W/MediaPlayer(18879): Couldn't open rtsp://192.168.4.103:8554/BWC: java.io.FileNotFoundException: No content provider: rtsp://192.168.4.103:8554/BWC

and

11-11 18:15:43.688: E/MediaPlayer(18879): error (100, 0)

Any help would be appreciated!

答: There is a solution called Surge that may be of help - https://instil.co/surge/ </p>

Body:
UPDATE: I solved it by using vlc-sdk for android.

So i'm facing this problem where i have a URL which provides a stream from an IP camera.

It's something like

rtsp://192.168.x.xxx:8554/BWC

Note: there is no extension like .mp4 or .mov

I tried the URL in VLC player on my Computer and with the Android application "rtsp player" and both work. They both show me the stream from the cam.

Now i need to write an Application, which also displays the stream from the cam and i have to write it with Xamarin.

I have the following code:

[Activity(Label = "StreamActivity", ScreenOrientation = ScreenOrientation.Portrait, HardwareAccelerated = true, Theme = "@style/Theme.AppCompat.Light.NoActionBar")]
public class StreamActivity : AppCompatActivity
{
    String urlPrefix = "rtsp://";
    String urlSuffix = ":8554/BWC";

    VideoView streamView { get; set; }

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.StreamView);

        var ipAddress = Intent.GetStringExtra("ip");
        var url = urlPrefix + ipAddress + urlSuffix;
        var vidUri = Android.Net.Uri.Parse(url);

        streamView = FindViewById<VideoView>(Resource.Id.view_stream);
        streamView.SetMediaController(new MediaController(this));
        streamView.SetVideoURI(vidUri);
        streamView.RequestFocus();
        streamView.Start();
    }
}

In the main activity i just enter the IP and hit a button then the StreamActivity is starting, but after i hit the button the new activity starts and i get an error message:

Can't play this video

In the LogCat i get the following Warnings and Errors:

11-11 18:14:56.594: W/MediaPlayer(18879): Couldn't open rtsp://192.168.4.103:8554/BWC: java.io.FileNotFoundException: No content provider: rtsp://192.168.4.103:8554/BWC

and

11-11 18:15:43.688: E/MediaPlayer(18879): error (100, 0)

Any help would be appreciated!


问:
Problem doing reverse polish notation (Java)
One of the problems that im finding is that i cant manage to compare the +,-,*,/  is there any other way?  THx for the help

CODE:

```<code>import java.util.Scanner;

public class Question2 {

    public static void main(String args[]){

    Scanner scan = new Scanner(System.in);

    double array[] = new double[20];

    System.out.print("Enter sum: ");
    String sum = scan.nextLine();

    getValue(sum, array, 0);

    System.out.print(array[0]);
    }

    public static void getValue(String input, double array[], int poi){
     int counter = 0;
     char nextValue = ' ';
     String value = "";
     double num = 0;
     boolean checkDub = true;

        do{
            value = value + input.charAt(counter);

            counter ++;
            nextValue = input.charAt(counter);
        }while(nextValue != ' ');

     try {num = Integer.parseInt(value);}
     catch (Exception e) {
      checkDub = false;

      double l2 = array[poi];
      poi--;

      double l1 = array[poi];

      if(value.equals("+")){ array[poi] =  l1 + l2;} // <--- comparing problem?
      else if(value.equals("-")){ array[poi] =  l1 - l2;}
      else if(value.equals("*")){ array[poi] =  l1 * l2;}
      else if(value.equals("/")){ array[poi] =  l1 / l2;}
      else{System.out.println("Error");}

    }
        if(checkDub = true){
        array[poi] = num;}

        String nextInput = input.substring(counter);
        getValue(nextInput, array, poi + 1);

    }

}
</code>```

答:
Hints:

Try printing out what value contains at the point where you think that there is a problem with comparison.

Try solving the problem in an OO way; e.g. change the getValue method to be non-static, and use instance variables for the state.

You cannot use = to compare values.  Use == instead.  Also a == true is equivalent to a.

Body:
One of the problems that im finding is that i cant manage to compare the +,-,*,/  is there any other way?  THx for the help

CODE:

import java.util.Scanner;

public class Question2 {

    public static void main(String args[]){

    Scanner scan = new Scanner(System.in);

    double array[] = new double[20];

    System.out.print("Enter sum: ");
    String sum = scan.nextLine();

    getValue(sum, array, 0);

    System.out.print(array[0]);
    }

    public static void getValue(String input, double array[], int poi){
     int counter = 0;
     char nextValue = ' ';
     String value = "";
     double num = 0;
     boolean checkDub = true;

        do{
            value = value + input.charAt(counter);

            counter ++;
            nextValue = input.charAt(counter);
        }while(nextValue != ' ');

     try {num = Integer.parseInt(value);}
     catch (Exception e) {
      checkDub = false;

      double l2 = array[poi];
      poi--;

      double l1 = array[poi];

      if(value.equals("+")){ array[poi] =  l1 + l2;} // <--- comparing problem?
      else if(value.equals("-")){ array[poi] =  l1 - l2;}
      else if(value.equals("*")){ array[poi] =  l1 * l2;}
      else if(value.equals("/")){ array[poi] =  l1 / l2;}
      else{System.out.println("Error");}

    }
        if(checkDub = true){
        array[poi] = num;}

        String nextInput = input.substring(counter);
        getValue(nextInput, array, poi + 1);

    }

}


问:
Creating EnumType Solr using SolrJ
I need to create a schema which will containt few enums. I'm trying to do that using SolrJ.
I've found this link DefininganEnumFieldinschema but I couldn't find any examples using Schema API or SolrJ.

Here is my enum:

```<code>public enum Attributes {
    SPONSORED("sponsored"),

    TOP_RATED("top-rated"),

    GENERIC("generic"),

    PROMOTION("promotion"),

    QUICK_ORDER("quick-order");

    private String value;

    Attributes(String value) {
        this.value = value;
    }

    @Override
    @JsonValue
    public String toString() {
        return String.valueOf(value);
    }

    @JsonCreator
    public static Attributes fromValue(String text) {
        for (Attributes b : Attributes.values()) {
            if (String.valueOf(b.value).equals(text)) {
                return b;
            }
        }
        return null;
    }
}
</code>```

And I want to add a field to my schema using SolrJ:

```<code>Map<String, Object> fieldAttributes = new LinkedHashMap<>();
    fieldAttributes.put("name", "address.**attributes**");
    fieldAttributes.put("type", "**attributesEnum**");
    fieldAttributes.put("stored", true);
    SchemaRequest.AddField addFieldRequest = new SchemaRequest.AddField(fieldAttributes);

    addFieldRequest.process(client);
</code>```

答:
First you need to specify your enum field in schema, like in the documentation:

```<code><fieldType name="myEnumField" class="solr.EnumField" enumsConfig="enumsConfig.xml" enumName="attribute"/>
</code>```

in the enumsConfig.xml you will specify all your enum values, like:

```<code><?xml version="1.0" ?>
<enumsConfig>
  <enum name="attribute">
    <value>sponsored</value>
    <value>generic</value>
  </enum>
</enumsConfig>
</code>```

Alternatively, you could create this fieldType dynamically via Schema API as follows:

```<code>curl -X POST -H 'Content-type:application/json' --data-binary '{
  "add-field-type" : {
     "name":"myEnumField",
     "class":"solr.EnumField",
     "enumsConfig":"enumsConfig.xml",
     "enumName" : "attribute"}
}' http://localhost:8983/solr/demo/schema
</code>```

You could do this as well in SolrJ fashion, by using org.apache.solr.client.solrj.request.schema.SchemaRequest.AddFieldType, you need to specify FieldTypeDefinition, method setAttributes(Map<String,Object> attributes) will be helpful

Title: Creating EnumType Solr using SolrJ

Body:
I need to create a schema which will containt few enums. I'm trying to do that using SolrJ.
I've found this link DefininganEnumFieldinschema but I couldn't find any examples using Schema API or SolrJ.

Here is my enum:

public enum Attributes {
    SPONSORED("sponsored"),

    TOP_RATED("top-rated"),

    GENERIC("generic"),

    PROMOTION("promotion"),

    QUICK_ORDER("quick-order");

    private String value;

    Attributes(String value) {
        this.value = value;
    }

    @Override
    @JsonValue
    public String toString() {
        return String.valueOf(value);
    }

    @JsonCreator
    public static Attributes fromValue(String text) {
        for (Attributes b : Attributes.values()) {
            if (String.valueOf(b.value).equals(text)) {
                return b;
            }
        }
        return null;
    }
}

And I want to add a field to my schema using SolrJ:

Map<String, Object> fieldAttributes = new LinkedHashMap<>();
    fieldAttributes.put("name", "address.**attributes**");
    fieldAttributes.put("type", "**attributesEnum**");
    fieldAttributes.put("stored", true);
    SchemaRequest.AddField addFieldRequest = new SchemaRequest.AddField(fieldAttributes);

    addFieldRequest.process(client);

Body:
First you need to specify your enum field in schema, like in the documentation:

<fieldType name="myEnumField" class="solr.EnumField" enumsConfig="enumsConfig.xml" enumName="attribute"/>

in the enumsConfig.xml you will specify all your enum values, like:

<?xml version="1.0" ?>
<enumsConfig>
  <enum name="attribute">
    <value>sponsored</value>
    <value>generic</value>
  </enum>
</enumsConfig>

Alternatively, you could create this fieldType dynamically via Schema API as follows:

curl -X POST -H 'Content-type:application/json' --data-binary '{
  "add-field-type" : {
     "name":"myEnumField",
     "class":"solr.EnumField",
     "enumsConfig":"enumsConfig.xml",
     "enumName" : "attribute"}
}' http://localhost:8983/solr/demo/schema

You could do this as well in SolrJ fashion, by using org.apache.solr.client.solrj.request.schema.SchemaRequest.AddFieldType, you need to specify FieldTypeDefinition, method setAttributes(Map<String,Object> attributes) will be helpful


答:
```<code>public boolean insertNode
</code>```

returns a boolean. If you want to do something in a function without returning anything, just replace

```<code>public void insertNode
</code>```

Return value is SUPER important in all programming languages. Get used to always put the correct return value of a function (If you precised it on the function's prototype).

In your case, you should return the only boolean variable you're using

return found;

Title: Method error - missing return statement in Java

Body:
public boolean insertNode

returns a boolean. If you want to do something in a function without returning anything, just replace

public void insertNode

Return value is SUPER important in all programming languages. Get used to always put the correct return value of a function (If you precised it on the function's prototype).

In your case, you should return the only boolean variable you're using

return found;


问:
How to implement an onboarding page with Prism.Forms?
I am developing a Xamarin.Forms app with Prism in which I'd like to incorporate an onboarding page (more specific a top user benefits page, following the Material Design guidelines).

The app itself is structured around a NavigationPage to which I navigate with

```<code>NavigationService.NavigateAsync("/NavigationRootPage/MainPage")
</code>```

in my App(). On the first start I'd like to show the onboarding page instead and I am having quite some issues getting it right.

My first approach was to navigate to MainPage with

```<code>_navigationService.NavigateAsync("/NavigationRootPage/MainPage")
</code>```

from my viewmodel, when the user clicks the Get Started! button. This kind of worked by is also kind of ugly, since this absolute navigation will destroy the oboarding page immediately and not animate the transition. Furthermore at the moment the oboarding page is destroyed, the MainPage will be built, which will take a small, but noticeable, amount of time. In effect the user will notice the MainPage being built up, which does not look smooth at all.

My second approach was to navigate in a relative fashion from my viewmodel.

```<code>_navigationService.NavigateAsync("NavigationRootPage/MainPage")
</code>```

This works way smoother, with the transition animation and after the animation is done, the MainPage is already ready to go. But again there is a major drawback. You can navigate back to the onbaording page, which we dont't want neither. And - to my knowledge - there is no (clean) way to remove the page from the navigation stack, too. I tried calling PageUtility.DestroyPage on my onboarding page, but this only worsened things, since it seemed to keep the page, but destroy the viewmodel, resulting in my onboarding page being shown without data when pushing the back button.

My third approach did not work at all, although it seemed promising to me. In my App() I pushed my navigation page with the main page then then my onboarding page modal

```<code>NavigationService.NavigateAsync("/NavigationRootPage/MainPage");
NavigationService.NavigateAsync("OnboardingPage", useModalNavigation: true);
</code>```

and then in my viewmodel

```<code>_navigationService.GoBackAsync(useModalNavigation: true)
</code>```

but this approach

showed the header of the NavigationPage although the onbaording page was supposed to be shown as a modal

refused to GoBackAsync - when calling this method, nothing happens

waiting for the first call to NavigateAsync did not change anything either.

Some other things I've tried

Implemented INavigationOptions in my viewmodel with ClearNavigationStackOnNavigation being true

Tried setting Application.MainPage after my NavigationPage was shown, but to no avail

I would have believed that this was king of a common requirement when programming an app. Is there something I've missed? Or will I have to live with one of those drawbacks?

答:
I think you are overthinking this.  If you want to show your Onborading page first then just navigate to it first.

`NavigateAsync("NavigationPage/OnboardingPage");

Or if you want to have the MainPage in the stack, then start the app with a deeplink

`NavigateAsync("NavigationPage/MainPage/OnboardingPage");

If you don't want to show the navigation header, just hide it for the onboarding page.

Don't use an absolute navigation unless you want to completely reset the navigation stack (equivalent to MainPage = new MainPage()).

Body:
I am developing a Xamarin.Forms app with Prism in which I'd like to incorporate an onboarding page (more specific a top user benefits page, following the Material Design guidelines).

The app itself is structured around a NavigationPage to which I navigate with

NavigationService.NavigateAsync("/NavigationRootPage/MainPage")

in my App(). On the first start I'd like to show the onboarding page instead and I am having quite some issues getting it right.

My first approach was to navigate to MainPage with

_navigationService.NavigateAsync("/NavigationRootPage/MainPage")

from my viewmodel, when the user clicks the Get Started! button. This kind of worked by is also kind of ugly, since this absolute navigation will destroy the oboarding page immediately and not animate the transition. Furthermore at the moment the oboarding page is destroyed, the MainPage will be built, which will take a small, but noticeable, amount of time. In effect the user will notice the MainPage being built up, which does not look smooth at all.

My second approach was to navigate in a relative fashion from my viewmodel.

_navigationService.NavigateAsync("NavigationRootPage/MainPage")

This works way smoother, with the transition animation and after the animation is done, the MainPage is already ready to go. But again there is a major drawback. You can navigate back to the onbaording page, which we dont't want neither. And - to my knowledge - there is no (clean) way to remove the page from the navigation stack, too. I tried calling PageUtility.DestroyPage on my onboarding page, but this only worsened things, since it seemed to keep the page, but destroy the viewmodel, resulting in my onboarding page being shown without data when pushing the back button.

My third approach did not work at all, although it seemed promising to me. In my App() I pushed my navigation page with the main page then then my onboarding page modal

NavigationService.NavigateAsync("/NavigationRootPage/MainPage");
NavigationService.NavigateAsync("OnboardingPage", useModalNavigation: true);

and then in my viewmodel

_navigationService.GoBackAsync(useModalNavigation: true)

but this approach

showed the header of the NavigationPage although the onbaording page was supposed to be shown as a modal

refused to GoBackAsync - when calling this method, nothing happens

waiting for the first call to NavigateAsync did not change anything either.

Some other things I've tried

Implemented INavigationOptions in my viewmodel with ClearNavigationStackOnNavigation being true

Tried setting Application.MainPage after my NavigationPage was shown, but to no avail

I would have believed that this was king of a common requirement when programming an app. Is there something I've missed? Or will I have to live with one of those drawbacks?


问:
Node Identity Registration in Corda
I have generated self signed keystore and certificate using keytool command, is there any way to register it as part of node's identity.
Thanks</p>

答:
The keystore and certificates are generated automatically when running the nodes in dev mode. You do this by adding the following line to each node's node.conf file:

```<code>devMode : true
</code>```

See https://docs.corda.net/corda-configuration-file.html for more details.

Once the keystore and certificates have been generated, you can turn off dev mode if you want. You do this by stopping each node, setting devMode : false, and restarting each node.

Title: Node Identity Registration in Corda

Body:
The keystore and certificates are generated automatically when running the nodes in dev mode. You do this by adding the following line to each node's node.conf file:

devMode : true

See https://docs.corda.net/corda-configuration-file.html for more details.

Once the keystore and certificates have been generated, you can turn off dev mode if you want. You do this by stopping each node, setting devMode : false, and restarting each node.


问:
How to use mogrify (ImageMagick) to convert from NEF to *.jpg and retain EXIF data?
I'm converting about 9000 photos from .NEF to .jpg.

I'd like to retain all EXIF data, most importantly Date and time created, Latidude and Longitude.

I'd like the JPGs to be at the highest possible quality.

I've just gotten started using ImageMagick from the command line. I also have Exiftool installed. I'm using the mogrify command because it handles batches nicely.

When I run

```<code>mogrify -format jpg *.NEF
</code>```

All of my .NEF files are successfully converted to JPGs, but all EXIF data are lost.

I've searched around quite a bit to try and find a solution to this and it seems like I may have to install ufraw, but if possible I'd like a solution that uses software I already have - ImageMagick and Exiftool.

Thanks in advance for any advice you have about how to do this.

Update:

The images I converted using mogrify are slightly smaller (~ 1-2 MB) than those output by my colleague using picasa to convert NEF to JPG. But when I specify -quality 100 in ImageMagick the image sizes gain about 45 MB! Why?

The code exiftool -tagsfromfile %d%f.NEF -ext jpg -overwrite_original . adds the exif information to the JPGs.

答:
Think twice before doing this - you really are discarding a lot of information - and if you don't want it, why not shoot JPEG instead of RAW in the first place?

FWIW, you can use ImageMagick to get the JPEG:

```<code>convert somefile.NEF somefile.jpg
</code>```

Then you can copy the tags across from the original to the file newly created by ImageMagick:

```<code>exiftool -tagsfromfile somefile.NEF -all:all somefile.jpg
</code>```

If you have thousands of images, and are on macOS or a decent Linux/Unix-based OS, I would recommend GNU Parallel like this and it will keep busy all those lovely cores that you paid Intel so dearly for:

```<code>parallel --dry-run 'convert {} {.}.jpg; exiftool -tagsfromfile {} -all:all {.}.jpg' ::: *nef
</code>```

Sample Output

```<code>convert a.nef a.jpg; exiftool -tagsfromfile a.nef -all:all a.jpg
convert b.nef b.jpg; exiftool -tagsfromfile b.nef -all:all b.jpg
</code>```

and if that looks good remove the --dry-run so it actually runs the command.

If you are on Windows, you will have to do some ad-hoc jiggery-pokery to get it done in any reasonable time frame. You can use the mogrify command and get all the conversions done to JPEG and then do all the exiftool re-embedding of the EXIF data later. If your files are named with some sort of system with incrementing numbers, you can start two or three copies of mogrify in parallel - say one doing files whose names end in [0-4] and another one doing files whose names end in [5-9]. I don't speak Windows, but that would probably look like these two commands each running in its own Command Prompt:

```<code>mogrify -format jpg *0.NEF *1.NEF *2.NEF *3.NEF *4.NEF

mogrify -format jpg *5.NEF *6.NEF *7.NEF *8.NEF *9.NEF
</code>```

Then you would do the exiftool stuff when they had all finished but you would have to use a FOR loop like this:

```<code>FOR %%G IN (*.NEF) DO (
   exiftool -tagsfromfile %%G -all:all %%~dpnG.jpg
)
</code>```

The %%~dpnG part is a guess based on this answer.

Body:
I'm converting about 9000 photos from .NEF to .jpg.

I'd like to retain all EXIF data, most importantly Date and time created, Latidude and Longitude.

I'd like the JPGs to be at the highest possible quality.

I've just gotten started using ImageMagick from the command line. I also have Exiftool installed. I'm using the mogrify command because it handles batches nicely.

When I run

mogrify -format jpg *.NEF

All of my .NEF files are successfully converted to JPGs, but all EXIF data are lost.

I've searched around quite a bit to try and find a solution to this and it seems like I may have to install ufraw, but if possible I'd like a solution that uses software I already have - ImageMagick and Exiftool.

Thanks in advance for any advice you have about how to do this.

Update:

The images I converted using mogrify are slightly smaller (~ 1-2 MB) than those output by my colleague using picasa to convert NEF to JPG. But when I specify -quality 100 in ImageMagick the image sizes gain about 45 MB! Why?

The code exiftool -tagsfromfile %d%f.NEF -ext jpg -overwrite_original . adds the exif information to the JPGs.

Body:
Think twice before doing this - you really are discarding a lot of information - and if you don't want it, why not shoot JPEG instead of RAW in the first place?

FWIW, you can use ImageMagick to get the JPEG:

convert somefile.NEF somefile.jpg

Then you can copy the tags across from the original to the file newly created by ImageMagick:

exiftool -tagsfromfile somefile.NEF -all:all somefile.jpg

If you have thousands of images, and are on macOS or a decent Linux/Unix-based OS, I would recommend GNU Parallel like this and it will keep busy all those lovely cores that you paid Intel so dearly for:

parallel --dry-run 'convert {} {.}.jpg; exiftool -tagsfromfile {} -all:all {.}.jpg' ::: *nef

Sample Output

convert a.nef a.jpg; exiftool -tagsfromfile a.nef -all:all a.jpg
convert b.nef b.jpg; exiftool -tagsfromfile b.nef -all:all b.jpg

and if that looks good remove the --dry-run so it actually runs the command.

If you are on Windows, you will have to do some ad-hoc jiggery-pokery to get it done in any reasonable time frame. You can use the mogrify command and get all the conversions done to JPEG and then do all the exiftool re-embedding of the EXIF data later. If your files are named with some sort of system with incrementing numbers, you can start two or three copies of mogrify in parallel - say one doing files whose names end in [0-4] and another one doing files whose names end in [5-9]. I don't speak Windows, but that would probably look like these two commands each running in its own Command Prompt:

mogrify -format jpg *0.NEF *1.NEF *2.NEF *3.NEF *4.NEF

mogrify -format jpg *5.NEF *6.NEF *7.NEF *8.NEF *9.NEF

Then you would do the exiftool stuff when they had all finished but you would have to use a FOR loop like this:

FOR %%G IN (*.NEF) DO (
   exiftool -tagsfromfile %%G -all:all %%~dpnG.jpg
)

The %%~dpnG part is a guess based on this answer.


问:
VHDL: compare a signal against multiple values
I want to compare a signal against the list of pre-defined values and check if there is at least equal value it this list (or, alternatively, if there is no equal values in the list).

Example application: compare received command to the pre-defined list of valid commands and go to error state if the command is invalid. Imagine, we have only 3 valid commands: 0x00, 0x01 and 0xFF. Then this code would do the job:

```<code>--valid commands: 0x00, 0x01, 0xFF

process(clk) is
--somewhere in the middle of FSM
  if cmd /= x"00" and cmd /= x"01" and cmd /= x"01" then
    next_state <= error;
  end if;
end process;
</code>```

But I wonder how to efficiently (in terms of coding style) implement the same thing for longer lists, without having to manually compare against each value (i.e. avoid writing lines like this:)

```<code>if cmd=val1 or cmd=val2 or ... or cmd=valN then --imagine N=100
</code>```

I imagine it's something to do with arrays and loops?

答:
A loop over an array of reference values is probably easier to maintain:</p>

```<code>subtype ref_value is std_ulogic_vector(7 downto 0);
type ref_value_array is array (natural range <>) of ref_value;
constant ref_values: ref_value_array(0 to 2) := (x"00", x"01",...);
...
next_state <= error;
for i in ref_values'range loop
  if cmd = ref_values(i) then
    next_state <= no_error;
    break;
  end if;
end loop;
</code>```

Body:
I want to compare a signal against the list of pre-defined values and check if there is at least equal value it this list (or, alternatively, if there is no equal values in the list).

Example application: compare received command to the pre-defined list of valid commands and go to error state if the command is invalid. Imagine, we have only 3 valid commands: 0x00, 0x01 and 0xFF. Then this code would do the job:

--valid commands: 0x00, 0x01, 0xFF

process(clk) is
--somewhere in the middle of FSM
  if cmd /= x"00" and cmd /= x"01" and cmd /= x"01" then
    next_state <= error;
  end if;
end process;

But I wonder how to efficiently (in terms of coding style) implement the same thing for longer lists, without having to manually compare against each value (i.e. avoid writing lines like this:)

if cmd=val1 or cmd=val2 or ... or cmd=valN then --imagine N=100

I imagine it's something to do with arrays and loops?

Body:
A loop over an array of reference values is probably easier to maintain:

subtype ref_value is std_ulogic_vector(7 downto 0);
type ref_value_array is array (natural range <>) of ref_value;
constant ref_values: ref_value_array(0 to 2) := (x"00", x"01",...);
...
next_state <= error;
for i in ref_values'range loop
  if cmd = ref_values(i) then
    next_state <= no_error;
    break;
  end if;
end loop;


问:
Understanding Memory Layouts of an Interpreter (JVM/JS)
I am trying to understand the memory layout of a process at OS level and we are used to this diagram.

Forget the multithreading part of the diagram but now for general purposes, we assume the "code" block shown in the diagram above to be the binary instructions of our program. This assumes that the code has already been compiled to now be available in its binary form. But what about interpreted languages e.g. a bytecode to be executed by the JVM interpreter. While I am choosing the JVM interpreter here, my question is for any interpreted language and how does it fit in the diagram shown above. My understanding is that the Interpreter itself is a program and therefore has to sit in the code block shown in the diagram above and the .class program in case of Java or a .js file in case of Javascript interpreters is the "argument" so to speak that this interpreter works upon to translate them to OS/machine understandable code which is then executed. Request your thoughts on this.

答:
It is a matter of perspective whether you would consider bytecode „code“. The terminology is a bit fuzzy.

The „code“ in the diagram is native executable code, i.e. your interpreter. As far as the CPU and operating system are concerned, that is the only code that ever runs. To the OS, the bytecode being interpreted is simply data that the actual native code operates on.

That in this case, the data happens to be a form of instructions as well is a detail the CPU is unaware of and doesn‘t care about.


问:
how to use different WHERE clause in left join
I have two textfields, I posted each textfield value into MySQL query specially in WHERE CLAUSE.

```<code>$sWhere = " WHERE MONTH(Inspection_datetime) = '".$Month."' AND
            YEAR(Inspection_datetime) = '".$Year."' ";
</code>```

Then i tried to combine this query become like below:

```<code>$sQuery = "SELECT A.id,A.Line,
                  week1.1st, week2.2nd, week3.3rd, week4.4th, week5.5th,
                  IFNULL(week1.1st,0) + IFNULL(week2.2nd,0) + IFNULL(week3.3rd,0)
                + IFNULL(week4.4th,0) + IFNULL(week5.5th,0) AS Total
           FROM inspection_report AS A
           LEFT JOIN(
                     SELECT Line, (SUM(S) + SUM(A) + SUM(B)*0.4 +
                                   SUM(C)*0.1)/COUNT(Serial_number) AS 1st
                     FROM inspection_report
                     WHERE DAY(Inspection_datetime) BETWEEN 1 AND 7
                     GROUP BY Line, WEEK(Inspection_datetime),
                                    YEAR(Inspection_datetime)
                     ) AS week1 USING (Line)

                 LEFT JOIN(
                           SELECT Line, (SUM(S) + SUM(A) + SUM(B)*0.4 + SUM(C)*0.1)/COUNT(Serial_number) AS 2nd
                           FROM inspection_report
                           WHERE DAY(Inspection_datetime) BETWEEN 8 AND 14
                           GROUP BY Line, WEEK(Inspection_datetime), YEAR(Inspection_datetime)
                           ) AS week2 USING (Line)";
.........//SAME LIKE ABOVE JUST CHANGE INTO another week's range

$sWhere = " WHERE MONTH(Inspection_datetime) = '".$Month."' AND
           YEAR(Inspection_datetime) = '".$Year."' ";

$sGroupBy = " GROUP BY A.Line ";
$sQuery.= $sWhere.$sGroupBy;
</code>```

i want it can counting data in weekly and also it can filtering by $Month and $Year.

But i got incorrect result. The result count data weekly for all month and all year.
How do i do to fix it?

答:
You need to add the WHERE MONTH(Inspection_datetime) = '".$Month."' AND YEAR(Inspection_datetime) = '".$Year. to every subquery

There are a couple things wrong with your current query:

You are joining the table by the Line field only, what you are telling MySql to do, is find the lines that have data for a month and year, and for those lines pull all their weekly data.

You are joining and grouping the tables multiple times (once for each week), is there a need for that? The query would be much quicker if you can get the weekly results by rows.

You are creating a new sub query for every 7 days of the month, but want to show the results by week

Body:
I have two textfields, I posted each textfield value into MySQL query specially in WHERE CLAUSE.

$sWhere = " WHERE MONTH(Inspection_datetime) = '".$Month."' AND
            YEAR(Inspection_datetime) = '".$Year."' ";

Then i tried to combine this query become like below:

$sQuery = "SELECT A.id,A.Line,
                  week1.1st, week2.2nd, week3.3rd, week4.4th, week5.5th,
                  IFNULL(week1.1st,0) + IFNULL(week2.2nd,0) + IFNULL(week3.3rd,0)
                + IFNULL(week4.4th,0) + IFNULL(week5.5th,0) AS Total
           FROM inspection_report AS A
           LEFT JOIN(
                     SELECT Line, (SUM(S) + SUM(A) + SUM(B)*0.4 +
                                   SUM(C)*0.1)/COUNT(Serial_number) AS 1st
                     FROM inspection_report
                     WHERE DAY(Inspection_datetime) BETWEEN 1 AND 7
                     GROUP BY Line, WEEK(Inspection_datetime),
                                    YEAR(Inspection_datetime)
                     ) AS week1 USING (Line)

                 LEFT JOIN(
                           SELECT Line, (SUM(S) + SUM(A) + SUM(B)*0.4 + SUM(C)*0.1)/COUNT(Serial_number) AS 2nd
                           FROM inspection_report
                           WHERE DAY(Inspection_datetime) BETWEEN 8 AND 14
                           GROUP BY Line, WEEK(Inspection_datetime), YEAR(Inspection_datetime)
                           ) AS week2 USING (Line)";
.........//SAME LIKE ABOVE JUST CHANGE INTO another week's range

$sWhere = " WHERE MONTH(Inspection_datetime) = '".$Month."' AND
           YEAR(Inspection_datetime) = '".$Year."' ";

$sGroupBy = " GROUP BY A.Line ";
$sQuery.= $sWhere.$sGroupBy;

i want it can counting data in weekly and also it can filtering by $Month and $Year.

But i got incorrect result. The result count data weekly for all month and all year.
How do i do to fix it?


问:
Extract element value in react
calling function onclick event

```<code><th onClick={this.sort}>Grades</th>
</code>```

and in Function, trying to get the value of text.

```<code>  sort(e){
    console.log(e.target);

  }
</code>```

e.target catch Grades

how can just get text ie Grades' without th

答:
You can get the text inside the element via innerText:

```<code>sort (e) {
    console.log(e.target.innerText);
}
</code>```

However, in this case it may be better to pass the text in directly, depending on your use case:

```<code><th onClick={() => this.sort('Grades')}>Grades</th>
</code>```

Title: Extract element value in react

Body:
calling function onclick event

Grades

and in Function, trying to get the value of text.

  sort(e){
    console.log(e.target);

  }

e.target catch Grades

how can just get text ie Grades' without th

Body:
You can get the text inside the element via innerText:

sort (e) {
    console.log(e.target.innerText);
}

However, in this case it may be better to pass the text in directly, depending on your use case:

<th onClick={() => this.sort('Grades')}>Grades</th>


问:
Angular 2 - Is it possible to use the new router while upgrading with the "Upgrade Adapter"
I am upgrading my application progressively using the Upgrade Adapter. My app uses ui-router (+ has child routes).

I read this great article about routing in Angular 2. My question is:

Is it possible to use new router while still in Angular 1.X app + Upgrade adapter?

For example:

I have an angular 1.X template with

. When I upgrade it to be Angular 2.0 component I must use the new component router with it, because Angular 2.0 is rendering this component now. But, in order to use it I should do:

```<code>bootstrap(App, [provide(LocationStrategy, { useClass: PathLocationStrategy })])
</code>```

Which I do not have when bootstraping with the Upgrade Adater!

Should I first move the bootstrap to be Angular 2 and only then move to the Component router?

Thanks

答: Absolutely! Your component containing ui-view should be changed to a router-outlet, but otherwise, you should be able to convert your routes to AngularJS components and use them with the new RouterModule.

Body:
I am upgrading my application progressively using the Upgrade Adapter. My app uses ui-router (+ has child routes).

I read this great article about routing in Angular 2. My question is:

Is it possible to use new router while still in Angular 1.X app + Upgrade adapter?

For example:

I have an angular 1.X template with

. When I upgrade it to be Angular 2.0 component I must use the new component router with it, because Angular 2.0 is rendering this component now. But, in order to use it I should do:

bootstrap(App, [provide(LocationStrategy, { useClass: PathLocationStrategy })])

Which I do not have when bootstraping with the Upgrade Adater!

Should I first move the bootstrap to be Angular 2 and only then move to the Component router?

Thanks


问:
Rest Api Hit Difference B/w Browser and Postman
I am calling a REST API using postman and a Browser.
Each gives me the same result but,
I need know the how to identify which requests come from postman and which come from a browser.
I need to stop hits from Postman.</p>

答:
Add an additional identifier to Postman request - like Header.

Under Headers tab in Postman, click under New Key and write some name like myFlag, then under Value part set something like "postman"

You can pass other useful data in this manner. And for some servers you will need to setup stuff before you can use them, for example authorization tokens etc..

Now on the backend side (in part of code where you handle request for API in question) you should be able to read all headers including the one we added.
Say if this one is present it's a postman open a new block with empty line or console block in it and set breakpoint to that line


问:
Java 8 filter a stream to replace SQL IN (...) clause
Is there any way to achieve the same result with a collection like with SQL IN clause ? For example, there a list of objects and I have to choose those with ids in (2, 17, 31, ...) what is equal to SQL</p>

```<code>SELECT *
FROM table_name
WHERE column_name IN (value1, value2, ...);
</code>```

答:
You can use a predicate in the filter to emulate the IN clause:

A litle and non tested example:

```<code>List<Number> myList= Arrays.asList(1, 2, 3);
List<Integer> finalList= Arrays
    .stream(new Integer[] { 1, 2, 3, 4, 5 })
    .filter(element -> myList.contains(element))
    .collect(Collectors.toList());
</code>```

The output should be 1, 2, 3

Body:
Is there any way to achieve the same result with a collection like with SQL IN clause ? For example, there a list of objects and I have to choose those with ids in (2, 17, 31, ...) what is equal to SQL

SELECT *
FROM table_name
WHERE column_name IN (value1, value2, ...);

Body:
You can use a predicate in the filter to emulate the IN clause:

A litle and non tested example:

List<Number> myList= Arrays.asList(1, 2, 3);
List<Integer> finalList= Arrays
    .stream(new Integer[] { 1, 2, 3, 4, 5 })
    .filter(element -> myList.contains(element))
    .collect(Collectors.toList());

The output should be 1, 2, 3


问:
Add a space between value in a cookie using PHP
Simple question but cant find the answer. I have this line of code:

```<code>setcookie($prodAmount, $pQuantity." ".$pOriginalQuan, time() + (86400 * 60), "/");
</code>```

As you can see there is a space in the middle. however when I look at the cookie in the browser values are like this 3+4. how can I add space to the cookie so it looks like this 3 4.

Thanks

答:
A cookie value and name is a sequence of characters excluding semi-colon, comma and white space.

So you can't do that.

But you can use the function string urldecode ( string $str ) to get back you whitespace.

Body:
Simple question but cant find the answer. I have this line of code:

setcookie($prodAmount, $pQuantity." ".$pOriginalQuan, time() + (86400 * 60), "/");

As you can see there is a space in the middle. however when I look at the cookie in the browser values are like this 3+4. how can I add space to the cookie so it looks like this 3 4.

Thanks


问:
Transforming data from one form to another
I have the following list:

```<code>l = [
        %{id: 1, name: "aash", possess: "car"},
        %{id: 1, name: "aash", possess: "bike"},
        %{id: 2, name: "rahul", possess: "scooter"}
]
</code>```

I want to convert this into the following format:

```<code>ans = [
        %{id: 1, name: "aash", possess: ["car", "bike"]},
        %{id: 2, name: "rahul", possess: ["scooter"]}
]
</code>```

Any idea on how to do this in elixir? Since all the variables are immutable, I don't know how to achieve the above transformation.

答:
l
|> Enum.group_by(fn %{id: id, name: name} -> [id, name] end)
|> Enum.map(fn {[k, v], m} ->
     %{id: k, name: v, possess: Enum.map(m, & &1.possess)}
end)
#⇒ [
#  %{id: 1, name: "aash", possess: ["car", "bike"]},
#  %{id: 2, name: "rahul", possess: ["scooter"]}
# ]
```

In a case of generic fields the solution would be slightly more complicated, involving Enum.reduce/3 instead of Enum.map/2 on the last step.

Body:
I have the following list:

l = [
        %{id: 1, name: "aash", possess: "car"},
        %{id: 1, name: "aash", possess: "bike"},
        %{id: 2, name: "rahul", possess: "scooter"}
]

I want to convert this into the following format:

ans = [
        %{id: 1, name: "aash", possess: ["car", "bike"]},
        %{id: 2, name: "rahul", possess: ["scooter"]}
]

Any idea on how to do this in elixir? Since all the variables are immutable, I don't know how to achieve the above transformation.

Body:
l
|> Enum.group_by(fn %{id: id, name: name} -> [id, name] end)
|> Enum.map(fn {[k, v], m} ->
     %{id: k, name: v, possess: Enum.map(m, & &1.possess)}
end)
#⇒ [
#  %{id: 1, name: "aash", possess: ["car", "bike"]},
#  %{id: 2, name: "rahul", possess: ["scooter"]}
# ]

In a case of generic fields the solution would be slightly more complicated, involving Enum.reduce/3 instead of Enum.map/2 on the last step.


问:
Save input into a char array C++
How can I save input into a char array C++?

The problem I have is that I do not know beforehand how much input will the user provide.

I would like to use only arrays and chars.

答:
```<code>#include <iostream>
#include <string>

int main()
{
  std::string foo;
  std::getline(std::cin, foo);

  std::cout << "Text: [" << foo << "]" << std::endl;
  const char* asCStr = foo.c_str();

  std::cout << "Text: [" << asCStr << "]" << std::endl;
}
</code>```

You can convert the std::string to a char pointer as shown in the second part of the code snippet.

Title: Save input into a char array C++

Body:
#include <iostream>
#include <string>

int main()
{
  std::string foo;
  std::getline(std::cin, foo);

  std::cout << "Text: [" << foo << "]" << std::endl;
  const char* asCStr = foo.c_str();

  std::cout << "Text: [" << asCStr << "]" << std::endl;
}

You can convert the std::string to a char pointer as shown in the second part of the code snippet.


问:
makefile use variable defined in target
How can one use the variable defined inside a make target

```<code>.PHONY: foo

VAR_GLOBAL=$(shell cat /tmp/global)

foo:
    echo "local" > /tmp/local
    VAR_LOCAL=$(shell cat /tmp/local)
    echo ${VAR_GLOBAL}
    echo ${VAR_LOCAL}
</code>```

here is the execution output:

```<code>$ echo global > /tmp/global
$ make foo
echo "local" > /tmp/local
VAR_LOCAL=local
echo global
global
echo
</code>```

答:
As @KelvinSherlock pointed out this is a duplicate of another question

here is the specific solution for my question:

```<code>.PHONY: foo

VAR_GLOBAL=$(shell cat /tmp/global)

foo:
    echo "local" > /tmp/local
    $(eval VAR_LOCAL := $(shell cat /tmp/local))
    echo ${VAR_GLOBAL}
    echo ${VAR_LOCAL}
</code>```

Title: makefile use variable defined in target

Body:
How can one use the variable defined inside a make target

.PHONY: foo

VAR_GLOBAL=$(shell cat /tmp/global)

foo:
    echo "local" > /tmp/local
    VAR_LOCAL=$(shell cat /tmp/local)
    echo ${VAR_GLOBAL}
    echo ${VAR_LOCAL}

here is the execution output:

$ echo global > /tmp/global
$ make foo
echo "local" > /tmp/local
VAR_LOCAL=local
echo global
global
echo

Body:
As @KelvinSherlock pointed out this is a duplicate of another question

here is the specific solution for my question:

.PHONY: foo

VAR_GLOBAL=$(shell cat /tmp/global)

foo:
    echo "local" > /tmp/local
    $(eval VAR_LOCAL := $(shell cat /tmp/local))
    echo ${VAR_GLOBAL}
    echo ${VAR_LOCAL}


问:
Playground Import: No Such Module 'Foo'
I've diligently followed the Apple instructions to import a custom module into a playground, including the instructions here.  And yet I get:

Playground execution failed: /var/folders/z3/kd0nj4ln1rgcpm8bdz7067wh0000gs/T/./lldb/1874/playground1.swift:7:8: error: no such module 'Foo'
  import Foo

How can I recover to a working Playground import? [Edit: Note, two answers have produced detailed instructions to associate a playground with a framework; I have followed those instructions but no luck.  The solution will need to involve reconfiguring something in Xcode; my installation is apparently broken]

Detailed images of the error and attempts:

Here is another attempt, based on the answer of @EricD, showing the directory structure, no dice.

答:
I had my playground working fine but found that when I quit Xcode and re-opened it, I would get an error like this:

error:
  /var/folders/ft/bmk8wh6s5ms4my2pxhn3qbp40000gn/T/playground1-9216e0..swift:3:8:
  error: no such module 'Playground_Sources' import Playground_Sources

... where "Playground" is the name of my playground file.

The solution to this (in Xcode 9.0) is to:

click any playground file in your workspace

show the Utilities panel (opt-cmd-0)

under "Playground Settings" change the "Platform" to anything else then set it back.

In my case, it's set to macOS.  I changed it to iOS then back to macOS (no recompilation necessary) and it started to work fine... that is until I close Xcode and open it again.

This is the only solution I found to work with macOS playgrounds.  This bug still exists in Xcode 9.3.

Title: Playground Import: No Such Module 'Foo'


问:
Google AppEngine use Google Compute for Task?
I need to run some specific code that can't be run on Google AppEngine (because of restrictions).

Since these workers are asynchronous, I thought about launching a Compute instance every time I need it and connecting them via a specific Tasks via the Task Queue from Google AppEngine, but I can not find any documentation about if this is possible?

TL;DR: Is it possible to specify a Google Compute as instance for a Task queue?

答:
No, there is no way to specify a Google Compute as instance for a Task queue.

But did you consider using the Flexible environment (eventually with a custom runtime to try to address the restrictions) instead? Or the alternatives suggested for the Flexible env (only has limited task queue support) From Task Queue:

The Task Queue service has limited availability outside of the
  standard environment. If you want to use the service outside of the
  standard environment, you can sign up for the Cloud Tasks alpha.

Outside of the standard environment, you can't add tasks to push
  queues, but a service running in the flexible environment can be
  the target of a push task. You can specify this using the
  target parameter when adding a task to queue or by specifying
  the default target for the queue in queue.yaml.

In many cases where you might use pull queues, such as queuing up
  tasks or messages that will be pulled and processed by separate
  workers, Cloud Pub/Sub can be a good alternative as it offers
  similar functionality and delivery guarantees.


答:
You can use a vector of char's, with no fixed size.
You can add the char using cin >> and push_back to your vector.

```<code>#include <vector>
#include <iostream>

int main()
{
    char myChar;
    std::vector<char> myInputs = {};

    while(true)
    {
        std::cin >> myChar;
        myInputs.push_back(myChar);

        for(char& i: myInputs)
        {
            std::cout << "input:" << i << std::endl;
        }
    }

    return 0;
}
</code>```

Title: Save input into a char array C++

Body:
How can I save input into a char array C++?

The problem I have is that I do not know beforehand how much input will the user provide.

I would like to use only arrays and chars.

Body:
You can use a vector of char's, with no fixed size.
You can add the char using cin >> and push_back to your vector.

#include <vector>
#include <iostream>

int main()
{
    char myChar;
    std::vector<char> myInputs = {};

    while(true)
    {
        std::cin >> myChar;
        myInputs.push_back(myChar);

        for(char& i: myInputs)
        {
            std::cout << "input:" << i << std::endl;
        }
    }

    return 0;
}


问:
get difference between 3 lists
I am working on differences of lists.

```<code>>>a = [1, 2, 3]
>>b = [2, 4, 5]
>>c = [3, 2, 6]
</code>```

Symmetric difference between 2 sets can be done using:

```<code>>>z = set(a).symmetric_difference(set(b))
>>print z
>>set([1, 3, 4, 5])
</code>```

How to get difference between 3 sets?
For difference of 3 sets, expected output is :

```<code>expected output : set([1, 3, 4, 5, 6])
</code>```

答:
@NPE that answer doesn't work as expected since it relies on the result of the proceeding operations. In your example you can see the '3' overlapping from the first to the third but still being included in the result.

```<code>>>> a = set(('a','b','c'))
>>> b = set(('c','d','e'))
>>> c = set(('e','f','g'))
>>> (a | b | c) - (a & b & c)
set(['a', 'c', 'b', 'e', 'd', 'g', 'f'])
</code>```

This happens because it does the intersection of 'a' to 'b' and then the intersection to 'c'. To fix this you could:

```<code>>>> (a | b | c) - ((a & b) | (a & c) | (b & c))
set(['a', 'b', 'd', 'g', 'f'])
</code>```

Also to save two operations you could get the the symmetric difference of two, union with the third, then do the difference of the union of the intersections of the first and third and second and third.

```<code>>>> ((a ^ b) | c) - ((a & c) | (b & c))
set(['a', 'b', 'd', 'g', 'f'])
</code>```

Title: get difference between 3 lists

Body:
I am working on differences of lists.

>>a = [1, 2, 3]
>>b = [2, 4, 5]
>>c = [3, 2, 6]

Symmetric difference between 2 sets can be done using:

>>z = set(a).symmetric_difference(set(b))
>>print z
>>set([1, 3, 4, 5])

How to get difference between 3 sets?
For difference of 3 sets, expected output is :

expected output : set([1, 3, 4, 5, 6])

Body:
@NPE that answer doesn't work as expected since it relies on the result of the proceeding operations. In your example you can see the '3' overlapping from the first to the third but still being included in the result.

>>> a = set(('a','b','c'))
>>> b = set(('c','d','e'))
>>> c = set(('e','f','g'))
>>> (a | b | c) - (a & b & c)
set(['a', 'c', 'b', 'e', 'd', 'g', 'f'])

This happens because it does the intersection of 'a' to 'b' and then the intersection to 'c'. To fix this you could:

>>> (a | b | c) - ((a & b) | (a & c) | (b & c))
set(['a', 'b', 'd', 'g', 'f'])

Also to save two operations you could get the the symmetric difference of two, union with the third, then do the difference of the union of the intersections of the first and third and second and third.

>>> ((a ^ b) | c) - ((a & c) | (b & c))
set(['a', 'b', 'd', 'g', 'f'])


问:
recovery the deleted Xml file from app in android
Is it possible to recover a deleted XML file from app in Android IDE?

Unfortunately I deleted important files from my app.

答:
UPDATED SHORT ALTERNATIVE:

Android Studio:

Go to Project Window tool

Expand res folder

Right click on layout and Place cursor on Local History (it is perhaps the 5th or 6th last option)

Select Show history

here we have all the past versions available, right click a version which you want to roll back and select Revert!


问:
Open links with the same call is not working
This is my list:

```<code> <ul id="nav" class="nav nav-tabs" style="font-size:10px;color:white;background-color:#283e4a;border-bottom:5px solid #f05514;border-top-left-radius:5px;">
    <li class="active"><a style="color:white" href="#fn" data-toggle="tab">FN</a></li>
    <li><a style="color:white"  class="current" href="@Url.Action("HomeFirstHalf","Home")">FH</a></li>

</ul>
<div id="mainInfoMatches"></div>
</code>```

And this is my script:

```<code>$(document).ready(function () {
        $("#nav li a").click(function () {
        $("#mainInfoMatches").empty().append("<div id='loading'><img class='img-responsive' id='img1' src='~/Images/loadingGif2.gif' /></div>");
            $("#nav li a").removeClass('current');
            $(this).addClass('current');

            $.ajax({
                url: this.href, success: function (html) {
                    $("#mainInfoMatches").empty().append(html);
                }
            });
            return false;
        });
    });
</code>```

When I click the second link it doesn't load the page.It doesn't do anything.Please help me

答:
If you hover over or inspect the link, is the "href" parameter completely missing from the anchor tag?

If so, this will be because you have spelt either your action or your controller name incorrectly.

Body:
This is my list:

FN

FH

And this is my script:

$(document).ready(function () {
        $("#nav li a").click(function () {
        $("#mainInfoMatches").empty().append("

");
            $("#nav li a").removeClass('current');
            $(this).addClass('current');

            $.ajax({
                url: this.href, success: function (html) {
                    $("#mainInfoMatches").empty().append(html);
                }
            });
            return false;
        });
    });

When I click the second link it doesn't load the page.It doesn't do anything.Please help me


问:
How to select all elements whose id contains a particular substring?
I want to select all elements whose id contains a particular substring. For example for these:

```<code><div id="foobootoo"><div>
<div id="foowoohoo"><div>
<div id="foodoowoo"><div>
<div id="soobootoo"><div>
</code>```

I want to get elements that has foo in the id.

答:
Did you try something like... </p>

```<code>$result = $xml->xpath("div[contains(@id,'foo')]");
</code>```

Body:
I want to select all elements whose id contains a particular substring. For example for these:

I want to get elements that has foo in the id.

Body:
Did you try something like...

$result = $xml->xpath("div[contains(@id,'foo')]");


问:
Rename file in Node.js without using fs
Is there any way to rename file in Node js without using fs package. Since it says Security holding package in NPM Respository
 https://www.npmjs.com/package/fs.

答:
fs module is not deprecated. Also, it has a rename method:

https://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback

Title: Rename file in Node.js without using fs