问:
Page shared DataTrigger style converter cannot be found with StaticResource
I am trying to learn some WPF in my free time, and I have gotten an application up and running, but one of the things that has eluded me for a while is how to set up a style for several datagrids that can appear on the pages, based on the row's value for a column which they will all share.

The intent is that I can style an entire row's text color (Foreground property) based on whether a currency amount is positive or negative.

What I have been able to get to so far works for single pair of hardcoded values, the issue I am having is wiring up to a Converter that will do the comparison I want in order to return True/False...

This is what I have so far:

```<code><DataGrid AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Width="*" Binding="{Binding Date}" Header="Date"/>
        <DataGridTextColumn Width="*" Binding="{Binding Category}" Header="Category"/>
        <DataGridTextColumn Width="*" Binding="{Binding Amount}" Header="Amount"/>
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

The specific Page I am trying to set up will have this same type of grid 3 different times, with different permutations of the data. The grids themselves are all working as desired.

The datagrid is populated with a collection of this class:

```<code>public class TransactionDto
{
    public long Id { get; set; }
    public decimal Amount { get; set; }
    public string Category { get; set; }
    public DateTime Date { get; set; }
}
</code>```

The converter I have set up is as follows:

```<code>public class AmountConverter : IValueConverter
{
    private const decimal Threshold = 0.00m;
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (decimal)value >= Threshold;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

However, I cannot seem to get the binding between the datagrid's columns and this converter figured out. This is what I have tried so far, based on experimenting with answers posted on other SO questions and elsewhere, but those have not been quite the same situation and attempting to apply it for my situation has not worked yet - I am getting an exception due to the converter binding here:

```<code><Page.Resources>
<Style TargetType="DataGridRow">
    <Style.Triggers >
        <DataTrigger Binding="{Binding Amount, RelativeSource={RelativeSource Self}, Converter={StaticResource ResourceKey=AmountConverter}}" Value="False">
            <Setter Property="Foreground" Value="Red"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding Amount}" Value="-24.71">
            <Setter Property="Foreground" Value="Green"/>
        </DataTrigger>
    </Style.Triggers>
</Style>
</code>```

The trigger that uses the hardcoded value of -24.71 works fine, as did a similar one for a positive value.

The code-behind C# file contains a property with the desired Converter type:

public AmountConverter AmountConverter { get; set; } = new AmountConverter();

The current exception I am getting is the following:

System.Windows.Markup.XamlParseException

Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception.

I don't really understand this exception and am not quite sure how to proceed or what it is telling me is the issue.

Ideally, I would set up this styling stuff in App.xaml, and reference it from the datagrids it is relevant to.

答:
It seems to me your approach is a bit complicated using 2 Triggers to make green or read. Your converter could as well return the color and you don't need the triggers.

```<code>class AmountConverter: IValueConverter {
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
    if (value is int) {
      int quantity = (int)value;
      if (quantity>=100) return Brushes.White;
      if (quantity>=10) return Brushes.WhiteSmoke;
      if (quantity>=0) return Brushes.LightGray;
      return Brushes.White; //quantity should not be below 0
    }
    //value is not an integer. Do not throw an exception
    // in the converter, but return something that is obviously wrong
    return Brushes.Yellow;
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
    throw new NotImplementedException();
   }
}
</code>```

Formating a WPF datagrid is notoriously difficult and the Microsoft documentation doesn't tell you how to do it. To get a good understanding how the different parts of a datagrid can easily be formatted, read my article CodeProject: Guide to WPF DataGrid formatting using bindings

Body:
I am trying to learn some WPF in my free time, and I have gotten an application up and running, but one of the things that has eluded me for a while is how to set up a style for several datagrids that can appear on the pages, based on the row's value for a column which they will all share.

The intent is that I can style an entire row's text color (Foreground property) based on whether a currency amount is positive or negative.

What I have been able to get to so far works for single pair of hardcoded values, the issue I am having is wiring up to a Converter that will do the comparison I want in order to return True/False...

This is what I have so far:

<DataGrid AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Width="*" Binding="{Binding Date}" Header="Date"/>
        <DataGridTextColumn Width="*" Binding="{Binding Category}" Header="Category"/>
        <DataGridTextColumn Width="*" Binding="{Binding Amount}" Header="Amount"/>
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

The specific Page I am trying to set up will have this same type of grid 3 different times, with different permutations of the data. The grids themselves are all working as desired.

The datagrid is populated with a collection of this class:

public class TransactionDto
{
    public long Id { get; set; }
    public decimal Amount { get; set; }
    public string Category { get; set; }
    public DateTime Date { get; set; }
}

The converter I have set up is as follows:

public class AmountConverter : IValueConverter
{
    private const decimal Threshold = 0.00m;
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (decimal)value >= Threshold;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

However, I cannot seem to get the binding between the datagrid's columns and this converter figured out. This is what I have tried so far, based on experimenting with answers posted on other SO questions and elsewhere, but those have not been quite the same situation and attempting to apply it for my situation has not worked yet - I am getting an exception due to the converter binding here:

<Page.Resources>

</Style>

The trigger that uses the hardcoded value of -24.71 works fine, as did a similar one for a positive value.

The code-behind C# file contains a property with the desired Converter type:

public AmountConverter AmountConverter { get; set; } = new AmountConverter();

The current exception I am getting is the following:

System.Windows.Markup.XamlParseException

Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception.

I don't really understand this exception and am not quite sure how to proceed or what it is telling me is the issue.

Ideally, I would set up this styling stuff in App.xaml, and reference it from the datagrids it is relevant to.

Body:
It seems to me your approach is a bit complicated using 2 Triggers to make green or read. Your converter could as well return the color and you don't need the triggers.

class AmountConverter: IValueConverter {
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
    if (value is int) {
      int quantity = (int)value;
      if (quantity>=100) return Brushes.White;
      if (quantity>=10) return Brushes.WhiteSmoke;
      if (quantity>=0) return Brushes.LightGray;
      return Brushes.White; //quantity should not be below 0
    }
    //value is not an integer. Do not throw an exception
    // in the converter, but return something that is obviously wrong
    return Brushes.Yellow;
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
    throw new NotImplementedException();
   }
}

Formating a WPF datagrid is notoriously difficult and the Microsoft documentation doesn't tell you how to do it. To get a good understanding how the different parts of a datagrid can easily be formatted, read my article CodeProject: Guide to WPF DataGrid formatting using bindings


来源: stackexchange

问:
Extracting values of nested objects in JSON
Updated question, with full code in relevant places:

```<code>var app=express()

app.get('/api/imagesearch/:topic',function(req,res){
    var topic=req.params.topic
    var offset=req.query.offset

    var opts = {
        host: 'www.googleapis.com',
        path: '/myapi'
        // The result of calling this URL below
        };

    https.get(opts,function(resp){
          resp.pipe(bl(function(err,data){
          if(err) throw err
          // data is a buffer
          var myString=data.toString() // string
          var myData=JSON.parse(data.toString()) // object
          var myArray=myData.items // array

          var result=[]
          myArray.forEach(function(element){
            result.push({"url":element.pagemap.cse_image[0].src,
                         "snippet":element.snippet,
                     "thumbnail":element.pagemap.cse_thumbnail[0].src,
                        "context":element.link})

          })

              res.end(JSON.stringify(result))

    }))

  })
</code>```

})

Result of calling the URL https://www.googleapis.com/myapi

```<code>var myData={"items":[
   {
      "snippet": "string",
      "link": "string",
      "pagemap": {
               "cse_image":[{
                             "src":"value" }],

               "cse_thumbnail":[{
                             "src":"value"}]

              }

    },
    {
      "snippet": "string",
      "link": "string",
      "pagemap": {
               "cse_image":[{
                             "src":"value" }],

               "cse_thumbnail":[{
                             "src":"value"}]

              }

    },...]}
</code>```

The request is:

```<code>https://www.myweb.com/api/imagesearch/cat?offset=1
</code>```

The point is that the call of the first key in myArray.forEach (element.snippet,element.link,element.pagemap) return correctly the desired array. The problem when calling the nested keys: element.pagemap.cse_image, element.pagemap.cse_thumbnail return TypeError:cannot read property  'cse_image' of undefined

答:
You don't need to use JSON.parse(). myData is already a JSON object and not a String.

Array.each() is not a standard JS function. Use forEach() instead. Are you using a library?

UPDATE: I've created the following JsFiddle for you. Check the console for the output.

ContentLicense: CC BY-SA 3.0

Body:
Updated question, with full code in relevant places:

var app=express()

app.get('/api/imagesearch/:topic',function(req,res){
    var topic=req.params.topic
    var offset=req.query.offset

    var opts = {
        host: 'www.googleapis.com',
        path: '/myapi'
        // The result of calling this URL below
        };

    https.get(opts,function(resp){
          resp.pipe(bl(function(err,data){
          if(err) throw err
          // data is a buffer
          var myString=data.toString() // string
          var myData=JSON.parse(data.toString()) // object
          var myArray=myData.items // array

          var result=[]
          myArray.forEach(function(element){
            result.push({"url":element.pagemap.cse_image[0].src,
                         "snippet":element.snippet,
                     "thumbnail":element.pagemap.cse_thumbnail[0].src,
                        "context":element.link})

          })

              res.end(JSON.stringify(result))

    }))

  })

})

Result of calling the URL https://www.googleapis.com/myapi

var myData={"items":[
   {
      "snippet": "string",
      "link": "string",
      "pagemap": {
               "cse_image":[{
                             "src":"value" }],

               "cse_thumbnail":[{
                             "src":"value"}]

              }

    },
    {
      "snippet": "string",
      "link": "string",
      "pagemap": {
               "cse_image":[{
                             "src":"value" }],

               "cse_thumbnail":[{
                             "src":"value"}]

              }

    },...]}

The request is:

https://www.myweb.com/api/imagesearch/cat?offset=1

The point is that the call of the first key in myArray.forEach (element.snippet,element.link,element.pagemap) return correctly the desired array. The problem when calling the nested keys: element.pagemap.cse_image, element.pagemap.cse_thumbnail return TypeError:cannot read property  'cse_image' of undefined


问:
Call TextToSpeech Activity Without Any UI Display
What is the recommended way to call TextToSpeech without invoking any UI change? The examples given are all bound to Activities, and the default behavior for an activity is to display its own UI.

I'm trying to call a TextToSpeechActivity via my main activity via an Intent. I don't want the UI to change at all. I want the TextToSpeech to sound without anything in the UI changing. Here's what I have so far.

```<code> public class MyActivity extends Activity {

    public void onClick(View v) {
       Intent intent = new Intent(this, TextToSpeechActivity.class);
       startActivity(intent);
    }

    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
    }
}
</code>```

Every time I click, the main UI is replaced with the UI for the TextToSpeech activity. And no, I don't want the main Activity to implement TextToSpeech.OnInitListener. There's already enough code in main. It's messy enough already.

答:
You don't need to start a new activity. The hairy thing with TTS is that you need to have some initialization done before you can use it. And doing that e.g. within onClick() does not work at all.
I've implemented that in Zwitscher:
https://github.com/pilhuhn/ZwitscherA/blob/master/src/de/bsd/zwitscher/OneTweetActivity.java#L317
speak() is called from a button on the UI, and the initialization needed is called from within onCreate(): https://github.com/pilhuhn/ZwitscherA/blob/master/src/de/bsd/zwitscher/OneTweetActivity.java#L62
And don't forget to shut down the TTS system if no longer needed:
https://github.com/pilhuhn/ZwitscherA/blob/master/src/de/bsd/zwitscher/OneTweetActivity.java#L394

HTH ( and let me know if there is a better solution)

Body:
What is the recommended way to call TextToSpeech without invoking any UI change? The examples given are all bound to Activities, and the default behavior for an activity is to display its own UI.

I'm trying to call a TextToSpeechActivity via my main activity via an Intent. I don't want the UI to change at all. I want the TextToSpeech to sound without anything in the UI changing. Here's what I have so far.

 public class MyActivity extends Activity {

    public void onClick(View v) {
       Intent intent = new Intent(this, TextToSpeechActivity.class);
       startActivity(intent);
    }

    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
    }
}

Every time I click, the main UI is replaced with the UI for the TextToSpeech activity. And no, I don't want the main Activity to implement TextToSpeech.OnInitListener. There's already enough code in main. It's messy enough already.

ContentLicense: CC BY-SA 2.5


问:
AWK Counting - Weird Behaviour
I Have a csv which contains below format

Field 1, Field 2, Success Count, Failure Count

I wrote a awk script to count the sum of Success count and Failure count of Field 2 values. This script seems to work fine. But suddenly it acts strange.
It adds 2 before even start counting. So the result will be two more greater than actual. Below is my script.

```<code>sed 's/\r//' FileName.csv | grep 'HTTP Requests - POST' | awk -F "," '{failure += $3; success += $4} END {print "HTTP Requests - POST,  Failure : " failure " Success : "success " Total : " success+failure;}'
</code>```

Then I added success to print on execution.
It prints below.

2

9

27

```<code>sed 's/\r//' FileName.csv | grep 'HTTP Requests - POST' | awk -F "," '{failure += $3; success += $4; print success;} END {print "HTTP Requests - POST,  Failure : " failure " Success : "success " Total : " success+failure;}'
</code>```

Can anyone help ?

CSV is looks like below.

```<code>OPERATOR,HTTP_METHOD,SUCCESS_COUNT,FAILURE_COUNT
CELL_01,HTTP Requests - POST,10,19
CELL_03,HTTP Requests - GET,12,17
CELL_04,HTTP Requests - POST,1,15
CELL_05,HTTP Requests - PUT,16,14
CELL_01,HTTP Requests - DELETE,19,13
CELL_03,HTTP Requests - POST,17,12
CELL_05,HTTP Requests - PUT,11,13
</code>```

sed was used to remove windows line breaks and replace them with linux line breaks.

Grep was used to filter only POST Requests.

According to @glenn's answer below I tried this.
See output below

```<code>awk -F "," '/\/GET/ { sub(/\r$/,""); failure += $3; success += $4; print failure; print success; print ""; } END  {print "HTTP Requests - POST,  Failure : " failure " Success : "success " Total : " success+failure}' Sandbox.csv
0
2

0
9

0
27
</code>```

Expected Output
HTTP Requests - POST, Failure : 0 Success :25 Total : 25

答:
You don't need sed and grep when using awk:

```<code>awk -F "," '
    /POST/ {
        sub(/\r$/,"")
        failure += $3
        success += $4
        print success
    }
    END {print "HTTP Requests - POST,  Failure : " failure " Success : "success " Total : " success+failure}
' FileName.csv
</code>```

Also, it appears that column 3 is success and column 4 is failure, yet you have the variables reversed in your code. Could that account for the strange behaviour?

Title: AWK Counting - Weird Behaviour

Body:
I Have a csv which contains below format

Field 1, Field 2, Success Count, Failure Count

I wrote a awk script to count the sum of Success count and Failure count of Field 2 values. This script seems to work fine. But suddenly it acts strange.
It adds 2 before even start counting. So the result will be two more greater than actual. Below is my script.

sed 's/\r//' FileName.csv | grep 'HTTP Requests - POST' | awk -F "," '{failure += $3; success += $4} END {print "HTTP Requests - POST,  Failure : " failure " Success : "success " Total : " success+failure;}'

Then I added success to print on execution.
It prints below.

2

9

27

sed 's/\r//' FileName.csv | grep 'HTTP Requests - POST' | awk -F "," '{failure += $3; success += $4; print success;} END {print "HTTP Requests - POST,  Failure : " failure " Success : "success " Total : " success+failure;}'

Can anyone help ?

CSV is looks like below.

OPERATOR,HTTP_METHOD,SUCCESS_COUNT,FAILURE_COUNT
CELL_01,HTTP Requests - POST,10,19
CELL_03,HTTP Requests - GET,12,17
CELL_04,HTTP Requests - POST,1,15
CELL_05,HTTP Requests - PUT,16,14
CELL_01,HTTP Requests - DELETE,19,13
CELL_03,HTTP Requests - POST,17,12
CELL_05,HTTP Requests - PUT,11,13

sed was used to remove windows line breaks and replace them with linux line breaks.

Grep was used to filter only POST Requests.

According to @glenn's answer below I tried this.
See output below

awk -F "," '/\/GET/ { sub(/\r$/,""); failure += $3; success += $4; print failure; print success; print ""; } END  {print "HTTP Requests - POST,  Failure : " failure " Success : "success " Total : " success+failure}' Sandbox.csv
0
2

0
9

0
27

Expected Output
HTTP Requests - POST, Failure : 0 Success :25 Total : 25

Body:
You don't need sed and grep when using awk:

awk -F "," '
    /POST/ {
        sub(/\r$/,"")
        failure += $3
        success += $4
        print success
    }
    END {print "HTTP Requests - POST,  Failure : " failure " Success : "success " Total : " success+failure}
' FileName.csv

Also, it appears that column 3 is success and column 4 is failure, yet you have the variables reversed in your code. Could that account for the strange behaviour?


问:
SCNNode Disobeying Position after Placement
I'm using Apples SceneKit and have a custom .dae asset. I've converted the asset to a .scn file. I am grabbing the SCNNode by name from the .scn file. After placing the SCNNode in my SCNView scene as a child node and setting it's position to be SCNVector3(0,0,-1), it ignores this position and instead follows my phone location. The asset renders right on top of me and when I walk away, it follows me. It's getting to be very annoying and I can't find a solution.

However, if I replace the SCNNode taken from the .scn file, and use a SCNBox, instead, everything works just fine. The cube stays in it's set position.

Here is the relevant code:

```<code>func addCoins(at position: SCNVector3) {

    let donorScene = SCNScene(named: "art.scnassets/nodes.scn")
    if let coin = donorScene?.rootNode.childNode(withName: "coin", recursively: true) {
        coin.position = position // 0, 0, -1 (right in front of me)
        scene.scene.rootNode.addChildNode(coin)
    }
}
</code>```

Attached is a screenshot showing what I see whenever I move.

答: So the problem was that my 3d asset was too large. The asset was created at 200cm^2 which is 2meter^2 in the 3d modeling program. After the asset was imported into Xcode, it's interpreted by SceneKit as 200meters, which is way too large for SceneKit, apparently.</p>

Body:
I'm using Apples SceneKit and have a custom .dae asset. I've converted the asset to a .scn file. I am grabbing the SCNNode by name from the .scn file. After placing the SCNNode in my SCNView scene as a child node and setting it's position to be SCNVector3(0,0,-1), it ignores this position and instead follows my phone location. The asset renders right on top of me and when I walk away, it follows me. It's getting to be very annoying and I can't find a solution.

However, if I replace the SCNNode taken from the .scn file, and use a SCNBox, instead, everything works just fine. The cube stays in it's set position.

Here is the relevant code:

func addCoins(at position: SCNVector3) {

    let donorScene = SCNScene(named: "art.scnassets/nodes.scn")
    if let coin = donorScene?.rootNode.childNode(withName: "coin", recursively: true) {
        coin.position = position // 0, 0, -1 (right in front of me)
        scene.scene.rootNode.addChildNode(coin)
    }
}

Attached is a screenshot showing what I see whenever I move.


问:
Regarding Encrypted Javascript
when we write javascript in web page then other user can see that javascript and understand how the script work. i have seen few site where javascript was written in such a way user can read the script but will not be able to understand how it works. so for the security reason how can i encrypt my javascript in the page where browser can understand & render properly but any user may not be able to understand the flow. looking for your suggestion.

thanks

答:
This process is called obfuscation, not encryption which is not the same. It means that it makes it hard to read the code but not impossible.

There are many tools allowing you to achieve this such as:

YUI Compressor

Google Closure Compiler

Title: Regarding Encrypted Javascript


问:
print statements are not coming on console with logging module
I am using below logging code in unittest module framework

```<code>logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(output_dir, "w")
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
</code>```

Problem is that when I am having print statements in the code, these are not getting printed anywhere. Not on the console and not in the output file (though I understand why these are not getting printed in file).

Can anybody tell me the reason and solution to print print statements on the console
I am using python 2.7

答:
You aren't setting StreamHandler anywhere, modified your example below.

```<code>import logging
output_dir = "/tmp/somefile"

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(output_dir, "w")
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)

# HERE
ch = logging.StreamHandler()
logger.addHandler(ch)

logger.info("test")
logger.info("test")
logger.info("test")
logger.info("test")
</code>```

This gives me both output on console as well as in file.

EDIT:

Not the best idea, agree, but taken straight from documentation

```<code>import logging
import unittest

logger = None

class TestStringMethods(unittest.TestCase):

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')
        logger.info(self)
    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

        logger.info(self)
    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)

        logger.info(self)

def setup_log():
    global logger
    output_dir = "/tmp/somefile"
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler(output_dir, "w")
    handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(levelname)s - %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    ch = logging.StreamHandler()
    logger.addHandler(ch)
    logger.info("Logger ready")

if __name__ == '__main__':
    setup_log()
    unittest.main()
</code>```

It works, so probably you have some other problem in your code, if you update with more elaborate version, perhaps we can help.

Body:
I am using below logging code in unittest module framework

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(output_dir, "w")
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)

Problem is that when I am having print statements in the code, these are not getting printed anywhere. Not on the console and not in the output file (though I understand why these are not getting printed in file).

Can anybody tell me the reason and solution to print print statements on the console
I am using python 2.7

Body:
You aren't setting StreamHandler anywhere, modified your example below.

import logging
output_dir = "/tmp/somefile"

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(output_dir, "w")
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)

# HERE
ch = logging.StreamHandler()
logger.addHandler(ch)

logger.info("test")
logger.info("test")
logger.info("test")
logger.info("test")

This gives me both output on console as well as in file.

EDIT:

Not the best idea, agree, but taken straight from documentation

import logging
import unittest

logger = None

class TestStringMethods(unittest.TestCase):

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')
        logger.info(self)
    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

        logger.info(self)
    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)

        logger.info(self)

def setup_log():
    global logger
    output_dir = "/tmp/somefile"
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler(output_dir, "w")
    handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(levelname)s - %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    ch = logging.StreamHandler()
    logger.addHandler(ch)
    logger.info("Logger ready")

if __name__ == '__main__':
    setup_log()
    unittest.main()

It works, so probably you have some other problem in your code, if you update with more elaborate version, perhaps we can help.


问:
(Background-color) switch isn't working
I'm using the following code to turn the color of a guitar string first to red on the first click, then lightblue on the second click, and so on back and fourth between the two colors. The string turns red on the first click, but remains red with following clicks and I don't understand why.

```<code>var string = document.getElementById("a-string");
if (string.backgroundColor !== "red") {
  string.style.backgroundColor = "red";
} else {
  string.style.backgroundColor = "lightblue";
}
</code>```

Cam anyone see why this shouldn't work as I expect?

答:
var string = document.getElementById("a-string");
if (string.style.backgroundColor !== "red") {
  string.style.backgroundColor = "red";
} else {
  string.style.backgroundColor = "lightblue";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
font-size:30px;
}</code>```

 A Sample Text
```

Title: (Background-color) switch isn't working

Body:
I'm using the following code to turn the color of a guitar string first to red on the first click, then lightblue on the second click, and so on back and fourth between the two colors. The string turns red on the first click, but remains red with following clicks and I don't understand why.

var string = document.getElementById("a-string");
if (string.backgroundColor !== "red") {
  string.style.backgroundColor = "red";
} else {
  string.style.backgroundColor = "lightblue";
}

Cam anyone see why this shouldn't work as I expect?

Body:
var string = document.getElementById("a-string");
if (string.style.backgroundColor !== "red") {
  string.style.backgroundColor = "red";
} else {
  string.style.backgroundColor = "lightblue";
}

div{
font-size:30px;
}

<div id="a-string"> A Sample Text</div>


问:
What is a good image zoom pan made with jquery or javascript to create a google maps like effect
The goal is to let the user move the image around inside a fixed frame and then crop the image using rails.

So far i have only found http://wayfarerweb.com/jquery/plugins/mapbox/, but i was wondering if there was something that also did the cropping?

Thanks!

答:
What comes to cropping images with Rails (and Paperclip) in this case, have a look at this Railscast. It uses jCrop which uses a different approach then the one you had in mind, but it should give you an idea on how to do this yourself.
My best guess would be to convert your image into a jQuery UI "draggable" with constrained movement and when cropping to read out the offset and send it to the server.</p>


问:
Put a view on top of AppBarLayout
I am working on a UI that utilizes the CoordinatorLayout/AppBarLayout combo as normally seen in most examples but there is this requirement of mine: I want to overlay the AppBarLayout with a View at all times. So, whatever scrolling behavior that happens, should happen under this view. Currently, this is what I am seeing:

Here, the blue bar that you see is the one that I want on top of everything. As you can see, it is hidden initially and only gets exposed when we have scrolled AppBarLayout off the screen. For your reference, here is the code for this layout and its id is android:id="@+id/linearLayout":

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.snapsboardmainpage.MainActivity"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/linearLayout3"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            app:layout_scrollFlags="scroll|snap"
            android:orientation="vertical">

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="112dp"
            android:orientation="vertical"
            app:layout_scrollFlags="scroll|snap"
            android:background="@android:color/holo_green_light">

        </LinearLayout>

        <android.support.design.widget.TabLayout
            android:id="@+id/id_tab_photosvideos_albums"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|snap">

            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </android.support.design.widget.TabLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/nested_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v4.view.ViewPager
            android:id="@+id/id_viewpager_photosvideos_albums"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </android.support.v4.view.ViewPager>

    </android.support.v4.widget.NestedScrollView>

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="vertical"
        android:layout_gravity="top"
        app:layout_behavior="com.example.snapsboardmainpage.TopActionBarBehavior"
        android:background="@android:color/holo_blue_light">

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:orientation="vertical"
        android:layout_gravity="bottom"
        android:background="@android:color/holo_orange_light">

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

How can I achieve this overlay behavior?(it would be preferable if this blue bar could remain as a direct child of CoordinatorLayout)

答:
Although the question seems to be difficult, the solution turned out to be amazingly simple:

```<code>android:elevation="8dp"
</code>```

Yes, that was it. Just set it on the the view that had to overlay the AppBarLayout.

Title: Put a view on top of AppBarLayout

Body:
I am working on a UI that utilizes the CoordinatorLayout/AppBarLayout combo as normally seen in most examples but there is this requirement of mine: I want to overlay the AppBarLayout with a View at all times. So, whatever scrolling behavior that happens, should happen under this view. Currently, this is what I am seeing:

Here, the blue bar that you see is the one that I want on top of everything. As you can see, it is hidden initially and only gets exposed when we have scrolled AppBarLayout off the screen. For your reference, here is the code for this layout and its id is android:id="@+id/linearLayout":

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.snapsboardmainpage.MainActivity"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/linearLayout3"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            app:layout_scrollFlags="scroll|snap"
            android:orientation="vertical">

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="112dp"
            android:orientation="vertical"
            app:layout_scrollFlags="scroll|snap"
            android:background="@android:color/holo_green_light">

        </LinearLayout>

        <android.support.design.widget.TabLayout
            android:id="@+id/id_tab_photosvideos_albums"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|snap">

            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </android.support.design.widget.TabLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/nested_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v4.view.ViewPager
            android:id="@+id/id_viewpager_photosvideos_albums"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </android.support.v4.view.ViewPager>

    </android.support.v4.widget.NestedScrollView>

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="vertical"
        android:layout_gravity="top"
        app:layout_behavior="com.example.snapsboardmainpage.TopActionBarBehavior"
        android:background="@android:color/holo_blue_light">

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:orientation="vertical"
        android:layout_gravity="bottom"
        android:background="@android:color/holo_orange_light">

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>

How can I achieve this overlay behavior?(it would be preferable if this blue bar could remain as a direct child of CoordinatorLayout)

Body:
Although the question seems to be difficult, the solution turned out to be amazingly simple:

android:elevation="8dp"

Yes, that was it. Just set it on the the view that had to overlay the AppBarLayout.


问:
How to write scipy sparse matrix on a file
I have a coo scipy sparse matrix 1000 x 12000 columns.
want to write on disk file following this format :
By row, all no-zeros columns :

col_id1:value    col_id2:value     ....
col_id2:value    ....

Is there a way to do in fast way ?
(without iterating manually)

Body:
An example of what I suggested in the comment:

In [2]: from scipy import sparse
In [3]: M = sparse.random(10,10,.2)
In [4]: M
Out[4]:
<10x10 sparse matrix of type '<class 'numpy.float64'>'
    with 20 stored elements in COOrdinate format>
In [5]: print(M)
  (1, 9)    0.61465832998
  (8, 8)    0.894080347124
  (2, 7)    0.709001342736
  (3, 2)    0.809025517922
  (9, 8)    0.974650428753
  (7, 8)    0.495271225449
  (5, 6)    0.356408870324
  (0, 8)    0.57026318308
  (3, 6)    0.69919575217
  (5, 8)    0.226445982654
  (5, 1)    0.191857394963
  (7, 9)    0.121634028589
  (6, 6)    0.815836601813
  (7, 3)    0.585401171842
  (6, 7)    0.526762154792
  (6, 9)    0.775136319014
  (4, 1)    0.517647147906
  (0, 5)    0.484673192725
  (7, 5)    0.72827335905
  (2, 8)    0.527635893465

lil format collects values by row:

In [6]: Ml = M.tolil()
In [7]: Ml.rows
Out[7]:
array([list([5, 8]), list([9]), list([7, 8]), list([2, 6]), list([1]),
       list([1, 6, 8]), list([6, 7, 9]), list([3, 5, 8, 9]), list([8]),
       list([8])], dtype=object)
In [8]: Ml.data
Out[8]:
array([list([0.4846731927245771, 0.5702631830799726]),
       list([0.6146583299803253]),
       list([0.7090013427361257, 0.5276358934648013]),
       list([0.8090255179222732, 0.6991957521702542]),
       list([0.5176471479060225]),
       list([0.19185739496268694, 0.3564088703236009, 0.2264459826535451]),
       list([0.8158366018134895, 0.5267621547920701, 0.7751363190143352]),
       list([0.5854011718424482, 0.7282733590496102, 0.49527122544858804, 0.12163402858941941]),
       list([0.8940803471238159]), list([0.9746504287533381])], dtype=object)

Format lines according to your specs with a loop and list comprehension:

In [9]: for r,d in zip(Ml.rows, Ml.data):
   ...:     print(' '.join(['%s:%s'%(r1,d1) for r1,d1 in zip(r,d)]))
   ...:
5:0.4846731927245771 8:0.5702631830799726
9:0.6146583299803253
7:0.7090013427361257 8:0.5276358934648013
2:0.8090255179222732 6:0.6991957521702542
1:0.5176471479060225
1:0.19185739496268694 6:0.3564088703236009 8:0.2264459826535451
6:0.8158366018134895 7:0.5267621547920701 9:0.7751363190143352
3:0.5854011718424482 5:0.7282733590496102 8:0.49527122544858804 9:0.12163402858941941
8:0.8940803471238159
8:0.9746504287533381

Substitute your file write line for the print.

We are looping 'manually', but access time to the data elements is relatively fast.  Certainly faster than indexing M[i,j], which isn't possible with coo format anyways.

Fast row access via the csr format attributes is also possible, but requires a bit more knowledge of how that data is stored.

Your : syntax is not common, so you'll have do that formatting regardless.  How are intending to read this file?


问:
Re-position div on mobile with CSS Grid
I have a grid layout that is several blocks of copy with an accompanying image (link to jsfiddle).

```<code><div class="story-body">

    <div class="body-copy">
         <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar, elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus. </p>
    </div>

    <div class="regular-photo">
         <img src="http://placehold.it/500x500">
    </div>

    <div class="body-copy">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar, elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus. </p>
    </div>

    <div class="regular-photo">
         <img src="http://placehold.it/500x500">
    </div>

</div>
</code>```

It displays perfectly on desktop — the image lines up next to the top of the accompanying copy block. The problem is, on mobile, the images show up after the body copy sections which, makes sense, considering I organized the HTML that way.

```<code>.story-body {
    display: grid;
    grid-template-columns: 50% 50%;
    grid-auto-flow: row;
}

.body-copy {
    justify-self: center;
    max-width: 80%;
}

.regular-photo {
justify-self: left;
}

@media screen and (max-width: 500px) {
    .story-body {
    grid-template-columns: 100%;
    }
    .regular-photo {
    justify-self: center;
    }
}
</code>```

Is there a way to position the .regular-photo divs before the .body-copy divs on mobile without having to reorganize the HTML?

答:
You could explicitly declare grid-template-areas and place each div accordingly.

fiddle

.story-body {
      display: grid;
      grid-template-columns: 50% 50%;
      grid-auto-flow: row;
    }

    .body-copy {
      justify-self: center;
      max-width: 80%;
    }

    .regular-photo {
      justify-self: left;
    }

    @media screen and (max-width: 500px) {
      .story-body {
        grid-template-columns: 100%;
        grid-template-areas: "image"
                             "text"
                             "image2"
                             "text2";
      }

      .regular-photo {
        justify-self: center;
      }

      .story-body > div:nth-of-type(1) {
        grid-area: text;
      }
      .story-body > div:nth-of-type(2) {
        grid-area: image;
      }
      .story-body > div:nth-of-type(3) {
        grid-area: text2;
      }
      .story-body > div:nth-of-type(4) {
        grid-area: image2;
      }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="story-body">
  <div class="body-copy">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar,
      elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus. </p>
  </div>
  <div class="regular-photo">
    <img src="http://placehold.it/500x500">
  </div>

  <div class="body-copy">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar,
      elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus. </p>
  </div>
  <div class="regular-photo">
    <img src="http://placehold.it/500x500">
  </div>
</div></code>```

Title: Re-position div on mobile with CSS Grid

Body:
I have a grid layout that is several blocks of copy with an accompanying image (link to jsfiddle).

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar, elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar, elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus.

It displays perfectly on desktop — the image lines up next to the top of the accompanying copy block. The problem is, on mobile, the images show up after the body copy sections which, makes sense, considering I organized the HTML that way.

.story-body {
    display: grid;
    grid-template-columns: 50% 50%;
    grid-auto-flow: row;
}

.body-copy {
    justify-self: center;
    max-width: 80%;
}

.regular-photo {
justify-self: left;
}

@media screen and (max-width: 500px) {
    .story-body {
    grid-template-columns: 100%;
    }
    .regular-photo {
    justify-self: center;
    }
}

Is there a way to position the .regular-photo divs before the .body-copy divs on mobile without having to reorganize the HTML?

Body:
You could explicitly declare grid-template-areas and place each div accordingly.

fiddle

.story-body {
      display: grid;
      grid-template-columns: 50% 50%;
      grid-auto-flow: row;
    }

    .body-copy {
      justify-self: center;
      max-width: 80%;
    }

    .regular-photo {
      justify-self: left;
    }

    @media screen and (max-width: 500px) {
      .story-body {
        grid-template-columns: 100%;
        grid-template-areas: "image"
                             "text"
                             "image2"
                             "text2";
      }

      .regular-photo {
        justify-self: center;
      }

      .story-body > div:nth-of-type(1) {
        grid-area: text;
      }
      .story-body > div:nth-of-type(2) {
        grid-area: image;
      }
      .story-body > div:nth-of-type(3) {
        grid-area: text2;
      }
      .story-body > div:nth-of-type(4) {
        grid-area: image2;
      }
    }

<div class="story-body">
  <div class="body-copy">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar,
      elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus. </p>
  </div>
  <div class="regular-photo">
    <img src="http://placehold.it/500x500">
  </div>

  <div class="body-copy">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar,
      elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus. </p>
  </div>
  <div class="regular-photo">
    <img src="http://placehold.it/500x500">
  </div>
</div>


问:
Spyder doesn't detect changes in imported python files
I'm using Spyder 3.2.4 (Python 3.6). Spyder doesn't detect changes in imported python files. For example:

test2.py:

```<code>def func():
    return 5
</code>```

test1.py:

```<code>import test2

a = test2.func()
print(a)
</code>```

When I wrote those classes, and saved them (in the same working directory), and ran test1.py the output was 5.

BUT when I change the function in test2.py, to like:

```<code>def func():
    return 10
</code>```

Save it, and then run python1.py, I still get 5. Only when I save, exit the IDE, and return, I will get the changed code (10).

This behavior is going on since I started using Spyder (few months by now), and it's super annoying. Help would be appreciated.

答:
What you are experiencing is a Python feature. Modules are initialized when first imported and kept in a cache. Each subsequent import uses the cache, so the module code is not run again.

What in most cases is an eminently reasonable economy, is rather annoying when developing. You can force python to reload a module using importlib.reload.

Body:
I'm using Spyder 3.2.4 (Python 3.6). Spyder doesn't detect changes in imported python files. For example:

test2.py:

def func():
    return 5

test1.py:

import test2

a = test2.func()
print(a)

When I wrote those classes, and saved them (in the same working directory), and ran test1.py the output was 5.

BUT when I change the function in test2.py, to like:

def func():
    return 10

Save it, and then run python1.py, I still get 5. Only when I save, exit the IDE, and return, I will get the changed code (10).

This behavior is going on since I started using Spyder (few months by now), and it's super annoying. Help would be appreciated.


问:
Using SqlPackage.exe on a server without SSMS installed
I have a windows 2012 server. The server can access my SQL database.
I don't have access to the SQL database server, and I don't have access to install SSMS on the windows 2012 server running my website.

I want to use SqlPackage.exe to update my database scheme with a .dacpac file

I get the following error:

Unhandled Exception: System.TypeInitializationException: The type initializer for 'Microsoft.SqlServer.Dac.DacPackage' threw an exception. ---> System.TypeInitializationException: The type initializer for 'Microsoft.SqlServer.Dac.DacServices' threw an exception. ---> System.TypeInitializationException: The type initializer for 'SqlSchemaModelStaticState' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.SqlServer.TransactSql.ScriptDom, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

Is there some way that I can give SqlPackage.exe the needed Microsoft.SqlServer.TransactSql.ScriptDom without installing SSMS on the server?

If it is not possible, is there then an exsisting stand-alone exe out there that can do the job?

答:
You can download any of these nuget packages (depending on desired version and platform). There you will find any missing DLLs.

https://www.nuget.org/packages?q=microsoft.sqlserver.dac+microsoft.sqlserver.dacfx

(Or you could write your own C#/Powershell application, using Microsoft.SqlServer.Dac.DacServices directly from the package.)


问:
Trying to find the occurrences of a string in a linear algorithm
Ok i reformatted what im trying to do. The output has to return the values below. </p>

<p>I know I need to iteration using a multidimesion loop to check each character but im pretty stumped as far as how to go about it. </p>

```<code>String str = "what has the time"

value1 = "hatw hat has the time"
value2 = "wwhhaatt hhaas the time"
value3 = "what has thetime"

output line 1: 00001
output line 2: 00256
output line 3: 00000
</code>```

答:
If you're comfortable using RegEx, its methods and working could save you A LOT of hassle.

```<code>String str = "purrpppppllleeee ssaiyan purple saiyan";
String findStr = "purple saiyan";
String regexStr = "";
for(int i = 0; i < findStr.length(); i++)
{
    regexStr += findStr.charAt(i)+"+";
}
regexStr += "\\s*";
Pattern patt = Pattern.compile(regexStr);
Matcher m = patt.matcher(str);
int count = 0;
while(m.find())
{
    count++;
}
</code>```

The loops are just adding a plus after every character of the findStr.

Adding a plus after a character tells the matcher that there may be multiple occurrences of the letter.

At the end, the matcher finds how many times the phrase findStr has occurred (in the form of the code)

Body:
Ok i reformatted what im trying to do. The output has to return the values below.

I know I need to iteration using a multidimesion loop to check each character but im pretty stumped as far as how to go about it.

String str = "what has the time"

value1 = "hatw hat has the time"
value2 = "wwhhaatt hhaas the time"
value3 = "what has thetime"

output line 1: 00001
output line 2: 00256
output line 3: 00000

Body:
If you're comfortable using RegEx, its methods and working could save you A LOT of hassle.

String str = "purrpppppllleeee ssaiyan purple saiyan";
String findStr = "purple saiyan";
String regexStr = "";
for(int i = 0; i < findStr.length(); i++)
{
    regexStr += findStr.charAt(i)+"+";
}
regexStr += "\\s*";
Pattern patt = Pattern.compile(regexStr);
Matcher m = patt.matcher(str);
int count = 0;
while(m.find())
{
    count++;
}

The loops are just adding a plus after every character of the findStr.

Adding a plus after a character tells the matcher that there may be multiple occurrences of the letter.

At the end, the matcher finds how many times the phrase findStr has occurred (in the form of the code)


问:
Making an Entity Framework Model span multiple databases
Is it valid to do something such as

CREATE SYNONYM [dbo].[MyTable] FOR [AnotherDatabase].dbo.[MyTable]

and then modify Entity Framework's edmx file to read this object like it would any other table?

I did a quick sample test and it seems to work fine for selecting and updating, but I wanted to know if there was any reason why I shouldn't be doing this

I am getting the table definition by creating an edmx file pointing to the 2nd database, building out the entities there, then copy/pasting the definition into the 1st database's edmx file.

UPDATE

If anyone is interested, I wrote up what I did to make an edmx file span mulitple databases here. It includes scripts for generating synonyms and merging edmx files.

答:
I've found that this trick with synonyms works perfectly with the "Code first" approach without any manipulation with edmx files!

The only thing you have to do, is to "bind" your class to appropriate synonym in the OnModelCreating method of your DataContext.

For example, if I have a synonym to table Personnel in another DB (and the class name is also Personnel), and synonym's name is "myschema.MySynonym" then the OnModelCreating method should looks like:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("myschema");

        modelBuilder.Entity<Personnel>()
            .ToTable("MySynonym");

        Database.SetInitializer<TestSynonymContext>(null);

        base.OnModelCreating(modelBuilder);
    }
</code>```

Body:
I've found that this trick with synonyms works perfectly with the "Code first" approach without any manipulation with edmx files!

The only thing you have to do, is to "bind" your class to appropriate synonym in the OnModelCreating method of your DataContext.

For example, if I have a synonym to table Personnel in another DB (and the class name is also Personnel), and synonym's name is "myschema.MySynonym" then the OnModelCreating method should looks like:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("myschema");

        modelBuilder.Entity<Personnel>()
            .ToTable("MySynonym");

        Database.SetInitializer<TestSynonymContext>(null);

        base.OnModelCreating(modelBuilder);
    }


问:
How to gatherElementById starting with a specific word?
Using Prototype and Script.aculo.us, I am trying to make all tags with an ID starting with "idea" Droppable but I can't remember how to get all tags starting with a specific string.  Thank you in advance.</p>

答:
Don't do that. IDs are meant to be used to get a single element.

The proper way to do what you want is giving those elements a common class. Then you can use whatever method prototype has to retrieve all elements with that class name (in jQuery it would be $('.class')). By using classes you allow your JS framework to use highly optimized code to search for matching elements (might even be a native getElementsByClassName method) instead of iterating over basically every single element and doing a substring comparison.

Edit: In prototype you can use $$('.class') to get all matching elements.


问:
string comparison "=" != "+" , incorrect results
Task is to check whether string results true or false for following given condition:

If a letter a to z occurs it must have '+' before and after the particular letter
This works fine expect the case when '=' comes before or after the letter.
Why this condition is wrong for '=' ?
This code returns true for these strings
Thanks

function SimpleSymbols(str) {
    var temp=str.split("")
    if(temp.length==1 || temp.length==2 )
    return false;
    for(i=0;i<temp.length;i++){
        if(temp[i]>='a' && temp[i]<='z'){
            if(i===0 || i===(temp.length-1)||
            (temp[i-1]!=='+' && temp[i+1]!=='+')){
                return false;
            }
        }
    }
  return true;
}
   ```

答:
function SimpleSymbols(str) {
    var temp=str.split("")
    if(temp.length==1 || temp.length==2 )
    return false;
    for(i=0;i<temp.length;i++){
        if(temp[i]>='a' && temp[i]<='z'){
            if(i===0 || i===(temp.length-1)||
            (temp[i-1]!=='+' || temp[i+1]!=='+')){
                return false;
            }
        }
    }
  return true;
}
   ```

Body:
<!-- I think you should change the condition operator -->

function SimpleSymbols(str) {
    var temp=str.split("")
    if(temp.length==1 || temp.length==2 )
    return false;
    for(i=0;i<temp.length;i++){
        if(temp[i]>='a' && temp[i]<='z'){
            if(i===0 || i===(temp.length-1)||
            (temp[i-1]!=='+' || temp[i+1]!=='+')){
                return false;
            }
        }
    }
  return true;
}


问:
Multiple document.getElementById
I have an image zoomer that I am using in a modal. The zoomer plugin uses an document.getElementById to open the image but I need it to open multiple images.

I have read many of your posts that say I need to use other selectors such as

```<code>(document.querySelectorAll("#galley1, #galley2, #galley3));
</code>```

or a class selector

```<code>(document.getElementsByClassName("galley"));
</code>```

I have tried these but still can't get it to open the image zoomer with multiple ID's.

The ID I am using on the divs and for the selector are #galley1, #galley2, #galley3.

You can see the entire code at my website http://www.fitzgeraldoilworks.com. The first image on the page works perfect but the rest of the images will not zoom in the modal.

```<code><html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

<title>Photo Zoom</title>

<link rel="stylesheet" type="text/css" href="css/lity.css"/>
<link rel="stylesheet" type="text/css" href="css/viewer.css"/>

<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/lity.min.js"></script>
<script type="text/javascript" src="js/viewer.js"></script>

</head>

<body>

<div class="featured-body-wrap">
  <div class ="featured-image-container">

       <div class ="featured-image-holder">
           <div class="featured-title">KINGS CHOICE</div>

        <div class ="featured-image-wrap">
            <a href="#kings" data-lity> <img src="images/art/thmb/kings choice320.jpg"
            class="featured-image" style="width:100%;height:auto;border:0;"/></a>
        </div>
       </div>

<div id="kings" class="lity-hide">
<div id="galley1">

          <div class="modal-img-container">

                           <div class="modal-header">Kings Choice</div>

              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/kings choice1500.jpg" src="images/art/med/kings choice700.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>
              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/kings choice wall1500.jpg" src="images/art/med/kings choice wall700.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>
              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/kings choice head1400.jpg" src="images/art/med/kings choice head700.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>

          </div>
</div>
</div>

       <div class ="featured-image-holder">
           <div class="featured-title">WISPER</div>

        <div class ="featured-image-wrap">
            <a href="#wisper" data-lity> <img src="images/art/thmb/wisper thmb320.jpg"
            class="featured-image" style="width:100%;height:auto;border:0;"/></a>
        </div>
       </div>

<div id="wisper" class="lity-hide">
<div id="galley2">

          <div class="modal-img-container">

                           <div class="modal-header">WISPER</div>

              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/wisper hires.jpg" src="images/art/med/wisper md.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>
              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/wisper face hires.jpg" src="images/art/med/wisper face md.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>
              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/wisper wall hires.jpg" src="images/art/med/wisper wall md.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>

          </div>
</div>
</div>

        <div class ="featured-image-wrap">
            <a href="#shadow" data-lity> <img src="images/art/thmb/shadow thmb.jpg"
            class="featured-image" style="width:100%;height:auto;border:0;"/></a>
        </div>
       </div>

<div id="shadow" class="lity-hide">
<div id="galley3">

          <div class="modal-img-container">

                           <div class="modal-header">SHADOW</div>

              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/shadow-hires.jpg" src="images/art/med/shadow-md.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>
              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/shadow-easle-hires.jpg" src="images/art/med/shadow-easle-md.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>
              <div class="sized-box">
                 <div class="model-img-wrap"><img class="model-img"
                 data-original="images/art/hires/shadow-wall-hires.jpg" src="images/art/med/shadow-wall-md.jpg" alt="SCROLL MOUSE TO ZOOM"/></div>
              </div>

          </div>
</div>
</div>
</div>

      <script type="text/javascript">

    window.addEventListener('DOMContentLoaded', function () {
      var galley = (document.querySelectorAll("#galley1, #galley2, #galley3"));
      var viewer = new Viewer(galley, {
        url: 'data-original',
        button: true,
        navbar: false,
        title: true,
        toolbar: false,
        tooltip: true,
        movable: true,
        zoomable: true,
        scalable: true,
        transition: true,
        zoomRatio: 0.3,
        minZoomRatio: 0.01,
        maxZoomRatio: 100,
        zIndex: 2015,
        inline: false,
        minWidth: 200,
        minHeight: 100,
        viewed: function () {
var context = this;
$('.viewer-canvas').click(function(e){
if(e.target.className == 'viewer-canvas') {
context.viewer.hide();
}
});
}
      });
    });

          </script>

</body>
</html>
</code>```

答:
Place all your images under 1 class, for example "images".
Then do

```<code>var myImages = document.getElementsByClassName("images");
</code>```

You'll get an array containing all your images.
If you want to do this with ids, then give your images ids like "img1","img2","img3" Then do

```<code>var myImages = [];
for(var i = 0; i < numImages; i++) {
    myImages.push(document.getElementById("img"+i));
}
</code>```

he result should be the same.

Title: Multiple document.getElementById

Body:
I have an image zoomer that I am using in a modal. The zoomer plugin uses an document.getElementById to open the image but I need it to open multiple images.

I have read many of your posts that say I need to use other selectors such as

(document.querySelectorAll("#galley1, #galley2, #galley3));

or a class selector

(document.getElementsByClassName("galley"));

I have tried these but still can't get it to open the image zoomer with multiple ID's.

The ID I am using on the divs and for the selector are #galley1, #galley2, #galley3.

You can see the entire code at my website http://www.fitzgeraldoilworks.com. The first image on the page works perfect but the rest of the images will not zoom in the modal.

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

<title>Photo Zoom</title>

<link rel="stylesheet" type="text/css" href="css/lity.css"/>
<link rel="stylesheet" type="text/css" href="css/viewer.css"/>

KINGS CHOICE

Kings Choice

WISPER

WISPER

SHADOW

Body:
Place all your images under 1 class, for example "images".
Then do

var myImages = document.getElementsByClassName("images");

You'll get an array containing all your images.
If you want to do this with ids, then give your images ids like "img1","img2","img3" Then do

var myImages = [];
for(var i = 0; i < numImages; i++) {
    myImages.push(document.getElementById("img"+i));
}

he result should be the same.


问:
How do I get the current validator of a mongo collection?
How do I get the current validator of a mongo collection?

Or is there no way, and I just need to overwrite it?

答:
You can get it with the db.getCollectionInfos() method.

Example:

Create a collection in an empty database:

```<code>db.createCollection( "contacts",
   {
      validator: { $or:
         [
            { phone: { $type: "string" } },
            { email: { $regex: /@mongodb\.com$/ } },
            { status: { $in: [ "Unknown", "Incomplete" ] } }
         ]
      },
      validationAction: "warn"
   }
)
</code>```

{ "ok" : 1 }

Run the command:

```<code>db.getCollectionInfos()[0].options.validator
</code>```

Result:

```<code>{
  "$or" : [
    {
      "phone": {
        "$type": "string"
      }
    },
    {
      "email": {
        "$regex": /@mongodb\.com$/
      }
    },
    {
      "status": {
        "$in": [
          "Unknown",
          "Incomplete"
        ]
      }
    }
  ]
}
</code>```

The validator is found as an object in the options object.

Body:
You can get it with the db.getCollectionInfos() method.

Example:

Create a collection in an empty database:

db.createCollection( "contacts",
   {
      validator: { $or:
         [
            { phone: { $type: "string" } },
            { email: { $regex: /@mongodb\.com$/ } },
            { status: { $in: [ "Unknown", "Incomplete" ] } }
         ]
      },
      validationAction: "warn"
   }
)

{ "ok" : 1 }

Run the command:

db.getCollectionInfos()[0].options.validator

Result:

{
  "$or" : [
    {
      "phone": {
        "$type": "string"
      }
    },
    {
      "email": {
        "$regex": /@mongodb\.com$/
      }
    },
    {
      "status": {
        "$in": [
          "Unknown",
          "Incomplete"
        ]
      }
    }
  ]
}

The validator is found as an object in the options object.


问:
hidden field vs viewstate
What is the difference when using

Hidden field vs View state?

When to use each one ?

Which one more secure?

Which is better in performance?

what are the alternatives?

答:
ViewState internally uses hidden field. It is managed by ASP.NET Engine and is encrypted by default.

On the other hand, with hidden field control, you get to manage what is stored in it. By default, it's not encrypted.

Performance wise, both are same. But, I feel ViewState is more secure. ASP.NET maintains its hash to prevent/identify any tampering with it client side.

You can also use session to store data.

Title: hidden field vs viewstate


问:
How to set global variables from database in Laravel 5.4
I'm facing the same problem very often in various projects - I need to set some global variables from database and be able to receive them in anywhere in laravel - views, controllers, models. Is it possible? Or what is the most easy way to do this?

Why I need this? For language translations. I need them not cached and saved in file. For website options which can be taken from any place of app. For website language to set, because I don't want to make /language/ prefix on url.

Sorry if this question can be a duplicate, but none of the answers in similar questions worked in a way I have explained.

答:
You can try view composers for sharing data globally to all views.

```<code>public function compose(View $view)
{
    //get value from database
    $options = Model::where('domain_name', \Request::server("SERVER_NAME"))->get();
    //render to view
    $view->with('options', $options);
}
</code>```

The $options variable (model) would be available in every view.

To share data with all controllers define variables in base controller to access them in controllers which inherit base controller

```<code>class Controller extends BaseController
{
    public $options = Model::where('domain_name', \Request::server("SERVER_NAME"))->get();
}
</code>```

you can access it using

```<code>class LoginController extends Controller
{
    public function dashboard()
    {
        //access here using
        $x = $this->options;
    }
}
</code>```

Like this you can create a base model and use the inherit property to access data globally in models.

Hope it will be useful for you. The options variable may contain all the options from database.

Body:
You can try view composers for sharing data globally to all views.

public function compose(View $view)
{
    //get value from database
    $options = Model::where('domain_name', \Request::server("SERVER_NAME"))->get();
    //render to view
    $view->with('options', $options);
}

The $options variable (model) would be available in every view.

To share data with all controllers define variables in base controller to access them in controllers which inherit base controller

class Controller extends BaseController
{
    public $options = Model::where('domain_name', \Request::server("SERVER_NAME"))->get();
}

you can access it using

class LoginController extends Controller
{
    public function dashboard()
    {
        //access here using
        $x = $this->options;
    }
}

Like this you can create a base model and use the inherit property to access data globally in models.

Hope it will be useful for you. The options variable may contain all the options from database.


问:
Does c# offer a direct way to alias a property name?
Does c# (any version) offer an improved way to alias a property name? In AccountBase, I use the string Username to identify the account, but in NonstandardAccount I want the client (consumer of the API) to use CustomerNumber to prevent confusion.

Here is my code:

```<code>public abstract class AccountBase
{
    public string Username { get => Username; set => Username = value; }
}

public class StandardAccount
{
    // The username is the ID
}

public class NonstandardAccount : AccountBase
{
    // The Username or CustomerNumber is the ID
    public string CustomerNumber { get => Username; set => Username = value; }

    // OR ideally, but I don't think this works
    public string CustomerNumber => Username;
}
</code>```

I could forgo adding a CustomerNumber property and just document that it is the same as the Username, but it isn't clear. I could just leave my implementation as is, but extra storage for the sake of clarity may not be a good tradeoff.

答:
Thanks to Patrick Artner, I found not only an answer, but the ideal answer. It was right in my source code all along, but I didn't trust my intuition.

```<code>public class NonstandardAccount : AccountBase
{
    // Does work and works perfectly! Username is still accessible
    public string CustomerNumber => Username;
}
</code>```

A new hard learnt lesson: Just because your intuition was wrong on many occasions, doesn't mean you should discredit it as a pathological liar.

Body:
Does c# (any version) offer an improved way to alias a property name? In AccountBase, I use the string Username to identify the account, but in NonstandardAccount I want the client (consumer of the API) to use CustomerNumber to prevent confusion.

Here is my code:

public abstract class AccountBase
{
    public string Username { get => Username; set => Username = value; }
}

public class StandardAccount
{
    // The username is the ID
}

public class NonstandardAccount : AccountBase
{
    // The Username or CustomerNumber is the ID
    public string CustomerNumber { get => Username; set => Username = value; }

    // OR ideally, but I don't think this works
    public string CustomerNumber => Username;
}

I could forgo adding a CustomerNumber property and just document that it is the same as the Username, but it isn't clear. I could just leave my implementation as is, but extra storage for the sake of clarity may not be a good tradeoff.

Body:
Thanks to Patrick Artner, I found not only an answer, but the ideal answer. It was right in my source code all along, but I didn't trust my intuition.

public class NonstandardAccount : AccountBase
{
    // Does work and works perfectly! Username is still accessible
    public string CustomerNumber => Username;
}

A new hard learnt lesson: Just because your intuition was wrong on many occasions, doesn't mean you should discredit it as a pathological liar.


问:
What is the cost of calling jQuery and jQuery UI on every page?
I have an intranet site where half of the pages use jQuery, and ~20% use jQuery UI. Users who navigate the site will almost certainly open a page containing jQuery UI during their visit.

What I'd like to do is use for all pages a standard template that includes calls to jQuery and jQuery UI. It would make the site maintenance easier, but it also means that for 80% of my pages jQuery UI will be loaded for nothing.

What I have been told is that I should not worry too much about that. Calls to jQuery and jQuery UI will be cached by the browser, so anyway they'll only be called once during the user's visit.

Is this correct? Or are there other performance factors that could make the systematic call a bad idea?

答: You heard right. The files remain cached in the browser, so don't worry about that.</p>


问:
Default constructor setting random value
I'm writing a simple class for atoms objects. Here's what I've written so far:

```<code>#include <random>

class Atom {
    int mSpin;

public:
    Atom();
    Atom(int);
    Atom(const Atom&);
    ~Atom() {}

    Atom& operator= (const Atom &atom);
};
</code>```

And the .cpp file:

```<code>include "Atom.h"

Atom::Atom() {
}
Atom::Atom(int spin) : mSpin(spin) {}
Atom::Atom(const Atom& copy) : mSpin(copy.mSpin) {}

/*  OPERATORS  */

Atom& Atom::operator= (const Atom &copy) {
    mSpin = copy.mSpin;
    return *this;
}
</code>```

I want to make the default constructor such that when I'm creating an object, mSpin will be randomly set as 1 or -1. I understand how to do it with rand() but rand() is not very good and I'd like to use . I'm kind of confused by the use of , even after reading the documentation and other answers on here.
Usually I'd do something like this:

```<code>#include <random>
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0,1);
int random_number = dis(gen);
</code>```

but I'm not sure how to use it inside a class. I tried placing it inside the default constructor but I think it's wrong because it would seed each time I create an atom?

Hope the question is clear.

答:
You can delegate to a function in the cpp file:

namespace {
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dis(0,1);
}
int spin() {
    return dis(gen) == 0 ? -1 : 1;
}
```

<p>Delete your implementation of the default CTOR.</p>

<p>And to follow the rule 'initialise all variables' change Atom.hpp:</p>

```int spin(); // Return -1 or 1, randomly

class Atom {
    int mSpin = spin();
public:
    Atom() = default;
    ...
};
```

Then, in your cpp file, delete your Atom default CTOR implementation and move 'spin' function definition out of the anonymous namespace.

Body:
I'm writing a simple class for atoms objects. Here's what I've written so far:

#include <random>

class Atom {
    int mSpin;

public:
    Atom();
    Atom(int);
    Atom(const Atom&);
    ~Atom() {}

    Atom& operator= (const Atom &atom);
};

And the .cpp file:

include "Atom.h"

Atom::Atom() {
}
Atom::Atom(int spin) : mSpin(spin) {}
Atom::Atom(const Atom& copy) : mSpin(copy.mSpin) {}

/*  OPERATORS  */

Atom& Atom::operator= (const Atom &copy) {
    mSpin = copy.mSpin;
    return *this;
}

I want to make the default constructor such that when I'm creating an object, mSpin will be randomly set as 1 or -1. I understand how to do it with rand() but rand() is not very good and I'd like to use . I'm kind of confused by the use of , even after reading the documentation and other answers on here.
Usually I'd do something like this:

#include <random>
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0,1);
int random_number = dis(gen);

but I'm not sure how to use it inside a class. I tried placing it inside the default constructor but I think it's wrong because it would seed each time I create an atom?

Hope the question is clear.

Body:
You can delegate to a function in the cpp file:

namespace {
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dis(0,1);
}
int spin() {
    return dis(gen) == 0 ? -1 : 1;
}

Delete your implementation of the default CTOR.

And to follow the rule 'initialise all variables' change Atom.hpp:

int spin(); // Return -1 or 1, randomly

class Atom {
    int mSpin = spin();
public:
    Atom() = default;
    ...
};

Then, in your cpp file, delete your Atom default CTOR implementation and move 'spin' function definition out of the anonymous namespace.


问:
Where to start debugging, when you get the "Activity is not responding, Force Close, Wait"?
I have worked on a simple application. It application includes diffrent levels that can be solved by placing some components inside a canvas, dragging them to the right place and so on.

The application is working fine, but when trying it on my HTC Desire 2.2, I sometimes get the warning message:

Sorry:
Activity xxxxx is not respoding.
Force Close - Wait

If I press the wait-button and let it be for some seconds (up to ~30 sec sometimes), then it runs without any problems. I don´t know where I should start debugging the code, since it happenes only once in a while.

I have read the stuff in google developer site and it was just mostly very general stuff that did not really help.

any ideas?

since, I was not able to debug the problem myself, I am going to post the most important parts of the application. Please check and let me know If I need to post more classes.

```<code>//Evrything else
Bitmap bitmap;
GraphicObject.Coordinates coords;
for (GraphicObject graphic : _graphics) {
    bitmap = graphic.getGraphic();
    coords = graphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
// draw current graphic at last...
if (_currentGraphic != null) {
    bitmap = _currentGraphic.getGraphic();
    coords = _currentGraphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
</code>```

答:
You can use the new StrictMode to detect what is causing your UI thread to hang.
Take a look at this link.

It is only available for GingerBread (API level 9), so you can just test it on the emulator, perform the necessary cleanup, and then remove the StrictMode code

Body:
I have worked on a simple application. It application includes diffrent levels that can be solved by placing some components inside a canvas, dragging them to the right place and so on.

The application is working fine, but when trying it on my HTC Desire 2.2, I sometimes get the warning message:

Sorry:
Activity xxxxx is not respoding.
Force Close - Wait

If I press the wait-button and let it be for some seconds (up to ~30 sec sometimes), then it runs without any problems. I don´t know where I should start debugging the code, since it happenes only once in a while.

I have read the stuff in google developer site and it was just mostly very general stuff that did not really help.

any ideas?

since, I was not able to debug the problem myself, I am going to post the most important parts of the application. Please check and let me know If I need to post more classes.

//Evrything else
Bitmap bitmap;
GraphicObject.Coordinates coords;
for (GraphicObject graphic : _graphics) {
    bitmap = graphic.getGraphic();
    coords = graphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
// draw current graphic at last...
if (_currentGraphic != null) {
    bitmap = _currentGraphic.getGraphic();
    coords = _currentGraphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}


问:
sql query - to rent a car (php)
Im new to php and sql and having trouble writing a query.

I've already accomplished a query that show/get unrented cars.
And it looks this:

```<code>SELECT c.*
FROM cars c
WHERE NOT EXISTS (
          SELECT *
          FROM reservations as r
          WHERE r.car_id = c.id AND
          (r.res_from <= '2017-12-08 02:53:59' AND r.res_to >= '2017-12.09 23:58:59') OR
          (r.res_from <= '2017-12-08 23:59:59' AND r.res_to >= '2017-12.09 23:58:59') OR
          (r.res_from >= '2017-12-08 23:59:59' AND r.res_to <= '2017-12.09 23:58:59')
          );`
</code>```

The question is:  how to write a query that rent a car given from_date - to_date and a user/customer need enough points(money) to rent a specified car.

link to my database http://sqlfiddle.com/#!9/170f7f4/5

I tried something like this. Is this the right way to go?

```<code>    SELECT * FROM cars as c, reservations as r, users as u,
    WHERE HAVING c.id = r.car_id AND
                 r.user_id = u.user_id AND
          (res_from <= '2017-12-08 02:53:59' AND r.res_to >= '2017-12-08 02:53:59') OR
          (r.res_from >= '2017-12-08 23:59:59' AND r.res_to <= '2017-12-08 23:59:59' )
</code>```

.... what next?

And want to click on a car (as can be seen in the attached picture) and then chose a rent date.

答:
SELECT c.* FROM cars AS c
    LEFT JOIN (SELECT r. * FROM reservations AS r
               WHERE r.res_from >= '2017-12-09 23:58:59'
               AND r.res_to <= '2017-12-18 23:58:59'
              )

             AS r ON c.id = r.car_id
             WHERE r.car_id is null;

I think this one might work.

Title: sql query - to rent a car (php)

Body:
Im new to php and sql and having trouble writing a query.

I've already accomplished a query that show/get unrented cars.
And it looks this:

SELECT c.*
FROM cars c
WHERE NOT EXISTS (
          SELECT *
          FROM reservations as r
          WHERE r.car_id = c.id AND
          (r.res_from <= '2017-12-08 02:53:59' AND r.res_to >= '2017-12.09 23:58:59') OR
          (r.res_from <= '2017-12-08 23:59:59' AND r.res_to >= '2017-12.09 23:58:59') OR
          (r.res_from >= '2017-12-08 23:59:59' AND r.res_to <= '2017-12.09 23:58:59')
          );`

The question is:  how to write a query that rent a car given from_date - to_date and a user/customer need enough points(money) to rent a specified car.

link to my database http://sqlfiddle.com/#!9/170f7f4/5

I tried something like this. Is this the right way to go?

    SELECT * FROM cars as c, reservations as r, users as u,
    WHERE HAVING c.id = r.car_id AND
                 r.user_id = u.user_id AND
          (res_from <= '2017-12-08 02:53:59' AND r.res_to >= '2017-12-08 02:53:59') OR
          (r.res_from >= '2017-12-08 23:59:59' AND r.res_to <= '2017-12-08 23:59:59' )

.... what next?

And want to click on a car (as can be seen in the attached picture) and then chose a rent date.


问:
Adding a row from a dataframe into another by matching columns with NaN values in row pandas python

The Scenario:

I have 2 dataframes fc0 and yc0. Where fc0 is a Cluster and yc0 is another dataframe which needs to be merged in fc0.

The Nature of data is as follows:

fc0

```<code>uid         1         2         3         4         5         6
234  235  4.000000  4.074464  4.128026  3.973045  3.921663  4.024864
235  236  3.524208  3.125669  3.652112  3.626923  3.524318  3.650589
236  237  4.174080  4.226267  4.200133  4.150983  4.124157  4.200052
</code>```

yc0

```<code>iid  uid    1    2    5    6    9    15
0    944  5.0  3.0  4.0  3.0  3.0  5.0
</code>```

The Twist

I have 1682 columns in fc0 and I have few hundered values in yc0. Now I need the yc0 to go into fc0

In haste of resolving it, I even tried yc0.reset_index(inplace=True) but wasn't really helpful.

Expected Output

```<code>     uid         1         2         3         4         5         6
234  235  4.000000  4.074464  4.128026  3.973045  3.921663  4.024864
235  236  3.524208  3.125669  3.652112  3.626923  3.524318  3.650589
236  237  4.174080  4.226267  4.200133  4.150983  4.124157  4.200052
944  5.0       3.0       NaN       NaN       4.0       3.0       3.0
</code>```

References

Link1 Tried this, but landed up inserting NaN values for 1st 16 Columns and rest of the data shifted by that many columns

Link2 Couldn't match column keys, besides I tried it for row.

Link3 Merging doesn't match the columns in it.

Link4 Concatenation doesn't work that way.

Link5 Same issues with Join.

EDIT 1

```<code>fc0.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 235 entries, 234 to 468
Columns: 1683 entries, uid to 1682
dtypes: float64(1682), int64(1)
memory usage: 3.0 MB
</code>```

and

```<code>yc0.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1 entries, 0 to 0
Columns: 336 entries, uid to 1007
dtypes: float64(335), int64(1)
memory usage: 2.7 KB
</code>```

Body:
The Scenario:

I have 2 dataframes fc0 and yc0. Where fc0 is a Cluster and yc0 is another dataframe which needs to be merged in fc0.

The Nature of data is as follows:

fc0

uid         1         2         3         4         5         6
234  235  4.000000  4.074464  4.128026  3.973045  3.921663  4.024864
235  236  3.524208  3.125669  3.652112  3.626923  3.524318  3.650589
236  237  4.174080  4.226267  4.200133  4.150983  4.124157  4.200052

yc0

iid  uid    1    2    5    6    9    15
0    944  5.0  3.0  4.0  3.0  3.0  5.0

The Twist

I have 1682 columns in fc0 and I have few hundered values in yc0. Now I need the yc0 to go into fc0

In haste of resolving it, I even tried yc0.reset_index(inplace=True) but wasn't really helpful.

Expected Output

     uid         1         2         3         4         5         6
234  235  4.000000  4.074464  4.128026  3.973045  3.921663  4.024864
235  236  3.524208  3.125669  3.652112  3.626923  3.524318  3.650589
236  237  4.174080  4.226267  4.200133  4.150983  4.124157  4.200052
944  5.0       3.0       NaN       NaN       4.0       3.0       3.0

References

Link1 Tried this, but landed up inserting NaN values for 1st 16 Columns and rest of the data shifted by that many columns

Link2 Couldn't match column keys, besides I tried it for row.

Link3 Merging doesn't match the columns in it.

Link4 Concatenation doesn't work that way.

Link5 Same issues with Join.

EDIT 1

fc0.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 235 entries, 234 to 468
Columns: 1683 entries, uid to 1682
dtypes: float64(1682), int64(1)
memory usage: 3.0 MB

and

yc0.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1 entries, 0 to 0
Columns: 336 entries, uid to 1007
dtypes: float64(335), int64(1)
memory usage: 2.7 KB

Body:
Here's a MVCE example.    Does this small sample data show the functionality that you are expecting?

df1 = pd.DataFrame(np.random.randint(0,100,(5,4)), columns=list('ABCE'))

    A   B   C   E
0  81  57  54  88
1  63  63  74  10
2  13  89  88  66
3  90  81   3  31
4  66  93  55   4

df2 = pd.DataFrame(np.random.randint(0,100,(5,4)), columns=list('BCDE'))

    B   C   D   E
0  93  48  62  25
1  24  97  52  88
2  53  50  21  13
3  81  27   7  81
4  10  21  77  19

df_out = pd.concat([df1,df2])
print(df_out)

Output:

      A   B   C     D   E
0  81.0  57  54   NaN  88
1  63.0  63  74   NaN  10
2  13.0  89  88   NaN  66
3  90.0  81   3   NaN  31
4  66.0  93  55   NaN   4
0   NaN  93  48  62.0  25
1   NaN  24  97  52.0  88
2   NaN  53  50  21.0  13
3   NaN  81  27   7.0  81
4   NaN  10  21  77.0  19


问:
How can I convert part of code to Twig format?
I need convert this code to Twig format for Opencart3. But no success. Any idea?

```<code><div class="col-sm-10">
<?php
    $cm_count = 0;
    $cm_count = count($cannedmessages);
    if ($cm_count == 0) { ?>
        Use the button to setup a new canned message
    <?php } else { ?>
    <select name="cannedmessage" id="cannedmessage" class="form-control">
        <option></option>
        <?php foreach ($cannedmessages as $cannedmessage) {
            if( $cannedmessage['status']==1) { ?>
                <option value="<?php echo $cannedmessage['description']; ?>"><?php echo $cannedmessage['title']; ?></option>
            <?php }
        } ?>
    </select>
<?php } ?>
</div>
</code>```

I try this with converter on https://php2twig.com/index.php but with error..

```<code>  <div class="col-sm-10">
    cm_count 0
    cm_count count(cannedmessages)
    {% if cm_count is 0 %}
       Use the button to setup a new canned message
    {% else %}
        <select name="cannedmessage" id="cannedmessage" class="form-control">
      <option></option>
      {% for cannedmessage in cannedmessages %}
      {% if cannedmessage.status is 1 %}
          <option value="{{ cannedmessage.description }}">{{ cannedmessage.title }}</option>
      {% endif %}
      {% endfor %}

      </select>
    {% endif %}
  </div>
</code>```

I fight with creating "Canned message" in Opencart 3. But I'm losing the battle...

答:
First of all check if your cannedmessage has title property, and try this:

```<code>{% if cannedmessages|length > 0 %}
    <select name="cannedmessage" id="cannedmessage" class="form-control">
        <option></option>
        {% for cannedmessage in cannedmessages %}
            {% if cannedmessage.status == 1 %}
                <option value="{{ cannedmessage.description }}">{{ cannedmessage.title }}</option>
            {% endif %}
        {% endfor %}
    </select>
{% else %}
    Use the button to setup a new canned message
{% endif %}
</code>```

Body:
I need convert this code to Twig format for Opencart3. But no success. Any idea?

<?php
    $cm_count = 0;
    $cm_count = count($cannedmessages);
    if ($cm_count == 0) { ?>
        Use the button to setup a new canned message
    <?php } else { ?>
    <select name="cannedmessage" id="cannedmessage" class="form-control">
        <option></option>
        <?php foreach ($cannedmessages as $cannedmessage) {
            if( $cannedmessage['status']==1) { ?>
                <option value="<?php echo $cannedmessage['description']; ?>"><?php echo $cannedmessage['title']; ?></option>
            <?php }
        } ?>
    </select>
<?php } ?>

I try this with converter on https://php2twig.com/index.php but with error..

    cm_count 0
    cm_count count(cannedmessages)
    {% if cm_count is 0 %}
       Use the button to setup a new canned message
    {% else %}
        <select name="cannedmessage" id="cannedmessage" class="form-control">
      <option></option>
      {% for cannedmessage in cannedmessages %}
      {% if cannedmessage.status is 1 %}
          <option value="{{ cannedmessage.description }}">{{ cannedmessage.title }}</option>
      {% endif %}
      {% endfor %}

      </select>
    {% endif %}

I fight with creating "Canned message" in Opencart 3. But I'm losing the battle...

Body:
First of all check if your cannedmessage has title property, and try this:

{% if cannedmessages|length > 0 %}
    <select name="cannedmessage" id="cannedmessage" class="form-control">
        <option></option>
        {% for cannedmessage in cannedmessages %}
            {% if cannedmessage.status == 1 %}
                <option value="{{ cannedmessage.description }}">{{ cannedmessage.title }}</option>
            {% endif %}
        {% endfor %}
    </select>
{% else %}
    Use the button to setup a new canned message
{% endif %}


问:
Warning:scalac: there was one deprecation warning; re-run with -deprecation for details
Notice this in the message output:

Warning:scalac: there was one deprecation warning; re-run with -deprecation for details

What does this mean? And what should I re-run?

I tried rebuilding and syncing the project. But the warning message is still there.

答:
Found a solution from command line:

```<code>sbt
set scalacOptions in ThisBuild ++= Seq("-unchecked", "-deprecation")
compile
</code>```

And found the cause of the warning:

```<code>[warn] Blah.scala:53: Adaptation of argument list by inserting () has been deprecated: leaky (Object-receiving) target makes this especially dangerous.
[warn]         signature: Logger.error(x$1: Any): Unit
[warn]   given arguments: <none>
[warn]  after adaptation: Logger.error((): Unit)
[warn]       logger.error()
[warn]                   ^
[warn] one warning found
</code>```

The problem is that I used a deprecated function call logger.error(). It is weird that IntelliJ does not give any lint error though.

Reference: https://stackoverflow.com/a/9578787/1035008

Body:
Found a solution from command line:

sbt
set scalacOptions in ThisBuild ++= Seq("-unchecked", "-deprecation")
compile

And found the cause of the warning:

[warn] Blah.scala:53: Adaptation of argument list by inserting () has been deprecated: leaky (Object-receiving) target makes this especially dangerous.
[warn]         signature: Logger.error(x$1: Any): Unit
[warn]   given arguments: <none>
[warn]  after adaptation: Logger.error((): Unit)
[warn]       logger.error()
[warn]                   ^
[warn] one warning found

The problem is that I used a deprecated function call logger.error(). It is weird that IntelliJ does not give any lint error though.

Reference: https://stackoverflow.com/a/9578787/1035008