text:
Q: Center modal with fade in scale up I'm struggling with centering the modal together with fade in and scale up:

$('#md-trigger').on('click', function(e) {
      $('#modal-1').toggleClass("md-show"); //you can list several class names
      e.preventDefault();
    });

$('#md-close').on('click', function(e) {
      $('#modal-1').toggleClass("md-show"); //you can list several class names
      e.preventDefault();
    });
.md-modal {
  width: 100%;
  max-width: 550px;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  position: absolute;
  z-index: 9999;
  visibility: hidden;
  padding: 25px;
  border: 1px solid rgba(0,0,0,.2);
  border-radius: .3rem;
  background-color: #fff;
  font-family: Helvetica Neue,Helvetica,Arial,sans-serif;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,.2),0 6px 20px 0 rgba(0,0,0,.19);
  outline: 0;
}

.md-show {
    visibility: visible;
}

.md-overlay {
    position: fixed;
    width: 100%;
    height: 100%;
    visibility: hidden;
    top: 0;
    left: 0;
    z-index: 9998;
    opacity: 0;
    background: rgba(40,43,49,.8);
    -webkit-transition: all 0.3s;
    transition: all 0.3s;
}

.md-show ~ .md-overlay {
    opacity: 1;
    visibility: visible;
}

.md-content {
    color: #333;
}

.md-effect-1 {
    -webkit-transform: scale(0.7);
    -ms-transform: scale(0.7);
    transform: scale(0.7);
    opacity: 0;
    -webkit-transition: all 0.3s;
    transition: all 0.3s;
}

.md-show.md-effect-1 {
    -webkit-transform: scale(1);
    -ms-transform: scale(1);
    transform: scale(1);
    opacity: 1;
}

<button id="md-trigger">Show</button>

Modal Dialog

This is a modal window. You can do the following things with it:

      <button class="md-close" id="md-close">Close me!</button>

The absolute positioning approach with transform:translate(-50%,-50%); isn't working for me. It has to be responsive so I can't use the margin-left approach. Do you have an idea why it is simply not displayed in the middle?

A: Please try this,
Add this style to md-modal-wrapper class. added a md-modal-wrapper div to cover md-modal class
.md-modal-wrapper{
  width:100vw;
  height:100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

Remove this style
.md-modal {
   top: 50%;
   left: 50%;
   transform: translate(-50%,-50%);
   position: absolute;
}

$('#md-trigger').on('click', function(e) {
   $('#modal-1').toggleClass("md-show"); //you can list several class names
   e.preventDefault();
});

$('#md-close').on('click', function(e) {
   $('#modal-1').toggleClass("md-show"); //you can list several class names
   e.preventDefault();
});
.md-modal {
    width:100%;
    max-width: 550px;
    z-index: 9999;
    visibility: hidden;
    padding: 25px;
    border: 1px solid rgba(0,0,0,.2);
    border-radius: .3rem;
    background-color: #fff;
    font-family: Helvetica Neue,Helvetica,Arial,sans-serif;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,.2),0 6px 20px 0 rgba(0,0,0,.19);
    outline: 0;
}
.md-show {
    visibility: visible;
}
.md-overlay {
    position: fixed;
    width: 100%;
    height: 100%;
    visibility: hidden;
    top: 0;
    left: 0;
    z-index: 9998;
    opacity: 0;
    background: rgba(40,43,49,.8);
    -webkit-transition: all 0.3s;
    transition: all 0.3s;
}

.md-show ~ .md-overlay {
    opacity: 1;
    visibility: visible;
}

.md-content {
    color: #333;
}

.md-effect-1 {
    -webkit-transform: scale(0.7);
    -ms-transform: scale(0.7);
    transform: scale(0.7);
    opacity: 0;
    -webkit-transition: all 0.3s;
    transition: all 0.3s;
}

.md-show.md-effect-1 {
    -webkit-transform: scale(1);
    -ms-transform: scale(1);
    transform: scale(1);
    opacity: 1;
}
.md-modal-wrapper{
  width:100vw;
  height:100vh;
  display: flex;
  justify-content: center;
  align-items: center;

}
body{
  margin:0;
}

<button id="md-trigger">Show</button>

Modal Dialog

This is a modal window. You can do the following things with it:

      <button class="md-close" id="md-close">Close me!</button>

A: scale(1) was overriding the other transform property, translate(-50%,-50%).
It can be easily fixed by combining them both: transform: translate(-50%,-50%) scale(1).

$('#md-trigger').on('click', function(e) {
      $('#modal-1').toggleClass("md-show"); //you can list several class names
      e.preventDefault();
    });

$('#md-close').on('click', function(e) {
      $('#modal-1').toggleClass("md-show"); //you can list several class names
      e.preventDefault();
    });
.md-modal {
  width: 100%;
  max-width: 550px;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  position: absolute;
  z-index: 9999;
  visibility: hidden;
  padding: 25px;
  border: 1px solid rgba(0,0,0,.2);
  border-radius: .3rem;
  background-color: #fff;
  font-family: Helvetica Neue,Helvetica,Arial,sans-serif;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,.2),0 6px 20px 0 rgba(0,0,0,.19);
  outline: 0;
}

.md-show {
    visibility: visible;
}

.md-overlay {
    position: fixed;
    width: 100%;
    height: 100%;
    visibility: hidden;
    top: 0;
    left: 0;
    z-index: 9998;
    opacity: 0;
    background: rgba(40,43,49,.8);
    -webkit-transition: all 0.3s;
    transition: all 0.3s;
}

.md-show ~ .md-overlay {
    opacity: 1;
    visibility: visible;
}

.md-content {
    color: #333;
}

.md-effect-1 {
    -webkit-transform: scale(0.7);
    -ms-transform: scale(0.7);
    transform: scale(0.7);
    opacity: 0;
    -webkit-transition: all 0.3s;
    transition: all 0.3s;
}

.md-show.md-effect-1 {
    -webkit-transform: scale(1);
    -ms-transform: scale(1);
    transform: translate(-50%,-50%) scale(1);
    opacity: 1;
}

<button id="md-trigger">Show</button>

Modal Dialog

This is a modal window. You can do the following things with it:

      <button class="md-close" id="md-close">Close me!</button>

A: How about using flex?
Remove position: absolute; and transform: translate(-50%,-50%); from md-modal
and cover the modal with flex div
.md-container {
  display:flex;
  justify-content:center;
  align-items:center
}

  ~~

I don't know how to use snippet so I'm attaching a codePen link
https://codepen.io/seongmin0801/pen/MWyrYvm

A: Make transform: translate(-50%,-50%) !important;. There is .md-show.md-effect-1 { transform: scale(1); } that overrides it that's why you should use important


text:
Q: How to exclude a certain string from a pattern in regex I have a regex pattern that matches a URL "slug" which I use to redirect all URI's with one segment that contain alphanumeric characters and hyphens(I.E. mysite.com/about-us) to my pages controller.  My problem is that I have a separate controller for my home page, so I want to exclude the string "home" from any matches. How can I do this with the pattern that I have below?
^([a-zA-Z0-9-]+)$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails4 Foundation4 undefined mixin I can't use mixins of Foundation in my rails app (error: Undefined mixin 'column').
Gemfile
    gem 'rails', '~> 4.0.0'
    gem 'sass-rails'
    gem 'zurb-foundation'

Application.css.scss
    /*
    *= require_self
    *= require foundation_and_overrides
    *= require_tree .
    */

layout.css.scss
    section {
      @include column(12);
    }

    aside {
      @include column(4);
    }

And there it does not find the mixin.
I've also looked at https://github.com/zurb/foundation/issues/1230
and https://github.com/zurb/foundation/issues/2128 but none of them seemed to work.

A: I had the same problem when I wanted to use a mixing in my stories.css.scss
I had to remove the requires and import my scss files manually.
#application.css.scss
@import "foundation_and_overrides";
@import "stories";

source: https://github.com/zurb/foundation/issues/2128#issuecomment-17912556
Additionally I had following error message
Syntax error: File to import not found or unreadable: foundation/foundation-global.

I had to change following line in foundation_and_overrides.css.scss
#foundation_and_overrides.css.scss
@import "foundation/foundation-global";

to
#foundation_and_overrides.css.scss
@import "foundation/variables";

source: https://github.com/zurb/foundation/issues/1792#issuecomment-17041016
I hope that helps. It took me some time to get this working.

A: I'm experiencing the same issue... here's my app.scss... Everything works but I can't use foundation mixins I'm watching the file with Compass.
// Global Foundation Settings
@import "settings";

// Comment out this import if you don't want to use normalize
@import "normalize";

// Comment out this import if you are customizing you imports below
@import "foundation";
@import "compass";
@import "compass/css3";

@import "foundation/variables";

// Import specific parts of Foundation by commenting the import "foundation"
// and uncommenting what you want below. You must uncomment the following if customizing

@import "foundation/components/global"; // *always required
@import "foundation/components/grid";

//
// Use this grid if you want to start using the new Foundation 5 grid early.
// It will change breakpoints to min-width: 640px and 1024px.
//
@import "foundation/components/grid-5";
//

@import "foundation/components/visibility";
@import "foundation/components/block-grid";
@import "foundation/components/type";
@import "foundation/components/buttons";
@import "foundation/components/forms"; // *requires components/buttons
@import "foundation/components/custom-forms"; // *requires components/buttons, components/forms
@import "foundation/components/button-groups"; // *requires components/buttons
@import "foundation/components/dropdown-buttons"; // *requires components/buttons
@import "foundation/components/split-buttons"; // *requires components/buttons
@import "foundation/components/flex-video";
@import "foundation/components/section";
@import "foundation/components/top-bar";  // *requires components/grid
@import "foundation/components/orbit";
@import "foundation/components/reveal";
@import "foundation/components/joyride";
@import "foundation/components/clearing";
@import "foundation/components/alert-boxes";
@import "foundation/components/breadcrumbs";
@import "foundation/components/keystrokes";
@import "foundation/components/labels";
@import "foundation/components/inline-lists";
@import "foundation/components/pagination";
@import "foundation/components/panels";
@import "foundation/components/pricing-tables";
@import "foundation/components/progress-bars";
@import "foundation/components/side-nav";
@import "foundation/components/sub-nav";
@import "foundation/components/switch";
@import "foundation/components/magellan";
@import "foundation/components/tables";
@import "foundation/components/thumbs";
@import "foundation/components/tooltips";
@import "foundation/components/dropdown";

@media only screen and (min-width: $small-screen) {

    nav.top-bar > section > ul > li.has-dropdown{
        position: static;
        & > .dropdown{
            @include outerRow();

            & > li.has-dropdown{
                @include column(3);
                min-width: auto;

                .dropdown{

                    position: static;
                    visibility: inherit;
                    top: auto !important;
                    left: auto !important;
                    padding: 0;
                    min-width: auto;
                    li{
                        @include column(12);
                         min-width: auto;
                    }
                }
            }
        }
    }
}


text:
Q: algorithm for searching in ranges I am given a huge list of objects with attributes x and y. We are required to search for all objects lying between a given upper and lower bound of both the attributes.
I was wondering if there is an efficient algorithm to implement this.
Thanks!

A: There are standard algorithms for this.  See http://en.wikipedia.org/wiki/R-tree for one.

A: A quadtree or a spatial index (a space-filling curve, for example a hilbert curve).


text:
Q: swap the Multiple Video Html elements before Removing how to swap the elements before Removing them without the use of a clone using jquery
I created the video call app for using picture in picture mode that was working properly but I have a small issue when I click to swap the video that working properly, after swapping when I want to remove some video they are not working properly.
JsFile
/* swaping the videoElement */
function initVideoSwapping() {

    // check if there is an element first
    if ($('.video-list .videoWrap').length > 0 && $('.mainVideo').length > 0) {
        $('.video-list .videoWrap').on('click', function () {
            /* stopEvent Propogation */
            var $this = $(this);
            console.log($this)
            $this.data('clicked', true);
            initRemoveSwap()
            var IsadminTrue = getDataFromQueryString()
            if (IsadminTrue.isadmin) {
                var $StopthisDrop = $(this).find('#DropDown')[0];
                $StopthisDrop.addEventListener('click', (e) => {
                    e.stopImmediatePropagation()
                })
                var $StopthisBtn = $(this).find('button')[0];
                $StopthisBtn.addEventListener('click', (e) => {
                    e.stopImmediatePropagation()
                })
            }

            // name
            var $thisName = $(this).find('span')[0]
            var $mainName = $('.main-videoWrap').find('span')[0]
            // dropdown
            var $thisBtn = $(this).find('button')[0];
            var $mainbtn = $('.main-videoWrap').find('button')[0];
            var $thisUlElement = $(this).find('ul')[0];
            var $mainUlElement = $('.main-videoWrap').find('ul')[0];
            // video
            var $thisVideo = $(this).find('video')[0];
            var $mainVideo = $('.main-videoWrap').find('video')[0];
            swapNodes($thisVideo, $mainVideo, $thisName, $mainName, $thisBtn, $mainbtn, IsadminTrue, $thisUlElement, $mainUlElement);
        });

    }
}

function swapNodes(thisVideo, mainVideo, thisName, mainName, thisBtn, mainbtn, thisUlelement, mainUlElement) {
    var thisVideoparent = thisVideo.parentNode;
    var asibling = thisVideo.nextSibling === mainVideo ? thisVideo : thisVideo.nextSibling;
    mainVideo.parentNode.insertBefore(thisVideo, mainVideo);
    thisVideoparent.insertBefore(mainVideo, asibling);

    // Name Change
    var thisNameParent = thisName.parentNode;
    var Namesiblings = thisName.nextSibling === mainName ? thisName : thisName.nextSibling;
    mainName.parentNode.insertBefore(thisName, mainName);
    thisNameParent.insertBefore(mainName, Namesiblings);

    // dropdown change

        var BtnParanet = thisBtn.parentNode;
        var Btniblings = thisBtn.nextSibling === mainbtn ? thisBtn : thisBtn.nextSibling;
        mainbtn.parentNode.insertBefore(thisBtn, mainbtn);
        BtnParanet.insertBefore(mainbtn, Btniblings);
        // ulElement Change
        var UlParanet = thisUlelement.parentNode;
        var ULSiblings = thisUlelement.nextSibling === mainUlElement ? thisUlelement : thisUlelement.nextSibling;
        mainUlElement.parentNode.insertBefore(thisUlelement, mainUlElement);
        UlParanet.insertBefore(mainUlElement, ULSiblings);

}

    var asibling = thisVideo.nextSibling === mainVideo ? thisVideo : thisVideo.nextSibling;
    mainVideo.parentNode.insertBefore(thisVideo, mainVideo);
    thisVideoparent.insertBefore(mainVideo, asibling);
    // Name Change
    var thisNameParent = thisName.parentNode;
    var Namesiblings = thisName.nextSibling === mainName ? thisName : thisName.nextSibling;
    mainName.parentNode.insertBefore(thisName, mainName);
    thisNameParent.insertBefore(mainName, Namesiblings);
    // if (IsadminTrue.isadmin) {
    var BtnParanet = thisBtn.parentNode;
    var Btniblings = thisBtn.nextSibling === mainbtn ? thisBtn : thisBtn.nextSibling;
    mainbtn.parentNode.insertBefore(thisBtn, mainbtn);
    BtnParanet.insertBefore(mainbtn, Btniblings);
    // ulElement Change
    var UlParanet = thisUlelement.parentNode;
    var ULSiblings = thisUlelement.nextSibling === mainUlElement ? thisUlelement : thisUlelement.nextSibling;
    mainUlElement.parentNode.insertBefore(thisUlelement, mainUlElement);
    UlParanet.insertBefore(mainUlElement, ULSiblings);
    // }
}}

My Last Try was
function initRemoveSwap() {
    var IsadminTrue = getDataFromQueryString()
    if (IsadminTrue.isadmin) {
        $('.video-list .videoWrap').on('remove', function () {
            var $thisVideo = $(this).find('video')[0];
            var $mainVideo = $('.main-videoWrap').find('video')[0];
            // name
            var $thisName = $(this).find('span')[0]
            var $mainName = $('.main-videoWrap').find('span')[0]
            // dropdown
            var $thisBtn = $(this).find('button')[0];
            var $mainbtn = $('.main-videoWrap').find('button')[0];

            var $thisUlElement = $(this).find('ul')[0];
            var $mainUlElement = $('.main-videoWrap').find('ul')[0];

            RemoveswapNodes($mainVideo, $thisVideo, $thisName, $mainName, $thisBtn, $mainbtn, IsadminTrue, $thisUlElement, $mainUlElement);

        })

    }
function RemoveswapNodes(mainVideo, thisVideo, thisName, mainName, thisBtn, mainbtn, IsadminTrue, thisUlelement, mainUlElement) {
        // videoChange
        var thisVideoparent = thisVideo.parentNode;
        var asibling = thisVideo.nextSibling === mainVideo ? thisVideo : thisVideo.nextSibling;
        mainVideo.parentNode.insertBefore(thisVideo, mainVideo);
        thisVideoparent.insertBefore(mainVideo, asibling);
        // Name Change
        var thisNameParent = thisName.parentNode;
        var Namesiblings = thisName.nextSibling === mainName ? thisName : thisName.nextSibling;
        mainName.parentNode.insertBefore(thisName, mainName);
        thisNameParent.insertBefore(mainName, Namesiblings);
        // if (IsadminTrue.isadmin) {
        var BtnParanet = thisBtn.parentNode;
        var Btniblings = thisBtn.nextSibling === mainbtn ? thisBtn : thisBtn.nextSibling;
        mainbtn.parentNode.insertBefore(thisBtn, mainbtn);
        BtnParanet.insertBefore(mainbtn, Btniblings);
        // ulElement Change
        var UlParanet = thisUlelement.parentNode;
        var ULSiblings = thisUlelement.nextSibling === mainUlElement ? thisUlelement : thisUlelement.nextSibling;
        mainUlElement.parentNode.insertBefore(thisUlelement, mainUlElement);
        UlParanet.insertBefore(mainUlElement, ULSiblings);
        // }
    }
}

window.addEventListener('click', initVideoSwapping, false)

I've tried a lot of different ways to change items. I've tried with replaceWith(), before(), and after() but nothing worked.
NOTE: I've already written a function which displays the correct up / down DIVs. So the first and last one can only moved in one direction. That's already solved. I also can't use any kind of existing jQuery plugins.
Kindly Help to how to solve this issue!


text:
Q: Angular.js error I'm working on a project where I'm trying to allow me to upload weather data from an .xls file to an SQL database.  It's my first time using Angularjs so I used a tutorial and everything seemed to work fine.
My code is:

<head>
<title>.: Import Data with AngularJS :.</title>
<meta charset="utf-8" />
<script type="text/javascript"
src="C:\Users\Bryan\source\repos\Weather\weather\Scripts\jquery-
1.10.2.min.js"></script>
<script type="text/javascript"
src="C:\Users\Bryan\source\repos\Weather\weather\Scripts\angular.min.js">
</script>

<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-
route.min.js"
<script type="text/javascript"
src="C:\Users\Bryan\source\repos\Weather\weather\Scripts\bootstrap.min.js">
</script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.cs
s">
<script type="text/javascript"
src="C:\Users\Bryan\source\repos\Weather\weather\Scripts\ImportData.js">
</script>

<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.11.5/xlsx.full.min.js">
</script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.11.5/jszip.js"></script>

Everything goes well but I get the following errors:
ImportData.html:7 GET http://localhost:9000/Content/bootstrap.min.css
net::ERR_ABORTED
ImportData.html:1 Not allowed to load local resource: ImportData.js
angular.js:88 Uncaught Error: [$injector:modulerr]
at angular.js:88
at angular.js:4957
at p (angular.js:410)
at g (angular.js:4917)
at gb (angular.js:4839)
at c (angular.js:1949)
at Uc (angular.js:1970)
at xe (angular.js:1855)
at angular.js:33826
at HTMLDocument.b (angular.js:3468)

I've read that bootstrap and angular can conflict, but take it out and it still seems to error out.  Any ideas where the error is?  Thanks in advance.

A: The problem is that you are trying to load resources from your local computer. Try giving path as relative that will solve your issue. Also use base url in html if you want to control base url for all requests from your app.

A: Your files are not able to fetch by the browser from the mentioned locations. So better way to give relative paths i.e. "../../ImportData.js".
Also It shows injector module error that means, Angular file is missing and its module is not able to find the libraries.
You can try replacing all the file paths with as well. Also this http://localhost:9000/Content/bootstrap.min.css
net::ERR_ABORTED
is due to the internet failure or due to your firewall restrictions. So, you can replace this with "https" instead of 'http'.
Try these options. There's problem with file links only.


text:
Q: What part of speech is "alight" in "set alight"? In the clause it was set alight, is alight

*

*acting as adverb and modifying was set

*an adjective and modifying it; or

*something else entirely that I'm missing.

I'm fairly certain that set alight isn't a phrasal verb so I'm a little stumped.

A:
It was set alight.

I would understand alight here as an adjective describing it and acting syntactically as a resultative Predicate Complement to the verb set: [something] caused it to be alight.


text:
Q: Azure backup conflict with SQL database backup chain Our SQL VMs in Azure are currently being backed up via Azure backups on a daily basis. We have noticed however that this is affecting our differential backup chains - how do we create a regular server snapshot backup image of the SQL server without affecting the SQL database backup chains on it?

A: The Azure Backup service uses VSS snapshot backups, which means it's going to quiesce SQL Server. The good news is that you get good backups (as opposed to crash-consistent ones), but of course the bad news is that they're not copy-only backups.
What you're probably looking for is crash-consistent backups (dirty snapshots) - search for "crash" on that Azure Backup documentation link. To get that in Azure, you'd need to lose the Azure VM agent, which comes with different drawbacks. (On-premises, this is easier since you can just tell your hypervisor to grab a dirty snapshot backup without engaging VSS.)


text:
Q: Replace the default MessageBox

When I use Ext.MessageBox.show({...}) it show the box like IMG2 default. I want to use the box like IMG1 and how could I replace it.
Thanks!!!

A: you should use loadMask for your extjs component.

// Basic mask:
var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
myMask.show();


text:
Q: Replacing Dot to comma in VBA I have an issue when I try to replace all "." with ","
It works normal when I use Ctrl + H in the Excel Sheet and do it manually.
I have recorded the Macro from what I do in the sheet, and got this code
Columns("Q:S").Select
    Selection.Replace What:=".", Replacement:=",", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

But when I run the Macro it only removes the "." , instead of replacing it with "," .
So for instance, if the cell states 4.000 aftter I run the Macro, it returns 4000.
How do I fix this??
I have also tried changing decimal separators in the system, but it does not help me.
Thank you for your help.

A: This should replace all the periods with commas regardless of data type. (as a string, so you'll no longer be able to easily calculate from them)
You'll still be running into a lot of trouble if you want these numbers to be numbers, with correct separators.
As a side note, When I used find and replace (Ctrl + H) I got the same result where my "4.123" became "4,123.00". This may be related to our system settings.
Sub Test_Replace_Period_with_Comma()

    Dim ValueRange As Range
    Dim ValueSet

    Dim X As Long
    Dim Y As Long

    Set ValueRange = Intersect(Columns("Q:S"), Sheet8.UsedRange)
    ValueSet = ValueRange

    If ValueRange.Cells.Count = 1 Then
        ReDim ValueSet(1 To 1, 1 To 1)
    End If

    For X = 1 To UBound(ValueSet, 1)
        For Y = 1 To UBound(ValueSet, 2)
            'Debug.Print ValueSet(X, Y)
            If ValueSet(X, Y) <> "" Then
                ValueSet(X, Y) = Replace(CStr(ValueSet(X, Y)), ".", ",", 1, , vbTextCompare)
            End If
        Next Y
    Next X

    ValueRange.NumberFormat = "@"
    ValueRange = ValueSet

End Sub


text:
Q: Javascript + jquery, function inside a for loop Basically i've got a lot of repetition in my code as im changing a few bits and pieces inside my function to accomodate the different divs such as class name, text and padding. Rather then writing them all out individually like so;
$('.about').hover(function () {
        $('.clickable7').text("Find out about us").css('padding-top', '137px').fadeIn(200);
        $('.positional').css("background-image", "none");
    },
    function () {
        $('.clickable7').fadeOut(200);
        $('.positional').css('background-image', 'url(assets/imgs/prototype6.png)');
    });
$('.friends').hover(function () {
        $('.clickable7').text("Meet our Friends").css('padding-top', '137px').fadeIn(200);
        $('.positional').css("background-image", "none");
    },
    function () {
        $('.clickable7').fadeOut(200);
        $('.positional').css('background-image', 'url(assets/imgs/prototype6.png)');
    });

I'm trying to write a function that will do it for me, i've gotten the functionality down but it kills the rest of my javascript code for some reason.
var titles = [
    {
        name: ".about",
        text: "find out about us",
        padding: 137
    },
    {
        name: ".friends",
        text: "meet our friends",
        padding: 137
    }
];

for (i = 0; i <= 6; i++) {
    (function(index) {
        var name = titles[index].name;
        var text = titles[index].text;
        var padding = titles[index].padding;

        $(name).hover(function () {
            $('.clickable7').text(text).css('padding-top', padding).fadeIn(200);
            $('.positional').css("background-image", "none");
        },
        function () {
            $('.clickable7').fadeOut(200);
            $('.positional').css('background-image', 'url(assets/imgs/prototype6.png)');
        });
    })(i);
};

Any help will be greatly appreciated :)
edit--- my html

About

Friends

Purpose

Empowerment

Contact Us

Passion

A: Upon inspection of the loop termination condition, I suggest changing
for (i = 0; i <= 6; i++) {

to
for (i = 0; i < titles.length; i++) {

because it looks like you have 6 links, but you set your for-loop to terminate at 6, so titles[6] will cause an OOB error which probably prevents the rest of your code from running.

It's also not advisable to put anonymous functions in a loop if you can help it.
I took the liberty of making another way to accomplish your task without using loops. Basically, you can put data into the divs and use just one function to utilize the data and populate your hidden div. There are other ways, but this is just one humble solution.
Oh yes, you can use .stop() to prevent all the animation from chaining up between hovers.

$('.click').hover(function() {
  $this = $(this);
  $('.clickable7')
    .text($this.data('text'))
    .css('padding-top', $this.data('padding'))
    .stop()
    .fadeIn(200);
}, function() {
  $('.clickable7')
    .stop()
    .fadeOut(200);
});

About

Friends

Purpose

Empowerment

Contact Us

Passion

A: The for loop is terminated with a ; which is a wrong syntax. As Drakes mentioned, defining anonymous functions inside a loop should be avoided as this usually creates closure issues. I have extracted the anonymous function like this:
(function($){
    var i,
        titles = [
        {
            name: ".about",
            text: "find out about us",
            padding: 137
        },
        {
            name: ".friends",
            text: "meet our friends",
            padding: 137
        }
    ];

    function bindHoverHandlers(index){
        var name = titles[index].name,
            text = titles[index].text,
            padding = titles[index].padding;

        $(name).hover(function () {
             $('.clickable7').text(text).css('padding-top', padding).fadeIn(200);
             $('.positional').css("background-image", "none");
         }, function () {
             $('.clickable7').fadeOut(200);
             $('.positional').css('background-image', 'url(assets/imgs/prototype6.png)');
         });
    }

    for (i = 0; i < titles.length; i++) {
        bindHoverHandlers(i);
    }
}(window.jQuery));


text:
Q: create bar plot in ggplot2 and add dots according to labels from another data frame df1 <- data.frame(var=c("foo","bar","baz"), value=c(10,20,30))
df2 <- data.frame(var1=c("foo","foo","bar","baz"),var2=c("bar","baz","foo","foo"), value=c(23,18,26,33), color=c("blue","green","red","yellow"))

p <- ggplot(aes(x=var, y=value), data=df1) + geom_bar(stat="identity")

Now I would like to add a dot to each bar of p according to the labels in df2$var1 and df2$var2 with the color specified in df2$color.
For example, showing a blue dot over the bars foo and bar with a value of 23.
A green dot over the bars foo and baz with a value of 18, and so on.
I'm not sure how to implement this in ggplot2...

A: You can set the colour of geom_point by using colour outside of the aes. With your example, you can do something like that:
library(ggplot2)
ggplot(aes(x=var, y=value), data=df1) + geom_bar(stat="identity") +
  geom_point(data = df2, aes(x = var1, y= value), colour = df2$color)+
  geom_point(data = df2, aes(x = var2, y= value), colour = df2$color)

EDIT: Use of scale_color_identity
The solution above will work in your simple case. However, if you need to do faceting for example, it will be better to use the option  scale_color_identityas proposed by @MrFlick.
library(ggplot2)
ggplot(aes(x=var, y=value), data=df1) + geom_bar(stat="identity") +
  geom_point(data = df2, aes(x = var1, y= value, color = color))+
  geom_point(data = df2, aes(x = var2, y= value, color = color))+
  scale_color_identity()


text:
Q: Template functions strange linker error Consider this simple join function implementation.
#include <iostream>
#include <string>

namespace detail {
    template<typename... Args>
    size_t calcSize(const Args&... args);

    inline size_t calcSize(const std::string& head) {
        return head.size();
    }

    template<size_t N>
    size_t calcSize(char const(&) [N]) {
        return N - 1;
    }

    template<typename... Tail>
    size_t calcSize(const std::string& head, const Tail&... tail) {
        return head.size() + calcSize(tail...);
    }

    template<size_t N, typename... Tail>
    size_t calcSize(char const(&) [N], const Tail&... tail) {
        return N - 1 + calcSize(tail...);
    }

    template<typename... Args>
    void fillResult(std::string& result,
                    size_t startIndex,
                    const Args&... args);

    inline void fillResult(std::string& result,
                           size_t startIndex,
                           const std::string& head) {
        for (size_t i = 0; i < head.size(); ++i) {
            if (head[i] == '\0') {
                break;
            }
            result[startIndex++] = head[i];
        }
    }

    template<size_t N>
    void fillResult(std::string& result,
                    size_t startIndex,
                    char const(&head) [N]) {
        for (size_t i = 0; i < N; ++i) {
            if (head[i] == '\0') {
                break;
            }
            result[startIndex++] = head[i];
        }
    }

    template<typename... Tail>
    void fillResult(std::string& result,
                    size_t startIndex,
                    const std::string& head,
                    const Tail&... tail) {
        for (size_t i = 0; i < head.size(); ++i) {
            if (head[i] == '\0') {
                break;
            }
            result[startIndex++] = head[i];
        }
        fillResult(result, startIndex, tail...);
    }

    template<size_t N, typename... Tail>
    void fillResult(std::string& result,
                    size_t startIndex,
                    char const(&head) [N],
                    const Tail&... tail) {
        for (size_t i = 0; i < N; ++i) {
            if (head[i] == '\0') {
                break;
            }
            result[startIndex++] = head[i];
        }
        fillResult(result, startIndex, tail...);
    }
}

template<typename... Args>
std::string join(const Args&... args) {
    std::string result;
    result.resize(detail::calcSize(args...));
    detail::fillResult(result, 0, args...);
    return result;
}

int main() {
    std::cout << join("ab", "cd", "ef", "gh") << std::endl;
    std::cout << join(std::string("ab"), std::string("cd"), std::string("ef")) << std::endl;
    std::cout << join(std::string("ab"), "cd") << std::endl;
    //std::cout << join(std::string("ab"), "cd", "ef") << std::endl;
    //std::cout << join(std::string("ab"), "cd", std::string("ef")) << std::endl;
    return 0;
}

It works fine for the three first lines in main and fails with linker error if you uncomment any of two last invocations. Tried with gcc 4.9 and clang with the same result. Can anyone point out what's wrong?
Here is a link to coliru http://coliru.stacked-crooked.com/a/f55aa64fb4861e43

A: I think this is basically an ill-formed program, because you end up using an overload that wouldn't be used if all overloads had been visible at the time of use. This is because the overload you want isn't actually declared yet at the point where it is needed. To fix this, just add all the declarations up front:
namespace detail {

template<typename... Args>
size_t calcSize(const Args&... args);

template<size_t N, typename... Tail>
size_t calcSize(char const(&) [N], const Tail&... tail);

template<typename... Tail>
size_t calcSize(const std::string& head, const Tail&... tail);

template<typename... Tail>
void fillResult(std::string& result,
                size_t startIndex,
                const std::string& head,
                const Tail&... tail);

template<size_t N, typename... Tail>
void fillResult(std::string& result,
                size_t startIndex,
                char const(&head) [N],
                const Tail&... tail);


text:
Q: Jquery - hide element at specific browser width I am trying to get jQuery to remove an element when the browser eaches a specific width. I am kind of new to jquery. I can workout how to detect the browser width but I cant work out how to say
When browser reaches x width remove unordered list with id y
I have this so far
jQuery(function ($) {
                $(window).resize(function(){

                });
        });

Help appreciated

A: The following will work:
$(window).resize(function(){
  var width = $(this).width(); // The window width
  if (width < someSize) {
    $('#y').hide(); // Or to completely remove it form the DOM use `remove()`
  }
});

However, styling is generally best left as the concern of CSS, if you can avoid this approach please try to do so.

A: You should probably be doing this with CSS media queries. Trying to do this in Javascript is going to be horribly laggy because of all the resize events that get fired as the window is in the process of being resized.

A: You can use $(window).height(); and $(window).width(); to determine the size.

A: You know by using CSS media queries you can do this without jQuery?
Check out these resources:
https://www.w3.org/TR/css3-mediaqueries/
https://mislav.net/2010/04/targeted-css/
http://protofunc.com/scripts/jquery/mediaqueries/
It can still be done in jQuery by using:
    jQuery(function ($) {
            $(window).resize(function(){
                 var _width = $(this).width();
                 if(_width > 900 && $('#myElement').is(':visible'))
                      $('#myElement').hide();
                 else if (_width <= 900  && !$('#myElement').is(':visible'))
                      $('#myElement').show();
            });
    });

It can also be done as:
    jQuery(function ($) {
            $(window).resize(function(){
                 var _width = $(this).width();
                 if(_width > 900)
                      $('#myElement:visible').hide();
                 else if (_width <= 900)
                      $('#myElement:hidden').show();
            });
    });


text:
Q: Display one value and return another in text field with autocomplete Oracel Apex 5 I want to be able to have a text field with autocomplete in Apex 5 that displays a client name, city and state, but just returns that client's client_id from the table.
I'm currently using a popup LOV
Is something like this even possible? I've been digging around for hours for a way to make it happen.

A: There are plugins out there that accomplish this, but I haven't personally used them.
Here's what I've done:

*

*Add a hidden item

*Create a dynamic action to parse the autocomplete item and set the hidden item equal to this value.

*Create a validation to ensure that the hidden item's value meets your expectations.


text:
Q: Prove: if $a \mid c$ and $b \mid d$ then $ab \mid cd$ Can this be proven? Or does it need a counter example?

For any $a, b, c, d\in\mathbb{N}$, if $a \mid c$ and $b \mid d$ then $ab \mid cd$

Need help.

A: Yes, that can be proven:
Remember that $x|y$ iff there is a whole number $z$ such that $y=xz$
Take any $a,b,c,d$
Suppose $a|c$ and $b|d$. So, there is a whole number $e$ such that $c=ae$ and whole number $f$ such that $d=bf$. So, $cd=aebf=abef$. So, there is a whole number $g$ (namely $g=ef$) such that $abg=cd$. So, $ab|cd$.

A: Because $a | c$, there exists a natural number $m$ such that $c = m a$. Similarly, there exists a natural number $n$ such that $d = n b$. Therefore, $cd = mn ab$ and $ab | cd$.


text:
Q: How can I install Overpass API to query a smaller database locally on Mac OS Catalina? I am currently using jQuery to make requests to the Overpass server, in order to get information about the ways that exist close to a certain lat, lon pair. However, my program needs to make multiple requests to the server and each one is currently taking around 3 seconds which is too long. I am only interested in a small area and I downloaded the extract of data I needed from https://protomaps.com/extracts My question is how to install the Overpass API on my machine running Mac OS Catalina so I can execute queries in a timely manner on this local extract of data rather than continually making calls to the Overpass server. Below is my current code for executing an Overpass Query using jQuery and Angular:
const searchQuery = 'http://overpass-api.de/api/interpreter?data=[out:json]' + query;
let waysObject = {};
    $.ajax({
      url: searchQuery,
      async: false,
      dataType: 'json',
      success(result) {
          waysObject = result;
      }
    });
return waysObject;


text:
Q: Difference between [...]Async and Begin[...] .net asynchronous APIs Can anybody explain me what is the difference between the Begin[...]/End[...] asynchronous API pattern and the later [...]Async pattern in .NET 3.5?

*

*Why was the later created?

*Why would one prefer one pattern over another?

For example, Socket.BeginAccept() and Socket.AcceptAsync().

A: Note that most *Async methods (with corresponding *Completed events) are using the Event-Based Asynchronous Pattern. The older (but still perfectly valid) Begin* and End* is a pattern called the Asynchronous Programming Model. The Socket class is an exception to this rule; its *Async methods do not have any corresponding events; it's essentially just APM done in a way to avoid excessive memory allocations.
The biggest difference between APM and EBAP is the thread used for completion notification. APM will call back on a thread pool thread (unless the request completes synchronously). EBAP will use a cross-framework strategy to call back on a UI thread (if the operation was started from a UI thread).
However, both APM and EBAP are being replaced with a much more flexible approach based on the Task Parallel Library. Since the TPL can wrap APMs easily, older classes will likely not be updated directly; extension methods are used to provide Task equivalents for the old APM methods.
Update 2012-07-14: I was wrong when I stated "older classes will likely not be updated directly". For performance reasons, the BCL/TPL teams decided to review each BCL type and add TAP methods directly instead of using extension methods. These changes will be in .NET 4.5.

A: MSDN will answer that better than me:
http://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.aspx

The main feature of these enhancements
  is the avoidance of the repeated
  allocation and synchronization of
  objects during high-volume
  asynchronous socket I/O. The Begin/End
  design pattern currently implemented
  by the System.Net.Sockets.Socket class
  requires a System.IAsyncResult object
  be allocated for each asynchronous
  socket operation.


text:
Q: How to prevent Numba from parallelizing a particular loop when parallel=True is used? I have a test code like so:
import numpy as np
from numba import njit, prange
import random

def func():
    a = np.empty(0)
    for i in range(10):
        b = np.arange(np.random.randint(10))
        a = np.concatenate((a, b))
        print(len(b), ' / ', len(a))

func()

It works as expected:
3  /  3
6  /  9
5  /  14
8  /  22
9  /  31
6  /  37
9  /  46
5  /  51
3  /  54
9  /  63

If I compile with Numba by adding @njit(parallel=True) decorator, it stops working because Numba parallelizes this loop which causes issues:
2  /  0
1  /  0
2  /  0
7  /  0
0  /  0
3  /  0
2  /  0
5  /  0
7  /  0
2  /  0

In my real code there is another loop in this function which uses prange, so I want parallel=True on the whole function. But I don't want it for this loop.
How to prevent this?

A: I ended up splitting this portion of the code out of the @njit'ed function which had parallel=True, and on this function that was factored out I used @njit but left parallel=False
This did it for me.


text:
Q: Save webcam recording from scriptcam I'm looking for a solution similar to the one offered here (my problem is the same): How to save files in my server with ScriptCam plugin
unfortunately, that one doesn't work for me.
I have a scriptcam plugin on my website. The recorded videos should be sent to my ftp folder but it isn't working (although the .txt testfile does work). Scriptcam support is apparently non-existent..
so I thought it must be feasible to automatically capture the video from the generated link by scriptcam, but I'm not sure how. My PHP is very basic, and ironically, my php course is starting next week Wednesday, two days after the site (http://www.trainemotionmanagement.com) has to go live..
Any ideas?
The scriptcam 'recording ready' function looks like this:
function fileReady(fileName) {
            $('#recorder').hide();
            fileName2=fileName.replace('mp4','gif');
            $('#message').html('The MP4 file is now dowloadable for five minutes over here. The animated GIF can be downloaded here.');
            var fileNameNoExtension=fileName.replace(".mp4", "");
            jwplayer("mediaplayer").setup({
                width:320,
                height:240,
                file: fileName,
                image: fileNameNoExtension+'_0000.jpg',
                tracks: [{
                    file: fileNameNoExtension+'.vtt',
                    kind: 'thumbnails'
                }]
            });
            $('#mediaplayer').show();
        }

EDIT: ISSUE RESOLVED. HOW? No idea, it just started working all of a sudden..

A: If the test .txt file is stored in your ftp then it means ftp connection and other settings are fine.
From your description of the problem it seems you may not have used the write js codes to make the whole thing work.
There is a dome on scriptcam website which perfectly worked for me.
http://www.scriptcam.com/demo_2.cfm
This should work for you also.

A:

function fileReady(fileName) {
           $.ajax({
                  type: 'POST',
                  data:{"file_name":fileName},
                  url: URL,
                  contentType: 'application/json',
                  success: function(responseXml) {
                    $('#message').html('Video created successfully..');

              }

            });

    }

In server side
get the filename parameter,(where filename will be url for mp4 file)
if you are using php
file_put_contents("saving_filename", fopen(filename, 'r'));
and save.
please note that scriptcam will delete this file form their server after  5 minutes. So we need to copy the file using this method or need to setup the ftp server details.
enjoy !!!


text:
Q: bwu_datagrid - how to disable call of Editor for some cells in column? I use bwu_datagrid and some columns in my datagrid have cells that I don't want to be edited. Is there an existing way for this in bwu_datagrid? Returning null in Editor.newInstance(EditorArgs) brings to exception in _currentEditor.loadValue.

A: Just not assigning an editor in the column definition (Column(id: 'someid', name: 'Title', ...)) should have that effect.
To disable just specific cells listen to onBwuBeforeEditCell
grid.onBwuBeforeEditCell.listen((BeforeEditCell e) {
  if (!isCellEditable(e.cell.row, e.cell.cell, e.item)) {
    e.retVal = false;
  }
});


text:
Q: How do you find the distribution of Y? the problem says that $X$~$N(μ,σ^2)$ and $ Y=1.2X+3.8$ And you need to find  the distribution of Y. I tried to apply the transformation of random variables.
$Fy(y)=p(Y<y)=p(1.2X+3.8<y)=p(x<(y-3.8)/1.2)=Fx((y-3.8)/1.2)$ But i dont know how to find Fx

A: If $X$ has a normal distribution, then for any constants $a$ and $b$ (with $a \ne 0$), $aX + b$ has a normal distribution.  A normal distribution is characterized by its mean and variance...

A: You know the derivative of $F_X(x)$, it is the density function of $X$.
You can then use the result of your calculation to find the derivative of $F_Y(y)$ by applying the Chain Rule. That will give you the density function of $Y$.
You should find that $Y$ is normal mean $1.2\mu+3.8$ and variance $(1.2)^2\sigma^2$.
But perhaps it has already been proved that if $X$ is normal mean $\mu$, variance $\sigma^2$, then $aX+b$, where $a\ne 0$, is normal mean $a\mu+b$ and variance $a^2\sigma^2$.


text:
Q: Exchanging series and integrals I know that I can use Lebesgue or monotone convergence theorem to exchange limit of partial sums and a Lebesgue integral, given a power series or a generic function series. But in general given a series $\sum_{n=0}^{\infty}a_n$ which converges, and defined $\int_0^\infty\sum_{n=0}^{\infty}a_n f_n(u)du$ with $f_n(u)$ integrable, I was wondering when I could exchange the integration and the series. In particular in the context of Borel summation , given $\int_0^\infty e^{-u} \sum_{n=0}^{\infty}\frac{a_nu^n}{n!}du$, I was wondering how could I demonstrate that if $\sum_{n=0}^{\infty}a_n$ converges, then I can exchange the integral and the series. (I know that for power series $\sum_{n=0}^{\infty}a_n z^n$ the work can be done using the radius of convergence and I can always find a dominant)

A: As suggested by Gerald Edgar, we can use the Fubini--Tonelli theorem. By the Tonelli theorem,
$$\int_0^\infty \sum_{n=0}^{\infty}\Big|e^{-u} \frac{a_nu^n}{n!}\Big|\,du
=\sum_{n=0}^{\infty}\frac{|a_n|}{n!}\int_0^\infty e^{-u} u^n\,du
=\sum_{n=0}^{\infty}|a_n|<\infty.$$
So, the Fubini theorem is applicable, that is, one can interchange the integral and the series.


text:
Q: form_for validation messages for associated model I have a provider model which has comments. I have set the validation for comments to check the presence of the body of the comment presence is true.
here is whats in my model
  validates :body, presence: true

Here is my form where I am having issues. I get undefined method errors.
<%= form_for([@provider, Comment.new] ) do |f| %>
<% if @provider.comments.errors.any? %>

Errors

    <% @provider.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

<% end %>
<%= f.text_area :body, cols: 30, rows: 4, class: 'form-control' %>
<%= f.hidden_field :user_id, value: current_user.id, class: "form-control" %>

<%= f.submit :post, class: 'btn btn-primary btn-lg' %>

<% end %>

What is the best way to get the errors for the associated comments model? I have tried a few alternatives but had no luck. If anyone can point me in the right direction it would be very much appreciated.

A: errors method needs to be called on a single model like:
@comment.errors.any?

I would solve the problem like this:
I would set comment in controller's action @comment = Comment.new.
Then use it in form_for
<%= form_for([@provider, @comment] ) do |f| %>

And then you need to check only for comment errors if I got you right:
<% if @comment.errors.any? %>

Errors

    <% @comment.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

<% end %>

Try it out, I hope it works as you like

A: To be sure that your Provider validates its comments, you should use the validates_associated method in your Provider model:
class Provider < ActiveRecord::Base
  has_many :comments
  validates_associated :comments
end

Unfortunately you can't easily get specific errors from the comments this way. They'll show up in @provider.errors[:comments], but only with the description "Comments is invalid". However, you could use a custom validator that "bubbles up" errors from associated models.

In this case - where you're creating a single new model, and the others aren't being edited - it's easier to create a new Comment in your controller and pass that into your view for use in the form. That way you can access @comment.errors directly.


text:
Q: TTLauncherView url to view controllers? - iPhone SDK Hey, I would like to know how to link a view controller to a item in the TTLauncher?
[self launcherItemWithTitle:@"Apple" image:@"bundle://safari_logo.png" URL://What to write here?]

A: You link it to a URL in your TTURLMap that is linked to the view controller you want.  So you'd call for example:
[self launcherItemWithTitle:@"Apple" image:@"bundle://safari_logo.png" URL:@"tt://apple"]

and then when you declare your TTURLMAP:
TTNavigator *navigator = [TTNavigator navigator];
[navigator.URLMap from:@"tt://apple" toViewController:[YourViewController class]];

where YourViewController is the one you want to launch
Hope this helps


text:
Q: PHP extend regex to accept round brackets I have an existing regex which checks if the string is not wrapped in either quotes or square brackets then
I'm wrapping that string in quotes
My existing regex is as follow -
if (!preg_match('/^["\[].*["\]]$/', $filter)) {
 $filter = '%22' . $filter . '%22';
}

Now I want to extend this regex to check already wrapped in either quotes or square brackets or parentheses
For parentheses, my string value i.e my $filter value would be something like (123 456)
Can anyone help to extended this regex?

A:
I think the regular expression is good for complex string math but like this simple string match why do you use regex it takes almost O(n) time where n is you string size some time it takes O(2^m), where m is the length of regex. But if you check with a simple if just check 1st and the last characters of string it takes O(1). Here is the regex solution.

/^(?(?=")(["].*["])|(?=\[)([\[].*[\]]))|(?=\()(([\(].*[\)]))$/

A: The regular expressions are a powerful tool but they are not a Swiss army knife. There are problems that simply cannot be resolved using regex and there are problems that can be resolved using regex but a simpler approach produces code that is easier to read and understand. This is such a problem.
Let's reformulate the problem. If the first character of the string is " and also its last character is " then the string is wrapped in quotes and it does not need other processing. The same when the first character is [ and the last one is ]. Or ( and ).
The first character of a string stored in the variable $filter is $filter[0]. The last one is $filter[-1]. Extract them into a new string and search for it into a list of combinations of quotes and parentheses:
if (! in_array($filter[0].$filter[-1], ['""', '[]', '()'])) {
  // the string is not enclosed in quotes, square brackets or parentheses
  // do something with it (enclose it, etc)
}

If you are using PHP 5 (any version) or PHP 7.0 then you are out of luck (and out of PHP updates, btw) and you cannot use $filter[-1] (because this functionality has been introduced in PHP 7.1).
The PHP function substr() comes to the rescue.
substr($filter, -1) does the same thing as $filter[-1] (returns the last character of $filter and works in all PHP versions.

There are two corner cases to consider:

*

*When $filter is '"' (a string of exactly one character that is a double quote), the code above will report it as enclosed in quotes when, in fact, it is not.

*When $filter is '' (the empty string) the code produces two warnings (but does not report it as being enclosed in quotes.
Both cases can be easily solved by adding a check of the string's length to avoid running the other test if the string is too short:
if (strlen($filter) < 2 || ! in_array($filter[0].$filter[-1], ['""', '[]', '()'])) {
  // the string is not enclosed in quotes, square brackets or parentheses
  // do something with it (enclose it, etc)
}


text:
Q: SortableAsyncListView sort     <s:DataGrid id="materialsList">
        <s:dataProvider>
            <c:SortableAsyncListView list="{materials}" />
        </s:dataProvider>
        ....

materials is PagedQuery.
When I'm sorting by GridColumn with complex dataField ("group.name") I'll getting sort[0]=null and procedure on server-side can't order materials by this field. How to sort SortableAsyncListView by complex field?

A: There is no reason why sorting would not work with complex field.
Which version of Flex SDK are you using ?


text:
Q: How to screenshot particular part of the webpage I used the below script for screenshot of the webpage and i am successful in getting the entire webpage as a screenshot but i want only particular section of the webpage to be captured, So can you suggest me what are the changes to be done in the code.
      <script type="text/javascript" src="js/html2canvas.js"></script>  and

       function canvas(){
        html2canvas(document.body, {
        onrendered: function(canvas) {
       document.body.appendChild(canvas);
       },
      width: 1200,
     height:700
    })};

A: Change the first parameter of the html2canvas to point to the DOM element you want to copy.
Right now your are pointing it to <body> hence document.body.
You can select a div with a specific id by typing:
html2canvas(document.getElementById( "the_id_of_the_element" ), {...}...

So the first parameter you give it, is the element it is going to focus on.
If you also use jQuery you could do:
html2canvas( $('.class_of_element'), {...}...

The documentation:
http://html2canvas.hertzen.com/documentation.html


text:
Q: Как сделать так,чтобы виджет (Label в tkinter) двигался при нажатие на кнопку (Button)? Вот например у нас код:
from tkinter import *
def click():
    # дальше, я не знаю
k = Label(text="текст", fg="red",bg="black")
b = Button(text="click", command=click, fg = 'red', bg='green')
k.place(x=50, y=50)
b.place(x=100, y = 100)

Как сделать ,чтобы при нажатие на кнопку click виджет виджет "текст" двигался на 10 пикселей(при каждом нажатие)?

A: Не стоит пытаться динамически изменять расположение виджетов tkinter, ипользуйте для этого Canvas. Вот пример с перемещением текста:
import tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(root, width=500, height=400, bg='white')
canvas.pack()
text = canvas.create_text(250, 50, fill="green", text="VVVVVVVVV")

def move():
    canvas.move(text, 0, 10)
    canvas.update()

button = tk.Button(text='move', command=move)
button.pack(side='bottom', padx=5, pady=5)

root.mainloop()


text:
Q: Changing the font size of a bibliography using BibTeX with the amsrefs package I am using BibTeX with the amsrefs package to create a bibliography.  The output of the bibliography looks to be of a slightly smaller font size that that of the ambient document, and it's imperative that these font sizes be equal.  I have already tried
{\normalsize\bibliography{mybib}}

to no avail.  Can anyone please steer me in the right direction?  Thanks!

A: The font is controlled by the \biblistfont command; simply redefine this macro in your preamble (to change the default \footnotesize) by adding the following lines:
\renewcommand{\biblistfont}{%
  \normalfont
  \normalsize
}


text:
Q: Get value inside Div Javascript ho,
I have a div that I access like so:
 var gridcellrowvalue0 = gridcell0.innerHTML;

This returns to me the following div:

DefaultText

In my JS I would like to accesss the "DefaultText" variable and I have tried this:
 gridcellrowvalue0.innerHTML;
 gridcellrowvalue0.getAttribute("data-originaltext");

But none of them work. I'm assuming that getAttribute doesn't work because it is not really an element, it's innerhtml.
My goal is to use the "DefaultText" value in an IF-statement and therefore I simply need it.
I appreciate any pointers, my friends!

A: You could access your element directly from gridcell0 using  gridcell0.querySelector('.DivOverflowNoWrap') instead, like :
var gridcell0 = document.querySelector('#x');
console.log( gridcell0.querySelector('.DivOverflowNoWrap').innerHTML );

Snippet:

var gridcell0 = document.querySelector('#x');

if (gridcell0.querySelector('.DivOverflowNoWrap') !== null) {
  console.log(gridcell0.querySelector('.DivOverflowNoWrap').innerHTML);
} else {
  console.log('Does not exist');
}

DefaultText

A: With Javascript also it can be achieved but I am showing here using jQuery

$('document').ready(function() {
  var div = $(".DivOverflowNoWrap");
  var text = div.text();

  alert(text);
});

DefaultText

A: The problem is how you access the div in the first place. If you do it like you described (with gridcell0.innerHTML). It will return a string. Not an HTML element.
Therefore you can't use .getAttribute or .innerHTML, because you  try to apply it on a string. Access your div differently (querySelector or getElementBy...) and you will be able to use those.

A: You can use jquery:
$("[class='DivOverflowNoWrap']").text();

$("[class='DivOverflowNoWrap']").attr("data-originaltext")

A: It's pretty simple:

DefaultText


text:
Q: Passo a Passo com javascript Gostaria de saber como faço um Step-by-step em JavaScript. Esse é o
Modelo que preciso para ir montando um cartão de visita...
Preciso para montar uma foto para túmulo...
Meu modelo


text:
Q: String or binary data truncated i am using microsoft sql server management and  I received an error called " String or binary data would be truncated."
 Before posting this question, I have read similar posts regarding this question. Many have said that the field is NOT big enough to hold the data.
However, I declared my "TrainerDesc" to have a varchar(3000) which is way bigger than the data inserted. So why do I still receive this error?
Create Table Trainer
(TrainerNo          char(8)      not null,
 TrainerName        varchar(50)  not null,
 TrainerDesc        varchar(3000) null,
 Primary Key (TrainerNo))

----------------------------------------------------Inserting Values----------------------------------------------------
Insert into Trainer
values
('T5690146', 'Mary Hoe', 'Mary Hoe is a qualified and highly experienced Yoga trainer who holds a yoga instructor certificate obtained from the yoga center singapore in 2002. Furthermore, she taught yoga in various community clubs for more than a decade including Pek Kio CC, Choa Chu Kang cc and Yew Tee cc.Mary loves to spread her knowledge and skills with people who are keen to learn more about Yoga.')

A: Mention your columns explicitly which is best practice
The simplest reason for the error is that your table definition has different column order to what you expect, which can happen if you added TrainerName afterwards or changed it by drop+add
Insert into Trainer (TrainerNo, TrainerName, TrainerDesc)
values
('T5690146', 'Mary Hoe', ...)


text:
Q: Solar Battery Charging Circuit I designed this circuit:

to charge my 12 V UPS battery from a 40 W, 18 V solar panel. I specifically included an LM317T adjustable voltage regulator to control the output voltage to about 13.4 V as recommended by the battery manufacturer for cyclic use.

But I was surprised with the results since I obtained a very low charging current of 2.8 mA which means it takes several days to charge the battery.

From the solar I expected 40/18 = ~2 A
Though I understand the circuit draws current from the current division among other reasons, this low output current is a concern for me.
Any suggestions to improve the output current to about 1 A or more will be highly appreciated. Thank you.


text:
Q: SQL Update only updates one row This code is only updating one row, why?  It has to do with one of the sub-queries but I am not sure. I'm thinking the WHERE..IN in the UPDATE statement but I am not sure.
UPDATE [sde].[sy1].[Valve_evw]
SET [sde].[sy1].[Valve_evw].[MA]
             = (SELECT [sde].[sy1].[Valve_Join_evw].[MC]
                FROM [sde].[sy1].[Valve_Join_evw])
WHERE [sde].[sy1].[Valve_evw].[PrimaryKey]
            IN (SELECT [sde].[sy1].[Valve_Join_evw].[PrimaryKey]
                FROM [sde].[sy1].[Valve_Join_evw]
                WHERE  [sde].[sy1].[Valve_Join_evw].[MA]
                != [sde].[sy1].[Valve_Join_evw].[MC])

Context:
What I am trying to do is update the MA column in Valve_evw using the MC column in Valve_Join_evw.  The PrimaryKey in Valve_evw references equivalent rows as the PrimaryKey in Valve_Join_evw. As in, a single row in Valve_Join_evw will have the same PrimaryKey as a single row in Valve_evw, thus that equivalency can be used to update the records in Valve_evw.  Also the MA column is equivalent in both tables.  [Note: The Valve_Join_evw table is created with ESRI mapping software using the spatial relationship between the Valve_evw and a separate table, this is how the duplicate rows exist]
I am using database views (hence the '_evw') in SQL Server with a default INSTEAD OF UPDATE trigger. This combination, views and trigger, prevents the use of table joins to do this update.  I have also tried MERGE but that will not work either.  Therefore I am stuck with the ANSI standard, hence the sub-queries.  This script runs with no errors but it only updates a single row whereas there are about 9000 thousand rows in the tables.
The output message:
(1 row(s) affected)

(0 row(s) affected)

A: First of all let's reduce the eye hurting SQL to what it really is:
update sde.sy1.valve_evw
set ma = (select mc from sde.sy1.valve_join_evw)
where primarykey in (select primarykey from sde.sy1.valve_join_evw where ma <> mc)

WHERE clause
We look for all primarykey in valve_join_evw where a record's ma <> mc. We update all valve_evw records with such primarykey.
SET clause
For a record we want to update, we set ma to the value found with:
select mc from sde.sy1.valve_join_evw

But this query has no where clause, so what value does it select to fill the record's ma field? It selects all mc from valve_join_evw, so the DBMS probably picks one of these values arbitrarily. (It would be better, it raised an error.)
Conclusion
It is very easy to see which records the statement will update.
Which primarykey:
select primarykey from sde.sy1.valve_join_evw where ma <> mc

Which rows:
select *
from sde.sy1.valve_evw
where primarykey in (select primarykey from sde.sy1.valve_join_evw where ma <> mc)

As to the SET clause: Add a WHERE clause to your subquery that relates the record to select to the record to update (same ma? same primarykey?) E.g.:
set ma =
(
  select mc
  from sde.sy1.valve_join_evw vj
  where vj.primarykey = valve_evw.primarykey
    and vj.ma         = valve_evw.ma
)

A: Hi there i recomend first to do the select statement and when you are ok with te records retrieved use the same where for the update statement

A: Here is what the final script looks like.
UPDATE [Valve_evw]
SET [Valve_evw].[MA] =
              (
                SELECT [Valve_Join_evw].[MC]
                FROM [Valve_Join_evw]
                WHERE[Valve_Join_evw].[PrimaryKey] = [Valve_evw].[PrimaryKey]
               )
WHERE [Valve_evw].[PrimaryKey]
            IN (
                 SELECT [Valve_Join_evw].[PrimaryKey]
                 FROM [Valve_Join_evw]
                 WHERE  [Valve_Join_evw].[MA]
                 != [Valve_Join_evw].[MC]
                );


text:
Q: Finding roots of $P(z)$ through $\text{gcd}(P(z),P'(z))$
This is an excerpt from Zorich's book. I have some issues with understanding the last paragraph of it. This is what I understood so far:
Suppose we have polynomial with complex coefficients $P(z)$. We would like to find roots and their multiplicities.
Suppose $q(z):=\text{gcd}(P(z),P'(z)).$ Suppose we know factorization of $q(z)$, i.e. $q(z)=(z-z_1)^{\alpha_1}\dots (z-z_p)^{\alpha_p}$ then somehow he deduces that roots of $P(z)$ are also $z_1,\dots,z_p$ with multiplicities $\alpha_1+1,\dots, \alpha_p+1$.
Am I right that h is doing exactly this?
If yes how to prove it? I am bit confused.

A: Let $q$ be the monic $\gcd(P, P^\prime)$. Since $q$ is a monic divisor of $P$, then it must be of the form $$q(z) = (z - z_1)^{\alpha_1} \cdots (z - z_p)^{\alpha_p}$$ where each $\alpha_i$ is nonnegative and at most the multiplicity of the root $z_i$ in $P$.
There is an inverse statement to the corollary which is not stated that if $z_i$ is a root of $P$ of multiplicity $1$, then it is not a root of $P^\prime$.
Since $q$ is also a divisor of $P'$, there are two cases:

*

*The number $\alpha_i = 0$ and thus $z_i$ is not a root of $P^\prime$.

*The number $\alpha_i$ is positive, and thus $z_i$ is a common root of $P$ and $P^\prime$.

In the first case, the contrapositive to the corollary tells us that the multiplicity of $z_i$ in $P$ is $1$. In the second case, the inverse statement to the corollary shows that the multiplicity of $z_i$ in $P$ is greater than $1$.
In both cases, the maximal power of $(z - z_i)$ that divides $P$ and $P^\prime$ is $(z - z_i)^{k_i - 1}$, and $\alpha_i = k_i - 1$ where $k_i$ is the multiplicity of the root $z_i$ in $P$.


text:
Q: Intuitive Explanation of Hom Functor Property I am new to category theory and keep running across it while studying algebra. Whenever I see the $\mathrm{Hom}$ functor mentioned (in the context of modules), two of its basic properties are listed:

*

*$\mathrm{Hom}(\bigoplus_i{A_i},B) \cong \prod_i{\mathrm{Hom}(A_i,B)}$, and

*$\mathrm{Hom}(A,\prod_i{B_i}) \cong \prod_i{\mathrm{Hom}(A,B_i)}$.

Could anyone provide an intuitive explanation for why this is true? I have a hard time remembering this fact (where the product and sums ought to go on the left hand side.) Is there a concrete example which makes this clear?

A: Assume we are in the category of abelian groups (for intuition's sake).
a. $\mbox{Hom}(\bigoplus A_i,B)\simeq\prod\mbox{Hom}(A_i,B)$.
Let $\phi_i:A_i\hookrightarrow\bigoplus A_i$ be the natural inclusion (we put 0's in all the other coordinates), and if $f\in\mbox{Hom}(\bigoplus A_i,B)$, let $f_i$ be its restriction to $\phi_i(A_i)$ (Edit: If $p_i:\bigoplus A_i\to A_i$ is the natural projection, then by "restriction" I really mean $f_i=f\circ\phi_i\circ p_i$). We see then that $f=\sum f_i$. This sum is infinite, but since an element of $\bigoplus A_i$ has finite coordinates, we can see it as a well-defined function. The isomorphism above is easy then: send $f$ to $(f_i)_{i}$ (the $f_i$ are functions on $\phi_i(A_i)\simeq A_i$).
b. $\mbox{Hom}(A,\prod B_i)\simeq\prod\mbox{Hom}(A,B_i)$.
Let $\pi_i:\prod B_i\to B_i$ be the natural projection. If $f\in\mbox{Hom}(A,\prod B_i)$, then send $f$ to $(\pi_i\circ f)$; this gives an isomorphism.
Moral of the story:
A morphism in the first situation is determined by how it acts on each $A_i$, and a morphism in the second situation is determined by its image in each $B_i$.

A: As Andreas Blass commented, once you correct your statements, they are essentially the definition of coproduct and product. The way I think about these is that products have projection maps, coproducts have inclusion maps. (And to remember which is which, I think of Set, where products are cartesian products and coproducts are disjoint unions. Then "projection map" and "inclusion map" are very familiar concepts.)
Then what you are saying is, "to map from all these $A_i$'s to $B$, I could just as easily embed the $A_i$'s in their disjoint union then do one big map to $B$" and "to map from A to all these $B_i$'s, I could just as easily map from $A$ into the Cartesian product of all the $B_i$'s, then project out into the individuals".

A: Direct sums are colimits, and direct products are limits. The identities you mention are actually true for all limits and colimits, not just the special case of products and coproducts.
If you remember that much, it becomes a much simpler exercise to recall which way the identities go: just work out how they should look for binary Cartesian products and binary disjoint unions in Set.
Another way to recall which is which is to remember that $\text{Hom}$ is covariant in the second argument and contravariant in the first.
If you remember that you get a limit either way, then you can work out which identity is right by noting that if you apply $\text{Hom}(A, -)$ to a limit cone, you get a limit cone, and if you apply $\text{Hom}(-,B)$ to a colimit cone, you also get a limit cone.


text:
Q: Cannot reopen error when updating table in SAS with SQL I have 2 tables:

*

*t1 with columns A, B, X, Y, Z and

*t2 with columns A, B, N
I want to set t1.A to value t2.N where t1.A = t2.A and t1.B = T2.B.
It sounds simple, but I have no idea to solve this; I tried something like:
update t1 set A = (select t2.N
                     from t1,t2
                    where t1.A = t2.A
                      and t1.B = t2.B)
......

But this gives an error:
ERROR: You cannot reopen t1.DATA for update access with member-level control because t1.DATA .....

Any ideas?

A: I suspect you just want a correlated subquery:
update t1
    set A = (select t2.N
             from t2
             where t1.A = t2.A and t1.B = t2.B
            );

Note:  You should be careful that the subquery returns only one row.

A: A side note besides the syntax error: you're getting that ERROR: You cannot open WORK.T1.DATA for output access with member-level control because WORK.T1.DATA is in use by you in resource environment DATASTEP. because your output dataset is still open in the window. Close the VIEWTABLE:Work.T1 prior to re-running.


text:
Q: Can you check if a web application is already running on another browser tab? I have a web application written in ASP.NEt/C# and javascript.  It uses session variables.
When I open the application, is there a way to check if the application is running in another tab?
Or do you have any ideas on making session variables unique for each tab?
Any help would be great!
Thanks
Kev.

A: First understand sessions.  The session is a file which lives on the server and holds some data. When the user gets a session they are really getting a cookie with some key to find which session is theirs.
Because of this, between different tabs in the same browser the cookie will be the same so it will access the same session on the server in both tabs.  You can make them unique by when you start the session giving a random ID but this (to my knowledge) will simply overwrite the previous session's value...

A: You can use Session.IsNewSession() method to check For the Particular Session is a New one. Normally in web browsers with Multi Tabs the session is same through out that window


text:
Q: Reordering JList with Drag and Drop I encountered a problem regarding reordering elements in a JList using Drag and Drop. This following code is a modification of a code where you could drag elements from one JList to another (worked only one way). I tried to make it usable for only one JList, but the elements can't even be dragged out of the list. So I guess it can't be done this way. Any ideas what I'm doing wrong or not taking into consideration?
The idea is to get it to work for a Jlist with thumbnails, but since I can't even get it to work with just strings... I have been looking into several D'n'D tutorials, but still I can't get it to work.
Any help is appreciated.
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.IOException;

public class DragAndDrop extends JFrame {

DefaultListModel<String> transport = new DefaultListModel<String>();
JList<String> transportList = new JList<String>(transport);

public DragAndDrop() {
    setLayout(new FlowLayout());

    transport.addElement("Bike");
    transport.addElement("Car");
    transport.addElement("Truck");
    transport.addElement("Boat");

    JScrollPane transportScroll = new JScrollPane(transportList);
    transportScroll.setBorder(new TitledBorder("Transportation"));

    add(transportScroll);

    transportList.setDragEnabled(true);

    transportList.setTransferHandler(new TransferHandler() {
        int index;

        @Override
        public int getSourceActions(JComponent comp) {
            return COPY_OR_MOVE;
        }

        @Override
        public Transferable createTransferable(JComponent comp) {
            index = transportList.getSelectedIndex();
            return new StringSelection(transportList.getSelectedValue());
        }

        @Override
        public void exportDone( JComponent comp, Transferable trans, int action ) {
            if (action==MOVE) {
                transport.remove(index);
            }
        }
    });

    transportList.setDropMode(DropMode.ON);

    transportList.setTransferHandler(new TransferHandler() {
        @Override
        public boolean canImport(TransferHandler.TransferSupport support) {
            // data of type string?
            return support.isDataFlavorSupported(DataFlavor.stringFlavor);
        }

        @Override
        public boolean importData(TransferHandler.TransferSupport support) {
            try {
                // convert data to string
                String s = (String)support.getTransferable().getTransferData(DataFlavor.stringFlavor);
                JList.DropLocation dl = (JList.DropLocation)support.getDropLocation();
                transport.add(dl.getIndex(),s);
                return true;
            }
            catch (UnsupportedFlavorException e) {}
            catch (IOException e) {}

            return false;
        }
    });

    pack();

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}

public static void main(String[] args) {
    new DragAndDrop();
}

}

PS. Sorry if this turns out to be a re-post.
EDIT
I think I got it fixed: had to different transferHandlers - should only have one with all the methods from the second one as well.

A:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DragSource;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Objects;
// import javax.activation.ActivationDataFlavor;
// import javax.activation.DataHandler;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.DropMode;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

public class DragAndDropTest {
  public JComponent makeUI() {
    DefaultListModel<Thumbnail> m = new DefaultListModel<>();
    for (String s : Arrays.asList("error", "information", "question", "warning")) {
      m.addElement(new Thumbnail(s));
    }

    JList<Thumbnail> list = new JList<>(m);
    list.getSelectionModel().setSelectionMode(
      ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    list.setTransferHandler(new ListItemTransferHandler());
    list.setDropMode(DropMode.INSERT);
    list.setDragEnabled(true);
    // https://java-swing-tips.blogspot.com/2008/10/rubber-band-selection-drag-and-drop.html
    list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
    list.setVisibleRowCount(0);
    list.setFixedCellWidth(80);
    list.setFixedCellHeight(80);
    list.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

    list.setCellRenderer(new ListCellRenderer<Thumbnail>() {
      private final JPanel p = new JPanel(new BorderLayout());
      private final JLabel icon = new JLabel((Icon)null, JLabel.CENTER);
      private final JLabel label = new JLabel("", JLabel.CENTER);

      @Override
      public Component getListCellRendererComponent(
        JList<? extends Thumbnail> list, Thumbnail value, int index,
        boolean isSelected, boolean cellHasFocus) {
        icon.setIcon(value.icon);
        label.setText(value.name);
        label.setForeground(isSelected ? list.getSelectionForeground()
                            : list.getForeground());
        p.add(icon);
        p.add(label, BorderLayout.SOUTH);
        p.setBackground(isSelected ? list.getSelectionBackground()
                        : list.getBackground());
        return p;
      }
    });
    return new JScrollPane(list);
  }

  public static void main(String[] args) {
    EventQueue.invokeLater(() -> createAndShowGUI());
  }

  public static void createAndShowGUI() {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(new DragAndDropTest().makeUI());
    f.setSize(320, 240);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}

class Thumbnail implements Serializable {
  public final String name;
  public final Icon icon;
  public Thumbnail(String name) {
    this.name = name;
    this.icon = UIManager.getIcon("OptionPane." + name + "Icon");
  }
}

// @camickr already suggested above.
// https://docs.oracle.com/javase/tutorial/uiswing/dnd/dropmodedemo.html
@SuppressWarnings("serial")
class ListItemTransferHandler extends TransferHandler {
  protected final DataFlavor localObjectFlavor;
  protected int[] indices;
  protected int addIndex = -1; // Location where items were added
  protected int addCount; // Number of items added.

  public ListItemTransferHandler() {
    super();
    // localObjectFlavor = new ActivationDataFlavor(
    //   Object[].class, DataFlavor.javaJVMLocalObjectMimeType, "Array of items");
    localObjectFlavor = new DataFlavor(Object[].class, "Array of items");
  }

  @Override
  protected Transferable createTransferable(JComponent c) {
    JList<?> source = (JList<?>) c;
    c.getRootPane().getGlassPane().setVisible(true);

    indices = source.getSelectedIndices();
    Object[] transferedObjects = source.getSelectedValuesList().toArray(new Object[0]);
    // return new DataHandler(transferedObjects, localObjectFlavor.getMimeType());
    return new Transferable() {
      @Override public DataFlavor[] getTransferDataFlavors() {
        return new DataFlavor[] {localObjectFlavor};
      }
      @Override public boolean isDataFlavorSupported(DataFlavor flavor) {
        return Objects.equals(localObjectFlavor, flavor);
      }
      @Override public Object getTransferData(DataFlavor flavor)
            throws UnsupportedFlavorException, IOException {
        if (isDataFlavorSupported(flavor)) {
          return transferedObjects;
        } else {
          throw new UnsupportedFlavorException(flavor);
        }
      }
    };
  }

  @Override
  public boolean canImport(TransferSupport info) {
    return info.isDrop() && info.isDataFlavorSupported(localObjectFlavor);
  }

  @Override
  public int getSourceActions(JComponent c) {
    Component glassPane = c.getRootPane().getGlassPane();
    glassPane.setCursor(DragSource.DefaultMoveDrop);
    return MOVE; // COPY_OR_MOVE;
  }

  @SuppressWarnings("unchecked")
  @Override
  public boolean importData(TransferSupport info) {
    TransferHandler.DropLocation tdl = info.getDropLocation();
    if (!canImport(info) || !(tdl instanceof JList.DropLocation)) {
      return false;
    }

    JList.DropLocation dl = (JList.DropLocation) tdl;
    JList target = (JList) info.getComponent();
    DefaultListModel listModel = (DefaultListModel) target.getModel();
    int max = listModel.getSize();
    int index = dl.getIndex();
    index = index < 0 ? max : index; // If it is out of range, it is appended to the end
    index = Math.min(index, max);

    addIndex = index;

    try {
      Object[] values = (Object[]) info.getTransferable().getTransferData(localObjectFlavor);
      for (int i = 0; i < values.length; i++) {
        int idx = index++;
        listModel.add(idx, values[i]);
        target.addSelectionInterval(idx, idx);
      }
      addCount = values.length;
      return true;
    } catch (UnsupportedFlavorException | IOException ex) {
      ex.printStackTrace();
    }

    return false;
  }

  @Override
  protected void exportDone(JComponent c, Transferable data, int action) {
    c.getRootPane().getGlassPane().setVisible(false);
    cleanup(c, action == MOVE);
  }

  private void cleanup(JComponent c, boolean remove) {
    if (remove && Objects.nonNull(indices)) {
      if (addCount > 0) {
        // https://github.com/aterai/java-swing-tips/blob/master/DragSelectDropReordering/src/java/example/MainPanel.java
        for (int i = 0; i < indices.length; i++) {
          if (indices[i] >= addIndex) {
            indices[i] += addCount;
          }
        }
      }
      JList source = (JList) c;
      DefaultListModel model = (DefaultListModel) source.getModel();
      for (int i = indices.length - 1; i >= 0; i--) {
        model.remove(indices[i]);
      }
    }

    indices = null;
    addCount = 0;
    addIndex = -1;
  }
}

A: As the OP noted in their edit to the original question, the problem in the example given was that there were two transfer handlers and as camickr rightly pointed out in their answer, there is an example in the Java Tutorials which will work.
The problem with the example in the Java Tutorials is that, when using DropMode.INSERT and moving an item in the current JList to before the selected index, the item is duplicated. This deletes an item in the JList, puts a duplicate of the item in the place you wanted it to go, and leaves the original selected item as it is.
So, for those interested, here is an example which fixes that problem based upon the JList<String> example provided in the OP's question.
import java.awt.EventQueue;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import javax.swing.DefaultListModel;
import javax.swing.DropMode;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.TransferHandler;

@SuppressWarnings("serial")
public class GUI extends JFrame {
    protected GUI() {
        super("Simple Rearrangeable List");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        createPanel();
        setBounds(10, 10, 350, 500);
        setVisible(true);
    }

    private void createPanel() {
        DefaultListModel<String> strings = new DefaultListModel<String>();

        for(int i = 1; i <= 100; i++) {
            strings.addElement("Item " + i);
        }

        JList<String> dndList = new JList<String>(strings);
        dndList.setDragEnabled(true);
        dndList.setDropMode(DropMode.INSERT);
        dndList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        dndList.setTransferHandler(new TransferHandler() {
            private int index;
            private boolean beforeIndex = false; //Start with `false` therefore if it is removed from or added to the list it still works

            @Override
            public int getSourceActions(JComponent comp) {
                return MOVE;
            }

            @Override
            public Transferable createTransferable(JComponent comp) {
                index = dndList.getSelectedIndex();
                return new StringSelection(dndList.getSelectedValue());
            }

            @Override
            public void exportDone(JComponent comp, Transferable trans, int action) {
                if (action == MOVE) {
                    if(beforeIndex)
                        strings.remove(index + 1);
                    else
                        strings.remove(index);
                }
            }

            @Override
            public boolean canImport(TransferHandler.TransferSupport support) {
                return support.isDataFlavorSupported(DataFlavor.stringFlavor);
            }

            @Override
            public boolean importData(TransferHandler.TransferSupport support) {
                try {
                    String s = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
                    JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
                    strings.add(dl.getIndex(), s);
                    beforeIndex = dl.getIndex() < index ? true : false;
                    return true;
                } catch (UnsupportedFlavorException | IOException e) {
                    e.printStackTrace();
                }

                return false;
            }
        });

        JScrollPane scrollPane = new JScrollPane(dndList);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new GUI());
    }
}

A: See the Drop Demo from the Swing tutorial on DnD for an example that will drop on the same JList or another JList.

A: package draganddrop;

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.IOException;

public class DragAndDrop extends JFrame {

    DefaultListModel<String> transport = new DefaultListModel<String>();
    JList<String> transportList = new JList<String>(transport);

    public DragAndDrop() {
        setLayout(new FlowLayout());

        transport.addElement("Bike");
        transport.addElement("Car");
        transport.addElement("Truck");
        transport.addElement("Boat");

        JScrollPane transportScroll = new JScrollPane(transportList);
        transportScroll.setBorder(new TitledBorder("Transportation"));

        add(transportScroll);

        transportList.setDragEnabled(true);

        transportList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        transportList.setDropMode(DropMode.ON);

        transportList.setTransferHandler(new TransferHandler() {
            int index;
            int preindex;

            @Override
            public int getSourceActions(JComponent comp) {
                preindex = transportList.getSelectedIndex();
                return MOVE;
            }

            @Override
            public Transferable createTransferable(JComponent comp) {
                index = transportList.getSelectedIndex();
                return new StringSelection(transportList.getSelectedValue());
            }

            @Override
            public boolean canImport(TransferHandler.TransferSupport support) {
                // data of type string?
                return support.isDataFlavorSupported(DataFlavor.stringFlavor);
            }

            @Override
            public boolean importData(TransferHandler.TransferSupport support) {
                try {
                    if (support.isDrop()) {
                        String s = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
                        JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
                        if (index < dl.getIndex()) {
                            transport.add(dl.getIndex() + 1, s);
                            transport.remove(index);
                            transportList.setSelectedIndex(dl.getIndex());
                        } else {
                            transport.add(dl.getIndex(), s);
                            transport.remove(index + 1);
                            transportList.setSelectedIndex(dl.getIndex());
                        }
                        preindex = transportList.getSelectedIndex();
                        return true;
                    } else {
                        index = transportList.getSelectedIndex();
                        if (preindex < transportList.getSelectedIndex()) {
                            transport.add(transportList.getSelectedIndex() + 1, transport.getElementAt(preindex));
                            transport.remove(preindex);
                            transportList.setSelectedIndex(index);
                        } else {
                            transport.add(transportList.getSelectedIndex(), transport.getElementAt(preindex));
                            transport.remove(preindex + 1);
                            transportList.setSelectedIndex(index);
                        }
                        preindex = transportList.getSelectedIndex();
                        return true;
                    }
                } catch (UnsupportedFlavorException e) {
                } catch (IOException e) {
                }
                return false;
            }
        });

        pack();

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new DragAndDrop();
    }

}

Try this


text:
Q: Check if data returned from sql table contains decimal list values in linq? I want to return only those data from sql table which contains specific values from list.How can i do that ?
  List<decimal> userHeirarchyId = new List<decimal>();
  List<decimal> userGroupId = new List<decimal>();

 //Get groups based on user
 string userGroupIds = (from ucp in db.UserControlPrivileges
                        where ucp.UserId == (decimal)AMSECSessionData.userId
                        select ucp.GroupIds).FirstOrDefault().ToString();
 userGroupId = userGroupIds.Split(',').Select(x => decimal.Parse(x)).ToList();

 //Get heirarchy based on company and usergroup
 userHeirarchyId = db.Groups
                   .Where(x=>x.Hierarchy.CompanyId==(decimal)AMSECSessionData.companyId
  =>stuck here      && x.GroupId.contains(userGroupIds ))

Any help will be appreciated..

A: Try this. Change the order how you're using Contains like 'your compare list'.Contains(member name)
var userHeirarchyId = db.Groups
                   .Where(x=> x.Hierarchy.CompanyId == (decimal)AMSECSessionData.companyId
                   && userGroupIds.Contains(x.GroupId))

A: Write it like this :
var user = db.UserControlPrivileges.FirstOrDefault(u =>
                         u.UserId == (decimal)AMSECSessionData.userId);
if(user == null || user.GroupIds == null)
{
    return;
}
var userIds = user.GroupIds.Split(',').Select(x => decimal.Parse(x)).ToList();

And then :
var userHeirarchyId = db.Groups
                      .Where(x => x.Hierarchy.CompanyId==(decimal)AMSECSessionData.companyId
                      && userIds.Contains(x => x.GroupId));


text:
Q: Google data mining tool I recently read about a new Google-code hosted (open source) project from Google that allows you to perform data mining and analytics on various input files. There was even a video showing the user importing an Excel file and filtering on various conditions. However I cannot find it now even after looking for several hours, does anyone know the name of this project?

A: *

*For Classification and Prediction, Google Prediction API

*For operations on very large data set, BigQuery

*For Data Cleaning and Transformation, Google Refine

A: Original
Google Refine http://code.google.com/p/google-refine/
Update (2013/12/02)
Google Refine is now OpenRefine http://openrefine.org/

Please note that since October 2nd, 2012, Google is not supporting actively this project which have been rebranded to OpenRefine. Project development, documentation and promotion is now fully supported by volunteers.

Repository location:
https://github.com/OpenRefine


text:
Q: Service on AWS to move data from one service to another I want to build a service running on AWS that would fetch metrics from another service A, also running on AWS, do some processing, and then post it to a different service B for computing overall resource usage running on a different public cloud. The APIs for the existing services A and B are already defined, and are beyond my control.
My principal concern is that the volume of data I will fetch and post may be high, and I may have to do some computation on this data before posting the results. If the service is to run on a fixed periodic schedule, and I need to make it resilient, how should it be deployed?

*

*EC2 VM.

*Lambda.

Additionally:

*

*How do I make the service resilient / highly available?

*How do I scale it with higher data volumes? One thought is to partition the keyspace of the data based on tenant, etc. and perform the computation in concurrent compute instances that are independent, non-overlapping.

*If I store the data in transit for intermediate processing, how can I make the data in transit resilient?

These questions are from an AWS infrastructure perspective because I have very little prior knowledge of AWS.
Sample numbers

*

*Input data from service A: 10000 records per minute, each record about 1 KiB. So 10 MiB per minute.

*Processing latency in the service - maximum 0.1 second per record.

*Data posted to service B: About 2 MiB per minute. The connections are over WAN.


text:
Q: Search a file based on a text file's words I want to search several words at the same time in a text file.
For example think I want to search these 3 words: Majid,superuser,device
Normally I should search for them one by one, and I can not search all of them at the same time. So I want to search these words at the same time in a text file.
I want to enter those 3 words in a text file, one word per line. Let's name it SearchText. Now I have a Target Text which I want to search those words in it. Let's name it TargetText.
I want to tell an app or something similar to get words from SearchText and find them in TargetText and Highlights them or gives me the find result.
I hope I'm clear. So can anyone hep me?

A: You're clear. I think the best option would be Regex.
Try this:
Option Explicit
Dim oFso        : Set oFso = CreateObject("Scripting.FileSystemObject")
Dim srcPath     : SrcPath = oFso.GetParentFolderName(WScript.ScriptFullName)
Dim sWordList   : sWordList = ofso.OpenTextFile(oFso.BuildPath(srcPath, "search.txt")).ReadAll()
Dim sTargFile   : sTargFile = ofso.OpenTextFile(oFso.BuildPath(srcPath, "target.txt")).ReadAll()
Dim strWords    : strWords = Join(Split(sWordList, vbCrLf), "|")
Dim oReg        : Set oReg = New RegExp
Dim oDict       : Set oDict = CreateObject("Scripting.Dictionary") 'for found words
oDict.CompareMode = vbTextCompare 'case insensitive

With oReg
    .Global = True
    .IgnoreCase = True
    .Pattern = "("& strWords &")" ' (word1|word2|word3|etc..)
    'if the words contain some special chars for regex, you may need to escape with \ char
    'see the information below: http://goo.gl/cqGVp
    Dim collFND : Set collFND = oReg.Execute(sTargFile)
    Dim Fnd
    'WScript.Echo String(50, "-")
    For Each Fnd In collFND
        With Fnd
            'WScript.Echo "Word : "& .Value, ", Position: ("& .FirstIndex &","& .Length &")"
            oDict(.Value) = ""
        End With
    Next
    Set collFND = Nothing
    'WScript.Echo String(50, "-"), vbCrLf, "Higlighted Output:", oReg.Replace(sTargFile, "[$1]")
    ofso.CreateTextFile(oFso.BuildPath(srcPath, "foundwords.txt"),True).Write(Join(oDict.Keys, vbCrLf)) 'found words saved
End With


text:
Q: The Google Play services resources were not found: what do I do now? I know this problem is kind of common, but i literally tried everything to solve this error and i didn't come up with a solution. The problem with my app is that it doesn't log in in g+ (google play games), it shows the log-in screen, then the spinning circle and then it disappears without logging in, while on the logcat the only error that appears is this:
The Google Play services resources were not found. check your project configuration to ensure that the resources are included
the problem with this is that i cannot access the google play leaderboards, but the ads load just fine!
I tried by placing google-play-services_lib and BaseGameUtils in the folder where all the projects are, and importing them from there but nothing.
I tried by placing google-play-services_lib and BaseGameUtils in the libs folder of the project, and importing them from there but nothing.
I made all the correct references, i did everything correct. I even tried different versions of google-play-services_lib and BaseGameUtils that i found on the internet, but nothing.
The funny thing is that the first times that i used the app everything was working fine, even though i had the error **Google Play services resources were not found**. I could access the leaderboards with no problems. But then after a day of testing (BTW during this period i didn't change anything on the project), the app just won't log in for some strange reason.
so maybe it's not even this error's fault, i have no idea.

A: That error message is often  a red herring and can be ignored. e.g. my released app spits out that message every time it runs, and it logs in fine.
It can take a long time to  log in on an emulator the first time your app runs on it. Often I quit out and retry a couple of times. Look out for any other messages and the first thing to check if you are still having problems is the 12 character client id.