问:
Proper way to null check in Expression-Tree lambda
First of all, I want to excuse myself for posting a similar question to other existing ones, but I am new to C#, and only starting to grasp LINQ.
I have some business logic across two tables that gets a field of a row. If no such row exists, it should just default to an empty String.
Outside LINQ this would be easy:

```<code>var res = SomeClass.foo?.bar ?? "";
</code>```

But in LINQ the operators ?. and ?? are not supported, so I resorted to this:

```<code>     var projectTask = repository.Set<tblProject>().Where(p => includeInactive ||
                            (p.tblOrderStatus.OrderByDescending(s => s.Date).FirstOrDefault().StatusID != StatusIds.Deducted &&
                            p.tblOrderStatus.OrderByDescending(s => s.Date).FirstOrDefault().StatusID != StatusIds.Deduc_RestDecays &&
                            p.tblOrderStatus.OrderByDescending(s => s.Date).FirstOrDefault().StatusID != StatusIds.Cancelled))
                            .Select(p => new {
                                p.ID,
                                p.CustomerID,
                                p.CenterID,
                                p.FrameworkID,
                                p.DeductionmodeID,
                                p.Code,
                                p.Descriptioln,
                                p.StartDate,
                                p.EndDate,
                                Referencetext = p.tblOrderHistories.Where(m => m.OrderReferencetypeID == 1).OrderByDescending(m => m.Date).FirstOrDefault() != null ?
                                p.tblOrderHistories.Where(m => m.OrderReferencetypeID == 1).OrderByDescending(m => m.Date).FirstOrDefault().Referencetext : ""
                            })
                            .ToListAsync();
</code>```

Where I do the Query twice, which isn't performance killing in this case, but still not very elegant.

I understand you can construct LINQ expressions through Expression, but I can't quite find an example of my case.

Thank you in advance.

答:
But in LINQ the operators ?. and ?? are not supported

I guess by LINQ here you mean LINQ against IQueryable (inside expression trees) because in LINQ against IEnumerable (with delegates) both are supported.

While you are right that ?. operator is not supported in the expression trees (yet), the ?? is perfectly supported.

So if the question is for this expression:

```<code>Referencetext =
    p.tblOrderHistories.Where(m => m.OrderReferencetypeID == 1)
        .OrderByDescending(m => m.Date).FirstOrDefault() != null ?
    p.tblOrderHistories.Where(m => m.OrderReferencetypeID == 1)
        .OrderByDescending(m => m.Date).FirstOrDefault().Referencetext : ""
</code>```

it can easily be handled with combination of Select, FirstOrDefault and ?? operator:

```<code>Referencetext = p.tblOrderHistories
    .Where(m => m.OrderReferencetypeID == 1)
    .OrderByDescending(m => m.Date)
    .Select(m => m.Referencetext)
    .FirstOrDefault() ?? ""
</code>```

Body:
First of all, I want to excuse myself for posting a similar question to other existing ones, but I am new to C#, and only starting to grasp LINQ.
I have some business logic across two tables that gets a field of a row. If no such row exists, it should just default to an empty String.
Outside LINQ this would be easy:

var res = SomeClass.foo?.bar ?? "";

But in LINQ the operators ?. and ?? are not supported, so I resorted to this:

     var projectTask = repository.Set<tblProject>().Where(p => includeInactive ||
                            (p.tblOrderStatus.OrderByDescending(s => s.Date).FirstOrDefault().StatusID != StatusIds.Deducted &&
                            p.tblOrderStatus.OrderByDescending(s => s.Date).FirstOrDefault().StatusID != StatusIds.Deduc_RestDecays &&
                            p.tblOrderStatus.OrderByDescending(s => s.Date).FirstOrDefault().StatusID != StatusIds.Cancelled))
                            .Select(p => new {
                                p.ID,
                                p.CustomerID,
                                p.CenterID,
                                p.FrameworkID,
                                p.DeductionmodeID,
                                p.Code,
                                p.Descriptioln,
                                p.StartDate,
                                p.EndDate,
                                Referencetext = p.tblOrderHistories.Where(m => m.OrderReferencetypeID == 1).OrderByDescending(m => m.Date).FirstOrDefault() != null ?
                                p.tblOrderHistories.Where(m => m.OrderReferencetypeID == 1).OrderByDescending(m => m.Date).FirstOrDefault().Referencetext : ""
                            })
                            .ToListAsync();

Where I do the Query twice, which isn't performance killing in this case, but still not very elegant.

I understand you can construct LINQ expressions through Expression, but I can't quite find an example of my case.

Thank you in advance.

Body:
But in LINQ the operators ?. and ?? are not supported

I guess by LINQ here you mean LINQ against IQueryable (inside expression trees) because in LINQ against IEnumerable (with delegates) both are supported.

While you are right that ?. operator is not supported in the expression trees (yet), the ?? is perfectly supported.

So if the question is for this expression:

Referencetext =
    p.tblOrderHistories.Where(m => m.OrderReferencetypeID == 1)
        .OrderByDescending(m => m.Date).FirstOrDefault() != null ?
    p.tblOrderHistories.Where(m => m.OrderReferencetypeID == 1)
        .OrderByDescending(m => m.Date).FirstOrDefault().Referencetext : ""

it can easily be handled with combination of Select, FirstOrDefault and ?? operator:

Referencetext = p.tblOrderHistories
    .Where(m => m.OrderReferencetypeID == 1)
    .OrderByDescending(m => m.Date)
    .Select(m => m.Referencetext)
    .FirstOrDefault() ?? ""


来源: stackexchange

问:
How to extending C: drive volume with free space by using powershell script
I know I can use use Disk Management to extend the volume for C: drive to make the additional space available.

Or using Command line like below, but how do I write this in Powershell?

```<code>Diskpart
Select disk 0
Extend size=
Extend
</code>```

答:
Assuming you want to resize it to the Maximum size it can be extended to:</p>

```<code>$size = Get-PartitionSupportedSize -DriveLetter C
Resize-Partition -DriveLetter C -Size $size.SizeMax
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know I can use use Disk Management to extend the volume for C: drive to make the additional space available.

Or using Command line like below, but how do I write this in Powershell?

Diskpart
Select disk 0
Extend size=
Extend

Body:
Assuming you want to resize it to the Maximum size it can be extended to:

$size = Get-PartitionSupportedSize -DriveLetter C
Resize-Partition -DriveLetter C -Size $size.SizeMax


问:
Margin: 0 auto; not centering div with float:left
JSFiddle: https://jsfiddle.net/feyv4o4u/

```<code><div style="border:1px solid black;position:relative;float:left;margin:0 auto" >
</div>
</code>```

I have a division as presented in the fiddle above that cant be aligned in the center.

I have used float:left for the division so that the division width will fit the content as opposed to having 100% width.

How can I align a division as such to the center?
Note: Division width must fit content.

答:
It will not work in this way, istead of float: left, use display: table.

JSFiddle

Body:
JSFiddle: https://jsfiddle.net/feyv4o4u/

I have a division as presented in the fiddle above that cant be aligned in the center.

I have used float:left for the division so that the division width will fit the content as opposed to having 100% width.

How can I align a division as such to the center?
Note: Division width must fit content.


问:
Application not running on Android device
My application is running properly on emulator but not on device. Earlier I have run the same app on device many a times. I have turned USB- Debugging on my device, also set debuggable to true in manifest.

When I try to use command adb devices, it's showing me an empty list of devices.

Has anybody encountered same problem anytime?

Thanx in advance.

答:
Keep ur phone connected with the system and then restart ur system.
I think it will work then.</p>

ContentLicense: CC BY-SA 2.5


问:
Android Gradle: Version conflict of the google-services plugin after added firebase:firebase-core
So I added

```<code>compile 'com.google.firebase:firebase-core:10.0.1'
</code>```

with the Firebase Assistant inside Android Studio to my gradle dependencies but after the sync I got an error message:

Error:Execution failed for task ':app:processDebugGoogleServices'.
  Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 10.2.6.

and I don't know why. I'm using 10.2.6 from gms:play-service-ads. Here is my dependencies:

```<code>dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile files('lib/mysql-connector-java-5.1.6.jar')
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.android.gms:play-services-ads:10.2.6'
compile 'com.github.hani-momanii:SuperNova-Emoji:1.0'
compile 'com.google.firebase:firebase-core:10.0.1'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

答: Please download latest google-services.json file from firebase console and add it in your project app directory. It will resolve your issue.</p>

Body:
So I added

compile 'com.google.firebase:firebase-core:10.0.1'

with the Firebase Assistant inside Android Studio to my gradle dependencies but after the sync I got an error message:

Error:Execution failed for task ':app:processDebugGoogleServices'.
  Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 10.2.6.

and I don't know why. I'm using 10.2.6 from gms:play-service-ads. Here is my dependencies:

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile files('lib/mysql-connector-java-5.1.6.jar')
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.android.gms:play-services-ads:10.2.6'
compile 'com.github.hani-momanii:SuperNova-Emoji:1.0'
compile 'com.google.firebase:firebase-core:10.0.1'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'


问:
How to make anchor move with respect to a block dragged in jsplumb?
I am trying to build a flowchart using drag and drop options. The user should be able to drag an element from one div and drop it to another.

Now I'm able to drag and drop. I have given an option such that on dropping the block, anchors should appear on them. And I'm able to link these blocks with connectors using js plumb.

I have given the draggable option for dropped blocks. The problem is whenever I drag connected blocks, the anchors' position does not change.

How to make a change such that whenever I drag any block, its anchor and connecting lines should also drag?

Here's my code:
jsPlumb.ready(function() {

```<code>var EndpointOptions = {
    setDragAllowedWhenFull: true,
    endpoint: "Dot",
    maxConnections: 10,

    paintStyle: {
        width: 21,
        height: 21,
        fillStyle: '#666',

    },
    isSource: true,
    connectorStyle: {
        strokeStyle: "#666"
    },
    isTarget: true,
    dropOptions: {
        drop: function(e, ui) {
            alert('drop!');
        }
    }

};

var count = 0;
var x = "";
//Make element draggable
$(".drag").draggable({
    helper: 'clone',
    cursor: 'move',
    tolerance: 'fit',
    revert: true
});

$(".droppable").droppable({
    accept: '.drag',
    activeClass: "drop-area",
    <!--  stop: function( event, ui ) {}, -->
    drop: function(e, ui) {
        if ($(ui.draggable)[0].id !== "") {

            x = ui.helper.clone();
            console.log("x" + JSON.stringify(x));
            ui.helper.remove();
            x.draggable({
                helper: 'original',
                cursor: 'move',
                containment: '.droppable',
                tolerance: 'fit',

                drop: function(event, ui) {
                    $(ui.draggable).remove();

                }
            });

            x.appendTo('.droppable');

            x.addClass('clg');
            $(".clg").each(function() {

                //alert("hello");
                jsPlumb.addEndpoint($(this), EndpointOptions);

            });

        }

        <!-- $(".clg").dblclick(function() { -->

        <!-- //alert("hello"); -->
        <!-- jsPlumb.addEndpoint($(this), EndpointOptions); -->

        <!-- });     -->
        jsPlumb.bind('connection', function(e) {
            jsPlumb.select(e).addOverlay(["Arrow", {
                foldback: 0.2,
                location: 0.65,
                width: 25
            }]);
        });
        console.log("out x" + JSON.stringify(x));

    }

});
});
</code>```

答: You can use this jsPlumb.repaintEverything();</p>

Body:
I am trying to build a flowchart using drag and drop options. The user should be able to drag an element from one div and drop it to another.

Now I'm able to drag and drop. I have given an option such that on dropping the block, anchors should appear on them. And I'm able to link these blocks with connectors using js plumb.

I have given the draggable option for dropped blocks. The problem is whenever I drag connected blocks, the anchors' position does not change.

How to make a change such that whenever I drag any block, its anchor and connecting lines should also drag?

Here's my code:
jsPlumb.ready(function() {

var EndpointOptions = {
    setDragAllowedWhenFull: true,
    endpoint: "Dot",
    maxConnections: 10,

    paintStyle: {
        width: 21,
        height: 21,
        fillStyle: '#666',

    },
    isSource: true,
    connectorStyle: {
        strokeStyle: "#666"
    },
    isTarget: true,
    dropOptions: {
        drop: function(e, ui) {
            alert('drop!');
        }
    }

};

var count = 0;
var x = "";
//Make element draggable
$(".drag").draggable({
    helper: 'clone',
    cursor: 'move',
    tolerance: 'fit',
    revert: true
});

$(".droppable").droppable({
    accept: '.drag',
    activeClass: "drop-area",

    drop: function(e, ui) {
        if ($(ui.draggable)[0].id !== "") {

            x = ui.helper.clone();
            console.log("x" + JSON.stringify(x));
            ui.helper.remove();
            x.draggable({
                helper: 'original',
                cursor: 'move',
                containment: '.droppable',
                tolerance: 'fit',

                drop: function(event, ui) {
                    $(ui.draggable).remove();

                }
            });

            x.appendTo('.droppable');

            x.addClass('clg');
            $(".clg").each(function() {

                //alert("hello");
                jsPlumb.addEndpoint($(this), EndpointOptions);

            });

        }

        jsPlumb.bind('connection', function(e) {
            jsPlumb.select(e).addOverlay(["Arrow", {
                foldback: 0.2,
                location: 0.65,
                width: 25
            }]);
        });
        console.log("out x" + JSON.stringify(x));

    }

});
});


问:
How to send notification to user at particular time set in android app
I have created android app. Inside app, user can set time for notification so that at that time if user will not performed particular action then application should send notification to him automatically. I am new in android Please suggest me what i have to do (either create a backend services which will check either user set time reached then send notification to him or somelese solution). Please help</p>

答:
You can use an AlarmManager, with that you can set the time of the notification.

This AlarmManager is received by a class that extends BroadCastReceiver and that launchs what to be done, from that launched class you can define a service that can send the notification.

The way to set an alarmmanager that fires that class that extends BroadCastReceiver is:

```<code> Intent intent = new Intent(this, classExtendingBroadCastReceiver);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this.getApplicationContext(), 234324243, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(
                ALARM_SERVICE);

        alarmManager.set(AlarmManager.RTC_WAKEUP,//System.currentTimeMillis()+20*1000
                time
                , pendingIntent);
</code>```

Where time is the time when you want the alarm to fire.

Hope it helps.

Body:
You can use an AlarmManager, with that you can set the time of the notification.

This AlarmManager is received by a class that extends BroadCastReceiver and that launchs what to be done, from that launched class you can define a service that can send the notification.

The way to set an alarmmanager that fires that class that extends BroadCastReceiver is:

 Intent intent = new Intent(this, classExtendingBroadCastReceiver);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this.getApplicationContext(), 234324243, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(
                ALARM_SERVICE);

        alarmManager.set(AlarmManager.RTC_WAKEUP,//System.currentTimeMillis()+20*1000
                time
                , pendingIntent);

Where time is the time when you want the alarm to fire.

Hope it helps.


问:
Question on using List
I created an List like this

```<code>List<Dictionary<DicKeyCla, DicValCla>>

public Class DicKeyCla
{
   public EnKey1 DicKeyItem1,
   public EnKey2 DicKeyItem2,
}

public enum EnKey1
{
   A1,
   A2,
   A3,
   A4,
   A5
}

public enum EnKey2
{
   B11,
   B12,
   B13,
   B14,
   B15,
   B16,
   B17,
   B18,
   B19,
}
</code>```

As I know, there is contains() method available for List class.

If I called an function which argues contain the DicKeyCla members like A3 and B15.

How can I pick out the entirely dictionary member from the Top level List rapidly?

I need do more operation on dictionary member.

答:
Here's the easy way to do it:

```<code>public static Dictionary<DicKeyCla, DicValCla>
     FindDict(List<Dictionary<DicKeyCla, DicValCla>> haystack,
              DicKeyCla needle)
{
    foreach (Dictionary<DicKeyCla, DicValCla> dict in haystack)
        if (dict.ContainsKey(needle))
            return dict;
    return null;
}
</code>```

Given a list of dictionaries and a key, it will return the first dictionary that has that key, or null if none in the list do.

Or more generically:

```<code>public static IDictionary<TKey, TValue>
     FindDict<TKey, TValue>(IEnumerable<IDictionary<TKey, TValue>> haystack,
                            TKey needle)
{
    foreach (IDictionary<TKey, TValue> dict in haystack)
        if (dict.ContainsKey(needle))
            return dict;
    return null;
}
</code>```

If you need to do this lookup frequently or the list is very long, you may need to index your keys with a Dictionary<DicKeyCla, Dictionary<DicKeyCla, DicValCla>> that holds which dictionary contains which key. If multiple dictionaries can contain the same key then you would need a Dictionary<DicKeyCla, List<Dictionary<DicKeyCla, DicValCla>>> to store your index.

If you already have the list and want to create an index, you could do this:

```<code>Dictionary<DicKeyCla, Dictionary<DicKeyCla, DicValCla>> index =
     new Dictionary<DicKeyCla, Dictionary<DicKeyCla, DicValCla>>();
foreach (Dictionary<DicKeyCla, DicValCla> dict in list)
    foreach (KeyValuePair<DicKeyCla, DicValCla> item in dict)
        index[item.Key] = dict;

// or in LINQ
Dictionary<DicKeyCla, Dictionary<DicKeyCla, DicValCla>> index =
    (from dict in list
     from item in dict
     select new { item.Key, dict })
    .ToDictionary(e => e.Key, e => e.dict);
</code>```

And here's how you'd use the index:

```<code>public static Dictionary<DicKeyCla, DicValCla>
     FindDict(Dictionary<DicKeyCla, Dictionary<DicKeyCla, DicValCla>> index,
              DicKeyCla needle)
{
    Dictionary<DicKeyCla, DicValCla> result;
    index.TryGetValue(needle, out result);
    return result;
}
</code>```

Title: Question on using List

Body:
I created an List like this

List<Dictionary<DicKeyCla, DicValCla>>

public Class DicKeyCla
{
   public EnKey1 DicKeyItem1,
   public EnKey2 DicKeyItem2,
}

public enum EnKey1
{
   A1,
   A2,
   A3,
   A4,
   A5
}

public enum EnKey2
{
   B11,
   B12,
   B13,
   B14,
   B15,
   B16,
   B17,
   B18,
   B19,
}

As I know, there is contains() method available for List class.

If I called an function which argues contain the DicKeyCla members like A3 and B15.

How can I pick out the entirely dictionary member from the Top level List rapidly?

I need do more operation on dictionary member.

Body:
Here's the easy way to do it:

public static Dictionary<DicKeyCla, DicValCla>
     FindDict(List<Dictionary<DicKeyCla, DicValCla>> haystack,
              DicKeyCla needle)
{
    foreach (Dictionary<DicKeyCla, DicValCla> dict in haystack)
        if (dict.ContainsKey(needle))
            return dict;
    return null;
}

Given a list of dictionaries and a key, it will return the first dictionary that has that key, or null if none in the list do.

Or more generically:

public static IDictionary<TKey, TValue>
     FindDict<TKey, TValue>(IEnumerable<IDictionary<TKey, TValue>> haystack,
                            TKey needle)
{
    foreach (IDictionary<TKey, TValue> dict in haystack)
        if (dict.ContainsKey(needle))
            return dict;
    return null;
}

If you need to do this lookup frequently or the list is very long, you may need to index your keys with a Dictionary<DicKeyCla, Dictionary<DicKeyCla, DicValCla>> that holds which dictionary contains which key. If multiple dictionaries can contain the same key then you would need a Dictionary<DicKeyCla, List<Dictionary<DicKeyCla, DicValCla>>> to store your index.

If you already have the list and want to create an index, you could do this:

Dictionary<DicKeyCla, Dictionary<DicKeyCla, DicValCla>> index =
     new Dictionary<DicKeyCla, Dictionary<DicKeyCla, DicValCla>>();
foreach (Dictionary<DicKeyCla, DicValCla> dict in list)
    foreach (KeyValuePair<DicKeyCla, DicValCla> item in dict)
        index[item.Key] = dict;

// or in LINQ
Dictionary<DicKeyCla, Dictionary<DicKeyCla, DicValCla>> index =
    (from dict in list
     from item in dict
     select new { item.Key, dict })
    .ToDictionary(e => e.Key, e => e.dict);

And here's how you'd use the index:

public static Dictionary<DicKeyCla, DicValCla>
     FindDict(Dictionary<DicKeyCla, Dictionary<DicKeyCla, DicValCla>> index,
              DicKeyCla needle)
{
    Dictionary<DicKeyCla, DicValCla> result;
    index.TryGetValue(needle, out result);
    return result;
}


问:
How to connect to MYSQL database manually with Rails?
I want to connect to a MySQL database without adding it to database.yml. How can I connect and run a query on that database?

I understand I need to do something like this, but what's the code for actually making the connection to the specific IP/port first?

```<code>query = "SELECT 1"
ActiveRecord::Base.connection.execute(query)
</code>```

答:
You might want to try ActiveRecord::Base.establish_connection

Example from documentation:

```<code>ActiveRecord::Base.establish_connection(
  :adapter  => "mysql",
  :host     => "localhost",
  :username => "myuser",
  :password => "mypass",
  :database => "somedatabase"
)
</code>```

From:

https://apidock.com/rails/ActiveRecord/Base/establish_connection/class

Body:
I want to connect to a MySQL database without adding it to database.yml. How can I connect and run a query on that database?

I understand I need to do something like this, but what's the code for actually making the connection to the specific IP/port first?

query = "SELECT 1"
ActiveRecord::Base.connection.execute(query)

Body:
You might want to try ActiveRecord::Base.establish_connection

Example from documentation:

ActiveRecord::Base.establish_connection(
  :adapter  => "mysql",
  :host     => "localhost",
  :username => "myuser",
  :password => "mypass",
  :database => "somedatabase"
)

From:

https://apidock.com/rails/ActiveRecord/Base/establish_connection/class


答:
See this fiddle

margin:auto wont make the element centered if you use float property. One little hack to solve this problem will be to replace float:left with display:inline-block;

display:inline-block; will make the div look like a floated div. Now, to make it centered wrap the element in a div which has a style text-align:center.

Updated HTML

```<code><div class="centerd_div">

  <div style="border:1px solid black;position:relative;display:inline-block;margin:auto;text-align: left;" class="align-center">
    <div class="align-center" style="margin-top:2%;"><a style="font-size: 20px;color:darkgray;padding-right:33px" class="inline-block switch-workout">Workout</a><a style="color:darkgray; font-size: 20px;" class="inline-block" id="switch-calender">Calender</a></div>

    <a id="switch-border" style="font-size: 20px;color:black;border-top:1px solid black;" class="inline-block">Workout</a>
  </div>

</div>
</code>```

CSS

```<code>.centerd_div {
  text-align: center;
}
</code>```

Snippet

.centerd_div {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="centerd_div">

  <div style="border:1px solid black;position:relative;display:inline-block;margin:auto;text-align: left;" class="align-center">
    <div class="align-center" style="margin-top:2%;">WorkoutCalender</div>

    Workout
  </div>

</div></code>```

Title: Margin: 0 auto; not centering div with float:left

Body:
See this fiddle

margin:auto wont make the element centered if you use float property. One little hack to solve this problem will be to replace float:left with display:inline-block;

display:inline-block; will make the div look like a floated div. Now, to make it centered wrap the element in a div which has a style text-align:center.

Updated HTML

<div class="centerd_div">

  <div style="border:1px solid black;position:relative;display:inline-block;margin:auto;text-align: left;" class="align-center">
    <div class="align-center" style="margin-top:2%;"><a style="font-size: 20px;color:darkgray;padding-right:33px" class="inline-block switch-workout">Workout</a><a style="color:darkgray; font-size: 20px;" class="inline-block" id="switch-calender">Calender</a></div>

    <a id="switch-border" style="font-size: 20px;color:black;border-top:1px solid black;" class="inline-block">Workout</a>
  </div>

</div>

CSS

.centerd_div {
  text-align: center;
}

Snippet

.centerd_div {
  text-align: center;
}

<div class="centerd_div">

  <div style="border:1px solid black;position:relative;display:inline-block;margin:auto;text-align: left;" class="align-center">
    <div class="align-center" style="margin-top:2%;"><a style="font-size: 20px;color:darkgray;padding-right:33px" class="inline-block switch-workout">Workout</a><a style="color:darkgray; font-size: 20px;" class="inline-block" id="switch-calender">Calender</a></div>

    <a id="switch-border" style="font-size: 20px;color:black;border-top:1px solid black;" class="inline-block">Workout</a>
  </div>

</div>


问:
What is a valid use case for one thread accquring a semaphore and another one releasing it?
A difference between a Linux semaphore and mutex is that mutex can be unlocked by the thread who locked it. But then, what is a use case of one thread locking and another one unlocking it ?</p>

答:
It is allowing of thread or process to access specific Synchronised section at a time till Semaphore value becomes 0.
Programming use case:
This is not the way semaphores are used in the producer-consumer scenario. The standard solution is to use two counting semaphores, one for the empty slots (initialized to the number of available slots), and another for the filled slots (initialized to 0).</p>


问:
Can we retrieve caller location info using Twilio API using PHP?
I am using Twilio API on my php project, I am able to retrieve caller's information like Country Code etc. But I am not able to find something which can also provide its City/State info, here is the API I am using:

```<code><?php
    require 'Twilio/autoload.php';
    use Twilio\Rest\Client;

    // Your Account Sid and Auth Token from twilio.com/user/account
    $accountSid = "<ACCOUNT SID>";
    $authToken = "ACCOUNT TOKEN";
    $client = new Client($accountSid, $authToken);

    $number = $client->lookups->phoneNumbers("<PHONE NUMBER>")->fetch();

    echo "```";
    print_r($number);
    echo "```";
?>
</code>```

Here is the response I get:

```<code>[properties:protected] => Array
        (
            [callerName] =>
            [countryCode] => US
            [phoneNumber] => <PHONE NUMBER>
            [nationalFormat] => <PHONE NUMBER>
            [carrier] =>
            [addOns] =>
            [url] => https://lookups.twilio.com/v1/PhoneNumbers/<PHONE NUMBER>
        )
</code>```

答:
Twilio developer evangelist here.

You can't get address details from the basic, carrier or caller name Lookups API.

However, the Twilio Add-ons marketplace makes it easy to use third party services to find that information. You could add the White Pages Pro Caller Identification or the Next Caller Advanced Caller ID add-ons and get in depth address information.

Body:
I am using Twilio API on my php project, I am able to retrieve caller's information like Country Code etc. But I am not able to find something which can also provide its City/State info, here is the API I am using:

<?php
    require 'Twilio/autoload.php';
    use Twilio\Rest\Client;

    // Your Account Sid and Auth Token from twilio.com/user/account
    $accountSid = "<ACCOUNT SID>";
    $authToken = "ACCOUNT TOKEN";
    $client = new Client($accountSid, $authToken);

    $number = $client->lookups->phoneNumbers("<PHONE NUMBER>")->fetch();

    echo "
";
    print_r($number);
    echo "
";
?>

Here is the response I get:

[properties:protected] => Array
        (
            [callerName] =>
            [countryCode] => US
            [phoneNumber] => <PHONE NUMBER>
            [nationalFormat] => <PHONE NUMBER>
            [carrier] =>
            [addOns] =>
            [url] => https://lookups.twilio.com/v1/PhoneNumbers/<PHONE NUMBER>
        )


问:
How to get streaming bitrate with MediaPlayer?
I'm developing a stream video app in Android with MediaPlayer. The problem is that I need to show the current bitrate, but I haven't found any valid suggestions on how to do get it?

Here is how I'm setting the video url to play:

```<code>    mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(VIDEO_PATH);
        mediaPlayer.prepare();
        mediaPlayer.init();
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

I don't know if the only way to get that working is using ExoPlayer (which I've read it may be possible)

Any suggestions?

Thanks!

答:
Apparently you cannot do this with MediaPlayer but you can use MediaMetadataRetriever, which is available since API level 10, i.e., quite a while ago.

```<code>  int getBitRate(String url) {
        final MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        try {
            mmr.setDataSource(url, Collections.EMPTY_MAP);
            return Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE));
        } catch (NumberFormatException e) {
            return 0;
        } finally {
            mmr.release();
        }
    }
</code>```

The disadvantage this can have is that you will make an extra HTTP request for getting the metadata (only an RTT if you are streaming from an URI; if you are reading from an file descriptor it could be more serious).  Hopefully no big deal.

Body:
I'm developing a stream video app in Android with MediaPlayer. The problem is that I need to show the current bitrate, but I haven't found any valid suggestions on how to do get it?

Here is how I'm setting the video url to play:

    mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(VIDEO_PATH);
        mediaPlayer.prepare();
        mediaPlayer.init();
    } catch (IOException e) {
        e.printStackTrace();
    }

I don't know if the only way to get that working is using ExoPlayer (which I've read it may be possible)

Any suggestions?

Thanks!

Body:
Apparently you cannot do this with MediaPlayer but you can use MediaMetadataRetriever, which is available since API level 10, i.e., quite a while ago.

  int getBitRate(String url) {
        final MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        try {
            mmr.setDataSource(url, Collections.EMPTY_MAP);
            return Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE));
        } catch (NumberFormatException e) {
            return 0;
        } finally {
            mmr.release();
        }
    }

The disadvantage this can have is that you will make an extra HTTP request for getting the metadata (only an RTT if you are streaming from an URI; if you are reading from an file descriptor it could be more serious).  Hopefully no big deal.


问:
Unable to use RadioButton with JQuery - Alert doesn't pop up
I have two radio buttons and I want to display an alert when one of them is checked, it seems that the problem is that it doesn't recognize the element because the alert doesn't pop up!

This code used to work but it doesn't anymore (I think I changed the Id of one of the elements and that's what caused the issue)

JS:

```<code>/*This function is responsible for for the radio buttons*/
$(function() {
    $(".r1").checkboxradio({
        icon: false
    });
});
/*This function changes the RecordTypeId according to the BankEmployeeCheckbox*/

$("form input:radio").change(function() {
    if ($(this).val() == "Yes") {
        document.getElementById("recordType").value = "01220000000FdvyAAC";
        alert("Yes");

    } else {
        document.getElementById("recordType").value = "01220000000FffjAAC";
        console.log(document.getElementById("recordType").value);
        alert("No");
    }
});
</code>```

HTML

```<code>    <form method='post' id='prechatForm' autocomplete="on">
        <div id="bankEmployeeYesNoRadioButtonDiv">
          <label>{!$Label.Bank_Employee}</label><br/>
          <label for="radio-1" class="radioLabel">{!$Label.Yes}</label>
          <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-1" class="r1" value="Yes"></input>
          <label for="radio-2" class="radioLabel">{!$Label.No}</label>
          <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-2" class="r1" value="No"></input>
        </div>
</form>
</code>```

Result: When I click on a radio button nothing happens, no alert.
No Console Errors
Notes: Please note that I'm using Salesforce (Visualforce) syntax.

答:
Change this:

```<code>/*This function is responsible for for the radio buttons*/
$(function() {
    $(".r1").checkboxradio({
        icon: false
    });
});
/*This function changes the RecordTypeId according to the BankEmployeeCheckbox*/

$("form input:radio").change(function() {
    if ($(this).val() == "Yes") {
        document.getElementById("recordType").value = "01220000000FdvyAAC";
        alert("Yes");

    } else {
        document.getElementById("recordType").value = "01220000000FffjAAC";
        console.log(document.getElementById("recordType").value);
        alert("No");
    }
});
</code>```

To this:

```<code>/*This function is responsible for for the radio buttons*/
$(function() {
    $(".r1").checkboxradio({
        icon: false
    });
    /*This function changes the RecordTypeId according to the BankEmployeeCheckbox*/

    $("form input:radio").change(function() {
        if ($(this).val() == "Yes") {
            document.getElementById("recordType").value = "01220000000FdvyAAC";
            alert("Yes");

        } else {
            document.getElementById("recordType").value = "01220000000FffjAAC";
            console.log(document.getElementById("recordType").value);
            alert("No");
        }
    });

});
</code>```

Body:
I have two radio buttons and I want to display an alert when one of them is checked, it seems that the problem is that it doesn't recognize the element because the alert doesn't pop up!

This code used to work but it doesn't anymore (I think I changed the Id of one of the elements and that's what caused the issue)

JS:

/*This function is responsible for for the radio buttons*/
$(function() {
    $(".r1").checkboxradio({
        icon: false
    });
});
/*This function changes the RecordTypeId according to the BankEmployeeCheckbox*/

$("form input:radio").change(function() {
    if ($(this).val() == "Yes") {
        document.getElementById("recordType").value = "01220000000FdvyAAC";
        alert("Yes");

    } else {
        document.getElementById("recordType").value = "01220000000FffjAAC";
        console.log(document.getElementById("recordType").value);
        alert("No");
    }
});

HTML

    <form method='post' id='prechatForm' autocomplete="on">

          {!$Label.Bank_Employee}

          {!$Label.Yes}
          <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-1" class="r1" value="Yes"></input>
          {!$Label.No}
          <input type="radio" name="liveagent.prechat:BankEmployee" id="radio-2" class="r1" value="No"></input>

</form>

Result: When I click on a radio button nothing happens, no alert.
No Console Errors
Notes: Please note that I'm using Salesforce (Visualforce) syntax.

Body:
Change this:

/*This function is responsible for for the radio buttons*/
$(function() {
    $(".r1").checkboxradio({
        icon: false
    });
});
/*This function changes the RecordTypeId according to the BankEmployeeCheckbox*/

$("form input:radio").change(function() {
    if ($(this).val() == "Yes") {
        document.getElementById("recordType").value = "01220000000FdvyAAC";
        alert("Yes");

    } else {
        document.getElementById("recordType").value = "01220000000FffjAAC";
        console.log(document.getElementById("recordType").value);
        alert("No");
    }
});

To this:

/*This function is responsible for for the radio buttons*/
$(function() {
    $(".r1").checkboxradio({
        icon: false
    });
    /*This function changes the RecordTypeId according to the BankEmployeeCheckbox*/

    $("form input:radio").change(function() {
        if ($(this).val() == "Yes") {
            document.getElementById("recordType").value = "01220000000FdvyAAC";
            alert("Yes");

        } else {
            document.getElementById("recordType").value = "01220000000FffjAAC";
            console.log(document.getElementById("recordType").value);
            alert("No");
        }
    });

});


问:
How do I load multiple XML nodes with two attributes as key-value pairs?
I have a XML file which is like this;

```<code><?xml version="1.0" encoding="utf-8"?>
<Data>
  <StringMaps>
    <Menu>
      <String Target="BtnFile" Link="Файл" />
      <String Target="BtnOpen" Link="Открыто" />
      <String Target="BtnSave" Link="Сохранить" />
      <String Target="BtnClose" Link="Закрыть" />
    </Menu>
  </StringMaps>
</Data>
</code>```

and I load document using XmlDocument.

And then I have two XmlNodeList which are targetAttrs and linkAttrs.

I'm using this code to get the values;

```<code>        var targetAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Target");
        var linkAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Link");
        foreach (XmlNode temptarget in targetAttrs)
        {
            foreach (XmlNode templink in linkAttrs)
            {
                MessageBox.Show(string.Format("{0} = {1}", temptarget.Value, templink.Value));
            }
        }
</code>```

I'm trying to get values as key-value pairs like these;

```<code>BtnFile = Файл
BtnOpen = Открыто
BtnSave = Сохранить
BtnClose = Закрыть
</code>```

But I get these;

```<code>BtnFile = Файл
BtnFile = Открыто
BtnFile = Сохранить
BtnFile = Закрыть
BtnOpen = Файл
BtnOpen = Открыто
BtnOpen = Сохранить
BtnOpen = Закрыть
BtnSave = Файл
BtnSave = Открыто
BtnSave = Сохранить
BtnSave = Закрыть
BtnClose = Файл
BtnClose = Открыто
BtnClose = Сохранить
BtnClose = Закрыть
</code>```

If someone writes the code and explains the exact logic, i would be very appreciated.

答:
```<code>var strings = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String");
foreach (var node in strings)
{
    MessageBox.Show($"{node.Attributes["Target"].Value} = {node.Attributes["Link"].Value}");
}
</code>```

Body:
I have a XML file which is like this;

<?xml version="1.0" encoding="utf-8"?>
<Data>
  <StringMaps>
    <Menu>
      <String Target="BtnFile" Link="Файл" />
      <String Target="BtnOpen" Link="Открыто" />
      <String Target="BtnSave" Link="Сохранить" />
      <String Target="BtnClose" Link="Закрыть" />
    </Menu>
  </StringMaps>
</Data>

and I load document using XmlDocument.

And then I have two XmlNodeList which are targetAttrs and linkAttrs.

I'm using this code to get the values;

        var targetAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Target");
        var linkAttrs = xmldoc1.SelectNodes("/Data/StringMaps/Menu/String/@Link");
        foreach (XmlNode temptarget in targetAttrs)
        {
            foreach (XmlNode templink in linkAttrs)
            {
                MessageBox.Show(string.Format("{0} = {1}", temptarget.Value, templink.Value));
            }
        }

I'm trying to get values as key-value pairs like these;

BtnFile = Файл
BtnOpen = Открыто
BtnSave = Сохранить
BtnClose = Закрыть

But I get these;

BtnFile = Файл
BtnFile = Открыто
BtnFile = Сохранить
BtnFile = Закрыть
BtnOpen = Файл
BtnOpen = Открыто
BtnOpen = Сохранить
BtnOpen = Закрыть
BtnSave = Файл
BtnSave = Открыто
BtnSave = Сохранить
BtnSave = Закрыть
BtnClose = Файл
BtnClose = Открыто
BtnClose = Сохранить
BtnClose = Закрыть

If someone writes the code and explains the exact logic, i would be very appreciated.


答:
margin: auto deosn't work with float. You can add a parent and use display: flex; justify-content: center;

.parent {
  display: flex;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div style="border:1px solid black;position:relative;" class="align-center">
    <div class="align-center" style="margin-top:2%;">WorkoutCalender</div>

    Workout
  </div>
</div></code>```

Or you can make the child display: inline-block; text-align: left; then use text-align: center on the parent

.parent {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div style="border:1px solid black;position:relative;display: inline-block;text-align: left;" class="align-center">
    <div class="align-center" style="margin-top:2%;">WorkoutCalender</div>

    Workout
  </div>
</div></code>```

Body:
margin: auto deosn't work with float. You can add a parent and use display: flex; justify-content: center;

.parent {
  display: flex;
  justify-content: center;
}

<div class="parent">
  <div style="border:1px solid black;position:relative;" class="align-center">
    <div class="align-center" style="margin-top:2%;"><a style="font-size: 20px;color:darkgray;padding-right:33px" class="inline-block switch-workout">Workout</a><a style="color:darkgray; font-size: 20px;" class="inline-block" id="switch-calender">Calender</a></div>

    <a id="switch-border" style="font-size: 20px;color:black;border-top:1px solid black" class="inline-block">Workout</a>
  </div>
</div>

Or you can make the child display: inline-block; text-align: left; then use text-align: center on the parent

.parent {
  text-align: center;
}

<div class="parent">
  <div style="border:1px solid black;position:relative;display: inline-block;text-align: left;" class="align-center">
    <div class="align-center" style="margin-top:2%;"><a style="font-size: 20px;color:darkgray;padding-right:33px" class="inline-block switch-workout">Workout</a><a style="color:darkgray; font-size: 20px;" class="inline-block" id="switch-calender">Calender</a></div>

    <a id="switch-border" style="font-size: 20px;color:black;border-top:1px solid black" class="inline-block">Workout</a>
  </div>
</div>


问:
Differences in string compare methods in C#
Comparing string in C# is pretty simple.  In fact there are several ways to do it.  I have listed some in the block below.  What I am curious about are the differences between them and when one should be used over the others?  Should one be avoided at all costs?  Are there more I haven't listed?  </p>

```<code>string testString = "Test";
string anotherString = "Another";

if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}
</code>```

<p>(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)</p>

答:
Here are the rules for how these functions work:

stringValue.CompareTo(otherStringValue)

null comes before a string

it uses CultureInfo.CurrentCulture.CompareInfo.Compare, which means it will use a culture-dependent comparison. This might mean that ß will compare equal to SS in Germany, or similar

stringValue.Equals(otherStringValue)

null is not considered equal to anything

unless you specify a StringComparison option, it will use what looks like a direct ordinal equality check, i.e. ß is not the same as SS, in any language or culture

stringValue == otherStringValue

Is not the same as stringValue.Equals().

The == operator calls the static Equals(string a, string b) method (which in turn goes to an internal EqualsHelper to do the comparison.

Calling .Equals() on a null string gets null reference exception, while on == does not.

Object.ReferenceEquals(stringValue, otherStringValue)

Just checks that references are the same, i.e. it isn't just two strings with the same contents, you're comparing a string object with itself.

Note that with the options above that use method calls, there are overloads with more options to specify how to compare.

My advice if you just want to check for equality is to make up your mind whether you want to use a culture-dependent comparison or not, and then use .CompareTo or .Equals, depending on the choice.

OwnerDisplayName: Craig

Body:
Comparing string in C# is pretty simple.  In fact there are several ways to do it.  I have listed some in the block below.  What I am curious about are the differences between them and when one should be used over the others?  Should one be avoided at all costs?  Are there more I haven't listed?

string testString = "Test";
string anotherString = "Another";

if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}

(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)

OwnerDisplayName: lassevk

LastEditorDisplayName: lassevk


问:
Windows workflow 4.0 Persistence
Would someone please explain to me why i would need to persist a workflow in a database. Please am just trying to understand the concepts</p>

答: Workflow are often long running in nature, like weeks or months. And keeping them in memory means you can't recycle the application or machine. By saving the state to disk, ie database, you can restart the process and machine. Also keeping worklflows in memory when they aren't doing anything just wasts memory resources and thus hinders scalability. Finally saving state in a database means we can restart the workflow from that state so it also helps when error handling.</p>

Title: Windows workflow 4.0 Persistence


问:
trying to transfer content from a ol to ul
I'm trying to move the li elements from a li list that contains 4 elements (first, second, third, fourth) to a newly created ol element. I decided to create the ol elemend and append the elements to it in a for loop, and then use replacechild to switch out the lists, but the result that I am getting is a new ol list with only two elements inside: first, third

it seems that the iterator skips one element at a time and I don't understand why?

HTML:

```<code><input type="button" value="update" onclick="updateList()">
<ul id="ul"><li>first</li><li>second</li><li>third</li><li>fourth</li></ul>
</code>```

JavaScript:

```<code>function updateList() {

    var list = document.getElementById("ul");
    var newList = document.createElement("ol");

    var nodes = list.childNodes;

    for(i = 0; i < nodes.length; i++) {
        newList.appendChild(nodes[i]);
    }
parent = list.parentNode;
parent.replaceChild(newList, list)

}
</code>```

答:
When you move element 0, element 1 becomes element 0, and so on. Just move them in a while loop, while they exist:

function updateList() {

    var ul = document.getElementById("ul"),
        ol = document.createElement("ol");

    while (ul.childNodes.length) {
        ol.appendChild(ul.childNodes[0]);
    }

    ul.parentNode.replaceChild(ol, ul);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" value="Update" onclick="updateList()">
<ul id="ul"><li>first</li><li>second</li><li>third</li><li>fourth</li></ul></code>```

Body:
I'm trying to move the li elements from a li list that contains 4 elements (first, second, third, fourth) to a newly created ol element. I decided to create the ol elemend and append the elements to it in a for loop, and then use replacechild to switch out the lists, but the result that I am getting is a new ol list with only two elements inside: first, third

it seems that the iterator skips one element at a time and I don't understand why?

HTML:

<input type="button" value="update" onclick="updateList()">

first

second

third

fourth

JavaScript:

function updateList() {

    var list = document.getElementById("ul");
    var newList = document.createElement("ol");

    var nodes = list.childNodes;

    for(i = 0; i < nodes.length; i++) {
        newList.appendChild(nodes[i]);
    }
parent = list.parentNode;
parent.replaceChild(newList, list)

}

Body:
When you move element 0, element 1 becomes element 0, and so on. Just move them in a while loop, while they exist:

function updateList() {

    var ul = document.getElementById("ul"),
        ol = document.createElement("ol");

    while (ul.childNodes.length) {
        ol.appendChild(ul.childNodes[0]);
    }

    ul.parentNode.replaceChild(ol, ul);
}

<input type="button" value="Update" onclick="updateList()">
<ul id="ul"><li>first</li><li>second</li><li>third</li><li>fourth</li></ul>


问:
d3.scaleSequential is not a function
Following Mike Bostock's great tutorial on command-line cartography, when trying to produce a choropleth, I receive a TypeError saying that d3.scaleSequential is not a function. I imagine it is just not being exposed? But I don't know how to deal with that through the CLI...?

Error Traceback:

```
TypeError: d3.scaleSequential is not a function
    at evalmachine.:1:26
    at Interface. (/usr/local/lib/node_modules/ndjson-cli/ndjson-map:45:14)
    at emitOne (events.js:77:13)
    at Interface.emit (events.js:169:7)
    at Interface._onLine (readline.js:210:10)
    at Interface. (readline.js:340:12)
    at Array.forEach (native)
    at Interface._normalWrite (readline.js:339:11)
    at ReadStream.ondata (readline.js:86:10)
    at emitOne (events.js:77:13)
```

I have all of the needed libraries installed and updated through npm, so that isn't the issue..any thoughts on how to debug this would be greatly appreciated.

Currently Installed:

d3@4.9.1

d3-geo-projection@2.1.2

d3-scale@1.0.6

d3-scale-chromatic@1.1.1

Sample Code

The code is copied pretty much straight from the tutorial and this is the first step that doesn't work..

```
ndjson-map -r d3 \
  '(d.properties.fill = d3.scaleSequential(d3.interpolateViridis).domain([0, 4000])(d.properties.density), d)' \
   ca-albers-color.ndjson
```

答:
When you are using the CLI, d3 needs to be accessible to node.js, so you should npm install -g d3 (global), or in the directory from which you're running the command line scripts, npm install d3.

UPDATE: If you use the global approach, you may need to link the package (https://nodejs.org/en/blog/npm/npm-1-0-global-vs-local-installation/) or set your NODE_PATH variable to have access to the folder where global modules are installed.

Title: d3.scaleSequential is not a function

Body:
Following Mike Bostock's great tutorial on command-line cartography, when trying to produce a choropleth, I receive a TypeError saying that d3.scaleSequential is not a function. I imagine it is just not being exposed? But I don't know how to deal with that through the CLI...?

Error Traceback:

TypeError: d3.scaleSequential is not a function
    at evalmachine.:1:26
    at Interface. (/usr/local/lib/node_modules/ndjson-cli/ndjson-map:45:14)
    at emitOne (events.js:77:13)
    at Interface.emit (events.js:169:7)
    at Interface._onLine (readline.js:210:10)
    at Interface. (readline.js:340:12)
    at Array.forEach (native)
    at Interface._normalWrite (readline.js:339:11)
    at ReadStream.ondata (readline.js:86:10)
    at emitOne (events.js:77:13)

I have all of the needed libraries installed and updated through npm, so that isn't the issue..any thoughts on how to debug this would be greatly appreciated.

Currently Installed:

d3@4.9.1

d3-geo-projection@2.1.2

d3-scale@1.0.6

d3-scale-chromatic@1.1.1

Sample Code

The code is copied pretty much straight from the tutorial and this is the first step that doesn't work..

ndjson-map -r d3 \
  '(d.properties.fill = d3.scaleSequential(d3.interpolateViridis).domain([0, 4000])(d.properties.density), d)' \
   ca-albers-color.ndjson


问:
Spring security permit a url
I have implemented a Rest api using spring and used Spring security for securing the api, my security config code is :

```<code>http
     .authorizeRequests()
     .anyRequest().authenticated()
     .and()
     .requestCache()
     .requestCache(new NullRequestCache())
     .and()
     .httpBasic();
</code>```

this code will authenticate all the urls but I want to permit a specific url for anonymous users to sign-up in my application so I did change the security config to below code :

```<code>http
     .authorizeRequests()
     .antMatchers("/signup").permitAll()
     .antMatchers("/**").authenticated()
     .and()
     .requestCache()
     .requestCache(new NullRequestCache())
     .and()
     .httpBasic();
</code>```

but I still needs to be authenticated to access the /signup request call.
How can I permit just some request calls in my api?

答:
I should Override configure method with WebSecurity parameter and use the following code to ignore the /signup request.</p>

```<code>@Override
public void configure(WebSecurity web) throws Exception {
    super.configure(web);
    web.ignoring().antMatchers("/signup");
}
</code>```

Title: Spring security permit a url

Body:
I have implemented a Rest api using spring and used Spring security for securing the api, my security config code is :

http
     .authorizeRequests()
     .anyRequest().authenticated()
     .and()
     .requestCache()
     .requestCache(new NullRequestCache())
     .and()
     .httpBasic();

this code will authenticate all the urls but I want to permit a specific url for anonymous users to sign-up in my application so I did change the security config to below code :

http
     .authorizeRequests()
     .antMatchers("/signup").permitAll()
     .antMatchers("/**").authenticated()
     .and()
     .requestCache()
     .requestCache(new NullRequestCache())
     .and()
     .httpBasic();

but I still needs to be authenticated to access the /signup request call.
How can I permit just some request calls in my api?

Body:
I should Override configure method with WebSecurity parameter and use the following code to ignore the /signup request.

@Override
public void configure(WebSecurity web) throws Exception {
    super.configure(web);
    web.ignoring().antMatchers("/signup");
}


问:
How do I update Wagtail to the latest release?
I'm new to Wagtail and I got as far as being able to create an account and now I have access to http://127.0.0.1:8000/. That said the banner informed me that I have the 1.3 version and I need to upgrade to 1.10. I looked at all the release notes but there were no instructions. How do I go about this? Thank you!</p>

答:
Wagtail is a Python module, and is found at https://pypi.python.org/pypi/wagtail/. You can install version 1.10.1 on a typical Linux/Unix/Mac OS system with

$ pip install wagtail==1.10.1
```

Or you can always upgrade to the latest with pip install --upgrade wagtail.

This isn't a Wagtail-specific question, so I suggest looking at pip itself if you want some further reading: https://pip.pypa.io/en/stable/user_guide/

Body:
Wagtail is a Python module, and is found at https://pypi.python.org/pypi/wagtail/. You can install version 1.10.1 on a typical Linux/Unix/Mac OS system with

$ pip install wagtail==1.10.1

Or you can always upgrade to the latest with pip install --upgrade wagtail.

This isn't a Wagtail-specific question, so I suggest looking at pip itself if you want some further reading: https://pip.pypa.io/en/stable/user_guide/


问:
Call to undefined method Illuminate\Auth\GenericUser::fill() :: when update
I want to update user password

This is my function:

```<code>public function modifiermdp(Request $request)
{
    $userupdate = Auth::user();
    $password = bcrypt($request['password']);
    $userupdate->fill(['password' => $password])->save();
    return Redirect::back()->with('message', 'تم التعديل بنجاح');
}
</code>```

This is my route:

```<code>Route::prefix('/compte')->group(function() {
    Route::get('/', 'CompteController@index');
    Route::post('/changemdp', 'CompteController@modifiermdp');
});
</code>```

And I'm using database driver in config/auth.php

```<code>'providers' => [
     'enseignant' => [
         'driver' => 'database',
         'table' => 'enseignant',
     ],
],
</code>```

I get this error

FatalErrorException in CompteController.php line 38:
  Call to undefined method Illuminate\Auth\GenericUser::fill()

答:
Since it's a database driver, you have to do it manually.</p>

```<code>\DB::table('enseignant')
    ->where('id', $user->getAuthIdentifier())
    ->update(['password' => $password]);
</code>```

Body:
I want to update user password

This is my function:

public function modifiermdp(Request $request)
{
    $userupdate = Auth::user();
    $password = bcrypt($request['password']);
    $userupdate->fill(['password' => $password])->save();
    return Redirect::back()->with('message', 'تم التعديل بنجاح');
}

This is my route:

Route::prefix('/compte')->group(function() {
    Route::get('/', 'CompteController@index');
    Route::post('/changemdp', 'CompteController@modifiermdp');
});

And I'm using database driver in config/auth.php

'providers' => [
     'enseignant' => [
         'driver' => 'database',
         'table' => 'enseignant',
     ],
],

I get this error

FatalErrorException in CompteController.php line 38:
  Call to undefined method Illuminate\Auth\GenericUser::fill()

Body:
Since it's a database driver, you have to do it manually.

\DB::table('enseignant')
    ->where('id', $user->getAuthIdentifier())
    ->update(['password' => $password]);


问:
Join two tables with same ID and merge ID columns
This is probably a pretty simple question, but most of the searches I do have to do with merging rows (not merging columns) or concatenating them.

I want to join two tables on an ID column, but I only want it to return a single ID column.

Example:

Table 1:

```<code>ID|Data1|Data2
</code>```

Table2:

```<code>ID|Data3|Data4
</code>```

I want it to return:

```<code>ID|Data1|Data2|Data3|Data4
</code>```

EDIT:

I realize I can specify every column, but there are actually closer to 50 columns that I'm bringing over and I would prefer not to have to specify every single one. Is there a way to do this without specifying each column to bring over from the query?

I believe natural join is what I need, but see this error I'm getting:

```<code>SELECT *
FROM allqachecklists t1
WHERE t1.IsIncorrect=1
NATURAL JOIN (SELECT QAID, PMC, SiteName, Submitter, QAer FROM qabin.allqas) t2
</code>```

1 errors were found during analysis.

Unrecognized keyword. (near "NATURAL" at position 59)

答:
A natural join would allow you to select * from both tables and join on the key. These two columns are then returned as ONE in the result set; provided no other columns are named the same in both tables.

```<code>SELECT *
FROM Table1 A
NATURAL JOIN Table2 B
</code>```

An example can be found: http://rextester.com/FNT36037

mySQL Docs state:
...

Natural joins and joins with USING, including outer join variants, are processed according to the SQL:2003 standard:

Redundant columns of a NATURAL join do not appear.
...

With your edit to question: we can modify your SQL to the below.

```<code>SELECT *
FROM allqachecklists t1
NATURAL JOIN (SELECT QAID, PMC, SiteName, Submitter, QAer FROM qabin.allqas) t2
WHERE t1.IsIncorrect=1
LIMIT 10
</code>```

Joins then where clause; though careful with outer joins as the limits on the table not having all records need to be put on the join or the outer join will behave like an inner.

Body:
This is probably a pretty simple question, but most of the searches I do have to do with merging rows (not merging columns) or concatenating them.

I want to join two tables on an ID column, but I only want it to return a single ID column.

Example:

Table 1:

ID|Data1|Data2

Table2:

ID|Data3|Data4

I want it to return:

ID|Data1|Data2|Data3|Data4

EDIT:

I realize I can specify every column, but there are actually closer to 50 columns that I'm bringing over and I would prefer not to have to specify every single one. Is there a way to do this without specifying each column to bring over from the query?

I believe natural join is what I need, but see this error I'm getting:

SELECT *
FROM allqachecklists t1
WHERE t1.IsIncorrect=1
NATURAL JOIN (SELECT QAID, PMC, SiteName, Submitter, QAer FROM qabin.allqas) t2

1 errors were found during analysis.

Unrecognized keyword. (near "NATURAL" at position 59)

Body:
A natural join would allow you to select * from both tables and join on the key. These two columns are then returned as ONE in the result set; provided no other columns are named the same in both tables.

SELECT *
FROM Table1 A
NATURAL JOIN Table2 B

An example can be found: http://rextester.com/FNT36037

mySQL Docs state:
...

Natural joins and joins with USING, including outer join variants, are processed according to the SQL:2003 standard:

Redundant columns of a NATURAL join do not appear.
...

With your edit to question: we can modify your SQL to the below.

SELECT *
FROM allqachecklists t1
NATURAL JOIN (SELECT QAID, PMC, SiteName, Submitter, QAer FROM qabin.allqas) t2
WHERE t1.IsIncorrect=1
LIMIT 10

Joins then where clause; though careful with outer joins as the limits on the table not having all records need to be put on the join or the outer join will behave like an inner.


问:
Elements doesn't survive state change for css transitions in React
I have a highscore list that updates automatically with current scores once every minute.

It then updates the component with this.setState({ data: newData });.

Below I sort the new data by score, run each item through map that updates their style.top.

Javascript

```<code>...

let current = this.state.data.sort((a,b) => {
  if(a.score < b.score) return -1;
  if(a.score > b.score) return 1;
  return 0;
});

let items = current.map((item,i) => {
  return (
    <div
      key={item.name}
      className="item"
      style={{ top: (i*30) + 'px', backgroundColor: item.color }}>
        {item.name}
    </div>
  );
});

return (
  <div>
    {items}
  </div>
);
</code>```

CSS

```<code>.item {
  position: absolute;
  transition: top 1s;
}
</code>```

I want the items to animate up and down to their new positions, but this doesn't happen. The browser seems to remember parts of the DOM, but not others.

React seems to understand which item is which by using the unique key, if I inspect using React Developer Tools, but the actual DOM doesn't.

Even stranger, only items moving up the list (higher score) seems to be remembered. Items moving down is recreated, and therefor the transition doesn't work. They just pop into existence without transitioning to their new position.

Here is a working example to demonstrate. (JSFiddle)

答:
If you change it so that the items are not reordered between render cycles, but are always rendered in the same order with different top styles, it animates correctly.  I think this is because changing the order of elements forces them to be removed from the DOM and re-added by react.

The relevant code is:

```<code>render() {
    let current = this.state.data.slice().sort((a,b) => {
        if(a.score < b.score) return -1;
        if(a.score > b.score) return 1;
        return 0;
    });

    let items = this.state.data.map(item => {
        let position = current.indexOf(item);
        return (
          <div
            key={item.name}
            className="item"
            style={{ top: (position*30) + 'px', backgroundColor: item.color }}>
                {item.name}
          </div>
        );
    });

    return (
      <div>
        {items}
      </div>
    );
}
</code>```

Updated demo

Body:
I have a highscore list that updates automatically with current scores once every minute.

It then updates the component with this.setState({ data: newData });.

Below I sort the new data by score, run each item through map that updates their style.top.

Javascript

...

let current = this.state.data.sort((a,b) => {
  if(a.score  b.score) return 1;
  return 0;
});

let items = current.map((item,i) => {
  return (

        {item.name}

  );
});

return (

    {items}

);

CSS

.item {
  position: absolute;
  transition: top 1s;
}

I want the items to animate up and down to their new positions, but this doesn't happen. The browser seems to remember parts of the DOM, but not others.

React seems to understand which item is which by using the unique key, if I inspect using React Developer Tools, but the actual DOM doesn't.

Even stranger, only items moving up the list (higher score) seems to be remembered. Items moving down is recreated, and therefor the transition doesn't work. They just pop into existence without transitioning to their new position.

Here is a working example to demonstrate. (JSFiddle)

Body:
If you change it so that the items are not reordered between render cycles, but are always rendered in the same order with different top styles, it animates correctly.  I think this is because changing the order of elements forces them to be removed from the DOM and re-added by react.

The relevant code is:

render() {
    let current = this.state.data.slice().sort((a,b) => {
        if(a.score < b.score) return -1;
        if(a.score > b.score) return 1;
        return 0;
    });

    let items = this.state.data.map(item => {
        let position = current.indexOf(item);
        return (
          <div
            key={item.name}
            className="item"
            style={{ top: (position*30) + 'px', backgroundColor: item.color }}>
                {item.name}
          </div>
        );
    });

    return (
      <div>
        {items}
      </div>
    );
}

Updated demo


问:
Can I instance 2 memcache classes on Google App Engine?
I'm new in Google App Engine and I am creating a web app that uses memcache(Java).

I have 2 different classes of memcache, one to store Users and another one to store Events. Each one of them uses their IDs as the key to store the data in the memcache. So my problem is, i.e. when I store an Event with the ID 115 and later I store a User with the same ID 115, the Event data is overwritten with this User data.

So, is it possible to have different instances of memcache in order to avoid this? Or am I obligated to use always unique keys?

Thank you very much in advance everyone :)

答:
There is only one Memcache available to your application. You cannot have multiple instances.

A simple solution is to use an entity key, instead of ID, when adding/retrieving entities from Memcache. An entity key is always unique.


问:
preventDefault() stops form validation
having a problem with browser form validation using .preventDefault()

Is there a way to let browser check validation of required inputs, but stops submit?

Is there any flags I can use to get if form is valid?

Thanks

update:
using both backbone and jquery

```<code>events: {
    "click #commentFormSubmit": "commentFormSubmit",
},
commentFormSubmit: function(el){
    el.preventDefault();
    var $el = $(el.target).parent();

    // this.$el.find('button').prop('disabled', true).addClass('disabled');
    var commentData = {};
    commentData.name = this.$el.find('input[name=comment_name]').val();
    commentData.country = this.$el.find('input[name=comment_country]').val();
    commentData.email = this.$el.find('input[name=comment_email]').val();
    commentData.comment = this.$el.find('textarea[name=comment_text]').val();
    commentData.grade = this.$el.find('.commnt_grade:checked').val();
    console.log('dd')
    this.model.onSubmitComment(commentData);
},
</code>```

and the form:

```<code>    <form action="" class="" method="post">
        <span>
            <input type="text" name="comment_name" class="comment_input" placeholder="{{ 'your name'|_ }}" required>
            <input type="text" name="comment_country" class="comment_input" placeholder="{{ 'country'|_ }}">
            <input type="text" name="comment_email" class="comment_input" placeholder="{{ 'your email'|_ }}" required>
        </span>

        <textarea name="comment_text" id="comment_text" cols="30" rows="10" placeholder="{{ 'your comment'|_ }}" required></textarea>
        <span class="grades">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_1" value="1">
            <label for="grade_1" class="selectGrades" data-eq="1"></label>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_2" value="2">
            <label for="grade_2" class="selectGrades" data-eq="2"></label>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_3" value="3">
            <label for="grade_3" class="selectGrades" data-eq="3"></label>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_4" value="4">
            <label for="grade_4" class="selectGrades" data-eq="4"></label>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_5" value="5">
            <label for="grade_5" class="selectGrades" data-eq="5"></label>
        </span>
        <button type="submit" id="commentFormSubmit">{{ 'submit'|_ }}</button>

    </form>
</code>```

答:
If you want to validate without submitting, you can get the browser to check the validity of the form by calling checkValidity on it, and to report the validity by calling reportValidity. (On browsers that support HTML validation.)

Calling both checks and then reports, without submitting:

```<code>yourFormElement.checkValidity();
yourFormElement.reportValidity();
</code>```

Example:

$("input[type=button]").on("click", function() {
  var yourFormElement = $("form")[0];
  yourFormElement.checkValidity();
  yourFormElement.reportValidity();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<input type="text" required>
<br><input type="text" required>
<br><input type="button" value="Click to check">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

You can also do it at the individual element level:

```<code>yourInputElement.checkValidity();
yourInputElement.reportValidity();
</code>```

Example:

$("input[type=button]").on("click", function() {
  var yourInputElement = $("#second")[0];
  yourInputElement.checkValidity();
  yourInputElement.reportValidity();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<input id="first" type="text" required>
<br><input id="second" type="text" required>
<br><input type="button" value="Click to check second field only">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Since you've mentioned you're using jQuery, I'll just emphasize that these are methods of the DOM element, not the jQuery object. So for instance, if your form has an id and you look it up like this:

```<code>var $myForm = $("#the-form");
</code>```

then you'd use

```<code>$myForm[0].checkValidity();
$myForm[0].reportValidity();
</code>```

not

```<code>$myForm.checkValidity();  // Wrong
$myForm.reportValidity(); // Wrong
</code>```

Or you could give yourself a little plugin for it:

```<code>jQuery.fn.checkValidity = function() {
    var el = this[0];
    return el && el.checkValidity();
};
jQuery.fn.reportValidity = function() {
    var el = this[0];
    return el && el.reportValidity();
};
</code>```

That's in keeping with jQuery's various other "getters" in that it only looks at the first element in the set inside the jQuery object.

Title: preventDefault() stops form validation

Body:
having a problem with browser form validation using .preventDefault()

Is there a way to let browser check validation of required inputs, but stops submit?

Is there any flags I can use to get if form is valid?

Thanks

update:
using both backbone and jquery

events: {
    "click #commentFormSubmit": "commentFormSubmit",
},
commentFormSubmit: function(el){
    el.preventDefault();
    var $el = $(el.target).parent();

    // this.$el.find('button').prop('disabled', true).addClass('disabled');
    var commentData = {};
    commentData.name = this.$el.find('input[name=comment_name]').val();
    commentData.country = this.$el.find('input[name=comment_country]').val();
    commentData.email = this.$el.find('input[name=comment_email]').val();
    commentData.comment = this.$el.find('textarea[name=comment_text]').val();
    commentData.grade = this.$el.find('.commnt_grade:checked').val();
    console.log('dd')
    this.model.onSubmitComment(commentData);
},

and the form:

    <form action="" class="" method="post">

            <input type="text" name="comment_name" class="comment_input" placeholder="{{ 'your name'|_ }}" required>
            <input type="text" name="comment_country" class="comment_input" placeholder="{{ 'country'|_ }}">
            <input type="text" name="comment_email" class="comment_input" placeholder="{{ 'your email'|_ }}" required>

        <textarea name="comment_text" id="comment_text" cols="30" rows="10" placeholder="{{ 'your comment'|_ }}" required></textarea>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_1" value="1">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_2" value="2">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_3" value="3">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_4" value="4">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_5" value="5">

        <button type="submit" id="commentFormSubmit">{{ 'submit'|_ }}</button>

    </form>

Body:
If you want to validate without submitting, you can get the browser to check the validity of the form by calling checkValidity on it, and to report the validity by calling reportValidity. (On browsers that support HTML validation.)

Calling both checks and then reports, without submitting:

yourFormElement.checkValidity();
yourFormElement.reportValidity();

Example:

$("input[type=button]").on("click", function() {
  var yourFormElement = $("form")[0];
  yourFormElement.checkValidity();
  yourFormElement.reportValidity();
});

<form>
<input type="text" required>
<br><input type="text" required>
<br><input type="button" value="Click to check">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can also do it at the individual element level:

yourInputElement.checkValidity();
yourInputElement.reportValidity();

Example:

$("input[type=button]").on("click", function() {
  var yourInputElement = $("#second")[0];
  yourInputElement.checkValidity();
  yourInputElement.reportValidity();
});

<form>
<input id="first" type="text" required>
<br><input id="second" type="text" required>
<br><input type="button" value="Click to check second field only">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Since you've mentioned you're using jQuery, I'll just emphasize that these are methods of the DOM element, not the jQuery object. So for instance, if your form has an id and you look it up like this:

var $myForm = $("#the-form");

then you'd use

$myForm[0].checkValidity();
$myForm[0].reportValidity();

not

$myForm.checkValidity();  // Wrong
$myForm.reportValidity(); // Wrong

Or you could give yourself a little plugin for it:

jQuery.fn.checkValidity = function() {
    var el = this[0];
    return el && el.checkValidity();
};
jQuery.fn.reportValidity = function() {
    var el = this[0];
    return el && el.reportValidity();
};

That's in keeping with jQuery's various other "getters" in that it only looks at the first element in the set inside the jQuery object.


问:
XML shape drawable not rendering desired color
I defined a drawable

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <solid android:color="#ffffffff" />
  <size android:width="60dp"
        android:height="40dp" />
</shape>
</code>```

But how to use it in the layout definition?

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              >
    <ImageView
        android:src="@drawable/ic_title"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        />
</LinearLayout>
</code>```

I still see only black background.

Edited:

It turned out I missed one : in the drawable xmlns declaration. Now this example works in the Gingerbread device :)

答:
In drawable I use this xml code to define the border and background:</p>

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android">
  <stroke android:width="4dp" android:color="#D8FDFB" />
  <padding android:left="7dp" android:top="7dp"
    android:right="7dp" android:bottom="7dp" />
  <corners android:radius="4dp" />
  <solid android:color="#f0600000"/>
</shape>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I defined a drawable

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <solid android:color="#ffffffff" />
  <size android:width="60dp"
        android:height="40dp" />
</shape>

But how to use it in the layout definition?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              >
    <ImageView
        android:src="@drawable/ic_title"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        />
</LinearLayout>

I still see only black background.

Edited:

It turned out I missed one : in the drawable xmlns declaration. Now this example works in the Gingerbread device :)

Body:
In drawable I use this xml code to define the border and background:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <stroke android:width="4dp" android:color="#D8FDFB" />
  <padding android:left="7dp" android:top="7dp"
    android:right="7dp" android:bottom="7dp" />
  <corners android:radius="4dp" />
  <solid android:color="#f0600000"/>
</shape>


问:
Exporting from Excel to Access error
I am trying to export a table from Excel to a table in an Access DB, but I keep getting an error "Database or Object is read only".  Here is the code in qestion.

```<code>    dbWB = Application.ActiveWorkbook.FullName
    dbWS = Application.ActiveSheet.Name
    dsh = "[" & dbWS & "$]"

    Set DB = CreateObject("ADODB.Connection")
    dbPath = "\\Corpaa.aa.com\CampusHome\IOCADHome02\758673\Projects\Global Analysis Tool\MX Analysis DB\Global Line MX Hub Review DB.accdb"
    scn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath

    DB.Open scn

    DB.Execute "DELETE * FROM tblNewSchedule;"

    SQLInsert = "INSERT INTO tblNewSchedule "
    SQLSelect = "SELECT * "
    SQLFrom = "FROM [Excel 8.0; HDR=YES; DATABASE= " & dbWB & "]." & dsh & " "

    strQry = SQLInsert & SQLSelect & SQLFrom & ";"
   DB.Execute strQry
   DB.Close
</code>```

The DELETE qry executes just fine with no errors.  The problem is the strQry execution.  I believe it is refrencing that the WB is read-only, but I am running the code from the WB.  I am running Office 2010.  Thank you for your assistance.

答:
so, after continuing my search, I discovered a different approach that worked perfectly.  I found it on this here

Here is my new working code.  Thanks for the assistance.

```<code>    dbWB = Application.ActiveWorkbook.FullName
    dbWS = Application.ActiveSheet.Name
    dsh = "[" & dbWS & "$]"

    Set DB = CreateObject("ADODB.Connection")
    dbPath = "\\Corpaa.aa.com\CampusHome\IOCADHome02\758673\Projects\Global Analysis Tool\MX Analysis DB\Global Line MX Hub Review DB.accdb"
    scn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath

    DB.Open scn

    Dim rs As ADODB.Recordset
    Dim r As Long
    Dim y As Long

    y = TWB.Cells(1, 1).End(xlDown).Row
    r = TWB.Cells(1, 1).End(xlToRight).Column

    DB.Execute "DELETE * FROM tblNewSchedule;"
    Set rs = New ADODB.Recordset
    rs.Open "tblNewSchedule", DB, adOpenKeyset, adLockOptimistic, adCmdTable

    For i = 2 To y
        With rs
            .AddNew
                For j = 1 To r
                    fName = TWB.Cells(1, j)
                    fData = TWB.Cells(i, j)
                    .Fields(fName) = fData
                Next j
        End With
    Next i

   DB.Close
</code>```

Title: Exporting from Excel to Access error

Body:
I am trying to export a table from Excel to a table in an Access DB, but I keep getting an error "Database or Object is read only".  Here is the code in qestion.

    dbWB = Application.ActiveWorkbook.FullName
    dbWS = Application.ActiveSheet.Name
    dsh = "[" & dbWS & "$]"

    Set DB = CreateObject("ADODB.Connection")
    dbPath = "\\Corpaa.aa.com\CampusHome\IOCADHome02\758673\Projects\Global Analysis Tool\MX Analysis DB\Global Line MX Hub Review DB.accdb"
    scn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath

    DB.Open scn

    DB.Execute "DELETE * FROM tblNewSchedule;"

    SQLInsert = "INSERT INTO tblNewSchedule "
    SQLSelect = "SELECT * "
    SQLFrom = "FROM [Excel 8.0; HDR=YES; DATABASE= " & dbWB & "]." & dsh & " "

    strQry = SQLInsert & SQLSelect & SQLFrom & ";"
   DB.Execute strQry
   DB.Close

The DELETE qry executes just fine with no errors.  The problem is the strQry execution.  I believe it is refrencing that the WB is read-only, but I am running the code from the WB.  I am running Office 2010.  Thank you for your assistance.

Body:
so, after continuing my search, I discovered a different approach that worked perfectly.  I found it on this here

Here is my new working code.  Thanks for the assistance.

    dbWB = Application.ActiveWorkbook.FullName
    dbWS = Application.ActiveSheet.Name
    dsh = "[" & dbWS & "$]"

    Set DB = CreateObject("ADODB.Connection")
    dbPath = "\\Corpaa.aa.com\CampusHome\IOCADHome02\758673\Projects\Global Analysis Tool\MX Analysis DB\Global Line MX Hub Review DB.accdb"
    scn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath

    DB.Open scn

    Dim rs As ADODB.Recordset
    Dim r As Long
    Dim y As Long

    y = TWB.Cells(1, 1).End(xlDown).Row
    r = TWB.Cells(1, 1).End(xlToRight).Column

    DB.Execute "DELETE * FROM tblNewSchedule;"
    Set rs = New ADODB.Recordset
    rs.Open "tblNewSchedule", DB, adOpenKeyset, adLockOptimistic, adCmdTable

    For i = 2 To y
        With rs
            .AddNew
                For j = 1 To r
                    fName = TWB.Cells(1, j)
                    fData = TWB.Cells(i, j)
                    .Fields(fName) = fData
                Next j
        End With
    Next i

   DB.Close


问:
Produckt url send not to top of product page
please help:
produckt url send not to top of product page.
Only to aditional information (“Dodatkowe informacje” on my page).
See my shop:
category link, than press any product:

direct product link:

How to fix it?
I want to see always the top of product page.
Thanks.

答:
You got some JavaScript that runs after the page load and sends the visitor to the bottom of the page. When you disable JavaScript you will see that the page loads fine.

I couldn't locate that JavaScript in the few minutes I looked into the page. You could try to locate that JavaScript by disabling functions (mainly JavaScripts) of your theme one by one and see if it starts working.

You could also switch to another theme for testing reasons and see if the issue persists. If yes then the problem is not in the theme but within one of your plugins you use.


问:
How do I map with rarely used state in clojure?
The situation is as follows: I'm transforming a sequence of values. The transformation of each value breaks down into a number of different cases. Most values are completely independent of each other. However there is one special case that requires me to keep track of how many special cases I've encountered so far. In imperative programming this is pretty straightforward:

```<code>int i = 0;
List<String> results = new ArrayList<>();
for (String value : values) {
  if (case1(value)) {
    results.add(handleCase1(value));
  } else if (case2(value)) {
  ...
  } else if (special(value)) {
    results.add(handleSpecial(value, i));
    i++;
  }
}
</code>```

However in Clojure the best I've come up with is:

```<code>(first
 (reduce
  (fn [[results i] value]
      (cond
       (case-1? value) [(conj results (handle-case-1 value)) i]
       (case-2? value) ...
       (special? value) [(conj results (handle-special value i))
                         (inc i)]))
  [[] 0] values))
</code>```

Which is pretty ugly considering that without the special case this would become:

```<code>(map #(cond
       (case-1? %) (handle-case-1 %)
       (case-2? %) ...)
      values)
</code>```

The trouble is that I'm manually stitching a sequence together during the reduction. Also most cases don't even care about the index but must nonetheless pass it along for the next reduction step.

Is there a cleaner solution to this problem?

答:
Sometimes code using loop and recur looks better than the equivalent code using reduce.

```<code>(loop [[v & more :as vs] values, i 0, res []]
  (if-not (seq vs)
    res
    (cond
      (case-1? v) (recur more i (conj res (handle-case-1 v)))
      (case-2? v) (recur more i (conj res (handle-case-2 v)))
      (special? v) (recur more (inc i) (conj res (handle-special i v))))))
</code>```

Since there seems to be some demand, here is a version that produces lazy sequence. Customary warnings about premature optimization and keeping it simple apply.

```<code>(let [handle (fn handle [[v & more :as vs] i]
               (when (seq vs)
                 (let [[ii res] (cond
                                 (case-1? v) [i (handle-case-1 v)]
                                 (case-2? v) [i (handle-case-2 v)]
                                 (special-case? v) [(inc i) (handle-special i v)])]
                   (cons res (lazy-seq (handle more ii))))))]
  (lazy-seq (handle values 0)))
</code>```

Body:
The situation is as follows: I'm transforming a sequence of values. The transformation of each value breaks down into a number of different cases. Most values are completely independent of each other. However there is one special case that requires me to keep track of how many special cases I've encountered so far. In imperative programming this is pretty straightforward:

int i = 0;
List<String> results = new ArrayList<>();
for (String value : values) {
  if (case1(value)) {
    results.add(handleCase1(value));
  } else if (case2(value)) {
  ...
  } else if (special(value)) {
    results.add(handleSpecial(value, i));
    i++;
  }
}

However in Clojure the best I've come up with is:

(first
 (reduce
  (fn [[results i] value]
      (cond
       (case-1? value) [(conj results (handle-case-1 value)) i]
       (case-2? value) ...
       (special? value) [(conj results (handle-special value i))
                         (inc i)]))
  [[] 0] values))

Which is pretty ugly considering that without the special case this would become:

(map #(cond
       (case-1? %) (handle-case-1 %)
       (case-2? %) ...)
      values)

The trouble is that I'm manually stitching a sequence together during the reduction. Also most cases don't even care about the index but must nonetheless pass it along for the next reduction step.

Is there a cleaner solution to this problem?

Body:
Sometimes code using loop and recur looks better than the equivalent code using reduce.

(loop [[v & more :as vs] values, i 0, res []]
  (if-not (seq vs)
    res
    (cond
      (case-1? v) (recur more i (conj res (handle-case-1 v)))
      (case-2? v) (recur more i (conj res (handle-case-2 v)))
      (special? v) (recur more (inc i) (conj res (handle-special i v))))))

Since there seems to be some demand, here is a version that produces lazy sequence. Customary warnings about premature optimization and keeping it simple apply.

(let [handle (fn handle [[v & more :as vs] i]
               (when (seq vs)
                 (let [[ii res] (cond
                                 (case-1? v) [i (handle-case-1 v)]
                                 (case-2? v) [i (handle-case-2 v)]
                                 (special-case? v) [(inc i) (handle-special i v)])]
                   (cons res (lazy-seq (handle more ii))))))]
  (lazy-seq (handle values 0)))


问:
How can I change React Material-ui Drawer menu items spacing?
I'm trying to use Material-UI for the first time on a React project.  I have put together the AppBar to call Drawer and a list of menu items appear from the sidebar.  The problem I'm facing is that they have giant margin-top spacing.

Example of the spacing

```<code>Close (X)

About

Contact
</code>```

I would like this all next to each other, one by one.

```<code>Close (X)
About
Contact
</code>```

I'm not sure what is causing the extra spacing.  I put together a similar mock up to the design I'm using now and the spacing was normal.  I have included the full component below.

Code

```<code>import React, { Component } from 'react'
import { Router, Route, Redirect, IndexRoute, Link, hashHistory } from 'react-router';
import AppBar from 'material-ui/AppBar'
import Menu from 'material-ui/Menu'
import MenuItem from 'material-ui/MenuItem'
import Drawer from 'material-ui/Drawer'
import FlatButton from 'material-ui/FlatButton'

class AppBars extends Component {
    constructor(props) {
        super(props)
            this.state = {
                open: false
            }
    }

    //toggleDrawer = () => this.setState({open: !this.state.open});

    toggleDrawer() {
        this.setState({
            open: !this.state.open,
        });
    }

    render() {
        return(
            <div>
                <AppBar
                    title="Advanced Surface Innovations"
                    onLeftIconButtonTouchTap={this.toggleDrawer.bind(this)}
                />
                <Drawer open={this.state.open} onToggleDrawer={this.toggleDrawer.bind(this)}>
                    <MenuItem onTouchTap={this.toggleDrawer.bind(this)}>
                    CLOSE ( X )
                    </MenuItem>
                    <MenuItem onTouchTap={this.toggleDrawer.bind(this)}><Link to="/">
                        <FlatButton label="Home" primary={true} />
                    </Link>
                    </MenuItem>
                    <MenuItem onTouchTap={this.toggleDrawer.bind(this)}><Link to="/About">
                        <FlatButton label="About" primary={true} />
                    </Link>
                    </MenuItem>
                    <MenuItem onTouchTap={this.toggleDrawer.bind(this)}><Link to ="/Contact">
                        <FlatButton label="Contact" primary={true} />
                    </Link>
                    </MenuItem>
                </Drawer>
            </div>
        )
    }
}

class NavBar extends Component {
    constructor(props) {
        super(props)
        this.state = {
            nav: ''
        }
    }

    handleScroll(event) {
        console.log('handleScroll invoked');
    }

    componentDidMount() {
        console.log('componentDidMount invoked');
        window.addEventListener('scroll', this.handleScroll);
    }

    componentWillUnmount() {
        console.log('componentWillUnmount invoked');
        window.removeEventListener('scroll', this.handleScroll);
    }

    render() {
        return (
            <div>
                 <AppBars />
            </div>
        )
    }
}

export default NavBar;
</code>```

答:
You might want to enclose your MenuItems in a Menu block:

```<code><Drawer open={this.state.open} onToggleDrawer={this.toggleDrawer.bind(this)}>
  <Menu onItemTouchTap={this.toggleDrawer.bind(this)}>
    <MenuItem >
      CLOSE ( X )
    </MenuItem>
    …
  </Menu>
</Drawer>
</code>```

This also spares you from repeating the onTouchTap code on every item.

Also I'd use the route links as a prop to MenuItem instead of as children. That way the whole item will be clickable (otherwise it will only be the link text) and you don't need to style it as a button:

```<code><MenuItem primaryText="Home" containerElement={<Link to="/">} />
</code>```

Body:
I'm trying to use Material-UI for the first time on a React project.  I have put together the AppBar to call Drawer and a list of menu items appear from the sidebar.  The problem I'm facing is that they have giant margin-top spacing.

Example of the spacing

Close (X)

About

Contact

I would like this all next to each other, one by one.

Close (X)
About
Contact

I'm not sure what is causing the extra spacing.  I put together a similar mock up to the design I'm using now and the spacing was normal.  I have included the full component below.

Code

import React, { Component } from 'react'
import { Router, Route, Redirect, IndexRoute, Link, hashHistory } from 'react-router';
import AppBar from 'material-ui/AppBar'
import Menu from 'material-ui/Menu'
import MenuItem from 'material-ui/MenuItem'
import Drawer from 'material-ui/Drawer'
import FlatButton from 'material-ui/FlatButton'

class AppBars extends Component {
    constructor(props) {
        super(props)
            this.state = {
                open: false
            }
    }

    //toggleDrawer = () => this.setState({open: !this.state.open});

    toggleDrawer() {
        this.setState({
            open: !this.state.open,
        });
    }

    render() {
        return(

                <AppBar
                    title="Advanced Surface Innovations"
                    onLeftIconButtonTouchTap={this.toggleDrawer.bind(this)}
                />
                <Drawer open={this.state.open} onToggleDrawer={this.toggleDrawer.bind(this)}>
                    <MenuItem onTouchTap={this.toggleDrawer.bind(this)}>
                    CLOSE ( X )
                    </MenuItem>
                    <MenuItem onTouchTap={this.toggleDrawer.bind(this)}><Link to="/">
                        <FlatButton label="Home" primary={true} />
                    </Link>
                    </MenuItem>
                    <MenuItem onTouchTap={this.toggleDrawer.bind(this)}><Link to="/About">
                        <FlatButton label="About" primary={true} />
                    </Link>
                    </MenuItem>
                    <MenuItem onTouchTap={this.toggleDrawer.bind(this)}><Link to ="/Contact">
                        <FlatButton label="Contact" primary={true} />
                    </Link>
                    </MenuItem>
                </Drawer>

        )
    }
}

class NavBar extends Component {
    constructor(props) {
        super(props)
        this.state = {
            nav: ''
        }
    }

    handleScroll(event) {
        console.log('handleScroll invoked');
    }

    componentDidMount() {
        console.log('componentDidMount invoked');
        window.addEventListener('scroll', this.handleScroll);
    }

    componentWillUnmount() {
        console.log('componentWillUnmount invoked');
        window.removeEventListener('scroll', this.handleScroll);
    }

    render() {
        return (

                 <AppBars />

        )
    }
}

export default NavBar;

Body:
You might want to enclose your MenuItems in a Menu block:

<Drawer open={this.state.open} onToggleDrawer={this.toggleDrawer.bind(this)}>
  <Menu onItemTouchTap={this.toggleDrawer.bind(this)}>
    <MenuItem >
      CLOSE ( X )
    </MenuItem>
    …
  </Menu>
</Drawer>

This also spares you from repeating the onTouchTap code on every item.

Also I'd use the route links as a prop to MenuItem instead of as children. That way the whole item will be clickable (otherwise it will only be the link text) and you don't need to style it as a button:

<MenuItem primaryText="Home" containerElement={<Link to="/">} />