问:
Cannot connect to VoltDB over network
I am getting started with VoltDB. Running VoltDB community on a server in LAN. Server initialization completed as reported after server start

```<code>Build: 9.0 voltdb-9.0-0-g6aae38a-local Community Edition
Loaded node-specific settings from voltdbroot/config/path.properties
Connecting to VoltDB cluster as the leader...
Host id of this node is: 0
Restarting the database cluster from the command logs
WARN: User authentication is not enabled. The database is accessible and could be modified or shut down by anyone on the network.
Partition placement has been restored.
Initializing the database. This may take a moment...
WARN: This is not a highly available cluster. K-Safety is set to 0.
WARN: Durability is turned off. Command logging is off.
Restoring from path: /home/samtech/voltdb-db/voltdbroot/snapshots with nonce: SHUTDOWN_20190530T151422_my4epdwk9mv4
Duplicate rows will be output to: /home/samtech/voltdb-db/voltdbroot/snapshots nonce: SHUTDOWN_20190530T151422_my4epdwk9mv4
Finished restore of /home/samtech/voltdb-db/voltdbroot/snapshots with nonce: SHUTDOWN_20190530T151422_my4epdwk9mv4 in 0.09 seconds
Server Operational State is: NORMAL
Server completed initialization.
</code>```

I am able to connect to server locally, either with

```<code>sqlcmd --servers=192.168.1.4
</code>```

or by

```<code>sqlcmd
</code>```

But when i tried to connect using voltdb-client-go in my go application, it is showing following error

```<code>No valid connections failed to connect to server 192.168.1.4
</code>```

Here is my code that i am trying

```<code>package main

import (
    "database/sql"
    "log"

    _ "github.com/VoltDB/voltdb-client-go/voltdbclient"
)

func main() {
    InitVDb()
}

func InitVDb() {
    VDb, err := sql.Open("voltdb", "192.168.1.4")
    if err != nil {
        log.Fatalf("Voltdb Connection error %v\n", err)
    }

    err = VDb.Ping()
    if err != nil {
        VDb.Close()
        log.Fatalf("Ping failed: %v\n", err)
    }

    log.Println("Connection suceeded...")
}
</code>```

I also tried with "192.168.1.4:21212" but getting same error.
What is wrong in the code ?

There is no firewall (ipconfig) at database machine.

答:
In hello_word, it was using localhost:21212 as connection string, so i just followed and put 192.168.1.4:21212

But it should be

```<code>voltdb://192.168.1.4:21212
</code>```

It fixed the connection issue.

Title: Cannot connect to VoltDB over network

Body:
I am getting started with VoltDB. Running VoltDB community on a server in LAN. Server initialization completed as reported after server start

Build: 9.0 voltdb-9.0-0-g6aae38a-local Community Edition
Loaded node-specific settings from voltdbroot/config/path.properties
Connecting to VoltDB cluster as the leader...
Host id of this node is: 0
Restarting the database cluster from the command logs
WARN: User authentication is not enabled. The database is accessible and could be modified or shut down by anyone on the network.
Partition placement has been restored.
Initializing the database. This may take a moment...
WARN: This is not a highly available cluster. K-Safety is set to 0.
WARN: Durability is turned off. Command logging is off.
Restoring from path: /home/samtech/voltdb-db/voltdbroot/snapshots with nonce: SHUTDOWN_20190530T151422_my4epdwk9mv4
Duplicate rows will be output to: /home/samtech/voltdb-db/voltdbroot/snapshots nonce: SHUTDOWN_20190530T151422_my4epdwk9mv4
Finished restore of /home/samtech/voltdb-db/voltdbroot/snapshots with nonce: SHUTDOWN_20190530T151422_my4epdwk9mv4 in 0.09 seconds
Server Operational State is: NORMAL
Server completed initialization.

I am able to connect to server locally, either with

sqlcmd --servers=192.168.1.4

or by

sqlcmd

But when i tried to connect using voltdb-client-go in my go application, it is showing following error

No valid connections failed to connect to server 192.168.1.4

Here is my code that i am trying

package main

import (
    "database/sql"
    "log"

    _ "github.com/VoltDB/voltdb-client-go/voltdbclient"
)

func main() {
    InitVDb()
}

func InitVDb() {
    VDb, err := sql.Open("voltdb", "192.168.1.4")
    if err != nil {
        log.Fatalf("Voltdb Connection error %v\n", err)
    }

    err = VDb.Ping()
    if err != nil {
        VDb.Close()
        log.Fatalf("Ping failed: %v\n", err)
    }

    log.Println("Connection suceeded...")
}

I also tried with "192.168.1.4:21212" but getting same error.
What is wrong in the code ?

There is no firewall (ipconfig) at database machine.

Body:
In hello_word, it was using localhost:21212 as connection string, so i just followed and put 192.168.1.4:21212

But it should be

voltdb://192.168.1.4:21212

It fixed the connection issue.


来源: stackexchange

问:
I have .aar file inside library module, how to use it in app module?
I have .aar file inside library module, how to use it in app module, although I added this line inside the app gradle, please help me.</p>

```<code>implementation project(":my_library")
</code>```

答:
Call like this in your project </p>

```<code>implementation(name: 'my_library', ext: 'aar')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have .aar file inside library module, how to use it in app module, although I added this line inside the app gradle, please help me.

implementation project(":my_library")

Body:
Call like this in your project

implementation(name: 'my_library', ext: 'aar')


问:
Microphone function in python doesnot stop listening
I am making a chatbot in python 3. I used the function Microphone to record my voice. If i plugin my earphone then it works perfectly. But without earphone if i say something, it takes the input (listens to me) but doesnot stop listening till i plugin my earphone and say something. Why does not it stop listening to me without earphone?
Here is my code snippet-

```<code>r = sr.Recognizer()
with sr.Microphone() as source:
    print("Listening....")
    r.pause_threshold = 1
    audio = r.listen(source)
</code>```

I want the chatbot to stop listening and start executing within 1 second gap when i have not connected earphone.

答:
```<code>import sys
!pip install -c conda-forge google-api-python-client
import speech_recognition as sr
r = sr.Recognizer()
r.energy_threshold = 2500
#Input your speech by listen(_)
with sr.Microphone() as source:
    print('Say Something:!')
    audio = r.listen(source)
    print('Done!')

try:
   print("You said: \n" + r.recognize_google(audio, language = 'hi-IN'))
except Exception as e:
   print(e)
</code>```

Above I tried and worked in my local.
Please explain a bit more about your query. What i understand is it is working fine with microphone and not working well when you speaking without microphone. It might be due to sr.Microphone() as a source.

You may try with using the audio file as the audio source  -

```<code>from os import path
AUDIO_FILE = "/Path of audio file.....wav"
r = sr.Recognizer()
with sr.AudioFile(AUDIO_FILE) as source:
    audio = r.record(source)  # read the entire audio file
</code>```

Body:
I am making a chatbot in python 3. I used the function Microphone to record my voice. If i plugin my earphone then it works perfectly. But without earphone if i say something, it takes the input (listens to me) but doesnot stop listening till i plugin my earphone and say something. Why does not it stop listening to me without earphone?
Here is my code snippet-

r = sr.Recognizer()
with sr.Microphone() as source:
    print("Listening....")
    r.pause_threshold = 1
    audio = r.listen(source)

I want the chatbot to stop listening and start executing within 1 second gap when i have not connected earphone.

Body:
import sys
!pip install -c conda-forge google-api-python-client
import speech_recognition as sr
r = sr.Recognizer()
r.energy_threshold = 2500
#Input your speech by listen(_)
with sr.Microphone() as source:
    print('Say Something:!')
    audio = r.listen(source)
    print('Done!')

try:
   print("You said: \n" + r.recognize_google(audio, language = 'hi-IN'))
except Exception as e:
   print(e)

Above I tried and worked in my local.
Please explain a bit more about your query. What i understand is it is working fine with microphone and not working well when you speaking without microphone. It might be due to sr.Microphone() as a source.

You may try with using the audio file as the audio source  -

from os import path
AUDIO_FILE = "/Path of audio file.....wav"
r = sr.Recognizer()
with sr.AudioFile(AUDIO_FILE) as source:
    audio = r.record(source)  # read the entire audio file


问:
How to silence 'The last statement should return a value' warning?
Sun Studio 12.1 prints the warning

```<code>Warning: The last statement should return a value.
</code>```

frequently for functions like that:

```<code>int f()
{
  /* some code that may return */

  // if we end up here, something is broken
  throw std::runtime_error("Error ...");
}
</code>```

It is perfectly clear that we do not need a return value at the end of the function. I hesitate to insert something like

```<code>// Silence a compiler warning
return 42;
</code>```

at the end of such a function, since it is dead code anyway. For more complicated return types, it might actually be difficult to construct a 'sensible' bogus value.

What is the recommended way to silence such a warning?

答:
I find it a perfect spot for abort(). You should never end there, according to you, so something like:

```<code>UNREACHABLE("message")
</code>```

which expands into:

```<code>#ifdef NDEBUG
  #define UNREACHABLE(Message_) abort();
#else
  #define UNREACHABLE(Message_) assert(0 && Message_);
#endif
</code>```

Looks appropriate

ContentLicense: CC BY-SA 3.0

Body:
Sun Studio 12.1 prints the warning

Warning: The last statement should return a value.

frequently for functions like that:

int f()
{
  /* some code that may return */

  // if we end up here, something is broken
  throw std::runtime_error("Error ...");
}

It is perfectly clear that we do not need a return value at the end of the function. I hesitate to insert something like

// Silence a compiler warning
return 42;

at the end of such a function, since it is dead code anyway. For more complicated return types, it might actually be difficult to construct a 'sensible' bogus value.

What is the recommended way to silence such a warning?

Body:
I find it a perfect spot for abort(). You should never end there, according to you, so something like:

UNREACHABLE("message")

which expands into:

#ifdef NDEBUG
  #define UNREACHABLE(Message_) abort();
#else
  #define UNREACHABLE(Message_) assert(0 && Message_);
#endif

Looks appropriate


问:
Using input text instead Dropdown list as Parameter (cube as Source of data )
I'm setting up a parameter in SSRS as an input text, but I don't know how to link it with my Query in the data set.

I'm working with the cube as my source in my report and I created many parameters as a drop down list.

I was able to manipulate them using their dataset and change their parameter caption and value. Now I want to set another Parameter but as an input text this time!

答:
Let's assume your input parameter is for Account name.
You wish to filter your report to show only data for let's say for Account "XYZ".

Parameter Name:ParameterAccountName

user have input ParameterAccountName as "XYZ"

Now in your query you could add it something like below

```<code>select * from account where accountname=@ParameterAccountName
</code>```

Here is the article which will help you more.
https://reportsyouneed.com/ssrs-tip-put-parameters-in-your-query-not-your-filter/

Body:
Let's assume your input parameter is for Account name.
You wish to filter your report to show only data for let's say for Account "XYZ".

Parameter Name:ParameterAccountName

user have input ParameterAccountName as "XYZ"

Now in your query you could add it something like below

select * from account where accountname=@ParameterAccountName

Here is the article which will help you more.
https://reportsyouneed.com/ssrs-tip-put-parameters-in-your-query-not-your-filter/


问:
Rebus Pub Sub: Retrieve headers on subscriber
Headers are published with Azure Service Bus, like below:

```<code> string content = "body";
 await _busPublisher.Activator.Bus.Publish(content, headers);
</code>```

How to retrieve both header and content on subscriber?

```<code>class Handler :  IHandleMessages<string>
    {

    public Handler(IMessageContext messageContext, ILog log)
    {
        _messageContext = messageContext;
        _log = log;
    }

        public async Task Handle(string message)
        {
            Console.WriteLine("Handle(string message): {0}", message);

        }
    }
</code>```

Update

Below is one solution. Is this the best solution?

```<code>        public Handler(IMessageContext messageContext, ILog log)
    {
        _messageContext = messageContext;
        _log = log;
    }
            public async Task Handle(string message)
            {
                Console.WriteLine("Handle(string message): {0} ", message);
                Console.WriteLine("headers: {0} ", string.Join(' ', _messageContext.Headers));

            }
</code>```

When a Handler is instantiated like below, is it possible to use dependency injection instead?

```<code>        var Activator = new BuiltinHandlerActivator();

        Activator.Register((mc) =>
            {
                return new Handler(mc, log);  //no new?

            }
</code>```

答:
Accepted IMessageContext injected into the constructor of your handler is the way to go:

public class Handler : IHandleMessages<string>
{
    readonly IMessageContext messageContext;

    public Handler(IMessageContext messageContext, ILog log)
    {
        this.messageContext = messageContext;
    }

    public async Task Handle(string message)
    {
        var headers = messageContext.Headers;

        // do stuff
    }
}
```

<p>If you're using <code>BuiltinHandlerActivator</code>, you can have it injected like this:</p>

<pre class="lang-cs prettyprint-override"><code>activator.Register(context => new Handler(context));
</code>```

or if you also need the IBus in your handler:

activator.Register((bus, context) => new Handler(bus, context));
```

Body:
Headers are published with Azure Service Bus, like below:

 string content = "body";
 await _busPublisher.Activator.Bus.Publish(content, headers);

How to retrieve both header and content on subscriber?

class Handler :  IHandleMessages<string>
    {

    public Handler(IMessageContext messageContext, ILog log)
    {
        _messageContext = messageContext;
        _log = log;
    }

        public async Task Handle(string message)
        {
            Console.WriteLine("Handle(string message): {0}", message);

        }
    }

Update

Below is one solution. Is this the best solution?

        public Handler(IMessageContext messageContext, ILog log)
    {
        _messageContext = messageContext;
        _log = log;
    }
            public async Task Handle(string message)
            {
                Console.WriteLine("Handle(string message): {0} ", message);
                Console.WriteLine("headers: {0} ", string.Join(' ', _messageContext.Headers));

            }

When a Handler is instantiated like below, is it possible to use dependency injection instead?

        var Activator = new BuiltinHandlerActivator();

        Activator.Register((mc) =>
            {
                return new Handler(mc, log);  //no new?

            }

Body:
Accepted IMessageContext injected into the constructor of your handler is the way to go:

public class Handler : IHandleMessages<string>
{
    readonly IMessageContext messageContext;

    public Handler(IMessageContext messageContext, ILog log)
    {
        this.messageContext = messageContext;
    }

    public async Task Handle(string message)
    {
        var headers = messageContext.Headers;

        // do stuff
    }
}

If you're using BuiltinHandlerActivator, you can have it injected like this:

activator.Register(context => new Handler(context));

or if you also need the IBus in your handler:

activator.Register((bus, context) => new Handler(bus, context));


问:
Code Signing Certificate Reputation with SmartScreen Filter
I am using a standard (i.e. not EV) Authenticode code signing certificate to sign a Windows desktop application in the hope that Smartscreen Filter will eventually stop blocking it.

I was hoping to certify the application but since my code signing certificate was issued by GoDaddy it appears that I can't do that since you need a certificate from Symantec, Entrust, GlobalSign, WoSign or Digicert in order to create a Windows Certification Dashboard account (the first step in the certification process).

So here's my question: Will my non-certified Windows application signed with a standard GoDaddy SHA-2 code signing certificate still accumulate reputation?

答:
According to these article, most likely yes, but you need to check details in your certificate
https://social.technet.microsoft.com/wiki/contents/articles/51151.microsoft-trusted-root-certificate-program-participants-as-of-january-30-2018.aspx </p>


问:
Firebase Realtime database Array query issue
I need a firebase query to filter the list based on the value of an array.

if any of the index of GID(Array) contains the given key. e.g my key is YsGMyfLSGRNHxDWQmhpuPRqtxlq1 and one node's GID have that on 0th index and other have that on 1st index. So these two lists need to be returned.

Currently, I can only get the one at 0th index using the code

```<code>//userID = YsGMyfLSGRNHxDWQmhpuPRqtxlq1
 firebaseDatabase.child("Groups").queryOrdered(byChild: "GID/0").queryEqual(toValue:userID)
</code>```

When I try to combine the query I am getting errors.

答:
There is no way you can filter your groups based on a value that exist within an array. If you want to query your database to get all groups a particular user is apart of, then you should consider augmenting your data structure to allow a reverse lookup. This means that you should add under each user object the groups in which that user is present.

This means that you'll need to duplicate some data, but this is not a problem when it comes to Firebase. This is a quite common practice, which is named denormalization and for that, I recommend you see this video, Denormalization is normal with the Firebase Database.

When you are duplicating data, there is one thing that need to keep in mind. In the same way you are adding data, you need to maintain it. With other words, if you want to update/detele an item, you need to do it in every place that it exists.

However, what you need is actually allowed in Cloud Firestore. Its array-contains operator allow you to filter documents that have a certain value in an array. For more on this topic, please see the following post:

Better Arrays in Cloud Firestore.

Body:
I need a firebase query to filter the list based on the value of an array.

if any of the index of GID(Array) contains the given key. e.g my key is YsGMyfLSGRNHxDWQmhpuPRqtxlq1 and one node's GID have that on 0th index and other have that on 1st index. So these two lists need to be returned.

Currently, I can only get the one at 0th index using the code

//userID = YsGMyfLSGRNHxDWQmhpuPRqtxlq1
 firebaseDatabase.child("Groups").queryOrdered(byChild: "GID/0").queryEqual(toValue:userID)

When I try to combine the query I am getting errors.


问:
Best way to wait for .forEach() to complete
Sometimes I need to wait for a .forEach() method to finish, mostly on 'loader' functions. This is the way I do that:

```<code>$q.when(array.forEach(function(item){
    //iterate on something
})).then(function(){
    //continue with processing
});
</code>```

I can't help but feel that this isn't the best way to wait for a .forEach() to finish. What is the best way to do this?

答:
forEach() doesn't return anything, so a better practice would be map() + Promise.all()

```<code>var arr = [1, 2, 3, 4, 5, 6]

var doublify = (ele) => {
  return new Promise((res, rej) => {
    setTimeout(() => {
        res(ele * 2)
    }, Math.random() ); // Math.random returns a random number from 0~1
  })
}

var promises = arr.map(async (ele) => {
  // do some operation on ele
  // ex: var result = await some_async_function_that_return_a_promise(ele)
  // In the below I use doublify() to be such an async function

  var result = await doublify(ele)
  return new Promise((res, rej) => {res(result)})
})

Promise.all(promises)
.then((results) => {
  // do what you want on the results
  console.log(results)
})
</code>```

Body:
Sometimes I need to wait for a .forEach() method to finish, mostly on 'loader' functions. This is the way I do that:

$q.when(array.forEach(function(item){
    //iterate on something
})).then(function(){
    //continue with processing
});

I can't help but feel that this isn't the best way to wait for a .forEach() to finish. What is the best way to do this?

Body:
forEach() doesn't return anything, so a better practice would be map() + Promise.all()

var arr = [1, 2, 3, 4, 5, 6]

var doublify = (ele) => {
  return new Promise((res, rej) => {
    setTimeout(() => {
        res(ele * 2)
    }, Math.random() ); // Math.random returns a random number from 0~1
  })
}

var promises = arr.map(async (ele) => {
  // do some operation on ele
  // ex: var result = await some_async_function_that_return_a_promise(ele)
  // In the below I use doublify() to be such an async function

  var result = await doublify(ele)
  return new Promise((res, rej) => {res(result)})
})

Promise.all(promises)
.then((results) => {
  // do what you want on the results
  console.log(results)
})


问:
VBA - Copy-Paste to another workbook
I am trying to copy specific cells from one workbook to another at the end of the table.
I assume the problem is with using 'ActiveWorkbook' a lot.
I get the error "Object doesnt support this property or method" and it seems that macro copies cells from CurrentBook and not uploader.

How can I fix my code?

```<code>
Dim uploadfile As Variant
Dim uploader As Workbook
Dim CurrentBook As Workbook
Dim lastRow As Integer

Set CurrentBook = ActiveWorkbook

uploadfile = Application.GetOpenFilename()
    If uploadfile = "False" Then
        Exit Sub
    End If
Workbooks.Open uploadfile

Set uploader = ActiveWorkbook

With uploader
    Application.CutCopyMode = False
    Range("A1:J100").Copy
End With

CurrentBook.Activate
lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Range("A" & lastRow & ":J" & lastRow + 100).Select
Selection.Paste

uploader.Close

End Sub
</code>```

答:
Below you could find a sample code on how to copy from one workbook to another:</p>

```<code>Option Explicit

Sub test()

    Dim wbSource As Workbook, wbDestination As Workbook

    'Set both workbooks by name to avoid conflicts
    Set wbSource = Workbooks("Book1")
    Set wbDestination = Workbooks("Book2")

    'Copy paste only values
    wbSource.Worksheets("Sheet1").Range("A1").Copy
    wbDestination.Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValues

End Sub
</code>```

Title: VBA - Copy-Paste to another workbook

Body:
I am trying to copy specific cells from one workbook to another at the end of the table.
I assume the problem is with using 'ActiveWorkbook' a lot.
I get the error "Object doesnt support this property or method" and it seems that macro copies cells from CurrentBook and not uploader.

How can I fix my code?

Dim uploadfile As Variant
Dim uploader As Workbook
Dim CurrentBook As Workbook
Dim lastRow As Integer

Set CurrentBook = ActiveWorkbook

uploadfile = Application.GetOpenFilename()
    If uploadfile = "False" Then
        Exit Sub
    End If
Workbooks.Open uploadfile

Set uploader = ActiveWorkbook

With uploader
    Application.CutCopyMode = False
    Range("A1:J100").Copy
End With

CurrentBook.Activate
lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Range("A" & lastRow & ":J" & lastRow + 100).Select
Selection.Paste

uploader.Close

End Sub

Body:
Below you could find a sample code on how to copy from one workbook to another:

Option Explicit

Sub test()

    Dim wbSource As Workbook, wbDestination As Workbook

    'Set both workbooks by name to avoid conflicts
    Set wbSource = Workbooks("Book1")
    Set wbDestination = Workbooks("Book2")

    'Copy paste only values
    wbSource.Worksheets("Sheet1").Range("A1").Copy
    wbDestination.Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValues

End Sub


问:
TypeError with model field
I add some new fields in model and django suggested me to add default value or set some default params in model. I added datetime object as value, but the value should be the int or number. Now I can't sync db becouse of type error. I tried to delete some objects which was instances of this model, where I did some changes but It doesn't help me.

How I can fix my model now?!

this is traceback

```<code>Applying card.0026_auto_20150104_1323...Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\__init__.p
y", line 385, in execute_from_command_line
    utility.execute()
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\__init__.p
y", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\base.py",
line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\base.py",
line 338, in execute
    output = self.handle(*args, **options)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\base.py",
line 533, in handle
    return self.handle_noargs(**options)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\commands\s
yncdb.py", line 27, in handle_noargs
    call_command("migrate", **options)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\__init__.p
y", line 115, in call_command
    return klass.execute(*args, **defaults)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\base.py",
line 338, in execute
    output = self.handle(*args, **options)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\commands\m
igrate.py", line 160, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\migrations\executor.py"
, line 63, in migrate
    self.apply_migration(migration, fake=fake)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\migrations\executor.py"
, line 97, in apply_migration
    migration.apply(project_state, schema_editor)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\migrations\migration.py
", line 107, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, ne
w_state)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\migrations\operations\f
ields.py", line 37, in database_forwards
    field,
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\backends\sqlite3\schema
.py", line 167, in add_field
    self._remake_table(model, create_fields=[field])
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\backends\sqlite3\schema
.py", line 74, in _remake_table
    self.effective_default(field)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\backends\schema.py", li
ne 184, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\models\fields\related.p
y", line 1735, in get_db_prep_save
    return self.related_field.get_db_prep_save(value, connection=connection)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\models\fields\__init__.
py", line 627, in get_db_prep_save
    prepared=False)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\models\fields\__init__.
py", line 907, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\models\fields\__init__.
py", line 915, in get_prep_value
    return int(value)
TypeError: int() argument must be a string or a number, not 'datetime.datetime'
</code>```

this is part of model code:

I added owner field in CollectionItem object:

```<code>class CollectionItem (models.Model):
    card = models.ForeignKey(Card)
    golden = models.BooleanField(default=False)
    count = models.IntegerField(default=0)
    level = models.IntegerField(default=1)
    owner = models.ForeignKey(User, related_name='collectionCards')

    @property
    def price(self):
        return self.card.price

class Collection (models.Model):
    owner = models.ForeignKey(User, related_name='collections')
    items = models.ManyToManyField(CollectionItem, through='CollectionCollector')

class CollectionAdmin (admin.ModelAdmin):
    fields = ['owner'] admin.site.register(Collection, CollectionAdmin)

class CollectionCollector (models.Model):
    item = models.ForeignKey(CollectionItem, related_name='collection_item')
    collection = models.ForeignKey(Collection)
</code>```

答: Delete the old python files in migration folder in your app directory and then migrate again. It will fix the issues.</p>

Title: TypeError with model field

Body:
I add some new fields in model and django suggested me to add default value or set some default params in model. I added datetime object as value, but the value should be the int or number. Now I can't sync db becouse of type error. I tried to delete some objects which was instances of this model, where I did some changes but It doesn't help me.

How I can fix my model now?!

this is traceback

Applying card.0026_auto_20150104_1323...Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\__init__.p
y", line 385, in execute_from_command_line
    utility.execute()
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\__init__.p
y", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\base.py",
line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\base.py",
line 338, in execute
    output = self.handle(*args, **options)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\base.py",
line 533, in handle
    return self.handle_noargs(**options)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\commands\s
yncdb.py", line 27, in handle_noargs
    call_command("migrate", **options)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\__init__.p
y", line 115, in call_command
    return klass.execute(*args, **defaults)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\base.py",
line 338, in execute
    output = self.handle(*args, **options)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\core\management\commands\m
igrate.py", line 160, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\migrations\executor.py"
, line 63, in migrate
    self.apply_migration(migration, fake=fake)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\migrations\executor.py"
, line 97, in apply_migration
    migration.apply(project_state, schema_editor)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\migrations\migration.py
", line 107, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, ne
w_state)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\migrations\operations\f
ields.py", line 37, in database_forwards
    field,
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\backends\sqlite3\schema
.py", line 167, in add_field
    self._remake_table(model, create_fields=[field])
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\backends\sqlite3\schema
.py", line 74, in _remake_table
    self.effective_default(field)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\backends\schema.py", li
ne 184, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\models\fields\related.p
y", line 1735, in get_db_prep_save
    return self.related_field.get_db_prep_save(value, connection=connection)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\models\fields\__init__.
py", line 627, in get_db_prep_save
    prepared=False)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\models\fields\__init__.
py", line 907, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\RIK\Envs\la\lib\site-packages\django\db\models\fields\__init__.
py", line 915, in get_prep_value
    return int(value)
TypeError: int() argument must be a string or a number, not 'datetime.datetime'

this is part of model code:

I added owner field in CollectionItem object:

class CollectionItem (models.Model):
    card = models.ForeignKey(Card)
    golden = models.BooleanField(default=False)
    count = models.IntegerField(default=0)
    level = models.IntegerField(default=1)
    owner = models.ForeignKey(User, related_name='collectionCards')

    @property
    def price(self):
        return self.card.price

class Collection (models.Model):
    owner = models.ForeignKey(User, related_name='collections')
    items = models.ManyToManyField(CollectionItem, through='CollectionCollector')

class CollectionAdmin (admin.ModelAdmin):
    fields = ['owner'] admin.site.register(Collection, CollectionAdmin)

class CollectionCollector (models.Model):
    item = models.ForeignKey(CollectionItem, related_name='collection_item')
    collection = models.ForeignKey(Collection)


问:
Work out the type of c# application a class contained in a DLL is being used by
Is there any way to know in C# the type of application that is running.

Windows Service
ASP.NET
Windows Form
Console

I would like to react to the application type but cannot find a way to determine it.

答: ASP.NET, check the if HttpContext.Current is null</p>

OwnerDisplayName: John Selkirk

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: CodeMeIt


问:
How to merge two columns of JTable
I am retriving data from database.TableName:Contacts. There are two fields of this table.First_Name and Last_Name. I want to merge these two columns and want one column of JTable as Full Name.I've tried to create concat sql query,which was:

```<code>String queryMerge="select (First_Name||Last_Name) as Full_Name from Contacts";
</code>```

But it gave me an error:

```<code>[Microsoft][ODBC Microsoft access driver] Invalid use of vertical bars in query expression '(First_Name||Last_Name)'
</code>```

I thought to store all retrieved data in vector and use that values to build JTable.I am using AbstractTableModel.Is there any other way to solve this problem?

答:
Merging the data in the SQL query should work fine, you just need to get the syntax right.

Another option is when you are pulling the columns out of the ResultSet, combine them before putting them in the table's model.

Title: How to merge two columns of JTable

Body:
I am retriving data from database.TableName:Contacts. There are two fields of this table.First_Name and Last_Name. I want to merge these two columns and want one column of JTable as Full Name.I've tried to create concat sql query,which was:

String queryMerge="select (First_Name||Last_Name) as Full_Name from Contacts";

But it gave me an error:

[Microsoft][ODBC Microsoft access driver] Invalid use of vertical bars in query expression '(First_Name||Last_Name)'

I thought to store all retrieved data in vector and use that values to build JTable.I am using AbstractTableModel.Is there any other way to solve this problem?


问:
Can we redo a plugin published on wordpress.org and disable update for the user who has it already installed on there site
I have the plugin on wordpress.org I want to redo that plugin, but when I redo that plugin it will be the same plugin but I can't migrate old plugin user to this new plugin, so I want to disable the update for the old users of this plugin so they continue to use the old plugin (and migrate on their own risk) but it should not auto update for them</p>

答:
You can change the plugin version in wp-content/plugins/your-plugin/your-plugin.php to something like:

 * Version: 9999
```

<p>Every plugin has comments at the start of the plugin's file that gives wordpress information. e.g </p>

<pre class="lang-php prettyprint-override"><code>/**
 * Plugin Name: the name of the plugin
 * Plugin URI: https://wordpress.org/plugins/plugin
 * Description: blah blah
 * Version: 9999
 * Author: author etc
**/
</code>```

By adding version 9999 wordpress thinks that your plugin is updated so it wont be shown as a plugin that needs update.

Hope this trick helps you.

Body:
You can change the plugin version in wp-content/plugins/your-plugin/your-plugin.php to something like:

 * Version: 9999

Every plugin has comments at the start of the plugin's file that gives wordpress information. e.g

/**
 * Plugin Name: the name of the plugin
 * Plugin URI: https://wordpress.org/plugins/plugin
 * Description: blah blah
 * Version: 9999
 * Author: author etc
**/

By adding version 9999 wordpress thinks that your plugin is updated so it wont be shown as a plugin that needs update.

Hope this trick helps you.


问:
Registry.LocalMachine.OpenSubKey() returns a result different from Registry Editor
I'm trying to Create an installer for my CAD plugin, and need to get the AutoCAD install location. but the return values of RegistryKey.GetSubKeyNames() is different from what I see in Registry Editor.

```<code>string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
{
    foreach (string subkey_name in key.GetSubKeyNames())
    {
        Console.WriteLine(subkey_name);
    }
}
</code>```

output:

AddressBook

  Autodesk Application Manager

  Autodesk Content Service

  Autodesk Material Library 2015

  Autodesk Material Library Base Resolution Image Library 2015

  Connection Manager

  DirectDrawEx

  DXM_Runtime

  f528b707

  Fontcore

  ...

In Registry Editor:

animizvideocn_is1

  AutoCAD 2015

  Autodesk 360

  Connection Manager

  ...

AutoCAD 2015 is what i need

答:
This might be not a direct answer to your question, but i had to do the same thing. I was not looking at the registry, but the Program Files directory. It will then add the netload command to the autoload lisp file. It will install a list of Plugin dlls to all installed autocad versions. This can easily be changed... Hopefully it helps.

```<code>using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace AMU.AutoCAD.Update
{
  public class AutoCadPluginInstaller
  {
    private static readonly Regex AutoloadFilenameRegex = new Regex("acad([\\d])*.lsp");

    public void Install(IEnumerable<string> pluginFiles)
    {
      var acadDirs = this.GetAcadInstallationPaths();
      var autoloadFiles = acadDirs.Select(this.GetAutoloadFile);

      foreach (var autoloadFile in autoloadFiles)
        this.InstallIntoAutoloadFile(autoloadFile, pluginFiles);
    }

    private void InstallIntoAutoloadFile(string autoloadFile, IEnumerable<string> pluginFiles)
    {
      try
      {
        var content = File.ReadAllLines(autoloadFile).ToList();
        foreach (var pluginFile in pluginFiles)
        {
          var loadLine = this.BuildLoadLine(pluginFile);
          if(!content.Contains(loadLine))
            content.Add(loadLine);
        }

        File.WriteAllLines(autoloadFile, content);
      }
      catch (Exception ex)
      {
        //log.Log();
      }
    }

    private string BuildLoadLine(string pluginFile)
    {
      pluginFile = pluginFile.Replace(@"\", "/");
      return $"(command \"_netload\" \"{pluginFile}\")";
    }

    private IEnumerable<string> GetAcadInstallationPaths()
    {
      var programDirs =
        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

      var autoDeskDir = Path.Combine(programDirs, "Autodesk");
      if (!Directory.Exists(autoDeskDir))
        return null;

      return Directory.EnumerateDirectories(autoDeskDir)
                             .Where(d => d.Contains("AutoCAD"));
    }

    private string GetAutoloadFile(string acadDir)
    {
      var supportDir = Path.Combine(acadDir, "Support");
      var supportFiles = Directory.EnumerateFiles(supportDir);
      return supportFiles.FirstOrDefault(this.IsSupportFile);
    }

    private bool IsSupportFile(string path)
      => AutoloadFilenameRegex.IsMatch(Path.GetFileName(path));
  }
}
</code>```

(see here: https://gist.github.com/felixalmesberger/4ff8ed27f66f872face4368a13123fff)

You can use it like this:

```<code>var installer = new AutoCadPluginInstaller();
installer.Install(new [] {"Path to dll"});
</code>```

Have fun.

Body:
I'm trying to Create an installer for my CAD plugin, and need to get the AutoCAD install location. but the return values of RegistryKey.GetSubKeyNames() is different from what I see in Registry Editor.

string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
{
    foreach (string subkey_name in key.GetSubKeyNames())
    {
        Console.WriteLine(subkey_name);
    }
}

output:

AddressBook

  Autodesk Application Manager

  Autodesk Content Service

  Autodesk Material Library 2015

  Autodesk Material Library Base Resolution Image Library 2015

  Connection Manager

  DirectDrawEx

  DXM_Runtime

  f528b707

  Fontcore

  ...

In Registry Editor:

animizvideocn_is1

  AutoCAD 2015

  Autodesk 360

  Connection Manager

  ...

AutoCAD 2015 is what i need

Body:
This might be not a direct answer to your question, but i had to do the same thing. I was not looking at the registry, but the Program Files directory. It will then add the netload command to the autoload lisp file. It will install a list of Plugin dlls to all installed autocad versions. This can easily be changed... Hopefully it helps.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace AMU.AutoCAD.Update
{
  public class AutoCadPluginInstaller
  {
    private static readonly Regex AutoloadFilenameRegex = new Regex("acad([\\d])*.lsp");

    public void Install(IEnumerable<string> pluginFiles)
    {
      var acadDirs = this.GetAcadInstallationPaths();
      var autoloadFiles = acadDirs.Select(this.GetAutoloadFile);

      foreach (var autoloadFile in autoloadFiles)
        this.InstallIntoAutoloadFile(autoloadFile, pluginFiles);
    }

    private void InstallIntoAutoloadFile(string autoloadFile, IEnumerable<string> pluginFiles)
    {
      try
      {
        var content = File.ReadAllLines(autoloadFile).ToList();
        foreach (var pluginFile in pluginFiles)
        {
          var loadLine = this.BuildLoadLine(pluginFile);
          if(!content.Contains(loadLine))
            content.Add(loadLine);
        }

        File.WriteAllLines(autoloadFile, content);
      }
      catch (Exception ex)
      {
        //log.Log();
      }
    }

    private string BuildLoadLine(string pluginFile)
    {
      pluginFile = pluginFile.Replace(@"\", "/");
      return $"(command \"_netload\" \"{pluginFile}\")";
    }

    private IEnumerable<string> GetAcadInstallationPaths()
    {
      var programDirs =
        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

      var autoDeskDir = Path.Combine(programDirs, "Autodesk");
      if (!Directory.Exists(autoDeskDir))
        return null;

      return Directory.EnumerateDirectories(autoDeskDir)
                             .Where(d => d.Contains("AutoCAD"));
    }

    private string GetAutoloadFile(string acadDir)
    {
      var supportDir = Path.Combine(acadDir, "Support");
      var supportFiles = Directory.EnumerateFiles(supportDir);
      return supportFiles.FirstOrDefault(this.IsSupportFile);
    }

    private bool IsSupportFile(string path)
      => AutoloadFilenameRegex.IsMatch(Path.GetFileName(path));
  }
}

(see here: https://gist.github.com/felixalmesberger/4ff8ed27f66f872face4368a13123fff)

You can use it like this:

var installer = new AutoCadPluginInstaller();
installer.Install(new [] {"Path to dll"});

Have fun.


问:
Rename Home screen icon
is there a way for an app to rename its icon on the Home screen (Springboard)? The name comes from info.plist which is in the bundle; has anyone ever tried to change it in run-time, will it break anything?</p>

答: No, it can't be done! You are not allowed to write to the application bundle, there's no other way to set the application name…</p>

Title: Rename Home screen icon


问:
Laravel: Accessing model attributes in the constructor method
How to use __construct on laravel eloquent and get attributes. I tired:

```<code>public function __construct() {
    parent::__construct();
    dd($this->attributes);
}
</code>```

My code return null. But on abstract class Model filled all attributes:

```<code>public function __construct(array $attributes = [])
{
    $this->bootIfNotBooted();

    $this->initializeTraits();

    $this->syncOriginal();

    $this->fill($attributes);
}
</code>```

It's possible get access to model attributes in the constructor method?

答:
I tested this locally by updating the constructor like this:

```<code>public function __construct(array $attributes = []) {
    parent::__construct($attributes);
    dd($this->getAttributes());
}
</code>```

However, I've discovered that when fetching the object from the database, its attributes are not filled in the constructor, and therefore it's not possible to access them there.

What you can do is access the attributes after the object has been initialized:

```<code>$post = Post::find(1);
dump($post->getAttributes());
</code>```

Not sure if that helps, but it is what it is.

Maybe Events or Observers can help you with what you need:
https://laravel.com/docs/5.8/eloquent#events

https://laravel.com/docs/5.8/eloquent#observers

Body:
How to use __construct on laravel eloquent and get attributes. I tired:

public function __construct() {
    parent::__construct();
    dd($this->attributes);
}

My code return null. But on abstract class Model filled all attributes:

public function __construct(array $attributes = [])
{
    $this->bootIfNotBooted();

    $this->initializeTraits();

    $this->syncOriginal();

    $this->fill($attributes);
}

It's possible get access to model attributes in the constructor method?

Body:
I tested this locally by updating the constructor like this:

public function __construct(array $attributes = []) {
    parent::__construct($attributes);
    dd($this->getAttributes());
}

However, I've discovered that when fetching the object from the database, its attributes are not filled in the constructor, and therefore it's not possible to access them there.

What you can do is access the attributes after the object has been initialized:

$post = Post::find(1);
dump($post->getAttributes());

Not sure if that helps, but it is what it is.

Maybe Events or Observers can help you with what you need:
https://laravel.com/docs/5.8/eloquent#events

https://laravel.com/docs/5.8/eloquent#observers


问:
Print vertical data in horizontal way
I have a data which is in vertical form => want to print in horizontal way.

How do I write it to the text file => FILE 2?

DATA I have in FILE 1

```<code>RAM
RAJ
RAHUL
VIRAJ
</code>```

Data should be Written to the FILE 2 in this format

NAME1|NAME2|NAME3|NAME 4

```<code>RAM | RAJ | RAHUL | VIRAJ
</code>```

My code

```<code>awk 'BEGIN{FS=""}{for(i=1;i<=NF;i++)print i,$i}'
</code>```

答:
Perhaps you want paste:</p>

```<code> < input-file paste -d \| - - - - > file2
</code>```

Title: Print vertical data in horizontal way

Body:
I have a data which is in vertical form => want to print in horizontal way.

How do I write it to the text file => FILE 2?

DATA I have in FILE 1

RAM
RAJ
RAHUL
VIRAJ

Data should be Written to the FILE 2 in this format

NAME1|NAME2|NAME3|NAME 4

RAM | RAJ | RAHUL | VIRAJ

My code

awk 'BEGIN{FS=""}{for(i=1;i<=NF;i++)print i,$i}'

Body:
Perhaps you want paste:

 < input-file paste -d \| - - - - > file2


问:
How to perform multiple updates in single merge statement
I need to update multiple columns in a single merge statement with two differ conditions like
1. row_ind = N; update some columns

2. row_ind = Y; update some columns

How i will achieves this one in sqlserver / oracle

```<code>WHEN MATCHED THEN
UPDATE SET TARGET.NodeId = SOURCE.StartNodeId,
           TARGET.LinkId = SOURCE.Id where row_ind ='Y'

UPDATE SET TARGET.NodeId = SOURCE.EndNodeId,
           TARGET.LinkId = SOURCE.Id where row_ind = 'N';
</code>```

答:
For tsql  you can try using AND <clause_search_condition>

```<code>MERGE
    [ TOP ( expression ) [ PERCENT ] ]
    [ INTO ] <target_table> [ WITH ( <merge_hint> ) ] [ [ AS ] table_alias ]
    USING <table_source>
    ON <merge_search_condition>
    [ WHEN MATCHED [ AND <clause_search_condition> ]     <==
        THEN <merge_matched> ] [ ...n ]
<merge_matched>::=
     { UPDATE SET <set_clause> | DELETE }
</code>```

as you can have multiple WHEN MATCHED with different additional condition after AND you can create multiple updates using single merge statement.

```<code>WHEN MATCHED AND row_ind ='Y' THEN
UPDATE SET TARGET.NodeId = SOURCE.StartNodeId,
           TARGET.LinkId = SOURCE.Id
WHEN MATCHED AND row_ind ='N' THEN
UPDATE SET TARGET.NodeId = SOURCE.EndNodeId,
           TARGET.LinkId = SOURCE.Id ;
</code>```

in oracle you cannot do this as only one merge_update_clause is allowed

MERGE is not supported by MySQL

Body:
I need to update multiple columns in a single merge statement with two differ conditions like
1. row_ind = N; update some columns

2. row_ind = Y; update some columns

How i will achieves this one in sqlserver / oracle

WHEN MATCHED THEN
UPDATE SET TARGET.NodeId = SOURCE.StartNodeId,
           TARGET.LinkId = SOURCE.Id where row_ind ='Y'

UPDATE SET TARGET.NodeId = SOURCE.EndNodeId,
           TARGET.LinkId = SOURCE.Id where row_ind = 'N';

Body:
For tsql  you can try using AND <clause_search_condition>

MERGE
    [ TOP ( expression ) [ PERCENT ] ]
    [ INTO ] <target_table> [ WITH ( <merge_hint> ) ] [ [ AS ] table_alias ]
    USING <table_source>
    ON <merge_search_condition>
    [ WHEN MATCHED [ AND <clause_search_condition> ]     <==
        THEN <merge_matched> ] [ ...n ]
<merge_matched>::=
     { UPDATE SET <set_clause> | DELETE }

as you can have multiple WHEN MATCHED with different additional condition after AND you can create multiple updates using single merge statement.

WHEN MATCHED AND row_ind ='Y' THEN
UPDATE SET TARGET.NodeId = SOURCE.StartNodeId,
           TARGET.LinkId = SOURCE.Id
WHEN MATCHED AND row_ind ='N' THEN
UPDATE SET TARGET.NodeId = SOURCE.EndNodeId,
           TARGET.LinkId = SOURCE.Id ;

in oracle you cannot do this as only one merge_update_clause is allowed

MERGE is not supported by MySQL


问:
Is there a keyboard shortcut to maximize/minimize the output window in Xcode 4?
I'm currently trying to workaround some apparent shortcomings of cocoa touch application tests in Xcode 4 (see this related question). Since failures of application tests are not highlighted in the editor window like failures of logic tests, I find myself using the mouse to scroll through the output window to see the results of failed tests.

I would prefer to use keyboard commands if possible to quickly look at the results of the tests and then quickly move back to the editor. Are there some keyboard shortcuts in Xcode 4 for maximizing and minimizing the output window?

答:
It looks like Command+Shift+Y opens and closes the debug area, but I don't know of a keyboard shortcut to maximize it.

Here's a nice cheat sheet you can print out with lots of keyboard shortcuts.


问:
How to replace one value calculated by COUNT with another value in SELECT result?
Suppose there are two tables

```<code>shop        seller
------      -------
id          id
seller_id   seller_name
goods       sallary
</code>```

seller_id may be repeated, parts from seller.id may not be there at all. So, I need to get the result of the request consisting of saller_name and counting the number of stores on each seller. I did it like this

```<code>SELECT seller_name, COUNT(seller_id) AS shops FROM seller
LEFT JOIN shop ON seller.id = shop.seller_id GROUP BY seller_name.
</code>```

And it works. But the problem is that I need to replace all 0 in shops with the text 'none'.
I tried to do it through

```<code>REPLACE(COUNT(seller_id),0,"none")
</code>```

and with

```<code>CASE
WHEN COUNT(seller_id)=0 THEN "none"
ELSE COUNT(seller_id)
END
</code>```

But instead of the expected numbers and none, I get a random set of numbers and letters. How to do it?

答:
The problem is that 'none' is a string, but the value is a count.  I would strongly advise you to stick with numbers, but that is not your query.

You need to do type conversion:

```<code>SELECT se.seller_name,
       (CASE WHEN COUNT(s.seller_id) = 0
             THEN 'none'
             ELSE CAST(COUNT(s.seller_id) AS VARCHAR(255))
        END) AS shops
FROM seller se LEFT JOIN
     shop s
     ON se.id = sh.seller_id
GROUP BY se.seller_name;
</code>```

In MySQL, use CAST(COUNT(s.seller_id) AS CHAR).  Or almost any database supports CONCAT(COUNT(s.seller_id), ''), but using CONCAT() to convert types seems misleading to me.

Body:
Suppose there are two tables

shop        seller
------      -------
id          id
seller_id   seller_name
goods       sallary

seller_id may be repeated, parts from seller.id may not be there at all. So, I need to get the result of the request consisting of saller_name and counting the number of stores on each seller. I did it like this

SELECT seller_name, COUNT(seller_id) AS shops FROM seller
LEFT JOIN shop ON seller.id = shop.seller_id GROUP BY seller_name.

And it works. But the problem is that I need to replace all 0 in shops with the text 'none'.
I tried to do it through

REPLACE(COUNT(seller_id),0,"none")

and with

CASE
WHEN COUNT(seller_id)=0 THEN "none"
ELSE COUNT(seller_id)
END

But instead of the expected numbers and none, I get a random set of numbers and letters. How to do it?

Body:
The problem is that 'none' is a string, but the value is a count.  I would strongly advise you to stick with numbers, but that is not your query.

You need to do type conversion:

SELECT se.seller_name,
       (CASE WHEN COUNT(s.seller_id) = 0
             THEN 'none'
             ELSE CAST(COUNT(s.seller_id) AS VARCHAR(255))
        END) AS shops
FROM seller se LEFT JOIN
     shop s
     ON se.id = sh.seller_id
GROUP BY se.seller_name;

In MySQL, use CAST(COUNT(s.seller_id) AS CHAR).  Or almost any database supports CONCAT(COUNT(s.seller_id), ''), but using CONCAT() to convert types seems misleading to me.


问:
Reverse a string word by word
I am able to reverse a string. For example, I can reverse "reverse a string" to "esrever a gnirts". But I am not able to reverse it word by word like "string a reverse".</p>

```<code>void reverseString(char string[],char *start, char* end)
{

    char tmp; //temporary variable to swap values
    int count = 0;
    while(start<end)
    {
        if(*start==' ')
        {
            printf("found space count %d \n",count);
            reverseString(string,start-count,start);
        }
        tmp = *start;
        *start = *end;
        *end = tmp;
        *start++;
        *end--;
        count++;
    }

    printf(" string %s \n", string);
}

int main()
{
    char string[] = "reverse a string word by word";
    char *start =string;
    char *end =start+ strlen(string) -1;
    reverseString(string,start,end);
    return 0;
}
</code>```

答:
Reverse words in String using C#

```<code>public  string ReverseWordsInString(string inputString)
{
    string output = string.Empty;
    string[] splitStrings = inputString.Split(' ');
    for (int i = splitStrings.Length-1; i > -1 ; i--)
    {
        output = output + splitStrings[i]+ " ";
    }
    return output;
}
</code>```

Title: Reverse a string word by word

Body:
I am able to reverse a string. For example, I can reverse "reverse a string" to "esrever a gnirts". But I am not able to reverse it word by word like "string a reverse".

void reverseString(char string[],char *start, char* end)
{

    char tmp; //temporary variable to swap values
    int count = 0;
    while(start<end)
    {
        if(*start==' ')
        {
            printf("found space count %d \n",count);
            reverseString(string,start-count,start);
        }
        tmp = *start;
        *start = *end;
        *end = tmp;
        *start++;
        *end--;
        count++;
    }

    printf(" string %s \n", string);
}

int main()
{
    char string[] = "reverse a string word by word";
    char *start =string;
    char *end =start+ strlen(string) -1;
    reverseString(string,start,end);
    return 0;
}

Body:
Reverse words in String using C#

public  string ReverseWordsInString(string inputString)
{
    string output = string.Empty;
    string[] splitStrings = inputString.Split(' ');
    for (int i = splitStrings.Length-1; i > -1 ; i--)
    {
        output = output + splitStrings[i]+ " ";
    }
    return output;
}


问:
How can we count number of records and show in rest api?
controller:

```<code><?php
    require APPPATH . '/libraries/REST_Controller.php';
    use Restserver\Libraries\REST_Controller;
    class User extends REST_Controller
    {
        function country_get()
        {
            $this->db->select('id,name');
            $this->db->from('countries');
            $sql = $this->db->get();
            $result = $sql->result_array();
            $this->response($result, 200);
        }
    }
</code>```

unexpected output:

```<code>[
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]
</code>```

expected output:

```<code>{
"Message": "Number of Country found: 5",
"Status": "Success",
"Country": [
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]
</code>```

}

In this code I want to show number of records as I mention in my expected output. So, How can I do this? Please help me.

Thank You

答:
Try this, No need to use count() CI already giving you a count in num_rows()

```<code>function country_get()
{
     $this->db->select('id,name');
     $this->db->from('countries');
     $sql = $this->db->get();
     $count = $sql->num_rows();
     $result = array();
     $result['Message'] = "Number of Country found: " . $count;
     $result['Status'] = "Success";
     $result['Country'] = $sql->result_array();
     $this->response($result, 200);
}
</code>```

Body:
controller:

<?php
    require APPPATH . '/libraries/REST_Controller.php';
    use Restserver\Libraries\REST_Controller;
    class User extends REST_Controller
    {
        function country_get()
        {
            $this->db->select('id,name');
            $this->db->from('countries');
            $sql = $this->db->get();
            $result = $sql->result_array();
            $this->response($result, 200);
        }
    }

unexpected output:

[
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]

expected output:

{
"Message": "Number of Country found: 5",
"Status": "Success",
"Country": [
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]

}

In this code I want to show number of records as I mention in my expected output. So, How can I do this? Please help me.

Thank You

Body:
Try this, No need to use count() CI already giving you a count in num_rows()

function country_get()
{
     $this->db->select('id,name');
     $this->db->from('countries');
     $sql = $this->db->get();
     $count = $sql->num_rows();
     $result = array();
     $result['Message'] = "Number of Country found: " . $count;
     $result['Status'] = "Success";
     $result['Country'] = $sql->result_array();
     $this->response($result, 200);
}


问:
Why does python thread consume so much memory?
Why does python thread consumes so much memory?

I measured that spawning one thread consumes 8 megs of memory, almost as big as a whole new python process!

OS: Ubuntu 10.10

Edit: due to popular demand I'll give some extraneous examples, here it is:

```<code>from os import getpid
from time import sleep
from threading import Thread

def nap():
    print 'sleeping child'
    sleep(999999999)

print getpid()
child_thread = Thread(target=nap)
sleep(999999999)
</code>```

On my box, pmap pid will give 9424K

Now, let's run the child thread:

```<code>from os import getpid
from time import sleep
from threading import Thread

def nap():
    print 'sleeping child'
    sleep(999999999)

print getpid()
child_thread = Thread(target=nap)
child_thread.start()             # <--- ADDED THIS LINE
sleep(999999999)
</code>```

Now pmap pid will give 17620K

So, the cost for the extra thread is 17620K - 9424K = 8196K

ie. 87% of running a whole new separate process!

Now isn't that just, wrong?

答:
This is not Python-specific, and has to do with the separate stack that gets allocated by the OS for every thread. The default maximum stack size on your OS happens to be 8MB.

Note that the 8MB is simply a chunk of address space that gets set aside, with very little memory committed to it initially. Additional memory gets committed to the stack when required, up to the 8MB limit.

The limit can be tweaked using ulimit -s, but in this instance I see no reason to do this.

As an aside, pmap shows address space usage. It isn't a good way to gauge memory usage. The two concepts are quite distinct, if related.

Body:
Why does python thread consumes so much memory?

I measured that spawning one thread consumes 8 megs of memory, almost as big as a whole new python process!

OS: Ubuntu 10.10

Edit: due to popular demand I'll give some extraneous examples, here it is:

from os import getpid
from time import sleep
from threading import Thread

def nap():
    print 'sleeping child'
    sleep(999999999)

print getpid()
child_thread = Thread(target=nap)
sleep(999999999)

On my box, pmap pid will give 9424K

Now, let's run the child thread:

from os import getpid
from time import sleep
from threading import Thread

def nap():
    print 'sleeping child'
    sleep(999999999)

print getpid()
child_thread = Thread(target=nap)
child_thread.start()             # <--- ADDED THIS LINE
sleep(999999999)

Now pmap pid will give 17620K

So, the cost for the extra thread is 17620K - 9424K = 8196K

ie. 87% of running a whole new separate process!

Now isn't that just, wrong?


问:
Selecting a record with several values in two tables
In two tables there are records (colors) with different values. I want the result to show only the color that has all the same values in both tables. If any of the values are missing, it should be completely rejected.

Another example:

Bellow code should return only BLUE

```<code>WITH
t1 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('2') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL),

t2 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('3') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL)

SELECT *
FROM t1
FULL OUTER JOIN t2 ON t2.VALUESY = t1.VALUESY AND t2.COLOUR = t1.COLOUR
</code>```

答:
There are various ways you can do this, one is to perform your FULL OUTER JOIN and then GROUP BY COALESCE( t1.COLOUR, t2.COLOUR ) and count whether there are any NULL values on either side of the join; if there are then there is an unmatched value (assuming that none of the input values is NULL:

Oracle Setup:

```<code>CREATE TABLE t1 ( colour, valuesy ) as
  SELECT 'RED',  '1' FROM DUAL UNION
  SELECT 'RED',  '2' FROM DUAL UNION
  SELECT 'BLUE', '1' FROM DUAL UNION
  SELECT 'BLUE', '2' FROM DUAL

CREATE TABLE t2 ( colour, valuesy ) as
  SELECT 'RED',  '1' FROM DUAL UNION
  SELECT 'RED',  '3' FROM DUAL UNION
  SELECT 'BLUE', '1' FROM DUAL UNION
  SELECT 'BLUE', '2' FROM DUAL
</code>```

Query:

```<code>SELECT COALESCE( t1.COLOUR, t2.COLOUR ) AS COLOUR
FROM t1
     FULL OUTER JOIN t2
     ON t2.VALUESY = t1.VALUESY AND t2.COLOUR = t1.COLOUR
GROUP BY COALESCE( t1.COLOUR, t2.COLOUR )
HAVING COUNT( CASE WHEN t1.COLOUR IS NULL OR t2.COLOUR IS NULL THEN 1 END ) = 0
</code>```

Output:

```
| COLOUR |
| :----- |
| BLUE   |
```

db<>fiddle here

Body:
In two tables there are records (colors) with different values. I want the result to show only the color that has all the same values in both tables. If any of the values are missing, it should be completely rejected.

Another example:

Bellow code should return only BLUE

WITH
t1 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('2') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL),

t2 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('3') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL)

SELECT *
FROM t1
FULL OUTER JOIN t2 ON t2.VALUESY = t1.VALUESY AND t2.COLOUR = t1.COLOUR

Body:
There are various ways you can do this, one is to perform your FULL OUTER JOIN and then GROUP BY COALESCE( t1.COLOUR, t2.COLOUR ) and count whether there are any NULL values on either side of the join; if there are then there is an unmatched value (assuming that none of the input values is NULL:

Oracle Setup:

CREATE TABLE t1 ( colour, valuesy ) as
  SELECT 'RED',  '1' FROM DUAL UNION
  SELECT 'RED',  '2' FROM DUAL UNION
  SELECT 'BLUE', '1' FROM DUAL UNION
  SELECT 'BLUE', '2' FROM DUAL

CREATE TABLE t2 ( colour, valuesy ) as
  SELECT 'RED',  '1' FROM DUAL UNION
  SELECT 'RED',  '3' FROM DUAL UNION
  SELECT 'BLUE', '1' FROM DUAL UNION
  SELECT 'BLUE', '2' FROM DUAL

Query:

SELECT COALESCE( t1.COLOUR, t2.COLOUR ) AS COLOUR
FROM t1
     FULL OUTER JOIN t2
     ON t2.VALUESY = t1.VALUESY AND t2.COLOUR = t1.COLOUR
GROUP BY COALESCE( t1.COLOUR, t2.COLOUR )
HAVING COUNT( CASE WHEN t1.COLOUR IS NULL OR t2.COLOUR IS NULL THEN 1 END ) = 0

Output:

| COLOUR |
| :----- |
| BLUE   |

db<>fiddle here


问:
ASP .NET MVC 4 OutputCache not working
I am having a problem with using OutputCache attribute.

I have API which does some calculations:

```<code>    [OutputCache(Duration = 600, VaryByParam = "userId;periodTypeId;dateRange;startData;endDate;", Location = OutputCacheLocation.Any)]
    public JsonResult Calculate(int userId, int periodTypeId, string dateRange, DateTime startDate, DateTime endDate)
    {
      ...
      return Json(answer, JsonRequestBehavior.AllowGet);
    }
</code>```

and I want to cache results. But for some reason it's not working. In the response headers I always see "Cache-Control:no-cache, no-store, must-revalidate".

API is called from js with jquery ajax:

```<code>$.ajax({
    type: "GET",
    url: url,
    data: data,
    success: callback,
    error: function (xhr, ajaxOptions, thrownError) {
        ...
    },
    contentType: 'application/json'
});
</code>```

Maybe I should enable caching on app level somehow?

答: In case anyone else comes across this - if the response from the server includes a Set-Cookie header, it won't be cached.</p>

Title: ASP .NET MVC 4 OutputCache not working

Body:
I am having a problem with using OutputCache attribute.

I have API which does some calculations:

    [OutputCache(Duration = 600, VaryByParam = "userId;periodTypeId;dateRange;startData;endDate;", Location = OutputCacheLocation.Any)]
    public JsonResult Calculate(int userId, int periodTypeId, string dateRange, DateTime startDate, DateTime endDate)
    {
      ...
      return Json(answer, JsonRequestBehavior.AllowGet);
    }

and I want to cache results. But for some reason it's not working. In the response headers I always see "Cache-Control:no-cache, no-store, must-revalidate".

API is called from js with jquery ajax:

$.ajax({
    type: "GET",
    url: url,
    data: data,
    success: callback,
    error: function (xhr, ajaxOptions, thrownError) {
        ...
    },
    contentType: 'application/json'
});

Maybe I should enable caching on app level somehow?


问:
Getting dates from access to pentaho
im new in pentaho, i'm trying to receive data from an access file but i got the actual date and time not the data stored in my access file

i use the microsoft access input and the modified java script value, and when i trie to se my variables in the modified js value i see that the data from the access file is not the same, actually is the real actual date and time

var msg = "The date is .. " +Fecha_Inicio+ "."  then i click on test script

https://drive.google.com/open?id=1kDSGLhfbLlXvYVotbkeDmBelc9JjVHrTenter image description here

答:
when you test the script you don't read the data from access. It'll run 10 test rows, and will use a sample value only (which you can modify if you need to test more thoroughly).

It's mostly used to check that there are no syntax errors in your javcascript, for example.

To test the javascript code against the actual Access data, right click the javascript step and choose Preview. That will run the transformation, pause it at 1000 rows and display the data you have at that point.

Title: Getting dates from access to pentaho


问:
Get greatest rows based on multiple columns in MySQL
I have a table that looks like:

```<code>id | title | value | language
---+-------+-------+---------
1  | a     | 1800  |    NULL
2  | a     | 1900  |    NULL
3  | b     | 1700  |    NULL
4  | b     | 1750  |    NULL
5  | b     | 1790  |    1
6  | c     | 1892  |    NULL
7  | c     | 1900  |    1
8  | c     | 1910  |    2
9  | d     | 3020  |    NULL
</code>```

Would like to have the following result:

```<code>id | title | value | language
---+-------+-------+---------
2  | a     | 1900  |    NULL
4  | b     | 1750  |    NULL
5  | b     | 1790  |    1
6  | c     | 1892  |    NULL
7  | c     | 1900  |    1
8  | c     | 1910  |    2
9  | d     | 3020  |    NULL
</code>```

The point is to select the greatest value in value column of every language of every title - greatest being the latest. Secondly, would like to avoid Aggregate functions like MAX, DISTINCT or GROUP-BY as I am building a MySQL View using the MERGE algorithm, and don't want to end up creating a temporary table (See the bottom section of https://dev.mysql.com/doc/refman/5.6/en/view-algorithms.html).

So far this works, but only returns greatest row per title:

```<code>SELECT t1.title
FROM table t1
LEFT OUTER JOIN table t2
  ON t1.title = t2.title
        AND t1.value < t2.value
WHERE t2.title IS NULL
</code>```

How can I create one that takes language into account like the results above? Thanx.

答:
This answer assumes that you are using MySQL 8+, in which your query becomes very easy.  MySQL 8 and later version support analytic functions, which were added with the intention to solve problems such as this.

We can try using ROW_NUMBER here:

```<code>WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY title, language ORDER BY value DESC) rn
    FROM yourTable
)

SELECT id, title, value, language
FROM cte
WHERE rn = 1;
</code>```

Demo

There is a way to handle this with earlier versions of MySQL, but it requires user variables, and tends to be very ugly.  So maybe consider upgrading if you expect to have many queries similar to this one.

Body:
I have a table that looks like:

id | title | value | language
---+-------+-------+---------
1  | a     | 1800  |    NULL
2  | a     | 1900  |    NULL
3  | b     | 1700  |    NULL
4  | b     | 1750  |    NULL
5  | b     | 1790  |    1
6  | c     | 1892  |    NULL
7  | c     | 1900  |    1
8  | c     | 1910  |    2
9  | d     | 3020  |    NULL

Would like to have the following result:

id | title | value | language
---+-------+-------+---------
2  | a     | 1900  |    NULL
4  | b     | 1750  |    NULL
5  | b     | 1790  |    1
6  | c     | 1892  |    NULL
7  | c     | 1900  |    1
8  | c     | 1910  |    2
9  | d     | 3020  |    NULL

The point is to select the greatest value in value column of every language of every title - greatest being the latest. Secondly, would like to avoid Aggregate functions like MAX, DISTINCT or GROUP-BY as I am building a MySQL View using the MERGE algorithm, and don't want to end up creating a temporary table (See the bottom section of https://dev.mysql.com/doc/refman/5.6/en/view-algorithms.html).

So far this works, but only returns greatest row per title:

SELECT t1.title
FROM table t1
LEFT OUTER JOIN table t2
  ON t1.title = t2.title
        AND t1.value < t2.value
WHERE t2.title IS NULL

How can I create one that takes language into account like the results above? Thanx.

Body:
This answer assumes that you are using MySQL 8+, in which your query becomes very easy.  MySQL 8 and later version support analytic functions, which were added with the intention to solve problems such as this.

We can try using ROW_NUMBER here:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY title, language ORDER BY value DESC) rn
    FROM yourTable
)

SELECT id, title, value, language
FROM cte
WHERE rn = 1;

Demo

There is a way to handle this with earlier versions of MySQL, but it requires user variables, and tends to be very ugly.  So maybe consider upgrading if you expect to have many queries similar to this one.


问:
pthread without static decelaration with class
Inside the class I declared the thread function. I used static keyword because with out static keyword it is not working with class.

But if the type of the function is static I could not able to access the member function and public variables of the class

```<code>#include <iostream>
#include <pthread.h>
using namespace std;

class Base{

private:
    static  void * fpga_read(void*); // Thread function
    void foo_2();
public:
    /* member variables */
    void foo(void);

protected:
    int b;
};

void Base::foo(void)
{
    pthread_t id;
    pthread_create(&id, NULL,fpga_read,NULL);
    cout << "\nInside base class" << endl;
}
void * Base::fpga_read(void *p)
{
    cout << "\nInside thread function " << endl;
    // error: invalid use of member ‘Base::b’ in static member function
    cout << "Value of B inside thread class" << b;

    int b;
}

int main()
{
    Base a;
    a.foo();

    pthread_exit(NULL);
    return 0;
}
</code>```

Any-body tell me how to use thread function with-out static keyword. so i can able to access all class variables.

答:
pthread_create, like all OS-specific thread creation APIs (CreateThread etc in Windows) has a "void*" parameter to pass to the thread function.

You can use this to pass a pointer to your class

```<code>class A
{
    void ThreadToUse() {}
    static void Thread2(void* p)
    {
        A* a = (A*)p;
        p->ThreadToUse();
    }

    void foo()
    {
        pthread_create(&A::Thread2,(void*)this);
    }
};
</code>```

That said, you can use C++11 std::thread with the same functionality as well in a standard way:

```<code>void foo()
{
    std::thread t(&A::Thread2,this);
}
</code>```

Body:
Inside the class I declared the thread function. I used static keyword because with out static keyword it is not working with class.

But if the type of the function is static I could not able to access the member function and public variables of the class

#include <iostream>
#include <pthread.h>
using namespace std;

class Base{

private:
    static  void * fpga_read(void*); // Thread function
    void foo_2();
public:
    /* member variables */
    void foo(void);

protected:
    int b;
};

void Base::foo(void)
{
    pthread_t id;
    pthread_create(&id, NULL,fpga_read,NULL);
    cout << "\nInside base class" << endl;
}
void * Base::fpga_read(void *p)
{
    cout << "\nInside thread function " << endl;
    // error: invalid use of member ‘Base::b’ in static member function
    cout << "Value of B inside thread class" << b;

    int b;
}

int main()
{
    Base a;
    a.foo();

    pthread_exit(NULL);
    return 0;
}

Any-body tell me how to use thread function with-out static keyword. so i can able to access all class variables.

Body:
pthread_create, like all OS-specific thread creation APIs (CreateThread etc in Windows) has a "void*" parameter to pass to the thread function.

You can use this to pass a pointer to your class

class A
{
    void ThreadToUse() {}
    static void Thread2(void* p)
    {
        A* a = (A*)p;
        p->ThreadToUse();
    }

    void foo()
    {
        pthread_create(&A::Thread2,(void*)this);
    }
};

That said, you can use C++11 std::thread with the same functionality as well in a standard way:

void foo()
{
    std::thread t(&A::Thread2,this);
}


问:
How can I find out if an ES6 value is var / const / let after it is declared?
I know I can find out if a value is var const or let by looking at where it is declared. However I am wondering - mainly for debugging, developing JS compilers, and academic interest - if it is possible to find out the immutability / scope of a variable (var / const / let-ness) after it has been created.

ie

```<code>doThing(something)
</code>```

Would return

```<code>let
</code>```

Or equivalent. Like we can determine types with typeof or something.constructor.name for constructors.

答: You can't directly access the environment record chain in any way, and therefore you can't tell were a variable was declared. The with statement might enable you to narrow down the scope were a variable was declared as it allows you to add a Proxy as an environment record, but that only gives some insight and it is generally a very dangerous thing to do.

Body:
I know I can find out if a value is var const or let by looking at where it is declared. However I am wondering - mainly for debugging, developing JS compilers, and academic interest - if it is possible to find out the immutability / scope of a variable (var / const / let-ness) after it has been created.

ie

doThing(something)

Would return

let

Or equivalent. Like we can determine types with typeof or something.constructor.name for constructors.


问:
how to display progress of service in android
In my android application, I am using the tab view and so I have two tabs: parameters and results.

the user enters the various parameters on the first tab and then switches to the second tab to view the results.

i have a service that performs some long-running calculations.  the user enters parameters on the first tab and hits 'calculate'.  They can make adjustments and hit 'recalculate' and the service is updated with the new parameters.

As these calculations progress, I want the user to be able to switch to the results tab to view the results of the latest calculation.  They would then view the results and be able to switch back to the parameters tab to make adjustments.

I can think of two approaches:

-register the 'results tab' with the service and when the service reaches a milestone, it calls directly to the 'results tab'.

-have a timer running in the 'results tab' and have it query against the bound service on a regular interval and update accordingly.

Do people have comments or recommendations for these two approaches?

答:
Using broadcast Receiver

```<code>public class Detail extends GDActivity {

    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(DownloadService.CUSTOM_INTENT)) {
                mProgressDialog.setProgress(intent.getFlags());
            }
        }
    };

    // Flag if receiver is registered
    private boolean mReceiversRegistered = false;
    // Define a handler and a broadcast receiver
    private final Handler mHandler = new Handler();

    @Override
    protected void onResume() {
      super.onResume();

      // Register Sync Recievers
      IntentFilter intentToReceiveFilter = new IntentFilter();
      intentToReceiveFilter.addAction(DownloadService.CUSTOM_INTENT);
      this.registerReceiver(mIntentReceiver, intentToReceiveFilter, null, mHandler);
      mReceiversRegistered = true;
    }

    @Override
    public void onPause() {
      super.onPause();

      // Make sure you unregister your receivers when you pause your activity
      if(mReceiversRegistered) {
        unregisterReceiver(mIntentReceiver);
        mReceiversRegistered = false;
      }
    }
}
}
</code>```

and the Sender

```<code>  @Override
    protected void onProgressUpdate(Integer... progress) {
        Intent i = new Intent();
        i.setAction(CUSTOM_INTENT);
        i.setFlags(progress[0]);
        ctx.sendBroadcast(i);
    }
</code>```

Body:
Using broadcast Receiver

public class Detail extends GDActivity {

    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(DownloadService.CUSTOM_INTENT)) {
                mProgressDialog.setProgress(intent.getFlags());
            }
        }
    };

    // Flag if receiver is registered
    private boolean mReceiversRegistered = false;
    // Define a handler and a broadcast receiver
    private final Handler mHandler = new Handler();

    @Override
    protected void onResume() {
      super.onResume();

      // Register Sync Recievers
      IntentFilter intentToReceiveFilter = new IntentFilter();
      intentToReceiveFilter.addAction(DownloadService.CUSTOM_INTENT);
      this.registerReceiver(mIntentReceiver, intentToReceiveFilter, null, mHandler);
      mReceiversRegistered = true;
    }

    @Override
    public void onPause() {
      super.onPause();

      // Make sure you unregister your receivers when you pause your activity
      if(mReceiversRegistered) {
        unregisterReceiver(mIntentReceiver);
        mReceiversRegistered = false;
      }
    }
}
}

and the Sender

  @Override
    protected void onProgressUpdate(Integer... progress) {
        Intent i = new Intent();
        i.setAction(CUSTOM_INTENT);
        i.setFlags(progress[0]);
        ctx.sendBroadcast(i);
    }


答: let and var are only about the scope, so it's not possible. Because JavaScript does not pass by reference, if you were to pass a variable to a function you would lose the " constness" and also the scope - on that function the variable would just be a locally scoped one. So my thoughts are: it's not possible.</p>

Title: How can I find out if an ES6 value is var / const / let after it is declared?


问:
BigQuery Querying Events Table
Objective : To take the users count which has event_name= 'Wallet'

Problem : I have limited the query's result to 100 to check so the expected result must be 100 but when I use count(params.value.string_value) it shows 124 .

Code : SELECT count(params.value.string_value) FROM "myproj.analytics_197163127.events_20190528",UNNEST(event_params) as params where event_name ='Wallet' and params.key = 'UserId' limit 100

Expected Result : if the query is returning 100 records the count should be 100 but how is it showing 124?

Hope the question is clear

答:
The query shows 100 records because of the limit 100 at the end:

```<code>SELECT event_date,event_timestamp,event_name, params.value.string_value
FROM myproj.analytics_197163127.events_20190528, UNNEST(event_params) as params
where event_name ='Wallet' and params.key = 'UserId'
limit 100
</code>```

Remove that and check again.

The LIMIT 100 specifies the number of rows to be returned from the SQL statement. It does not influence the COUNT() in your query. So there is a difference between :

```<code>select count(*) from table limit 100
</code>```

this will return a single value with the number of rows in the table. On the other hand :

```<code>select count(*) from (select * from table limit 100)
</code>```

This will return 100 (if the table has more than 100 rows - otherwise it will return the number of rows in table)

Title: BigQuery Querying Events Table

Body:
The query shows 100 records because of the limit 100 at the end:

SELECT event_date,event_timestamp,event_name, params.value.string_value
FROM myproj.analytics_197163127.events_20190528, UNNEST(event_params) as params
where event_name ='Wallet' and params.key = 'UserId'
limit 100

Remove that and check again.

The LIMIT 100 specifies the number of rows to be returned from the SQL statement. It does not influence the COUNT() in your query. So there is a difference between :

select count(*) from table limit 100

this will return a single value with the number of rows in the table. On the other hand :

select count(*) from (select * from table limit 100)

This will return 100 (if the table has more than 100 rows - otherwise it will return the number of rows in table)


问:
How to inject value to path variable of a web service call URL in Angular?
I want to call this backend URL to receive user profile data

```<code>/users/:userId/profile
</code>```

where :userId will be an actual number for the ID.

What is the syntax to inject the userId value to the URL before sending the request?

答:
One way ( using typescript ) is to use a template string

```<code>`/users/${this.userId}/profile`
</code>```

The template is surrounded by the backticks ( `` ).

The string inside the backticks can evaluate expressions when they're inside a ${...}.

The string above is the same as typing:

```<code>'/users/' + this.userId + '/profile'
</code>```

Body:
I want to call this backend URL to receive user profile data

/users/:userId/profile

where :userId will be an actual number for the ID.

What is the syntax to inject the userId value to the URL before sending the request?

Body:
One way ( using typescript ) is to use a template string

`/users/${this.userId}/profile`

The template is surrounded by the backticks ( `` ).

The string inside the backticks can evaluate expressions when they're inside a ${...}.

The string above is the same as typing:

'/users/' + this.userId + '/profile'


问:
Extracing elements from a nested list based on elements of another nested list
I have two nested lists - one containing userids and their individual location and the second nested list containing product first element and list of userid who have purchased the products. I need to find the unique locations of purchasers for each product.

I am able to get the results by using nested for loops. However, i wanted to the same by list comprehension. i don't want to use dataframes or sql commands.

```<code>users=([1,'MX'],[2,'EN'],[3,'US'],[4,'FR'],[5,'US'],[6,'EN'],[7,'MX'])

    prod=[
        (1005,[5]),
        (1004,[2,4,1]),
        (1003,[3,5]),
        (1002,[7,5,2]),
        (1001,[6,5,1])
        ]
    for p in prod:
        prod_loc=[]
        for u in p[1]:
          for uloc in users:

            if u==uloc[0]:
                if uloc[1] not in prod_loc:
                    prod_loc.append(uloc[1])

            else:
                continue
        print (p[0],prod_loc)

</code>```

答:
[(e[0], list(set(dict(users)[r] for r in e[1]))) for e in prod]

Explained:

```<code>[
    ( # Tuple
        e[0], # Prod name
        list( # Convert to list
            set( # Set of unique elements
                dict(users)[r] # Get region of user
                for r in e[1] # For each user in the list of prod
            )
        )
    )
    for e in prod # For each prod
]
</code>```

Result:

```<code>[(1005, ['US']),
 (1004, ['MX', 'EN', 'FR']),
 (1003, ['US']),
 (1002, ['MX', 'EN', 'US']),
 (1001, ['US', 'EN', 'MX'])]
</code>```

P.S. It can be better to move dict(users) to another variable.

Body:
I have two nested lists - one containing userids and their individual location and the second nested list containing product first element and list of userid who have purchased the products. I need to find the unique locations of purchasers for each product.

I am able to get the results by using nested for loops. However, i wanted to the same by list comprehension. i don't want to use dataframes or sql commands.

users=([1,'MX'],[2,'EN'],[3,'US'],[4,'FR'],[5,'US'],[6,'EN'],[7,'MX'])

    prod=[
        (1005,[5]),
        (1004,[2,4,1]),
        (1003,[3,5]),
        (1002,[7,5,2]),
        (1001,[6,5,1])
        ]
    for p in prod:
        prod_loc=[]
        for u in p[1]:
          for uloc in users:

            if u==uloc[0]:
                if uloc[1] not in prod_loc:
                    prod_loc.append(uloc[1])

            else:
                continue
        print (p[0],prod_loc)

Body:
[(e[0], list(set(dict(users)[r] for r in e[1]))) for e in prod]

Explained:

[
    ( # Tuple
        e[0], # Prod name
        list( # Convert to list
            set( # Set of unique elements
                dict(users)[r] # Get region of user
                for r in e[1] # For each user in the list of prod
            )
        )
    )
    for e in prod # For each prod
]

Result:

[(1005, ['US']),
 (1004, ['MX', 'EN', 'FR']),
 (1003, ['US']),
 (1002, ['MX', 'EN', 'US']),
 (1001, ['US', 'EN', 'MX'])]

P.S. It can be better to move dict(users) to another variable.


问:
My mailbox was received. But I don't know how to get the patch in the mailbox, because the content of the mailbox is only text
After I generated the patch, $ git send-email --to a1105773737@gmail.com ~/patches/*.patch sent the patch. My mailbox was received. But I don't know how to get the patch in the mailbox, because the content of the mailbox is only text.

Please take a look at the picture, I open the mailbox, I can only see a bunch of text, how should I merge the mailbox patch?

I feel the need to send the patch file to the mailbox, and then download the patch file, but I don't know how to send the file to the mailbox.

答:
I open the mailbox, I can only see a bunch of text,

That is expected: those patches follow a diff format.

To apply those patch, save then content of the email and use git apply.

Or, as recommended here, copy paste the content of the email into git am interractive step.


问:
webpack live hot reload for sass
I am building a workflow for a react starter and would like to have my browser auto reload when I make a change to my scss files.

Currently, webpack will hot reload when I make a change in my index.js file (set as my entry point).  However when I change/add scss code in my scss file, it gets compiled, but the css doesn't get output anywhere and does not trigger a browser reload.

I am new to webpack would really appreciate some insight here.

Here is my webpack.config.js

```<code>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: ['./src/js/index.js', './src/scss/style.scss'],
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'js/index_bundle.js',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader'
                }
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.scss$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].css',
                            outputPath: 'css/'
                        }
                    },
                    {
                        loader: 'extract-loader'
                    },
                    {
                        loader: 'css-loader'
                    },
                    {
                        loader: 'postcss-loader'
                    },
                    {
                        loader: 'sass-loader'
                    }
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'
        })
    ]
}
</code>```

My index.js entry point file

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from '../components/App';

ReactDOM.render(
    <App/>,
    document.getElementById('App')
);
</code>```

And my App component

```<code>import React, {Component} from 'react';
import '../../dist/css/style.css';

class App extends Component {
    render() {
        return (
            <div>
                <p>Test</p>
            </div>
        )
    }
}

export default App;
</code>```

答:
Try using Parcel instead of Webpack. I used to spend hours configuring Webpack to get things like hot reload working. With Parcel, most things just "work" without a configuration file. For example, I wanted to start using Pug templates. Parcel recognized the .pug extension and automatically downloaded the required NPM dependencies!

In your case, just include the SCSS file in your app like this: import '../scss/style.scss' (notice the path is to the .scss source file relative to index.js). Parcel will automatically do the "sensible" thing.

Here are some references to get started with Parcel + React + SASS:

Build a React web app with Parcel.js lightning fast

Parcel SCSS documentation

Notable advantages and disadvantages of Parcel vs WebPack:

Parcel requires minimal configuration; often no configuration.

Parcel usually builds much faster than WebPack.

The WebPack dev server seems more stable. (The Parcel dev server needs to restarted once in a while and doesn't play nice with Dropbox. Apparently this should be fixed in version 2.0.)

When (an uncommon) configuration is required, it might not be obvious how to do that in Parcel; at least in WebPack, all the configuration is in one place.

Sometimes Parcel's automatic configuration does thing people don't expect, confusing them.

Title: webpack live hot reload for sass

Body:
I am building a workflow for a react starter and would like to have my browser auto reload when I make a change to my scss files.

Currently, webpack will hot reload when I make a change in my index.js file (set as my entry point).  However when I change/add scss code in my scss file, it gets compiled, but the css doesn't get output anywhere and does not trigger a browser reload.

I am new to webpack would really appreciate some insight here.

Here is my webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: ['./src/js/index.js', './src/scss/style.scss'],
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'js/index_bundle.js',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader'
                }
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.scss$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].css',
                            outputPath: 'css/'
                        }
                    },
                    {
                        loader: 'extract-loader'
                    },
                    {
                        loader: 'css-loader'
                    },
                    {
                        loader: 'postcss-loader'
                    },
                    {
                        loader: 'sass-loader'
                    }
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'
        })
    ]
}

My index.js entry point file

import React from 'react';
import ReactDOM from 'react-dom';
import App from '../components/App';

ReactDOM.render(
    <App/>,
    document.getElementById('App')
);

And my App component

import React, {Component} from 'react';
import '../../dist/css/style.css';

class App extends Component {
    render() {
        return (

Test

        )
    }
}

export default App;