问:
Windows Phone 8.1 MediaCapture freezes the phone
I want to make a simple app that will allow me to check few parameters of every frame of preview, but I got stuck at running and stopping preview.

```<code>    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        MediaCapture _MediaCapture;
        bool _recording;
        public MainPage()
        {
            this.InitializeComponent();

            this.NavigationCacheMode = NavigationCacheMode.Required;
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            var rearCamera = devices[0];
            if (devices.Count > 0)
            {

                rearCamera = devices.Single(currDev =>
                  currDev.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back
                );
            }

            _MediaCapture = new MediaCapture();
            await _MediaCapture.InitializeAsync(new MediaCaptureInitializationSettings() { VideoDeviceId = rearCamera.Id });

// this is CaptureElement
            xCapture.Source = _MediaCapture;

            _recording = false;
        }

        protected override async void OnNavigatedFrom(NavigationEventArgs e)
        {
            if(_MediaCapture != null)
            {
                await _MediaCapture.StopPreviewAsync();
                await _MediaCapture.StopRecordAsync();

                _MediaCapture.Dispose();
                _MediaCapture = null;

                xCapture.Source = null;
            }

            base.OnNavigatedFrom(e);

        }

// button click handler
        private async void StartMeasure(object sender, RoutedEventArgs e)
        {
            if (_recording)
            {
                //await _MediaCapture.StopPreviewAsync();
                _MediaCapture.VideoDeviceController.TorchControl.Enabled = false;
                _recording = false;
            }
            else
            {
                //await _MediaCapture.StartPreviewAsync();
                _MediaCapture.VideoDeviceController.TorchControl.Enabled = true;
                _recording = true;
            }
        }
    }
</code>```

In this form it works perfectly.

If I uncomment those preview lines it works, but only once.

If I press the button three times: on, off and on again I get exception at line with enabling TorchControl.

System.Exception: Exception from HRESULT: 0xE801000D at Windows.Media.Devices.TorchControl.put_Enabled(Boolean value) at Pulsometr3.MainPage.d__d.MoveNext()

The HRESULT varies.

Whats even more weird, it sometimes freezes the phone (like 2 out of 3 times) and I need to hold Power + Volume Down.

I tried decorating all methods with [STAThread], but it didn't help (http://technet.microsoft.com/en-ca/br226599).

What's even more more interesting, when I hold operations by debbuger using F10 to step over lines I am able to toggle preview as many times as I possibly want. It's werid, since debugger hold all threads, right? So in theory there is no difference?

Also, phone sometimes freezes on deploy... And that's just annoying.

Any ideas?

答:
if I understand correctly the button has a handler StartMeasure which is an async method and awaits for Start/StopPreviewAsync().
The problem might be that if you click the button more than once the one action might be still awaited(in progress) and the other one is also called, this might cause some issues because it will try to start and stop the preview at the same time which will probably lead to some race conditions.
You could check this by adding a lock to manage the access to the capture manager in order to test this. Also checking the bool and assigning it after an awaited operation is for sure not an atomic operation so that could lead to race conditions too.</p>

```<code>    private object locker;

    private async void StartMeasure(object sender, RoutedEventArgs e)
    {
        lock (locker)
        {
            if (_recording)
            {
                await _MediaCapture.StopPreviewAsync();
            }
            else
            {
                await _MediaCapture.StartPreviewAsync();
            }
            _recording = !_recording;
            _MediaCapture.VideoDeviceController.TorchControl.Enabled = _recording;
        }
    }
</code>```

Body:
I want to make a simple app that will allow me to check few parameters of every frame of preview, but I got stuck at running and stopping preview.

    ///
    /// An empty page that can be used on its own or navigated to within a Frame.
    ///
    public sealed partial class MainPage : Page
    {
        MediaCapture _MediaCapture;
        bool _recording;
        public MainPage()
        {
            this.InitializeComponent();

            this.NavigationCacheMode = NavigationCacheMode.Required;
        }

        ///
        /// Invoked when this page is about to be displayed in a Frame.
        ///
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            var rearCamera = devices[0];
            if (devices.Count > 0)
            {

                rearCamera = devices.Single(currDev =>
                  currDev.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back
                );
            }

            _MediaCapture = new MediaCapture();
            await _MediaCapture.InitializeAsync(new MediaCaptureInitializationSettings() { VideoDeviceId = rearCamera.Id });

// this is CaptureElement
            xCapture.Source = _MediaCapture;

            _recording = false;
        }

        protected override async void OnNavigatedFrom(NavigationEventArgs e)
        {
            if(_MediaCapture != null)
            {
                await _MediaCapture.StopPreviewAsync();
                await _MediaCapture.StopRecordAsync();

                _MediaCapture.Dispose();
                _MediaCapture = null;

                xCapture.Source = null;
            }

            base.OnNavigatedFrom(e);

        }

// button click handler
        private async void StartMeasure(object sender, RoutedEventArgs e)
        {
            if (_recording)
            {
                //await _MediaCapture.StopPreviewAsync();
                _MediaCapture.VideoDeviceController.TorchControl.Enabled = false;
                _recording = false;
            }
            else
            {
                //await _MediaCapture.StartPreviewAsync();
                _MediaCapture.VideoDeviceController.TorchControl.Enabled = true;
                _recording = true;
            }
        }
    }

In this form it works perfectly.

If I uncomment those preview lines it works, but only once.

If I press the button three times: on, off and on again I get exception at line with enabling TorchControl.

System.Exception: Exception from HRESULT: 0xE801000D at Windows.Media.Devices.TorchControl.put_Enabled(Boolean value) at Pulsometr3.MainPage.d__d.MoveNext()

The HRESULT varies.

Whats even more weird, it sometimes freezes the phone (like 2 out of 3 times) and I need to hold Power + Volume Down.

I tried decorating all methods with [STAThread], but it didn't help (http://technet.microsoft.com/en-ca/br226599).

What's even more more interesting, when I hold operations by debbuger using F10 to step over lines I am able to toggle preview as many times as I possibly want. It's werid, since debugger hold all threads, right? So in theory there is no difference?

Also, phone sometimes freezes on deploy... And that's just annoying.

Any ideas?

Body:
if I understand correctly the button has a handler StartMeasure which is an async method and awaits for Start/StopPreviewAsync().
The problem might be that if you click the button more than once the one action might be still awaited(in progress) and the other one is also called, this might cause some issues because it will try to start and stop the preview at the same time which will probably lead to some race conditions.
You could check this by adding a lock to manage the access to the capture manager in order to test this. Also checking the bool and assigning it after an awaited operation is for sure not an atomic operation so that could lead to race conditions too.

    private object locker;

    private async void StartMeasure(object sender, RoutedEventArgs e)
    {
        lock (locker)
        {
            if (_recording)
            {
                await _MediaCapture.StopPreviewAsync();
            }
            else
            {
                await _MediaCapture.StartPreviewAsync();
            }
            _recording = !_recording;
            _MediaCapture.VideoDeviceController.TorchControl.Enabled = _recording;
        }
    }


来源: stackexchange

问:
After Effects vector animations
I need to make loading animation from the logo. Logo is: a circle of beads made from circles of different sizes. About 12 pieces as it falls out of the total circumference. Logo in the format .ai. I am creating a ilustrator separated layers for each drop-down circle and open in after effects.
I do so, create a new composition, import ai file, add to composition and open the transformation options, change x and y guides in new keyframe, but nothing.
How do I create animation for these vector objects?</p>

答:
Right click on the layer in the compositing and choose "convert to layered comp". This will import each .ai layer as a new after effects layer. From there you can animate all you want!

Alternately you can click "create shapes from vector layer" which will convert it to shape layers. This can be advantageous for more complex animations, but if you just need position I would go with the above solution.

ContentLicense: CC BY-SA 3.0

Title: After Effects vector animations


问:
Schema Markup Not Showing
I have set up schema markup and ran the link through the testing tool with no errors: https://search.google.com/structured-data/testing-tool#url=http%3A%2F%2Fwww.laverysbelfast.com%2Fbuy-ulster-rugby-tickets-transport-rugby-union-tickets-kingspan-stadium .
However after trying to rejig the markup and reindexing the the site multiple times, it's still not showing up on Google: https://www.google.co.uk/search?q=ulster+rugby+tickets&ie=utf-8&oe=utf-8&client=firefox-b-ab&gws_rd=cr&ei=G4LNV5r_B8ydgAbl6pfwCQ#q=laverys+ulster+rugby+tickets .

Has anyone else had difficulties with this, or can anyone see why this wouldn't be displaying?

Cheers
DC

答:
Here are some examples you can add too your header.php, singlepage.php singlepost.php files too help with schema markup. Just change your information around.

  ```

Title: Schema Markup Not Showing

Body:
Here are some examples you can add too your header.php, singlepage.php singlepost.php files too help with schema markup. Just change your information around.

<script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "Person",
  "name": "long distance movers quote",
  "url": "http://www.longdistancemoversquote.com",
  "sameAs":
    "https://www.facebook.com/richard.russ.50"},
 </script>
<script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "Person",
  "name": "long distance movers quote",
  "url": "http://www.longdistancemoversquote.com",
  "sameAs":
    "https://www.facebook.com/longdistancemoversquote/"},
 </script>
<script type="application/ld+json">
{
  "@context":"http://schema.org",
  "@type":"ItemList",
  "itemListElement":[
    {
      "@type":"ListItem",
      "position":1,
      "url":"http://longdistancemoversquote.com/wp-content/uploads/2017/06/packinghelp.jpg"
    },
    {
      "@type":"ListItem",
      "position":2,
      "url":"http://longdistancemoversquote.com/wp-content/uploads/2017/06/localmovers.jpg"
    },
    {
      "@type":"ListItem",
      "position":3,
      "url":"http://longdistancemoversquote.com/wp-content/uploads/2017/06/moving-truck.png"
    }
  ]
}
</script>
<script type="application/ld+json">
{
  "@context": "http://schema.org/",
        "@type": "Blog",
        "about": "A Blog about how too be prepared when your about to move. We will help you hire professional movers. Read our blog and tell us about your move and get a free moving quote!",
        "headline": "Free Moving Quote From Profressional Movers",
        "keywords": "Moving Quote, Local Movers Quote, Tips for Long Distance Moving, Long Distance Movers Quote",
        "url": "http://longdistancemoversquote.com/blog/"},
                </script>
<script type="application/ld+json">{
  "@context": "http://schema.org/",
        "@type": "Action",
        "description": "Get a free moving quote from local moving helpers to help you load and unload a truck or too help you pack and unpack your boxes",
        "image": "http://longdistancemoversquote.com/wp-content/uploads/2017/06/packinghelp.jpg",
        "url": "http://longdistancemoversquote.com/packing-loading-unloading-helpers/"},
</script>
<script type="application/ld+json">{
  "@context": "http://schema.org/",
        "@type": "Action",
        "description": "Get a free moving quote from local movers!",
        "image": "http://longdistancemoversquote.com/wp-content/uploads/2017/06/localmovers.jpg",
        "url": "http://longdistancemoversquote.com/free-local-movers-quote/"},
</script>
<script type="application/ld+json">{
  "@context": "http://schema.org/",
        "@type": "Action",
        "description": "Get a free moving quote from local and long distance movers!",
        "image": "http://longdistancemoversquote.com/wp-content/uploads/2017/06/cropped-movers-1.jpg",
        "url": "http://www.longdistancemoversquote.com"},
</script>
<script type="application/ld+json">{
 "@context": "http://schema.org/",
    "@type": "Product",
    "name": "Moving Quote",
    "category": "Local and Long Distance Movers",
    "description": "Moving quote, Local movers quote, long distance movers quote",
 "url": "http://www.longdistancemoversquote.com"},

</script>
<script type="application/ld+json">{
  "@context": "http://schema.org/",
        "@type": "Organization",
        "address": "2122 w butler Dr Phoenix, AZ 85021",
        "founder": "Richard Russ",
        "email": "richruss05@yahoo.com",
  "url": "https://www.facebook.com/longdistancemoversquote/",
  "url": "http://longdistancemoversquote.com/"},

</script>
<script type="application/ld+json">{
  "@context": "http://schema.org/",
         "@type": "Thing",
  "image": "http://longdistancemoversquote.com/wp-content/uploads/2017/06/packinghelp.jpg",
        "description": "image with a link to local movers quote",
        "disambiguatingDescription": "help for packing and unpacking loading and unloading helpers",
        "url": "http://longdistancemoversquote.com/packing-loading-unloading-helpers/",
        "name":"Packing Help"},
</script>
<script type="application/ld+json">{
 "@context": "http://schema.org/",
    "@type": "Thing",
    "Name": "Local Movers Quote",
    "description": "Get a quote from professional movers. Do you need help moving soon? Do you need to hite local movers?",
    "sameas": "http://longdistancemoversquote.com/free-local-movers-quote/",
    "url": "http://longdistancemoversquote.com/free-local-movers-quote/"},
}
</script>
<script type="application/ld+json">
 {
    "@context": "http://schema.org/",
    "@type": "CreativeWork",
    "name": "Long Distance Moving quote",
    "about": "Get a free long distance moving quote. Getting a moving quote by professional movers for both local and long distance moves. Need help packing? WE CAN HELP"},
    }
    </script>
<script type="application/ld+json">
     {
      "@context": "http://schema.org/",
      "@type": "Website",
      "about": "Free Moving Quote - Free Long Distance Movers Quote",
      "name": "moving quote",
      "url": "http://www.longdistancemoversquote.com",
      "@type": "Website",
      "name": "long distance movers quote",
 "url": "http://longdistancemoversquote.com/long-distance-movers-quote/"},
 {
     "datePublished": "2017-06-20",
     "description": "Moving quote local long distance movers quote moving help local movers quote long distance movers quote"},
   </script>


问:
sum each value in a list of tuples
I have a list of tuples similar to this:

```<code>l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]
</code>```

I want to create a simple one-liner that will give me the following result:

```<code>r = (25, 20) or r = [25, 20] # don't care if tuple or list.
</code>```

Which would be like doing the following:

```<code>r = [0, 0]
for t in l:
  r[0]+=t[0]
  r[1]+=t[1]
</code>```

I am sure it is something very simple, but I can't think of it.

Note: I looked at similar questions already:

How do I sum the first value in a set of lists within a tuple?

How do I sum the first value in each tuple in a list of tuples in Python?

答:
Without using zip</p>

```<code>sum(e[0] for e in l), sum(e[1] for e in l)
</code>```

Title: sum each value in a list of tuples

Body:
I have a list of tuples similar to this:

l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]

I want to create a simple one-liner that will give me the following result:

r = (25, 20) or r = [25, 20] # don't care if tuple or list.

Which would be like doing the following:

r = [0, 0]
for t in l:
  r[0]+=t[0]
  r[1]+=t[1]

I am sure it is something very simple, but I can't think of it.

Note: I looked at similar questions already:

How do I sum the first value in a set of lists within a tuple?

How do I sum the first value in each tuple in a list of tuples in Python?

Body:
Without using zip

sum(e[0] for e in l), sum(e[1] for e in l)


问:
SQL Server : multi-join with tuple IN clause
I'm trying to join 4 tables that have a somewhat complex relationship. Because of where this will be used, it needs to be contained in a single query, but I'm having trouble since the primary query and the IN clause query both join 2 tables together and the lookup is on two columns.

The goal is to input a SalesNum and SalesType and have it return the Price

Tables and relationships:

sdShipping

```<code>SalesNum[1]
SalesType[2]
Weight[3]
</code>```

sdSales

```<code>SalesNum[1]
SalesType[2]
Zip[4]
</code>```

spZones

```<code>Zip[4]
Zone[5]
</code>```

spPrices

```<code>Zone[5]
Price
Weight[3]
</code>```

Here's my latest attempt in T-SQL:

```<code>SELECT
    spp.Price
FROM
    spZones AS spz
LEFT OUTER JOIN
    spPrices AS spp ON spz.Zone = spp.Zone
WHERE
    (spp.Weight, spz.Zip) IN (SELECT ship.Weight, sales.Zip
                              FROM sdShipping AS ship
                              LEFT OUTER JOIN sdSales AS sales ON sales.SalesNum = ship.SalesNum
                                                               AND sales.SalesType = ship.SalesType
                              WHERE sales.SalesNum = (?)
                                AND ship.SalesType = (?));
</code>```

SQL Server Management Studio says I have an error in my syntax near ',' (appropriately useless error message). Does anybody have any idea whether this is even allowed in Microsoft's version of SQL? Is there perhaps another way to accomplish it? I've seen the multi-key IN questions answered on here, but never in the case where both sides require a JOIN.

答:
Many databases do support IN on tuples.  SQL Server is not one of them.

Use EXISTS instead:

```<code>SELECT spp.Price
FROM spZones spz LEFT OUTER JOIN
     spPrices spp
     ON spz.Zone = spp.Zone
WHERE EXISTS (SELECT 1
              FROM sdShipping ship LEFT JOIN
                   sdSales sales
                   ON sales.SalesNum = ship.SalesNum AND
                      sales.SalesType = ship.SalesType
              WHERE spp.Weight = ship.Weight AND spz.Zip = sales.Zip AND
                    sales.SalesNum = (?) AND
                    ship.SalesType = (?)
             );
</code>```

Body:
I'm trying to join 4 tables that have a somewhat complex relationship. Because of where this will be used, it needs to be contained in a single query, but I'm having trouble since the primary query and the IN clause query both join 2 tables together and the lookup is on two columns.

The goal is to input a SalesNum and SalesType and have it return the Price

Tables and relationships:

sdShipping

SalesNum[1]
SalesType[2]
Weight[3]

sdSales

SalesNum[1]
SalesType[2]
Zip[4]

spZones

Zip[4]
Zone[5]

spPrices

Zone[5]
Price
Weight[3]

Here's my latest attempt in T-SQL:

SELECT
    spp.Price
FROM
    spZones AS spz
LEFT OUTER JOIN
    spPrices AS spp ON spz.Zone = spp.Zone
WHERE
    (spp.Weight, spz.Zip) IN (SELECT ship.Weight, sales.Zip
                              FROM sdShipping AS ship
                              LEFT OUTER JOIN sdSales AS sales ON sales.SalesNum = ship.SalesNum
                                                               AND sales.SalesType = ship.SalesType
                              WHERE sales.SalesNum = (?)
                                AND ship.SalesType = (?));

SQL Server Management Studio says I have an error in my syntax near ',' (appropriately useless error message). Does anybody have any idea whether this is even allowed in Microsoft's version of SQL? Is there perhaps another way to accomplish it? I've seen the multi-key IN questions answered on here, but never in the case where both sides require a JOIN.

Body:
Many databases do support IN on tuples.  SQL Server is not one of them.

Use EXISTS instead:

SELECT spp.Price
FROM spZones spz LEFT OUTER JOIN
     spPrices spp
     ON spz.Zone = spp.Zone
WHERE EXISTS (SELECT 1
              FROM sdShipping ship LEFT JOIN
                   sdSales sales
                   ON sales.SalesNum = ship.SalesNum AND
                      sales.SalesType = ship.SalesType
              WHERE spp.Weight = ship.Weight AND spz.Zip = sales.Zip AND
                    sales.SalesNum = (?) AND
                    ship.SalesType = (?)
             );


问:
How to query json data in angular 2
I want to query JSON data based on some conditions using angular2

My json is:

```<code>{
"logsArray":[
    {
        "Id": "1",
        "ProjectName": "Project01",
        "ModuleName": "Module01",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "2",
        "ProjectName": "Project02",
        "ModuleName": "Module01",
        "MethodName": "Method03",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "3",
        "ProjectName": "Project03",
        "ModuleName": "Module05",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "4",
        "ProjectName": "Project01",
        "ModuleName": "Module07",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "5",
        "ProjectName": "Project03",
        "ModuleName": "Module01",
        "MethodName": "Method10",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "6",
        "ProjectName": "Project06",
        "ModuleName": "Module01",
        "MethodName": "Method05",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "7",
        "ProjectName": "Project03",
        "ModuleName": "Module03",
        "MethodName": "Method07",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "8",
        "ProjectName": "Project04",
        "ModuleName": "Module03",
        "MethodName": "Method05",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    }
]
}
</code>```

I want to get the particular property based on some conditions like

Distinct ProjectNames where PojectName = Project03

Distincts ModuleNames where ModuleName = Module02 && MethodName = Method01

Distinct Method Names ProjectName = Project01

答:
Use angular 2 http get method to get json data in your angular service.

this.http.get(./filename.json)
.map((res:Response)=>res.json())
.subscribe(data=>this.temp=data.logsArray.filter())

Or you can use filter method of Observables.

Title: How to query json data in angular 2

Body:
I want to query JSON data based on some conditions using angular2

My json is:

{
"logsArray":[
    {
        "Id": "1",
        "ProjectName": "Project01",
        "ModuleName": "Module01",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "2",
        "ProjectName": "Project02",
        "ModuleName": "Module01",
        "MethodName": "Method03",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "3",
        "ProjectName": "Project03",
        "ModuleName": "Module05",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "4",
        "ProjectName": "Project01",
        "ModuleName": "Module07",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "5",
        "ProjectName": "Project03",
        "ModuleName": "Module01",
        "MethodName": "Method10",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "6",
        "ProjectName": "Project06",
        "ModuleName": "Module01",
        "MethodName": "Method05",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "7",
        "ProjectName": "Project03",
        "ModuleName": "Module03",
        "MethodName": "Method07",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "8",
        "ProjectName": "Project04",
        "ModuleName": "Module03",
        "MethodName": "Method05",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    }
]
}

I want to get the particular property based on some conditions like

Distinct ProjectNames where PojectName = Project03

Distincts ModuleNames where ModuleName = Module02 && MethodName = Method01

Distinct Method Names ProjectName = Project01


问:
jQuery browser detection?
Is there a good way to detect if the user's browser is Internet Explorer using jQuery?

I have an issue with PNG graphics using IE and want to swap them for GIF's only if the user is viewing the site with IE.

答:
```<code><script>
    jQuery.each(jQuery.browser, function(i, val) {
      $("<div>" + i + " : <span>" + val + "</span>")
                .appendTo(document.body);
    });</script>
</code>```

$.browser.msie
 for IE

Title: jQuery browser detection?

Body:
<script>
    jQuery.each(jQuery.browser, function(i, val) {
      $("<div>" + i + " : <span>" + val + "</span>")
                .appendTo(document.body);
    });</script>

$.browser.msie
 for IE

ContentLicense: CC BY-SA 2.5


问:
Qt/QML: How to activate a Shortcut from C++?
I have an application which receives input from a serial port and interprets them as key events. The key events are created in C++ and sent to QGuiApplication::focusWindow() with qApp->sendEvent.

The GUI is implemented in QML and has been handling input through key event handlers. I would like to start using the Shortcut QML class to handle cases where I want behavior regardless of which object has focus.

I've discovered that Shortcuts which respond to a real keyboard will not respond to qApp->sendEvent, nor do they respond to qApp->postEvent.

Getting the behavior I want to reliably occur without Shortcut would be a real pain - is there I way I can handle my synthetic events which will make them visible to Shortcut?

答:
Qt shortcut objects work through parts of the Qt system which are not part of the regular API, but are exposed to QPA. Specifically, QWindowSystemInterface::handleShortcutEvent, which takes as arguments the current focus window and most of the information encapsulated in a QKeyEvent.

```<code>// A helper to send a QKeyEvent to shortcuts
bool handleShortcutEvent(const QKeyEvent &ev, QWindow *focusWindow) {
    return QWindowSystemInterface::handleShortcutEvent(focusWindow, ev.timestamp(), ev.key(), ev.modifiers(), ev.nativeScanCode(), ev.nativeVirtualKey(), ev.nativeModifiers(), ev.text(), ev.isAutoRepeat(), ev.count());
}
// in my key event generating function
    if(!handleShortcutEvent(event, focusWindow))
        qApp->sendEvent(focusWindow, &event);
</code>```

Body:
Qt shortcut objects work through parts of the Qt system which are not part of the regular API, but are exposed to QPA. Specifically, QWindowSystemInterface::handleShortcutEvent, which takes as arguments the current focus window and most of the information encapsulated in a QKeyEvent.

// A helper to send a QKeyEvent to shortcuts
bool handleShortcutEvent(const QKeyEvent &ev, QWindow *focusWindow) {
    return QWindowSystemInterface::handleShortcutEvent(focusWindow, ev.timestamp(), ev.key(), ev.modifiers(), ev.nativeScanCode(), ev.nativeVirtualKey(), ev.nativeModifiers(), ev.text(), ev.isAutoRepeat(), ev.count());
}
// in my key event generating function
    if(!handleShortcutEvent(event, focusWindow))
        qApp->sendEvent(focusWindow, &event);


问:
Kotlin + Dagger 2: Dagger* files won't generate
I started using Kotlin and Dagger 2 together for the first time. I assumed everything is the same as in Java, but apparently, not quite. Dagger won't generate Dagger*files for me. Here is my code:

Components:

```<code>@PerActivity
@Subcomponent(modules = arrayOf(ApplicationModule::class))
interface ActivityComponent {
    fun inject(app: OneAccountApplication)
}
</code>```

```<code>@Singleton
@Component(modules = arrayOf(ApplicationModule::class))
interface ApplicationComponent {

fun inject(syncService: SyncService)
@ApplicationContext fun context(): Context
fun application(): Application
fun ribotsService(): OneAccountService
fun preferencesHelper(): PreferencesHelper
fun databaseHelper(): DatabaseHelper
fun dataManager(): DataManager
}
</code>```

```<code>@ConfigPersistent
@Component(dependencies = arrayOf(ApplicationComponent::class))
interface ConfigPersistentComponent {
    fun activityComponent(activityModule: ActivityModule): ActivityComponent
}
</code>```

Modules:

```<code>@Module
class ActivityModule(private val mActivity: Activity) {

    @Provides
    internal fun provideActivity() = mActivity

    @Provides
    @ActivityContext
    internal fun providesContext() = mActivity
}
</code>```

```<code>@Module
class ApplicationModule(val mApplication: Application) {

    @Provides @Singleton
    internal fun provideApplication() = mApplication

    @Provides
    @ApplicationContext
    internal fun provideContext() = mApplication

    @Provides
    @Singleton
    internal fun provideOneAccountService() = OneAccountService.Creator.newOneAccountService()
}
</code>```

Scope Annotations:

```<code>@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityContext
</code>```

```<code>@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ApplicationContext
</code>```

```<code>@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ConfigPersistent
</code>```

```<code>@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class PerActivity
</code>```

This is basically my whole DI system which I was using in my java code successfully. But with Kotlin, for some reason it does not work. I have also added: apply plugin: 'kotlin-kapt' to gradle.build like:

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
</code>```

And in dependencies I have:

```<code>@Singleton
@Component(modules = arrayOf(ApplicationModule::class))
interface ApplicationComponent {

fun inject(syncService: SyncService)
@ApplicationContext fun context(): Context
fun application(): Application
fun ribotsService(): OneAccountService
fun preferencesHelper(): PreferencesHelper
fun databaseHelper(): DatabaseHelper
fun dataManager(): DataManager
}
</code>```0

Basically, this it https://github.com/ribot/android-boilerplate transformed into Kotlin.

答:
Kotlin works with kapt instead of the annotationProcessor from the Android plugin.

You need to include and use the following in your build.gradle file:

```<code>kapt {
    generateStubs = true
}
dependencies {
    // ...
    kapt daggerCompiler
}
</code>```

More detailed instructions can also be found here: Dagger and Kotlin

Body:
I started using Kotlin and Dagger 2 together for the first time. I assumed everything is the same as in Java, but apparently, not quite. Dagger won't generate Dagger*files for me. Here is my code:

Components:

@PerActivity
@Subcomponent(modules = arrayOf(ApplicationModule::class))
interface ActivityComponent {
    fun inject(app: OneAccountApplication)
}

@Singleton
@Component(modules = arrayOf(ApplicationModule::class))
interface ApplicationComponent {

fun inject(syncService: SyncService)
@ApplicationContext fun context(): Context
fun application(): Application
fun ribotsService(): OneAccountService
fun preferencesHelper(): PreferencesHelper
fun databaseHelper(): DatabaseHelper
fun dataManager(): DataManager
}

@ConfigPersistent
@Component(dependencies = arrayOf(ApplicationComponent::class))
interface ConfigPersistentComponent {
    fun activityComponent(activityModule: ActivityModule): ActivityComponent
}

Modules:

@Module
class ActivityModule(private val mActivity: Activity) {

    @Provides
    internal fun provideActivity() = mActivity

    @Provides
    @ActivityContext
    internal fun providesContext() = mActivity
}

@Module
class ApplicationModule(val mApplication: Application) {

    @Provides @Singleton
    internal fun provideApplication() = mApplication

    @Provides
    @ApplicationContext
    internal fun provideContext() = mApplication

    @Provides
    @Singleton
    internal fun provideOneAccountService() = OneAccountService.Creator.newOneAccountService()
}

Scope Annotations:

@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityContext

@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ApplicationContext

@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ConfigPersistent

@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class PerActivity

This is basically my whole DI system which I was using in my java code successfully. But with Kotlin, for some reason it does not work. I have also added: apply plugin: 'kotlin-kapt' to gradle.build like:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

And in dependencies I have:

dependencies {

    final DAGGER_VERSION = '2.8'
    def daggerCompiler = "com.google.dagger:dagger-compiler:$DAGGER_VERSION"
    annotationProcessor daggerCompiler
    testAnnotationProcessor daggerCompiler
    androidTestAnnotationProcessor daggerCompiler
    compile  "com.google.dagger:dagger:$DAGGER_VERSION"
}
kapt {
    generateStubs = true
}

Basically, this it https://github.com/ribot/android-boilerplate transformed into Kotlin.

Body:
Kotlin works with kapt instead of the annotationProcessor from the Android plugin.

You need to include and use the following in your build.gradle file:

kapt {
    generateStubs = true
}
dependencies {
    // ...
    kapt daggerCompiler
}

More detailed instructions can also be found here: Dagger and Kotlin


问:
Bash - file path can not be read for LAME encoder
How do I properly escape the path to come out of find to a new command argument?

```<code>#!/bin/bash

for f in $(find . -type f -name '*.flac')
       do
           if flac -cd "$f" | lame -bh 320 - "${f%.*}".mp3; then
              rm -f "$f"
              echo "removed $f"
            fi
       done
</code>```

returns

```<code>lame: excess arg Island of the Gods - 3.mp3
</code>```

答:
Using a Bash for loop is not ideal for the results of find or ls. There are other ways to do it.

You may want to use -print0 and xargs to avoid word splitting issues.

```<code>$ find [path] -type f -name *.flac -print0 | xargs -0 [command line {xargs puts in fn}]
</code>```

Or use -exec primary in find:

```<code>$ find [path] -type f -name *.flac -exec [process {find puts in fn}] \;
</code>```

Alternative, you can use a while loop:

```<code>find [path] -type f -name *.flac | while IFS= read -r fn; do  # fn not quoted here...
  echo "$fn"                                          # QUOTE fn here!
  # body of your loop
done
</code>```

Body:
How do I properly escape the path to come out of find to a new command argument?

#!/bin/bash

for f in $(find . -type f -name '*.flac')
       do
           if flac -cd "$f" | lame -bh 320 - "${f%.*}".mp3; then
              rm -f "$f"
              echo "removed $f"
            fi
       done

returns

lame: excess arg Island of the Gods - 3.mp3

Body:
Using a Bash for loop is not ideal for the results of find or ls. There are other ways to do it.

You may want to use -print0 and xargs to avoid word splitting issues.

$ find [path] -type f -name *.flac -print0 | xargs -0 [command line {xargs puts in fn}]

Or use -exec primary in find:

$ find [path] -type f -name *.flac -exec [process {find puts in fn}] \;

Alternative, you can use a while loop:

find [path] -type f -name *.flac | while IFS= read -r fn; do  # fn not quoted here...
  echo "$fn"                                          # QUOTE fn here!
  # body of your loop
done


问:
Eclipse plugin dependency on SWT classes not being resolved
I have an eclipse plugin project which uses some swt objects, eg -

```<code>import org.eclipse.swt.widgets.Composite;
</code>```

When I try to compile it with the 'Target Platform' set to 'Running Platform (Active)', it compiles fine and I dont need to import any swt specific plugins.

However, I created a target platform with Eclipse 3.6.0 and if I set it as the active platform the project has compile errors wherever swt classes are used and cannot resolve them.

Which plugin should I add a dependency to, to resolve these errors?

I tried adding 'org.eclipse.swt' but that does not seem to help.

答: I figured it out. I was trying to compile against a 32 bit target platform on a 64 bit OS, so the filters were not matching the SWT libraries until I set them manually from the target platform preferences.</p>

Body:
I have an eclipse plugin project which uses some swt objects, eg -

import org.eclipse.swt.widgets.Composite;

When I try to compile it with the 'Target Platform' set to 'Running Platform (Active)', it compiles fine and I dont need to import any swt specific plugins.

However, I created a target platform with Eclipse 3.6.0 and if I set it as the active platform the project has compile errors wherever swt classes are used and cannot resolve them.

Which plugin should I add a dependency to, to resolve these errors?

I tried adding 'org.eclipse.swt' but that does not seem to help.


问:
Understanding the Gemfile.lock file
After running the bundle install command, 'Gemfile.lock' is created in the working directory. What do the directives inside that file mean?

For example, let's take the following file:

```<code>PATH
  remote: .
  specs:
    gem_one (0.0.1)

GEM
  remote: http://example.org/
  specs:
    gem_two (0.0.2)
    gem_three (0.0.3)
      gem_four (0.0.4)

PLATFORMS
  platform

DEPENDENCIES
  gem_two
  gem_one!
</code>```

What do 'PATH', 'GEM', 'PLATFORMS' and 'DEPENDENCIES' describe? Are all of them required?

What should contain the 'remote' and 'specs' subdirectives?

What does the exclamation mark after the gem name in the 'DEPENDENCIES' group mean?

答:
I've spent the last few months messing around with Gemfiles and Gemfile.locks a lot whilst building an automated dependency update tool1. The below is far from definitive, but it's a good starting point for understanding the Gemfile.lock format. You might also want to check out the source code for Bundler's lockfile parser.

You'll find the following headings in a lockfile generated by Bundler 1.x:

GEM (optional but very common)

These are dependencies sourced from a Rubygems server. That may be the main Rubygems index, at Rubygems.org, or it may be a custom index, such as those available from Gemfury and others. Within this section you'll see:

remote: one or more lines specifying the location of the Rubygems index(es)

specs: a list of dependencies, with their version number, and the constraints on any subdependencies

GIT (optional)

These are dependencies sourced from a given git remote. You'll see a different one of these sections for each git remote, and within each section you'll see:

remote: the git remote. E.g., git@github.com:rails/rails

revision: the commit reference the Gemfile.lock is locked to

tag: (optional) the tag specified in the Gemfile

specs: the git dependency found at this remote, with its version number, and the constraints on any subdependencies

PATH (optional)

These are dependencies sourced from a given path, provided in the Gemfile. You'll see a different one of these sections for each path dependency, and within each section you'll see:

remote: the path. E.g., plugins/vendored-dependency

specs: the git dependency found at this remote, with its version number, and the constraints on any subdependencies

PLATFORMS

The Ruby platform the Gemfile.lock was generated against. If any dependencies in the Gemfile specify a platform then they will only be included in the Gemfile.lock when the lockfile is generated on that platform (e.g., through an install).

DEPENDENCIES

A list of the dependencies which are specified in the Gemfile, along with the version constraint specified there.

Dependencies specified with a source other than the main Rubygems index (e.g., git dependencies, path-based, dependencies) have a ! which means they are "pinned" to that source2 (although one must sometimes look in the Gemfile to determine in).

RUBY VERSION (optional)

The Ruby version specified in the Gemfile, when this Gemfile.lock was created. If a Ruby version is specified in a .ruby_version file instead this section will not be present (as Bundler will consider the Gemfile / Gemfile.lock agnostic to the installer's Ruby version).

BUNDLED WITH (Bundler >= v1.10.x)

The version of Bundler used to create the Gemfile.lock. Used to remind installers to update their version of Bundler, if it is older than the version that created the file.

PLUGIN SOURCE (optional and very rare)

In theory, a Gemfile can specify Bundler plugins, as well as gems3, which would then be listed here. In practice, I'm not aware of any available plugins, as of July 2017. This part of Bundler is still under active development!

https://dependabot.com

https://github.com/bundler/bundler/issues/4631

http://andre.arko.net/2012/07/23/towards-a-bundler-plugin-system/

ContentLicense: CC BY-SA 4.0

Title: Understanding the Gemfile.lock file

Body:
After running the bundle install command, 'Gemfile.lock' is created in the working directory. What do the directives inside that file mean?

For example, let's take the following file:

PATH
  remote: .
  specs:
    gem_one (0.0.1)

GEM
  remote: http://example.org/
  specs:
    gem_two (0.0.2)
    gem_three (0.0.3)
      gem_four (0.0.4)

PLATFORMS
  platform

DEPENDENCIES
  gem_two
  gem_one!

What do 'PATH', 'GEM', 'PLATFORMS' and 'DEPENDENCIES' describe? Are all of them required?

What should contain the 'remote' and 'specs' subdirectives?

What does the exclamation mark after the gem name in the 'DEPENDENCIES' group mean?


问:
Select Parent and Child if child has records
I have 3 tables: firearms_firearmbook, inventory_inventory and inventory_inventorytransaction.

And i have 2 Cases:

If inventory_inventory Table has no inventory_inventorytransaction with item action of 16, show inventory_inventory record

If inventory_inventory Table has inventory_inventorytransaction with item action of 16, show inventory_inventory and inventory_inventorytransaction.item_action_id

The query bellow works for the first cause, but its not working for the second cause.
It should show smth like this:

```<code>-----------------------------------
| id    |    serial   | action_id |
-----------------------------------
   1         MAGUM
   2         EAGLE
   2         EAGLE         16
</code>```

Query:

```<code>SELECT FB.id, INV.serial_number, INV.id, INVT.item_action_id FROM firearms_firearmbook AS FB
LEFT JOIN inventory_inventory AS INV ON INV.id = FB.item_id
LEFT JOIN inventory_inventorytransaction AS INVT ON INVT.item_id = INV.id AND INVT.item_action_id = 16
WHERE FB.store_id = 1
</code>```

答:
Hi I think this is what your after.

I've made a CASE statement for the two situation you describe. I wasn't sure what you column you wanted for 2) when you say "inventory_inventory" so I put the id column and you can change it for another column.

I've also removed INVT.item_action_id = 16 part of the inventory_inventorytransaction join as I don't think it's necessary as it is handled in the CASE statement.

```<code>SELECT
FB.id,
INV.serial_number,
INV.id,
INVT.item_action_id,
CASE
  WHEN INVT.item_action_id = 16 THEN CAST(INV.id as VARCHAR)  + ' ' + CAST(INVT.item_action_id as VARCHAR) -- This is Case 2
  ELSE INV.record -- This is Case 1
END as answer
FROM firearms_firearmbook AS FB
LEFT JOIN inventory_inventory AS INV ON INV.id = FB.item_id
LEFT JOIN inventory_inventorytransaction AS INVT ON INVT.item_id = INV.id -- Removed JOIN on INVT.item_action_id = 16 and moved it to CASE
WHERE FB.store_id = 1;
</code>```

Body:
I have 3 tables: firearms_firearmbook, inventory_inventory and inventory_inventorytransaction.

And i have 2 Cases:

If inventory_inventory Table has no inventory_inventorytransaction with item action of 16, show inventory_inventory record

If inventory_inventory Table has inventory_inventorytransaction with item action of 16, show inventory_inventory and inventory_inventorytransaction.item_action_id

The query bellow works for the first cause, but its not working for the second cause.
It should show smth like this:

-----------------------------------
| id    |    serial   | action_id |
-----------------------------------
   1         MAGUM
   2         EAGLE
   2         EAGLE         16

Query:

SELECT FB.id, INV.serial_number, INV.id, INVT.item_action_id FROM firearms_firearmbook AS FB
LEFT JOIN inventory_inventory AS INV ON INV.id = FB.item_id
LEFT JOIN inventory_inventorytransaction AS INVT ON INVT.item_id = INV.id AND INVT.item_action_id = 16
WHERE FB.store_id = 1

Body:
Hi I think this is what your after.

I've made a CASE statement for the two situation you describe. I wasn't sure what you column you wanted for 2) when you say "inventory_inventory" so I put the id column and you can change it for another column.

I've also removed INVT.item_action_id = 16 part of the inventory_inventorytransaction join as I don't think it's necessary as it is handled in the CASE statement.

SELECT
FB.id,
INV.serial_number,
INV.id,
INVT.item_action_id,
CASE
  WHEN INVT.item_action_id = 16 THEN CAST(INV.id as VARCHAR)  + ' ' + CAST(INVT.item_action_id as VARCHAR) -- This is Case 2
  ELSE INV.record -- This is Case 1
END as answer
FROM firearms_firearmbook AS FB
LEFT JOIN inventory_inventory AS INV ON INV.id = FB.item_id
LEFT JOIN inventory_inventorytransaction AS INVT ON INVT.item_id = INV.id -- Removed JOIN on INVT.item_action_id = 16 and moved it to CASE
WHERE FB.store_id = 1;


问:
Find a space with regex under specific conditions
```<code>ERY Som
</code>```

I wanna find the space between those words:

I can find the text like this:

```<code>([A-Z]{3}\s[A-Z]{1}[a-z]{2})
</code>```

But how can i select the space so i replace it with a \n?

Thanks!

答:
You don't select the part you want to replace, you select the parts you want to keep. Then copy them to the result, with the replacement for space put in its place.</p>

```<code>Match: ([A-Z]{3})\s([A-Z]{1}[a-z]{2})
Replace: $1\n$2
</code>```

Body:
ERY Som

I wanna find the space between those words:

I can find the text like this:

([A-Z]{3}\s[A-Z]{1}[a-z]{2})

But how can i select the space so i replace it with a \n?

Thanks!

Body:
You don't select the part you want to replace, you select the parts you want to keep. Then copy them to the result, with the replacement for space put in its place.

Match: ([A-Z]{3})\s([A-Z]{1}[a-z]{2})
Replace: $1\n$2


答:
Yes, you can, but they prefer you to use jQuery.support: http://api.jquery.com/jQuery.support/.

In this case, use jQuery.support.opacity.

Edit: assuming this is about opacity, of course.

Title: jQuery browser detection?

Body:
Is there a good way to detect if the user's browser is Internet Explorer using jQuery?

I have an issue with PNG graphics using IE and want to swap them for GIF's only if the user is viewing the site with IE.


问:
Why isn't my table updated after an ajax call?
I have a bootstrap-table.js table based on a HTML table build up from a MySQL database. See code:

```<code><table id="table2" class="table table-striped table-hover table-no-bordered"
data-toggle="table"
data-search="true"
data-pagination="true"
data-page-size="25"
data-show-refresh="true"
data-url="stemmen.php"
data-side-pagination="client"
data-unique-id="id"
>                                           <thead>
<tr>
    <th data-field="id" data-visible="false">ID</th>
   <th data-field="timestamp">datum & tijd</th>
   <th data-field="email">e-mailadres</th>
   <th data-field="stem">stem</th>
   <th data-formatter="operateFormatter" data-events="operateEvents"></th>
</tr>
</thead>
</table>
</code>```

As you can see in the last column there's a button to remove the row. This triggers an ajax script.

```<code>function operateFormatter(value, row, index) {
    return [
        '<button class="btn btn-xs btn-danger voteremove"><i class="fa fa-trash"></i></button>'
    ].join('');
};

window.operateEvents = {
        'click .like': function (e, value, row, index) {
        alert('You click like icon, row: ' + JSON.stringify(row));
        console.log(value, row, index);
    },
    'click .edit': function (e, value, row, index) {
        alert('You click edit icon, row: ' + JSON.stringify(row));
        console.log(value, row, index);
    },
    'click .voteremove': function (e, value, row, index) {
        var id = [row.id];
        if(confirm("Weet je zeker dat je deze stem wilt verwijderen?")){
        var $table = $(this).closest('table').attr('id');
               $.ajax({
                  type: 'POST',
                   url: 'functions.php?action=removeVote',
                   data: 'vote_id=' + id,
                   cache: false,
                   success: function () {
                        $($table).bootstrapTable('remove', {
                            field: 'id',
                            values: [row.id]
                        });

                       $(formMessages).removeClass('alert-danger');
                           $(formMessages).addClass('alert-success');
                        $(formMessages).text('succesvol verwijderd');
                       $(formMessages).show();

                    },
                   error: function(){
                           $(formMessages).removeClass('alert-success');
                           $(formMessages).addClass('alert-danger');
                        $(formMessages).text('er is een fout opgetreden!');
                       $(formMessages).show();
                   }
               });
        }
    }
};
</code>```

Now my issue. The ajax action is triggered and performing well, the message is displayed, but the row is not removed from the table, unless you refresh the page.

Thanks for your help in advance!

答:
OK, it's solved! Thanks to the motivation of univ to change the way of loading data, and some other small issues. Below you'll find the code.

JS

```<code>function operateFormatter(value, row, index) {
    return [
        '<button class="btn btn-xs btn-danger voteremove"><i class="fa fa-trash"></i></button>'
    ].join('');
};

window.operateEvents = {
        'click .like': function (e, value, row, index) {
        alert('You click like icon, row: ' + JSON.stringify(row));
        console.log(value, row, index);
    },
    'click .edit': function (e, value, row, index) {
        alert('You click edit icon, row: ' + JSON.stringify(row));
        console.log(value, row, index);
    },
    'click .voteremove': function (e, value, row, index) {
        if(confirm("Weet je zeker dat je deze stem wilt verwijderen?")){
            var id = [row.id];
            var formMessages = $('#messages');
            var table = '#table2';
               $.ajax({
                  type: 'POST',
                   url: 'functions.php?action=removeVote',
                   data: 'vote_id=' + id,
                   cache: false,
                   success: function () {
                        $(table).bootstrapTable('remove', {
                            field: 'id',
                            values: id
                        });
                        $(formMessages).removeClass('alert-danger');
                        $(formMessages).addClass('alert-success');
                        $(formMessages).text('succesvol verwijderd');
                        $(formMessages).show();
                    },
                   error: function(){
                        $(formMessages).removeClass('alert-success');
                        $(formMessages).addClass('alert-danger');
                        $(formMessages).text('er is een fout opgetreden!');
                        $(formMessages).show();
                   }
               });
        }
    }
};
</code>```

HTML

```<code><table id="table2" class="table table-striped table-hover table-no-bordered"
data-toggle="table"
data-search="true"
data-pagination="true"
data-page-size="25"
data-show-refresh="true"
data-url="stemmen.php"
data-side-pagination="client"
data-unique-id="id"
>                                           <thead>
<tr>
    <th data-field="id" data-visible="false">ID</th>
   <th data-field="timestamp">datum & tijd</th>
   <th data-field="email">e-mailadres</th>
   <th data-field="stem">stem</th>
   <th data-formatter="operateFormatter" data-events="operateEvents"></th>
</tr>
</thead>
</table>
</code>```

Body:
I have a bootstrap-table.js table based on a HTML table build up from a MySQL database. See code:

    ID
   datum & tijd
   e-mailadres
   stem

As you can see in the last column there's a button to remove the row. This triggers an ajax script.

function operateFormatter(value, row, index) {
    return [
        '<button class="btn btn-xs btn-danger voteremove"></button>'
    ].join('');
};

window.operateEvents = {
        'click .like': function (e, value, row, index) {
        alert('You click like icon, row: ' + JSON.stringify(row));
        console.log(value, row, index);
    },
    'click .edit': function (e, value, row, index) {
        alert('You click edit icon, row: ' + JSON.stringify(row));
        console.log(value, row, index);
    },
    'click .voteremove': function (e, value, row, index) {
        var id = [row.id];
        if(confirm("Weet je zeker dat je deze stem wilt verwijderen?")){
        var $table = $(this).closest('table').attr('id');
               $.ajax({
                  type: 'POST',
                   url: 'functions.php?action=removeVote',
                   data: 'vote_id=' + id,
                   cache: false,
                   success: function () {
                        $($table).bootstrapTable('remove', {
                            field: 'id',
                            values: [row.id]
                        });

                       $(formMessages).removeClass('alert-danger');
                           $(formMessages).addClass('alert-success');
                        $(formMessages).text('succesvol verwijderd');
                       $(formMessages).show();

                    },
                   error: function(){
                           $(formMessages).removeClass('alert-success');
                           $(formMessages).addClass('alert-danger');
                        $(formMessages).text('er is een fout opgetreden!');
                       $(formMessages).show();
                   }
               });
        }
    }
};

Now my issue. The ajax action is triggered and performing well, the message is displayed, but the row is not removed from the table, unless you refresh the page.

Thanks for your help in advance!

Body:
OK, it's solved! Thanks to the motivation of univ to change the way of loading data, and some other small issues. Below you'll find the code.

JS

function operateFormatter(value, row, index) {
    return [
        '<button class="btn btn-xs btn-danger voteremove"><i class="fa fa-trash"></i></button>'
    ].join('');
};

window.operateEvents = {
        'click .like': function (e, value, row, index) {
        alert('You click like icon, row: ' + JSON.stringify(row));
        console.log(value, row, index);
    },
    'click .edit': function (e, value, row, index) {
        alert('You click edit icon, row: ' + JSON.stringify(row));
        console.log(value, row, index);
    },
    'click .voteremove': function (e, value, row, index) {
        if(confirm("Weet je zeker dat je deze stem wilt verwijderen?")){
            var id = [row.id];
            var formMessages = $('#messages');
            var table = '#table2';
               $.ajax({
                  type: 'POST',
                   url: 'functions.php?action=removeVote',
                   data: 'vote_id=' + id,
                   cache: false,
                   success: function () {
                        $(table).bootstrapTable('remove', {
                            field: 'id',
                            values: id
                        });
                        $(formMessages).removeClass('alert-danger');
                        $(formMessages).addClass('alert-success');
                        $(formMessages).text('succesvol verwijderd');
                        $(formMessages).show();
                    },
                   error: function(){
                        $(formMessages).removeClass('alert-success');
                        $(formMessages).addClass('alert-danger');
                        $(formMessages).text('er is een fout opgetreden!');
                        $(formMessages).show();
                   }
               });
        }
    }
};

HTML

<table id="table2" class="table table-striped table-hover table-no-bordered"
data-toggle="table"
data-search="true"
data-pagination="true"
data-page-size="25"
data-show-refresh="true"
data-url="stemmen.php"
data-side-pagination="client"
data-unique-id="id"
>                                           <thead>
<tr>
    <th data-field="id" data-visible="false">ID</th>
   <th data-field="timestamp">datum &amp; tijd</th>
   <th data-field="email">e-mailadres</th>
   <th data-field="stem">stem</th>
   <th data-formatter="operateFormatter" data-events="operateEvents"></th>
</tr>
</thead>
</table>


问:
Set the image for switch button in flutter
How do I set the image for a switch button in flutter using the activeThumbImage property? I am a little confused on how to set the ImageProvider value for this property? Is there any example that I could look at that implements the activeThumbImage property of the Switch widget?</p>

答:
You can use an AssetImage or NetworkImage to get an ImageProvider that is suitable for use as an activeThumbImage. Learn more about asset images in the Adding Assets and Images in Flutter tutorial.

Here is some example code that draws the above Switch:

```<code>import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  MyHomePageState createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {

  bool _enabled;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new Switch(
          value: _enabled,
          onChanged: (bool value) {
            setState(() {
              _enabled = value;
            });
          },
          activeThumbImage: new NetworkImage('https://lists.gnu.org/archive/html/emacs-devel/2015-10/pngR9b4lzUy39.png'),
          inactiveThumbImage: new NetworkImage('http://wolfrosch.com/_img/works/goodies/icon/vim@2x'),
        ),
      )
    );
  }
}

void main() {
  runApp(new MaterialApp(
    title: 'Flutter Demo',
    theme: new ThemeData(
      primarySwatch: Colors.deepPurple,
    ),
    home: new MyHomePage(),
  ));
}
</code>```

Body:
You can use an AssetImage or NetworkImage to get an ImageProvider that is suitable for use as an activeThumbImage. Learn more about asset images in the Adding Assets and Images in Flutter tutorial.

Here is some example code that draws the above Switch:

import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  MyHomePageState createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {

  bool _enabled;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new Switch(
          value: _enabled,
          onChanged: (bool value) {
            setState(() {
              _enabled = value;
            });
          },
          activeThumbImage: new NetworkImage('https://lists.gnu.org/archive/html/emacs-devel/2015-10/pngR9b4lzUy39.png'),
          inactiveThumbImage: new NetworkImage('http://wolfrosch.com/_img/works/goodies/icon/vim@2x'),
        ),
      )
    );
  }
}

void main() {
  runApp(new MaterialApp(
    title: 'Flutter Demo',
    theme: new ThemeData(
      primarySwatch: Colors.deepPurple,
    ),
    home: new MyHomePage(),
  ));
}


问:
Remove the extra plot in the matplotlib subplot
I want to plot 5 data frames in a 2 by 3 setting (i.e. 2 rows and 3 columns). This is my code: However there is an extra empty plot in the 6th position (second row and third column) which I want to get rid of it. I am wondering how I could remove it so that I have three plots in the first row and two plots in the second row.

```<code>import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=3)

fig.set_figheight(8)
fig.set_figwidth(15)

df[2].plot(kind='bar',ax=axes[0,0]); axes[0,0].set_title('2')

df[4].plot(kind='bar',ax=axes[0,1]); axes[0,1].set_title('4')

df[6].plot(kind='bar',ax=axes[0,2]); axes[0,2].set_title('6')

df[8].plot(kind='bar',ax=axes[1,0]); axes[1,0].set_title('8')

df[10].plot(kind='bar',ax=axes[1,1]); axes[1,1].set_title('10')

plt.setp(axes, xticks=np.arange(len(observations)), xticklabels=map(str,observations),
        yticks=[0,1])

fig.tight_layout()
</code>```

答:
Try this:

```<code>fig.delaxes(axes[1][2])
</code>```

A much more flexible way to create subplots is the fig.add_axes() method. The parameters is a list of rect coordinates: fig.add_axes([x, y, xsize, ysize]). The values are relative to the canvas size, so an xsize of 0.5 means the subplot has half the width of the window.

Body:
I want to plot 5 data frames in a 2 by 3 setting (i.e. 2 rows and 3 columns). This is my code: However there is an extra empty plot in the 6th position (second row and third column) which I want to get rid of it. I am wondering how I could remove it so that I have three plots in the first row and two plots in the second row.

import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=3)

fig.set_figheight(8)
fig.set_figwidth(15)

df[2].plot(kind='bar',ax=axes[0,0]); axes[0,0].set_title('2')

df[4].plot(kind='bar',ax=axes[0,1]); axes[0,1].set_title('4')

df[6].plot(kind='bar',ax=axes[0,2]); axes[0,2].set_title('6')

df[8].plot(kind='bar',ax=axes[1,0]); axes[1,0].set_title('8')

df[10].plot(kind='bar',ax=axes[1,1]); axes[1,1].set_title('10')

plt.setp(axes, xticks=np.arange(len(observations)), xticklabels=map(str,observations),
        yticks=[0,1])

fig.tight_layout()

Body:
Try this:

fig.delaxes(axes[1][2])

A much more flexible way to create subplots is the fig.add_axes() method. The parameters is a list of rect coordinates: fig.add_axes([x, y, xsize, ysize]). The values are relative to the canvas size, so an xsize of 0.5 means the subplot has half the width of the window.


问:
Developing API from ARKit
I just started developing using Apple's new ARKit.  If I develop a useful app using the kit, is it possible to develop the app into an API?</p>

答:
If you mean, exposing your app somehow on a web server, it probably won't be possible, ARKit uses the sensors on your phone in order to calculate your position in the virtual/real space.

In any case, you might want to refine your question.

Title: Developing API from ARKit


问:
Git / SourceTree - remote invalid username or password
I've just reinstalled SourceTree on my new computer and I'm having trouble when trying to push my commits.

If I use the built-in Push button from SourceTree, it brings up a dialog where I enter my username and password but then I get an error: remote invalid username or password.

The strangest thing is that if I bring the Git console by clicking on the Console button in SourceTree, type git push then enter the exact same credentials, it works...

I'm assuming SourceTree might be overriding some Git config somehow but I can't find a solution.

I tried deleting all credentials saved by SourceTree, I disallowed SourceTree to modify my Git config in the Tools > General menu but it didn't change anything...

Thanks for your help!

答:
SourceTree on Mac then go to SourceTree -> Preference -> Network.
You'll see your username and GitHub location. Remove it.
Next, when you push to your repo, you'll be prompted for username and password (to save to chain).

Ideally, there was a password field here.


问:
Combining two programs with pipe won't work
I am supposed to make two programs:

First program takes a command line argument which is a number, and then it takes more inputs after execution, and if any those equal the command line number you entered, it comes back true, else it comes back false.

The second program generates a bunch of numbers, and if you want you can give it a seed.

Both of these programs work independently correctly, it stops working when I try to pipeline them (./generate 1000 50 | ./find 817).

Usage:

```<code>./find #
</code>```

if number is found: output true, else false

```<code>./generate [seed]
</code>```

Seeds are generated.

When i try and combine these two commands it doesn't work, I'll see that the generate command generated a number, and wrote ./find for that number, but it doesn't come out as true.

Source code for find.c

```<code>/**
 * Prompts user for as many as MAX values until EOF is reached,
 * then proceeds to search that "haystack" of values for given needle.
 *
 * Usage: ./find needle
 *
 * where needle is the value to find in a haystack of values
 */

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

#include "helpers.h"

// maximum amount of hay
const int MAX = 65536;

int main(int argc, string argv[])
{
    // ensure proper usage
    if (argc != 2)
    {
        printf("Usage: ./find needle\n");
        return -1;
    }

    // remember needle
    int needle = atoi(argv[1]);

    // fill haystack
    int size;
    int haystack[MAX];
    for (size = 0; size < MAX; size++)
    {
        // wait for hay until EOF
        printf("\nhaystack[%i] = ", size);
        int straw = get_int();
        if (straw == INT_MAX)
        {
            break;
        }

        // add hay to stack
        haystack[size] = straw;
    }
    printf("\n");

    // sort the haystack
    sort(haystack, size);

    // try to find needle in haystack
    if (search(needle, haystack, size))
    {
        printf("\nFound needle in haystack!\n\n");
        return 0;
    }
    else
    {
        printf("\nDidn't find needle in haystack.\n\n");
        return 1;
    }
}
</code>```

more find.c source code

```<code> /**
 * helpers.c
 *
 * Helper functions for Problem Set 3.
 */

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include "helpers.h"

/**
 * Returns true if value is in array of n values, else false.
 */
bool search(int value, int values[], int n)
{
    // TODO: implement a searching algorithm
    if(values[4] < 0) {
        return false;
    }
    if(value < 4) {
        printf("Valid usage: ./search array value\n");
        return 52;
    }
    //

    for( long long i = 0 ; i < n ; i++ )
    {
        if (value == values[i])
        {
            return true;
        }

        printf("%i", values[i]);
    }

    return false;
}

/**
 * Sorts array of n values.
 */

void sort(int values[], int n)
{

    int smallest = values[0];
    int smallestSpot = 0;
    for (long long i = 0; i < n ; i++)
    {

        for(long long j = i; j < n - i ; j++) //find the smallest int in array
        {

            if(values[j] < smallest)
            {
                smallestSpot = j;
                smallest = values[j];
            }

            values[smallestSpot] = values[i];
            values[i] = smallest;

        }

    }
    return;
}
</code>```

./generate source code

```<code>/**
 * generate.c
 *
 * Generates pseudo random numbers in [0,MAX), one per line.
 *
 * Usage: generate n [s]
 *
 * where n is number of pseudo random numbers to print
 * and s is an optional seed
 */

#define _XOPEN_SOURCE

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

// upper limit on range of integers that can be generated
#define LIMIT 65536

int main(int argc, string argv[])
{
    // Make sure user gave enough inputs
    if (argc != 2 && argc != 3)
    {
        printf("Usage: ./generate n [s]\n");
        return 1;
    }

    // convert the string that is inputted to an integer
    int n = atoi(argv[1]);

    // if user gives a seed, use that seed
    if (argc == 3)
    {
        srand48((long) atoi(argv[2]));
    }
    else
    {
        srand48((long) time(NULL));
    }

    // create this amount of random inputs
    for (int i = 0; i < n; i++)
    {
        printf("%i\n", (int) (drand48() * LIMIT));
    }

    // success
    return 0;
}
</code>```

答:
Your search program is too complicated: it is useless to sort the input and it is actually incorrect to try and read all of the input for this purpose:

reading all lines into an array is a waste of space.

sorting is a waste of time, comparing each input as it is read is simpler and faster.

your sorting algorithm is bogus: you do not swap the smallest value into the next index, you just overwrite the value there, the misplaced value is lost.

you could break out of the loop as soon as the needle is found.

Here is a modified version:

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

#include "helpers.h"

// maximum amount of hay
const int MAX = 65536;

int main(int argc, char *argv[]) {

    // ensure proper usage
    if (argc != 2) {
        printf("Usage: ./find needle\n");
        return 2;
    }

    // convert needle
    int needle = atoi(argv[1]);
    int found = 0;

    // parse input
    for (int count = 0; count < MAX; count++) {
        // wait for hay until EOF
        int straw = get_int();
        if (straw == INT_MAX) {
            break;
        }
        if (straw == needle) {
            found = 1;
            break;
        }
    }

    // report status
    if (found) {
        printf("\nFound needle in haystack!\n\n");
        return 0;
    } else {
        printf("\nDidn't find needle in haystack.\n\n");
        return 1;
    }
}
</code>```

Body:
I am supposed to make two programs:

First program takes a command line argument which is a number, and then it takes more inputs after execution, and if any those equal the command line number you entered, it comes back true, else it comes back false.

The second program generates a bunch of numbers, and if you want you can give it a seed.

Both of these programs work independently correctly, it stops working when I try to pipeline them (./generate 1000 50 | ./find 817).

Usage:

./find #

if number is found: output true, else false

./generate [seed]

Seeds are generated.

When i try and combine these two commands it doesn't work, I'll see that the generate command generated a number, and wrote ./find for that number, but it doesn't come out as true.

Source code for find.c

/**
 * Prompts user for as many as MAX values until EOF is reached,
 * then proceeds to search that "haystack" of values for given needle.
 *
 * Usage: ./find needle
 *
 * where needle is the value to find in a haystack of values
 */

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

#include "helpers.h"

// maximum amount of hay
const int MAX = 65536;

int main(int argc, string argv[])
{
    // ensure proper usage
    if (argc != 2)
    {
        printf("Usage: ./find needle\n");
        return -1;
    }

    // remember needle
    int needle = atoi(argv[1]);

    // fill haystack
    int size;
    int haystack[MAX];
    for (size = 0; size < MAX; size++)
    {
        // wait for hay until EOF
        printf("\nhaystack[%i] = ", size);
        int straw = get_int();
        if (straw == INT_MAX)
        {
            break;
        }

        // add hay to stack
        haystack[size] = straw;
    }
    printf("\n");

    // sort the haystack
    sort(haystack, size);

    // try to find needle in haystack
    if (search(needle, haystack, size))
    {
        printf("\nFound needle in haystack!\n\n");
        return 0;
    }
    else
    {
        printf("\nDidn't find needle in haystack.\n\n");
        return 1;
    }
}

more find.c source code

 /**
 * helpers.c
 *
 * Helper functions for Problem Set 3.
 */

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include "helpers.h"

/**
 * Returns true if value is in array of n values, else false.
 */
bool search(int value, int values[], int n)
{
    // TODO: implement a searching algorithm
    if(values[4] < 0) {
        return false;
    }
    if(value < 4) {
        printf("Valid usage: ./search array value\n");
        return 52;
    }
    //

    for( long long i = 0 ; i < n ; i++ )
    {
        if (value == values[i])
        {
            return true;
        }

        printf("%i", values[i]);
    }

    return false;
}

/**
 * Sorts array of n values.
 */

void sort(int values[], int n)
{

    int smallest = values[0];
    int smallestSpot = 0;
    for (long long i = 0; i < n ; i++)
    {

        for(long long j = i; j < n - i ; j++) //find the smallest int in array
        {

            if(values[j] < smallest)
            {
                smallestSpot = j;
                smallest = values[j];
            }

            values[smallestSpot] = values[i];
            values[i] = smallest;

        }

    }
    return;
}

./generate source code

/**
 * generate.c
 *
 * Generates pseudo random numbers in [0,MAX), one per line.
 *
 * Usage: generate n [s]
 *
 * where n is number of pseudo random numbers to print
 * and s is an optional seed
 */

#define _XOPEN_SOURCE

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

// upper limit on range of integers that can be generated
#define LIMIT 65536

int main(int argc, string argv[])
{
    // Make sure user gave enough inputs
    if (argc != 2 && argc != 3)
    {
        printf("Usage: ./generate n [s]\n");
        return 1;
    }

    // convert the string that is inputted to an integer
    int n = atoi(argv[1]);

    // if user gives a seed, use that seed
    if (argc == 3)
    {
        srand48((long) atoi(argv[2]));
    }
    else
    {
        srand48((long) time(NULL));
    }

    // create this amount of random inputs
    for (int i = 0; i < n; i++)
    {
        printf("%i\n", (int) (drand48() * LIMIT));
    }

    // success
    return 0;
}

Body:
Your search program is too complicated: it is useless to sort the input and it is actually incorrect to try and read all of the input for this purpose:

reading all lines into an array is a waste of space.

sorting is a waste of time, comparing each input as it is read is simpler and faster.

your sorting algorithm is bogus: you do not swap the smallest value into the next index, you just overwrite the value there, the misplaced value is lost.

you could break out of the loop as soon as the needle is found.

Here is a modified version:

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

#include "helpers.h"

// maximum amount of hay
const int MAX = 65536;

int main(int argc, char *argv[]) {

    // ensure proper usage
    if (argc != 2) {
        printf("Usage: ./find needle\n");
        return 2;
    }

    // convert needle
    int needle = atoi(argv[1]);
    int found = 0;

    // parse input
    for (int count = 0; count < MAX; count++) {
        // wait for hay until EOF
        int straw = get_int();
        if (straw == INT_MAX) {
            break;
        }
        if (straw == needle) {
            found = 1;
            break;
        }
    }

    // report status
    if (found) {
        printf("\nFound needle in haystack!\n\n");
        return 0;
    } else {
        printf("\nDidn't find needle in haystack.\n\n");
        return 1;
    }
}


问:
How often is file loaded from imported module?
I am curious how often a file would actually be loaded into memory when its needed from a module.  Here is the scenario:

lookup.py

```<code>import json

mapping_dict = json.load(open('map.json'))

def map_file(file_name):
    return(mapping_dict[file_name])

def other_function():
    --do something--
</code>```

main.py

```<code>import lookup

--something something--

for f in files:
    print(lookup.map_file(f))
</code>```

So my question is how many times is mapping_dict from lookup.py loaded?  Once upon the initial import?  Every time map_file is called? Every time any function in lookup.py is called (map_file and other_function in this case).

Some combination of the above?

答:
I'm not sure if the other answers are terribly clear about this, so let me post something else that may (or may not) help. Here is what effectively happens, under normal circumstances, when you import a module:

Python looks in sys.modules (which is basically a dict) for an entry with the name of the module being imported. If it finds something, it takes that object, creates a variable corresponding to the module's name, and assigns the object to the variable.

If it doesn't find an object in sys.modules, it creates an object to represent that module and puts it in sys.modules under the appropriate name. Then it looks up the file that contains the module's source code, runs that file as a Python script (ish), and then scoops up all the variable definitions that exist afterward and assigns them as attributes of the new module object.

Note that this means the code in the file only gets executed once, when the module is first imported.

Let's see how this works in practice, in your example. Python is happily running the code in main.py and it encounters

```<code>import lookup
</code>```

"OK (says Python), let's go to sys.modules and see if anything is stored under the name lookup. [...checking...] No, there is nothing stored under that name. Time to find lookup.py (using sys.path)."

Python creates a new, empty module object and puts it in sys.modules under the name lookup. Then it opens the file lookup.py and starts running code from it.

```<code>import json
</code>```

Python now looks in sys.modules under the name json. It will go through this whole procedure recursively, but I'll skip going into details and just jump ahead to where we have a fully loaded module object in sys.modules under the key json. Then Python assigns that object to the name json in the current scope (effectively, it does json = sys.modules['json']).

```<code>mapping_dict = json.load(open('map.json'))
</code>```

Python now loads the JSON file. I'm skipping over most of the details, but it involves accessing the json variable in the current scope (which, remember, refers to a module object) and taking the load attribute of that object, and then calling it. The thing that comes out of that call gets put into another variable in the current scope, mapping_dict.

```<code>def map_file(file_name):
    return(mapping_dict[file_name])
</code>```

Python now sees def and temporarily stops executing; instead, it reads a block of code, compiles it into bytecode, and sticks that bytecode into a function object. That function object gets assigned to the variable map_file in the current scope. Then, back to executing.

```<code>def other_function():
    --do something--
</code>```

Again, Python stops executing and reads a block of code, compiles it into bytecode, and sticks that bytecode into a function object which gets assigned to the variable other_function.

Now we are at the end of the file lookup.py. We have four variables in the current scope: json, mapping_dict, map_file, and other_function. Python assigns these four variables as attributes of the module object. Remember, the module object is stored in sys.modules under the key lookup, so now sys.modules['lookup'] is an object with the four attributes json, mapping_dict, map_file, and other_function.

Time to go back to main.py, where we are still finishing up the import lookup statement. The last thing this statement does is to assign the value of sys.modules['lookup'] to a variable in the current scope called lookup. (Effectively, lookup = sys.modules['lookup'].) Again, that object has four attributes, as previously described.

Moving on to

```<code>for f in files:
    print(lookup.map_file(f))
</code>```

On each iteration through that loop, Python accesses the lookup variable, which refers to a module object, then accesses the map_file attribute of that object, which is a function object that basically just contains a bunch of bytecode. Python then calls the function object, which actually executes the bytecode - and remember, this is the code that was inside the def map_file(...) definition, which was not executed at the time the lookup module was loaded. Only now does it get executed.

All that code does is access mapping_dict[file_name] and return it. mapping_dict is simply a variable that refers to an existing object; presumably a dict. So accessing mapping_dict[file_name] simply checks in the dict to see if it has an entry with key corresponding to the value of file_name, and if so, returns it. Accessing this entry doesn't open any files or do anything complicated. In particular, it does not run json.load(open('map.json')), because that bit of code is not part of the function. That bit of code was run long ago, when lookup was imported, and was not saved for running again, so it will not run again under normal circumstances.

Body:
I am curious how often a file would actually be loaded into memory when its needed from a module.  Here is the scenario:

lookup.py

import json

mapping_dict = json.load(open('map.json'))

def map_file(file_name):
    return(mapping_dict[file_name])

def other_function():
    --do something--

main.py

import lookup

--something something--

for f in files:
    print(lookup.map_file(f))

So my question is how many times is mapping_dict from lookup.py loaded?  Once upon the initial import?  Every time map_file is called? Every time any function in lookup.py is called (map_file and other_function in this case).

Some combination of the above?

Body:
I'm not sure if the other answers are terribly clear about this, so let me post something else that may (or may not) help. Here is what effectively happens, under normal circumstances, when you import a module:

Python looks in sys.modules (which is basically a dict) for an entry with the name of the module being imported. If it finds something, it takes that object, creates a variable corresponding to the module's name, and assigns the object to the variable.

If it doesn't find an object in sys.modules, it creates an object to represent that module and puts it in sys.modules under the appropriate name. Then it looks up the file that contains the module's source code, runs that file as a Python script (ish), and then scoops up all the variable definitions that exist afterward and assigns them as attributes of the new module object.

Note that this means the code in the file only gets executed once, when the module is first imported.

Let's see how this works in practice, in your example. Python is happily running the code in main.py and it encounters

import lookup

"OK (says Python), let's go to sys.modules and see if anything is stored under the name lookup. [...checking...] No, there is nothing stored under that name. Time to find lookup.py (using sys.path)."

Python creates a new, empty module object and puts it in sys.modules under the name lookup. Then it opens the file lookup.py and starts running code from it.

import json

Python now looks in sys.modules under the name json. It will go through this whole procedure recursively, but I'll skip going into details and just jump ahead to where we have a fully loaded module object in sys.modules under the key json. Then Python assigns that object to the name json in the current scope (effectively, it does json = sys.modules['json']).

mapping_dict = json.load(open('map.json'))

Python now loads the JSON file. I'm skipping over most of the details, but it involves accessing the json variable in the current scope (which, remember, refers to a module object) and taking the load attribute of that object, and then calling it. The thing that comes out of that call gets put into another variable in the current scope, mapping_dict.

def map_file(file_name):
    return(mapping_dict[file_name])

Python now sees def and temporarily stops executing; instead, it reads a block of code, compiles it into bytecode, and sticks that bytecode into a function object. That function object gets assigned to the variable map_file in the current scope. Then, back to executing.

def other_function():
    --do something--

Again, Python stops executing and reads a block of code, compiles it into bytecode, and sticks that bytecode into a function object which gets assigned to the variable other_function.

Now we are at the end of the file lookup.py. We have four variables in the current scope: json, mapping_dict, map_file, and other_function. Python assigns these four variables as attributes of the module object. Remember, the module object is stored in sys.modules under the key lookup, so now sys.modules['lookup'] is an object with the four attributes json, mapping_dict, map_file, and other_function.

Time to go back to main.py, where we are still finishing up the import lookup statement. The last thing this statement does is to assign the value of sys.modules['lookup'] to a variable in the current scope called lookup. (Effectively, lookup = sys.modules['lookup'].) Again, that object has four attributes, as previously described.

Moving on to

for f in files:
    print(lookup.map_file(f))

On each iteration through that loop, Python accesses the lookup variable, which refers to a module object, then accesses the map_file attribute of that object, which is a function object that basically just contains a bunch of bytecode. Python then calls the function object, which actually executes the bytecode - and remember, this is the code that was inside the def map_file(...) definition, which was not executed at the time the lookup module was loaded. Only now does it get executed.

All that code does is access mapping_dict[file_name] and return it. mapping_dict is simply a variable that refers to an existing object; presumably a dict. So accessing mapping_dict[file_name] simply checks in the dict to see if it has an entry with key corresponding to the value of file_name, and if so, returns it. Accessing this entry doesn't open any files or do anything complicated. In particular, it does not run json.load(open('map.json')), because that bit of code is not part of the function. That bit of code was run long ago, when lookup was imported, and was not saved for running again, so it will not run again under normal circumstances.


问:
How to get array of random A-Z letters?
Let me explain what I mean: I have a database that contains 4 columns, one of which is Letter, so each row has a character from 'A' to 'Z', and these aren't unique, so there are multiple rows with 'A', multiple rows with 'B' etc.

What I want to do is get 26 (a-z) rows with ALL letters, but randomize the rows that have the same letters. So I want 26 rows from A to Z, only one A, one B..., and these letters' rows are random. I hope you guys can understand what I mean. Thanks in advance!

I was thinking something like:

```<code>var randomQuestions = questions.Distinct().GroupBy(q => q.Letter).Take(26).ToArray();
</code>```

But I have no idea really.

答:
If I understand the question correctly, something like this should work:

```<code>Random random = new Random();

var randomQuestions = questions
    .GroupBy(q => q.Letter)
    .SelectMany(g => g.Skip(random.Next(g.Count())).Take(1));
</code>```

The Distinct() in your original effort is useless at best, and counter-productive at worst.

The above simply groups your data by letter, and then selects a random single element from each group. If you have twenty-six distinct letters in your original data, the above will select one random row of data for each of those distinct letters. You'll get twenty-six elements in the final result.

Title: How to get array of random A-Z letters?

Body:
Let me explain what I mean: I have a database that contains 4 columns, one of which is Letter, so each row has a character from 'A' to 'Z', and these aren't unique, so there are multiple rows with 'A', multiple rows with 'B' etc.

What I want to do is get 26 (a-z) rows with ALL letters, but randomize the rows that have the same letters. So I want 26 rows from A to Z, only one A, one B..., and these letters' rows are random. I hope you guys can understand what I mean. Thanks in advance!

I was thinking something like:

var randomQuestions = questions.Distinct().GroupBy(q => q.Letter).Take(26).ToArray();

But I have no idea really.

Body:
If I understand the question correctly, something like this should work:

Random random = new Random();

var randomQuestions = questions
    .GroupBy(q => q.Letter)
    .SelectMany(g => g.Skip(random.Next(g.Count())).Take(1));

The Distinct() in your original effort is useless at best, and counter-productive at worst.

The above simply groups your data by letter, and then selects a random single element from each group. If you have twenty-six distinct letters in your original data, the above will select one random row of data for each of those distinct letters. You'll get twenty-six elements in the final result.


问:
Reading a hash from a file on disk
Here is a hash that I save to a file to later be read.

```<code>my_hash = {-1 => 20, -2 => 30, -3 => 40}
File.open("my_file.txt", "w") { |f| f.write my_hash }
#how it looks opening the text file
{-1 => 20, -2 => 30, -3 => 40}
</code>```

When I go to read it, is where my problem is. (following code is separate from top)

```<code>my_hash = File.foreach("my_file.txt") { |f| print f }
p my_hash
#=> {-1 => 20, -2 => 30, -3 => 40}nil
</code>```

that nil messes up the rest of my code..not sure how to get rid of if. Just for clarity the rest of the code...

```<code>back_up_hash = {-1 => 20}
if my_hash.nil?
  my_hash = back_up_hash
end
</code>```

That little nil always makes my_hash equal to back_up_hash. I need that .nil? just in case the file is doesn't have the hash, otherwise the problem just gets pushed further down.

I also tried to read (slurp?..it's a small file) the file like this....

```<code>my_hash = File.read("my_file.txt") { |f| print f }
p my_hash
=> "{-1 => 20, -2 => 30, -3 => 40}"
# not sure how to get it out of string form...and I have searched for it.
</code>```

Title: Reading a hash from a file on disk

Body:
Here is a hash that I save to a file to later be read.

my_hash = {-1 => 20, -2 => 30, -3 => 40}
File.open("my_file.txt", "w") { |f| f.write my_hash }
#how it looks opening the text file
{-1 => 20, -2 => 30, -3 => 40}

When I go to read it, is where my problem is. (following code is separate from top)

my_hash = File.foreach("my_file.txt") { |f| print f }
p my_hash
#=> {-1 => 20, -2 => 30, -3 => 40}nil

that nil messes up the rest of my code..not sure how to get rid of if. Just for clarity the rest of the code...

back_up_hash = {-1 => 20}
if my_hash.nil?
  my_hash = back_up_hash
end

That little nil always makes my_hash equal to back_up_hash. I need that .nil? just in case the file is doesn't have the hash, otherwise the problem just gets pushed further down.

I also tried to read (slurp?..it's a small file) the file like this....

my_hash = File.read("my_file.txt") { |f| print f }
p my_hash
=> "{-1 => 20, -2 => 30, -3 => 40}"
# not sure how to get it out of string form...and I have searched for it.

Body:
You could use the eval method on the string (source)

eval("{-1 => 20, -2 => 30, -3 => 40}")
=> {-1 => 20, -2 => 30, -3 => 40}