Programs & Examples On #Jdic

JDIC is the Java Desktop Integration Components (JDIC) project, an attempt to improve Java apps' access to the underlying OS' facilities.

simulate background-size:cover on <video> or <img>

@Hidden Hobbes

This question has an open bounty worth +100 reputation from Hidden Hobbes ending in 6 days. Inventive use of viewport units to obtain a flexible CSS only solution.

You opened a bounty on this question for a CSS only solution, so I will give it a try. My solution to a problem like this is to use a fixed ratio to decide the height and width of the video. I usually use Bootstrap, but I extracted the necessary CSS from there to make it work without. This is a code I have used earlier to among other things center an embeded video with the correct ratio. It should work for <video> and <img> elements too It's the top one that is relevant here, but I gave you the other two as well since I already had them laying around. Best of luck! :)

jsfiddle fullscreen example

_x000D_
_x000D_
.embeddedContent.centeredContent {_x000D_
    margin: 0px auto;_x000D_
}_x000D_
.embeddedContent.rightAlignedContent {_x000D_
    margin: auto 0px auto auto;_x000D_
}_x000D_
.embeddedContent > .embeddedInnerWrapper {_x000D_
    position:relative;_x000D_
    display: block;_x000D_
    padding: 0;_x000D_
    padding-top: 42.8571%; /* 21:9 ratio */_x000D_
}_x000D_
.embeddedContent > .embeddedInnerWrapper > iframe {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    bottom: 0;_x000D_
    height: 100%;_x000D_
    width: 100%;_x000D_
    border: 0;_x000D_
}_x000D_
.embeddedContent {_x000D_
    max-width: 300px;_x000D_
}_x000D_
.box1text {_x000D_
    background-color: red;_x000D_
}_x000D_
/* snippet from Bootstrap */_x000D_
.container {_x000D_
    margin-right: auto;_x000D_
    margin-left: auto;_x000D_
}_x000D_
.col-md-12 {_x000D_
    width: 100%;_x000D_
}
_x000D_
<div class="container">_x000D_
    <div class="row">_x000D_
        <div class="col-md-12">_x000D_
            Testing ratio AND left/right/center align:<br />_x000D_
            <div class="box1text">_x000D_
                <div class="embeddedContent centeredContent">_x000D_
                    <div class="embeddedInnerWrapper">_x000D_
                        <iframe allowfullscreen="true" allowscriptaccess="always" frameborder="0" height="349" scrolling="no" src="//www.youtube.com/embed/u6XAPnuFjJc?wmode=transparent&amp;jqoemcache=eE9xf" width="425"></iframe>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
    <div class="row">_x000D_
        <div class="col-md-12">_x000D_
            Testing ratio AND left/right/center align:<br />_x000D_
            <div class="box1text">_x000D_
                <div class="embeddedContent rightAlignedContent">_x000D_
                    <div class="embeddedInnerWrapper">_x000D_
                        <iframe allowfullscreen="true" allowscriptaccess="always" frameborder="0" height="349" scrolling="no" src="//www.youtube.com/embed/u6XAPnuFjJc?wmode=transparent&amp;jqoemcache=eE9xf" width="425"></iframe>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
    <div class="row">_x000D_
        <div class="col-md-12">_x000D_
            Testing ratio AND left/right/center align:<br />_x000D_
            <div class="box1text">_x000D_
                <div class="embeddedContent">_x000D_
                    <div class="embeddedInnerWrapper">_x000D_
                        <iframe allowfullscreen="true" allowscriptaccess="always" frameborder="0" height="349" scrolling="no" src="//www.youtube.com/embed/u6XAPnuFjJc?wmode=transparent&amp;jqoemcache=eE9xf" width="425"></iframe>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to POST JSON request using Apache HttpClient?

For Apache HttpClient 4.5 or newer version:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://targethost/login");
    String JSON_STRING="";
    HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

Note:

1 in order to make the code compile, both httpclient package and httpcore package should be imported.

2 try-catch block has been ommitted.

Reference: appache official guide

the Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules

How to pattern match using regular expression in Scala?

Since version 2.10, one can use Scala's string interpolation feature:

implicit class RegexOps(sc: StringContext) {
  def r = new util.matching.Regex(sc.parts.mkString, sc.parts.tail.map(_ => "x"): _*)
}

scala> "123" match { case r"\d+" => true case _ => false }
res34: Boolean = true

Even better one can bind regular expression groups:

scala> "123" match { case r"(\d+)$d" => d.toInt case _ => 0 }
res36: Int = 123

scala> "10+15" match { case r"(\d\d)${first}\+(\d\d)${second}" => first.toInt+second.toInt case _ => 0 }
res38: Int = 25

It is also possible to set more detailed binding mechanisms:

scala> object Doubler { def unapply(s: String) = Some(s.toInt*2) }
defined module Doubler

scala> "10" match { case r"(\d\d)${Doubler(d)}" => d case _ => 0 }
res40: Int = 20

scala> object isPositive { def unapply(s: String) = s.toInt >= 0 }
defined module isPositive

scala> "10" match { case r"(\d\d)${d @ isPositive()}" => d.toInt case _ => 0 }
res56: Int = 10

An impressive example on what's possible with Dynamic is shown in the blog post Introduction to Type Dynamic:

object T {

  class RegexpExtractor(params: List[String]) {
    def unapplySeq(str: String) =
      params.headOption flatMap (_.r unapplySeq str)
  }

  class StartsWithExtractor(params: List[String]) {
    def unapply(str: String) =
      params.headOption filter (str startsWith _) map (_ => str)
  }

  class MapExtractor(keys: List[String]) {
    def unapplySeq[T](map: Map[String, T]) =
      Some(keys.map(map get _))
  }

  import scala.language.dynamics

  class ExtractorParams(params: List[String]) extends Dynamic {
    val Map = new MapExtractor(params)
    val StartsWith = new StartsWithExtractor(params)
    val Regexp = new RegexpExtractor(params)

    def selectDynamic(name: String) =
      new ExtractorParams(params :+ name)
  }

  object p extends ExtractorParams(Nil)

  Map("firstName" -> "John", "lastName" -> "Doe") match {
    case p.firstName.lastName.Map(
          Some(p.Jo.StartsWith(fn)),
          Some(p.`.*(\\w)$`.Regexp(lastChar))) =>
      println(s"Match! $fn ...$lastChar")
    case _ => println("nope")
  }
}

Set maxlength in Html Textarea

If you are using HTML 5, you need to specify that in your DOCTYPE declaration.

For a valid HTML 5 document, it should start with:

<!DOCTYPE html>

Before HTML 5, the textarea element did not have a maxlength attribute.

You can see this in the DTD/spec:

<!ELEMENT TEXTAREA - - (#PCDATA)       -- multi-line text field -->
<!ATTLIST TEXTAREA
  %attrs;                              -- %coreattrs, %i18n, %events --
  name        CDATA          #IMPLIED
  rows        NUMBER         #REQUIRED
  cols        NUMBER         #REQUIRED
  disabled    (disabled)     #IMPLIED  -- unavailable in this context --
  readonly    (readonly)     #IMPLIED
  tabindex    NUMBER         #IMPLIED  -- position in tabbing order --
  accesskey   %Character;    #IMPLIED  -- accessibility key character --
  onfocus     %Script;       #IMPLIED  -- the element got the focus --
  onblur      %Script;       #IMPLIED  -- the element lost the focus --
  onselect    %Script;       #IMPLIED  -- some text was selected --
  onchange    %Script;       #IMPLIED  -- the element value was changed --
  %reserved;                           -- reserved for possible future use --
  >

In order to limit the number of characters typed into a textarea, you will need to use javascript with the onChange event. You can then count the number of characters and disallow further typing.

Here is an in-depth discussion on text input and how to use server and client side scripting to limit the size.

Here is another sample.

Automatically capture output of last command into a variable using Bash?

This is a really hacky solution, but it seems to mostly work some of the time. During testing, I noted it sometimes didn't work very well when getting a ^C on the command line, though I did tweak it a bit to behave a bit better.

This hack is an interactive mode hack only, and I am pretty confident that I would not recommend it to anyone. Background commands are likely to cause even less defined behavior than normal. The other answers are a better way of programmatically getting at results.


That being said, here is the "solution":

PROMPT_COMMAND='LAST="`cat /tmp/x`"; exec >/dev/tty; exec > >(tee /tmp/x)'

Set this bash environmental variable and issues commands as desired. $LAST will usually have the output you are looking for:

startide seth> fortune
Courtship to marriage, as a very witty prologue to a very dull play.
                -- William Congreve
startide seth> echo "$LAST"
Courtship to marriage, as a very witty prologue to a very dull play.
                -- William Congreve

How to loop through an array containing objects and access their properties

for (element in array) {
    console.log(array[element].property);
  }

This works.

Capturing window.onbeforeunload

The reason why nothing happens when you use 'alert()' is probably as explained by MDN: "The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event."

But there is also another reason why you might not see the warning at all, whether it calls alert() or not, also explained on the same site:

"... browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with"

That is what I see with current versions of Chrome and FireFox. I open my page which has beforeunload handler set up with this code:

window.addEventListener
('beforeunload'
, function (evt)
  { evt.preventDefault();
    evt.returnValue = 'Hello';
    return "hello 2222"
  }
 );

If I do not click on my page, in other words "do not interact" with it, and click the close-button, the window closes without warning.

But if I click on the page before trying to close the window or tab, I DO get the warning, and can cancel the closing of the window.

So these browsers are "smart" (and user-friendly) in that if you have not done anything with the page, it can not have any user-input that would need saving, so they will close the window without any warnings.

Consider that without this feature any site might selfishly ask you: "Do you really want to leave our site?", when you have already clearly indicated your intention to leave their site.

SEE: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

VBScript - How to make program wait until process has finished?

Probably something like this? (UNTESTED)

Sub Sample()
    Dim strWB4, strMyMacro
    strMyMacro = "Sheet1.my_macro_name"

    '
    '~~> Rest of Code
    '

    'loop through the folder and get the file names
    For Each Fil In FLD.Files
        Set x4WB = x1.Workbooks.Open(Fil)
        x4WB.Application.Visible = True

        x1.Run strMyMacro

        x4WB.Close

        Do Until IsWorkBookOpen(Fil) = False
            DoEvents
        Loop
    Next

    '
    '~~> Rest of Code
    '
End Sub

'~~> Function to check if the file is open
Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsWorkBookOpen = False
    Case 70:   IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

storing user input in array

You're not actually going out after the values. You would need to gather them like this:

var title   = document.getElementById("title").value;
var name    = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;

You could put all of these in one array:

var myArray = [ title, name, tickets ];

Or many arrays:

var titleArr   = [ title ];
var nameArr    = [ name ];
var ticketsArr = [ tickets ];

Or, if the arrays already exist, you can use their .push() method to push new values onto it:

var titleArr = [];

function addTitle ( title ) {
  titleArr.push( title );
  console.log( "Titles: " + titleArr.join(", ") );
}

Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:

I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit

The new form follows:

<form>
  <h1>Please enter data</h1>
  <input id="title" type="text" />
  <input id="name" type="text" />
  <input id="tickets" type="text" />
  <input type="button" value="Save" onclick="insert()" />
  <input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>

There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).

I've also made some changes to your JavaScript. I start by creating three empty arrays:

var titles  = [];
var names   = [];
var tickets = [];

Now that we have these, we'll need references to our input fields.

var titleInput  = document.getElementById("title");
var nameInput   = document.getElementById("name");
var ticketInput = document.getElementById("tickets");

I'm also getting a reference to our message display box.

var messageBox  = document.getElementById("display");

The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.

Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.

function insert ( ) {
 titles.push( titleInput.value );
 names.push( nameInput.value );
 tickets.push( ticketInput.value );

 clearAndShow();
}

This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.

function clearAndShow () {
  titleInput.value = "";
  nameInput.value = "";
  ticketInput.value = "";

  messageBox.innerHTML = "";

  messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
  messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
  messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}

The final result can be used online at http://jsbin.com/ufanep/2/edit

How to create a session using JavaScript?

You can store and read string information in a cookie.

If it is a session id coming from the server, the server can generate this cookie. And when another request is sent to the server the cookie will come too. Without having to do anything in the browser.

However if it is javascript that creates the session Id. You can create a cookie with javascript, with a function like:

The read function work from any page or tab of the same domain that has written it, either if the cookie was created from the page in javascript or from the server.

How to checkout a specific Subversion revision from the command line?

It seems that you can use the repository browser. Click the revision button at top-right and change it to the revision you want. Then right-click your file in the browser and use 'Copy to working copy...' but change the filename it will check out, to avoid a clash.

jQuery textbox change event

I have found that this works:

$(document).ready(function(){
    $('textarea').bind('input propertychange', function() {
        //do your update here
    }

})

How to split a string in Ruby and get all items except the first one?

You probably mistyped a few things. From what I gather, you start with a string such as:

string = "test1, test2, test3, test4, test5"

Then you want to split it to keep only the significant substrings:

array = string.split(/, /)

And in the end you only need all the elements excluding the first one:

# We extract and remove the first element from array
first_element = array.shift

# Now array contains the expected result, you can check it with
puts array.inspect

Did that answer your question ?

return error message with actionResult

IN your view insert

@Html.ValidationMessage("Error")

then in the controller after you use new in your model

var model = new yourmodel();
try{
[...]
}catch(Exception ex){
ModelState.AddModelError("Error", ex.Message);
return View(model);
}

Array initialization in Perl

To produce the output in your comment to your post, this will do it:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @array;
my %uniqs;

$uniqs{$_}++ for @other_array;

foreach (keys %uniqs) { $array[$_]=$uniqs{$_} }

print "array[$_] = $array[$_]\n" for (0..$#array);

Output:

   array[0] = 3
   array[1] = 1
   array[2] = 2
   array[3] = 3
   array[4] = 1

This is different than your stated algorithm of producing a parallel array with zero values, but it is a more Perly way of doing it...

If you must have a parallel array that is the same size as your first array with the elements initialized to 0, this statement will dynamically do it: @array=(0) x scalar(@other_array); but really, you don't need to do that.

Image resizing client-side with JavaScript before upload to the server

http://nodeca.github.io/pica/demo/

In modern browser you can use canvas to load/save image data. But you should keep in mind several things if you resize image on the client:

  1. You will have only 8bits per channel (jpeg can have better dynamic range, about 12 bits). If you don't upload professional photos, that should not be a problem.
  2. Be careful about resize algorithm. The most of client side resizers use trivial math, and result is worse than it could be.
  3. You may need to sharpen downscaled image.
  4. If you wish do reuse metadata (exif and other) from original - don't forget to strip color profile info. Because it's applied when you load image to canvas.

Find first element in a sequence that matches a predicate

I don't think there's anything wrong with either solutions you proposed in your question.

In my own code, I would implement it like this though:

(x for x in seq if predicate(x)).next()

The syntax with () creates a generator, which is more efficient than generating all the list at once with [].

window.onunload is not working properly in Chrome browser. Can any one help me?

The onunload event won't fire if the onload event did not fire. Unfortunately the onload event waits for all binary content (e.g. images) to load, and inline scripts run before the onload event fires. DOMContentLoaded fires when the page is visible, before onload does. And it is now standard in HTML 5, and you can test for browser support but note this requires the <!DOCTYPE html> (at least in Chrome). However, I can not find a corresponding event for unloading the DOM. And such a hypothetical event might not work because some browsers may keep the DOM around to perform the "restore tab" feature.

The only potential solution I found so far is the Page Visibility API, which appears to require the <!DOCTYPE html>.

Redirect from an HTML page

I would also add a canonical link to help your SEO people:

<link rel="canonical" href="http://www.example.com/product.php?item=swedish-fish"/>

how to display full stored procedure code?

Use \df to list all the stored procedure in Postgres.

How to get height and width of device display in angular2 using typescript?

export class Dashboard {
    innerHeight: any;
    innerWidth: any;
    constructor() {
        this.innerHeight = (window.screen.height) + "px";
        this.innerWidth = (window.screen.width) + "px";
    }
}

Difference between request.getSession() and request.getSession(true)

request.getSession() or request.getSession(true) both will return a current session only . if current session will not exist then it will create a new session.

How to split a comma-separated value to columns

There are multiple ways to solve this and many different ways have been proposed already. Simplest would be to use LEFT / SUBSTRING and other string functions to achieve the desired result.

Sample Data

DECLARE @tbl1 TABLE (Value INT,String VARCHAR(MAX))

INSERT INTO @tbl1 VALUES(1,'Cleo, Smith');
INSERT INTO @tbl1 VALUES(2,'John, Mathew');

Using String Functions like LEFT

SELECT
    Value,
    LEFT(String,CHARINDEX(',',String)-1) as Fname,
    LTRIM(RIGHT(String,LEN(String) - CHARINDEX(',',String) )) AS Lname
FROM @tbl1

This approach fails if there are more 2 items in a String. In such a scenario, we can use a splitter and then use PIVOT or convert the string into an XML and use .nodes to get string items. XML based solution have been detailed out by aads and bvr in their solution.

The answers for this question which use splitter, all use WHILE which is inefficient for splitting. Check this performance comparison. One of the best splitters around is DelimitedSplit8K, created by Jeff Moden. You can read more about it here

Splitter with PIVOT

DECLARE @tbl1 TABLE (Value INT,String VARCHAR(MAX))

INSERT INTO @tbl1 VALUES(1,'Cleo, Smith');
INSERT INTO @tbl1 VALUES(2,'John, Mathew');


SELECT t3.Value,[1] as Fname,[2] as Lname
FROM @tbl1 as t1
CROSS APPLY [dbo].[DelimitedSplit8K](String,',') as t2
PIVOT(MAX(Item) FOR ItemNumber IN ([1],[2])) as t3

Output

Value   Fname   Lname
1   Cleo    Smith
2   John    Mathew

DelimitedSplit8K by Jeff Moden

CREATE FUNCTION [dbo].[DelimitedSplit8K]
/**********************************************************************************************************************
 Purpose:
 Split a given string at a given delimiter and return a list of the split elements (items).

 Notes:
 1.  Leading a trailing delimiters are treated as if an empty string element were present.
 2.  Consecutive delimiters are treated as if an empty string element were present between them.
 3.  Except when spaces are used as a delimiter, all spaces present in each element are preserved.

 Returns:
 iTVF containing the following:
 ItemNumber = Element position of Item as a BIGINT (not converted to INT to eliminate a CAST)
 Item       = Element value as a VARCHAR(8000)

 Statistics on this function may be found at the following URL:
 http://www.sqlservercentral.com/Forums/Topic1101315-203-4.aspx

 CROSS APPLY Usage Examples and Tests:
--=====================================================================================================================
-- TEST 1:
-- This tests for various possible conditions in a string using a comma as the delimiter.  The expected results are
-- laid out in the comments
--=====================================================================================================================
--===== Conditionally drop the test tables to make reruns easier for testing.
     -- (this is NOT a part of the solution)
     IF OBJECT_ID('tempdb..#JBMTest') IS NOT NULL DROP TABLE #JBMTest
;
--===== Create and populate a test table on the fly (this is NOT a part of the solution).
     -- In the following comments, "b" is a blank and "E" is an element in the left to right order.
     -- Double Quotes are used to encapsulate the output of "Item" so that you can see that all blanks
     -- are preserved no matter where they may appear.
 SELECT *
   INTO #JBMTest
   FROM (                                               --# & type of Return Row(s)
         SELECT  0, NULL                      UNION ALL --1 NULL
         SELECT  1, SPACE(0)                  UNION ALL --1 b (Empty String)
         SELECT  2, SPACE(1)                  UNION ALL --1 b (1 space)
         SELECT  3, SPACE(5)                  UNION ALL --1 b (5 spaces)
         SELECT  4, ','                       UNION ALL --2 b b (both are empty strings)
         SELECT  5, '55555'                   UNION ALL --1 E
         SELECT  6, ',55555'                  UNION ALL --2 b E
         SELECT  7, ',55555,'                 UNION ALL --3 b E b
         SELECT  8, '55555,'                  UNION ALL --2 b B
         SELECT  9, '55555,1'                 UNION ALL --2 E E
         SELECT 10, '1,55555'                 UNION ALL --2 E E
         SELECT 11, '55555,4444,333,22,1'     UNION ALL --5 E E E E E 
         SELECT 12, '55555,4444,,333,22,1'    UNION ALL --6 E E b E E E
         SELECT 13, ',55555,4444,,333,22,1,'  UNION ALL --8 b E E b E E E b
         SELECT 14, ',55555,4444,,,333,22,1,' UNION ALL --9 b E E b b E E E b
         SELECT 15, ' 4444,55555 '            UNION ALL --2 E (w/Leading Space) E (w/Trailing Space)
         SELECT 16, 'This,is,a,test.'                   --E E E E
        ) d (SomeID, SomeValue)
;
--===== Split the CSV column for the whole table using CROSS APPLY (this is the solution)
 SELECT test.SomeID, test.SomeValue, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
   FROM #JBMTest test
  CROSS APPLY dbo.DelimitedSplit8K(test.SomeValue,',') split
;
--=====================================================================================================================
-- TEST 2:
-- This tests for various "alpha" splits and COLLATION using all ASCII characters from 0 to 255 as a delimiter against
-- a given string.  Note that not all of the delimiters will be visible and some will show up as tiny squares because
-- they are "control" characters.  More specifically, this test will show you what happens to various non-accented 
-- letters for your given collation depending on the delimiter you chose.
--=====================================================================================================================
WITH 
cteBuildAllCharacters (String,Delimiter) AS 
(
 SELECT TOP 256 
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
        CHAR(ROW_NUMBER() OVER (ORDER BY (SELECT NULL))-1)
   FROM master.sys.all_columns
)
 SELECT ASCII_Value = ASCII(c.Delimiter), c.Delimiter, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
   FROM cteBuildAllCharacters c
  CROSS APPLY dbo.DelimitedSplit8K(c.String,c.Delimiter) split
  ORDER BY ASCII_Value, split.ItemNumber
;
-----------------------------------------------------------------------------------------------------------------------
 Other Notes:
 1. Optimized for VARCHAR(8000) or less.  No testing or error reporting for truncation at 8000 characters is done.
 2. Optimized for single character delimiter.  Multi-character delimiters should be resolvedexternally from this 
    function.
 3. Optimized for use with CROSS APPLY.
 4. Does not "trim" elements just in case leading or trailing blanks are intended.
 5. If you don't know how a Tally table can be used to replace loops, please see the following...
    http://www.sqlservercentral.com/articles/T-SQL/62867/
 6. Changing this function to use NVARCHAR(MAX) will cause it to run twice as slow.  It's just the nature of 
    VARCHAR(MAX) whether it fits in-row or not.
 7. Multi-machine testing for the method of using UNPIVOT instead of 10 SELECT/UNION ALLs shows that the UNPIVOT method
    is quite machine dependent and can slow things down quite a bit.
-----------------------------------------------------------------------------------------------------------------------
 Credits:
 This code is the product of many people's efforts including but not limited to the following:
 cteTally concept originally by Iztek Ben Gan and "decimalized" by Lynn Pettis (and others) for a bit of extra speed
 and finally redacted by Jeff Moden for a different slant on readability and compactness. Hat's off to Paul White for
 his simple explanations of CROSS APPLY and for his detailed testing efforts. Last but not least, thanks to
 Ron "BitBucket" McCullough and Wayne Sheffield for their extreme performance testing across multiple machines and
 versions of SQL Server.  The latest improvement brought an additional 15-20% improvement over Rev 05.  Special thanks
 to "Nadrek" and "peter-757102" (aka Peter de Heer) for bringing such improvements to light.  Nadrek's original
 improvement brought about a 10% performance gain and Peter followed that up with the content of Rev 07.  

 I also thank whoever wrote the first article I ever saw on "numbers tables" which is located at the following URL
 and to Adam Machanic for leading me to it many years ago.
 http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-numbers-table.html
-----------------------------------------------------------------------------------------------------------------------
 Revision History:
 Rev 00 - 20 Jan 2010 - Concept for inline cteTally: Lynn Pettis and others.
                        Redaction/Implementation: Jeff Moden 
        - Base 10 redaction and reduction for CTE.  (Total rewrite)

 Rev 01 - 13 Mar 2010 - Jeff Moden
        - Removed one additional concatenation and one subtraction from the SUBSTRING in the SELECT List for that tiny
          bit of extra speed.

 Rev 02 - 14 Apr 2010 - Jeff Moden
        - No code changes.  Added CROSS APPLY usage example to the header, some additional credits, and extra 
          documentation.

 Rev 03 - 18 Apr 2010 - Jeff Moden
        - No code changes.  Added notes 7, 8, and 9 about certain "optimizations" that don't actually work for this
          type of function.

 Rev 04 - 29 Jun 2010 - Jeff Moden
        - Added WITH SCHEMABINDING thanks to a note by Paul White.  This prevents an unnecessary "Table Spool" when the
          function is used in an UPDATE statement even though the function makes no external references.

 Rev 05 - 02 Apr 2011 - Jeff Moden
        - Rewritten for extreme performance improvement especially for larger strings approaching the 8K boundary and
          for strings that have wider elements.  The redaction of this code involved removing ALL concatenation of 
          delimiters, optimization of the maximum "N" value by using TOP instead of including it in the WHERE clause,
          and the reduction of all previous calculations (thanks to the switch to a "zero based" cteTally) to just one 
          instance of one add and one instance of a subtract. The length calculation for the final element (not 
          followed by a delimiter) in the string to be split has been greatly simplified by using the ISNULL/NULLIF 
          combination to determine when the CHARINDEX returned a 0 which indicates there are no more delimiters to be
          had or to start with. Depending on the width of the elements, this code is between 4 and 8 times faster on a
          single CPU box than the original code especially near the 8K boundary.
        - Modified comments to include more sanity checks on the usage example, etc.
        - Removed "other" notes 8 and 9 as they were no longer applicable.

 Rev 06 - 12 Apr 2011 - Jeff Moden
        - Based on a suggestion by Ron "Bitbucket" McCullough, additional test rows were added to the sample code and
          the code was changed to encapsulate the output in pipes so that spaces and empty strings could be perceived 
          in the output.  The first "Notes" section was added.  Finally, an extra test was added to the comments above.

 Rev 07 - 06 May 2011 - Peter de Heer, a further 15-20% performance enhancement has been discovered and incorporated 
          into this code which also eliminated the need for a "zero" position in the cteTally table. 
**********************************************************************************************************************/
--===== Define I/O parameters
        (@pString VARCHAR(8000), @pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
 RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
     -- enough to cover NVARCHAR(4000)
  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT 1 UNION ALL
                 SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
                ),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
                 SELECT s.N1,
                        ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
                   FROM cteStart s
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
        Item       = SUBSTRING(@pString, l.N1, l.L1)
   FROM cteLen l
;

GO

How to split a python string on new line characters

? Splitting line in Python:

Have you tried using str.splitlines() method?:

From the docs:

str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

For example:

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']

Which delimiters are considered?

This method uses the universal newlines approach to splitting lines.

The main difference between Python 2.X and Python 3.X is that the former uses the universal newlines approach to splitting lines, so "\r", "\n", and "\r\n" are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:

  • \v or \x0b: Line Tabulation (added in Python 3.2).
  • \f or \x0c: Form Feed (added in Python 3.2).
  • \x1c: File Separator.
  • \x1d: Group Separator.
  • \x1e: Record Separator.
  • \x85: Next Line (C1 Control Code).
  • \u2028: Line Separator.
  • \u2029: Paragraph Separator.

splitlines VS split:

Unlike str.split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>> ''.splitlines()
[]

>>> 'Line 1\n'.splitlines()
['Line 1']

While str.split('\n') returns:

>>> ''.split('\n')
['']

>>> 'Line 1\n'.split('\n')
['Line 1', '']

?? Removing additional whitespace:

If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines(), you could use str.splitlines() together with str.strip():

>>> [str.strip() for str in 'Line 1  \n  \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']

? Removing empty strings (''):

Lastly, if you want to filter out the empty strings from the resulting list, you could use filter():

>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']

>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']

Additional comment regarding the original question:

As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

How to get TimeZone from android mobile?

Try this code-

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();

It will return user selected timezone.

Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4

just in case this is relevant for someone. I got the exact same error using ASP.NET and C# in Visual studio. When I started the app from within the visual studio it worked, but I got this issue. In the meantime, it turned out, that the path to my project contained the character "#" (c:\C#\testapplication). This seems to confuse IIS Express (maybe also IIS) and causes this issue. I guess "#" is a reserved character somewhere in ASP.NET or below. Changing the path helped and now it works as expected.

Regards Christof

Execute a SQL Stored Procedure and process the results

My Stored Procedure Requires 2 Parameters and I needed my function to return a datatable here is 100% working code

Please make sure that your procedure return some rows

Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
    Try
        Connection.Connect()
        debug.print("Look up account number " & AccountNumber)
        Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP  '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
        Dim DST As New DataSet
        DP.Fill(DST)
        Return DST.Tables(0)      
    Catch ex As Exception
        Return Nothing
    End Try
End Function

How do I call a SQL Server stored procedure from PowerShell?

Consider calling osql.exe (the command line tool for SQL Server) passing as parameter a text file written for each line with the call to the stored procedure.

SQL Server provides some assemblies that could be of use with the name SMO that have seamless integration with PowerShell. Here is an article on that.

http://www.databasejournal.com/features/mssql/article.php/3696731

There are API methods to execute stored procedures that I think are worth being investigated. Here a startup example:

http://www.eggheadcafe.com/software/aspnet/29974894/smo-running-a-stored-pro.aspx

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

My problem was resolved just by adding http:// to my url address. for example I used http://localhost:3000/movies instead of localhost:3000/movies.

How to check command line parameter in ".bat" file?

The short answer - use square brackets:

if [%1]==[] goto :blank

or (when you need to handle quoted args, see the Edit below):

if [%~1]==[] goto :blank

Why? you might ask. Well, just as Jeremiah Willcock mentioned: http://ss64.com/nt/if.html - they use that! OK, but what's wrong with the quotes?

Again, short answer: they are "magical" - sometimes double (double) quotes get converted to a single (double) quote. And they need to match, for a start.

Consider this little script:

@rem argq.bat
@echo off

:loop 
if "%1"=="" goto :done
echo %1
shift
goto :loop

:done
echo Done.

Let's test it:

C:\> argq bla bla
bla
bla
Done.

Seems to work. But now, lets switch to second gear:

C:\> argq "bla bla"
bla""=="" was unexpected at this time.

Boom This didn't evaluate to true, neither did it evaluate to false. The script DIED. If you were supposed to turn off the reactor somewhere down the line, well - tough luck. You now will die like Harry Daghlian.

You may think - OK, the arguments can't contain quotes. If they do, this happens. Wrong Here's some consolation:

C:\> argq ""bla bla""
""bla
bla""
Done.

Oh yeah. Don't worry - sometimes this will work.

Let's try another script:

@rem args.bat
@echo off

:loop 
if [%1]==[] goto :done
echo %1
shift
goto :loop

:done
echo Done.

You can test yourself, that it works OK for the above cases. This is logical - quotes have nothing to do with brackets, so there's no magic here. But what about spicing the args up with brackets?

D:\>args ]bla bla[
]bla
bla[
Done.

D:\>args [bla bla]
[bla
bla]
Done.

No luck there. The brackets just can't choke cmd.exe's parser.

Let's go back to the evil quotes for a moment. The problem was there, when the argument ended with a quote:

D:\>argq "bla1 bla2"
bla2""=="" was unexpected at this time.

What if I pass just:

D:\>argq bla2"
The syntax of the command is incorrect.

The script won't run at all. Same for args.bat:

D:\>args bla2"
The syntax of the command is incorrect.

But what do I get, when the number of "-characters "matches" (i.e. - is even), in such a case:

D:\>args bla2" "bla3
bla2" "bla3
Done.

NICE - I hope you learned something about how .bat files split their command line arguments (HINT: *It's not exactly like in bash). The above argument contains a space. But the quotes are not stripped automatically.

And argq? How does it react to that? Predictably:

D:\>argq bla2" "bla3
"bla3"=="" was unexpected at this time.

So - think before you say: "Know what? Just use quotes. [Because, to me, this looks nicer]".

Edit

Recently, there were comments about this answer - well, sqare brackets "can't handle" passing quoted arguments and treating them just as if they weren't quoted.

The syntax:

if "%~1"=="" (...)

Is not some newly found virtue of the double quotes, but a display of a neat feature of stripping quotes from the argument variable, if the first and last character is a double quote.

This "technology" works just as well with square brackets:

if [%~1]==[] (...)

It was a useful thing to point this out, so I also upvote the new answer.

Finally, double quote fans, does an argument of the form "" exist in your book, or is it blank? Just askin' ;)

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

Check Following Things

  • Make Sure You Have MySQL Server Running
  • Check connection with default credentials i.e. username : 'root' & password : '' [Blank Password]
  • Try login phpmyadmin with same credentials
  • Try to put 127.0.0.1 instead localhost or your lan IP would do too.
  • Make sure you are running MySql on 3306 and if you have configured make sure to state it while making a connection

Set port for php artisan.php serve

as this example you can change ip and port this works with me

php artisan serve --host=0.0.0.0 --port=8000

Conversion failed when converting date and/or time from character string in SQL SERVER 2008

If you're trying to insert in to last_accessed_on, which is a DateTime2, then your issue is with the fact that you are converting it to a varchar in a format that SQL doesn't understand.

If you modify your code to this, it should work, note the format of your date has been changed to: YYYY-MM-DD hh:mm:ss:

UPDATE  student_queues 
SET  Deleted=0, 
     last_accessed_by='raja', 
     last_accessed_on=CONVERT(datetime2,'2014-07-23 09:37:00')
WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'

Or if you want to use CAST, replace with:

CAST('2014-07-23 09:37:00.000' AS datetime2)

This is using the SQL ISO Date Format.

ImportError: cannot import name NUMPY_MKL

I'm not sure if this is a good solution but it removed the error. I commented out the line:

from numpy._distributor_init import NUMPY_MKL 

and it worked. Not sure if this will cause other features to break though

Disable browser's back button

<body onLoad="if(history.length>0)history.go(+1)">

Error: macro names must be identifiers using #ifdef 0

Note that you can also hit this error if you accidentally type:

#define <stdio.h>

...instead of...

#include <stdio.>

How to split a list by comma not space

Read: http://linuxmanpages.com/man1/sh.1.php & http://www.gnu.org/s/hello/manual/autoconf/Special-Shell-Variables.html

IFS The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is ``''.

IFS is a shell environment variable so it will remain unchanged within the context of your Shell script but not otherwise, unless you EXPORT it. ALSO BE AWARE, that IFS will not likely be inherited from your Environment at all: see this gnu post for the reasons and more info on IFS.

You're code written like this:

IFS=","
for word in $(cat tmptest | sed -n 1'p' | tr ',' '\n'); do echo $word; done;

should work, I tested it on command line.

sh-3.2#IFS=","
sh-3.2#for word in $(cat tmptest | sed -n 1'p' | tr ',' '\n'); do echo $word; done;
World
Questions
Answers
bash shell
script

Python: Assign Value if None Exists

One-liner solution here:

var1 = locals().get("var1", "default value")

Instead of having NameError, this solution will set var1 to default value if var1 hasn't been defined yet.

Here's how it looks like in Python interactive shell:

>>> var1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'var1' is not defined
>>> var1 = locals().get("var1", "default value 1")
>>> var1
'default value 1'
>>> var1 = locals().get("var1", "default value 2")
>>> var1
'default value 1'
>>>

Android open camera from button

you can use the following code

         Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                pic = new File(Environment.getExternalStorageDirectory(),
                        mApp.getPreference().getString(Common.u_id, "") + ".jpg");

                picUri = Uri.fromFile(pic);

                cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, picUri);

                cameraIntent.putExtra("return-data", true);
                startActivityForResult(cameraIntent, PHOTO);

What's the difference between align-content and align-items?

align-content

align-content controls the cross-axis (i.e. vertical direction if the flex-direction is row, and horizontal if the flex-direction is column) positioning of multiple lines relative to each other.

(Think lines of a paragraph being vertically spread out, stacked toward the top, stacked toward the bottom. This is under a flex-direction row paradigm).

align-items

align-items controls the cross-axis of an individual line of flex elements.

(Think how an individual line of a paragraph is aligned, if it contains some normal text and some taller text like math equations. In that case, will it be the bottom, top, or center of each type of text in a line that will be aligned?)

Understanding dispatch_async

The main reason you use the default queue over the main queue is to run tasks in the background.

For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
    });
});

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

you can make a function like this

function translateTo($language, $word) {  
   define('defaultLang','english');  
   if (isset($lang[$language][$word]) == FALSE)  
      return $lang[$language][$word];  
   else  
      return $lang[defaultLang][$word];  
}

jquery change class name

You can set the class (regardless of what it was) by using .attr(), like this:

$("#td_id").attr('class', 'newClass');

If you want to add a class, use .addclass() instead, like this:

$("#td_id").addClass('newClass');

Or a short way to swap classes using .toggleClass():

$("#td_id").toggleClass('change_me newClass');

Here's the full list of jQuery methods specifically for the class attribute.

Use success() or complete() in AJAX call

Well, speaking from quarantine, the complete() in $.ajax is like finally in try catch block.

If you use try catch block in any programming language, it doesn't matter whether you execute a thing successfully or got an error in execution. the finally{} block will always be executed.

Same goes for complete() in $.ajax, whether you get success() response or error() the complete() function always will be called once the execution has been done.

How to convert 2D float numpy array to 2D int numpy array?

If you're not sure your input is going to be a Numpy array, you can use asarray with dtype=int instead of astype:

>>> np.asarray([1,2,3,4], dtype=int)
array([1, 2, 3, 4])

If the input array already has the correct dtype, asarray avoids the array copy while astype does not (unless you specify copy=False):

>>> a = np.array([1,2,3,4])
>>> a is np.asarray(a)  # no copy :)
True
>>> a is a.astype(int)  # copy :(
False
>>> a is a.astype(int, copy=False)  # no copy :)
True

Checking for NULL pointer in C/C++

Most compilers I've used will at least warn on the if assignment without further syntax sugar, so I don't buy that argument. That said, I've used both professionally and have no preference for either. The == NULL is definitely clearer though in my opinion.

How to enumerate an object's properties in Python?

If you're looking for reflection of all properties, the answers above are great.

If you're simply looking to get the keys of a dictionary (which is different from an 'object' in Python), use

my_dict.keys()

my_dict = {'abc': {}, 'def': 12, 'ghi': 'string' }
my_dict.keys() 
> ['abc', 'def', 'ghi']

Open Facebook page from Android app?

To launch facebook page from your app, let urlString = "fb://page/your_fb_page_id"

To launch facebook messenger let urlString = "fb-messenger://user/your_fb_page_id"

FB page id is usually numeric. To get it, goto Find My FB ID input your profile url, something like www.facebook.com/edgedevstudio then click "Find Numberic ID".

Voila, you now have your fb numeric id. replace "your_fb_page_id" with the generated Numeric ID

 val intent = Intent(Intent.ACTION_VIEW, Uri.parse(urlString))
 if (intent.resolveActivity(packageManager) != null) //check if app is available to handle the implicit intent
 startActivity(intent)

How do I work with a git repository within another repository?

The key is git submodules.

Start reading the Submodules chapter of the Git Community Book or of the Users Manual

Say you have repository PROJECT1, PROJECT2, and MEDIA...

cd /path/to/PROJECT1
git submodule add ssh://path.to.repo/MEDIA
git commit -m "Added Media submodule"

Repeat on the other repo...

Now, the cool thing is, that any time you commit changes to MEDIA, you can do this:

cd /path/to/PROJECT2/MEDIA
git pull
cd ..
git add MEDIA
git commit -m "Upgraded media to version XYZ"

This just recorded the fact that the MEDIA submodule WITHIN PROJECT2 is now at version XYZ.

It gives you 100% control over what version of MEDIA each project uses. git submodules are great, but you need to experiment and learn about them.

With great power comes the great chance to get bitten in the rump.

"Data too long for column" - why?

In my case this error occurred due to entering data a wrong type for example: if it is a long type column, i tried to enter in string type. so please check your data that you are entering and type are same or not

How to insert date values into table

date must be insert with two apostrophes' As example if the date is 2018/10/20. It can insert from these query

Query -

insert into run(id,name,dob)values(&id,'&name','2018-10-20')

What is the most efficient/quickest way to loop through rows in VBA (excel)?

EDIT Summary and reccomendations

Using a for each cell in range construct is not in itself slow. What is slow is repeated access to Excel in the loop (be it reading or writing cell values, format etc, inserting/deleting rows etc).

What is too slow depends entierly on your needs. A Sub that takes minutes to run might be OK if only used rarely, but another that takes 10s might be too slow if run frequently.

So, some general advice:

  1. keep it simple at first. If the result is too slow for your needs, then optimise
  2. focus on optimisation of the content of the loop
  3. don't just assume a loop is needed. There are sometime alternatives
  4. if you need to use cell values (a lot) inside the loop, load them into a variant array outside the loop.
  5. a good way to avoid complexity with inserts is to loop the range from the bottom up
    (for index = max to min step -1)
  6. if you can't do that and your 'insert a row here and there' is not too many, consider reloading the array after each insert
  7. If you need to access cell properties other than value, you are stuck with cell references
  8. To delete a number of rows consider building a range reference to a multi area range in the loop, then delete that range in one go after the loop

eg (not tested!)

Dim rngToDelete as range
for each rw in rng.rows
    if need to delete rw then

        if rngToDelete is nothing then
            set rngToDelete = rw
        else
            set rngToDelete = Union(rngToDelete, rw)
        end if

    endif
next
rngToDelete.EntireRow.Delete

Original post

Conventional wisdom says that looping through cells is bad and looping through a variant array is good. I too have been an advocate of this for some time. Your question got me thinking, so I did some short tests with suprising (to me anyway) results:

test data set: a simple list in cells A1 .. A1000000 (thats 1,000,000 rows)

Test case 1: loop an array

Dim v As Variant
Dim n As Long

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
    'i = i + 1
    'i = r.Cells(n, 1).Value 'i + 1
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Array Count = " & Format(n, "#,###")

Result:

Array Time = 0.249 sec
Array Count = 1,000,001

Test Case 2: loop the range

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")

Result:

Range Time = 0.296 sec
Range Count = 1,000,000

So,looping an array is faster but only by 19% - much less than I expected.

Test 3: loop an array with a cell reference

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
    i = r.Cells(n, 1).Value
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Array Count = " & Format(i, "#,###")

Result:

Array Time = 5.897 sec
Array Count = 1,000,000

Test case 4: loop range with a cell reference

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
    i = c.Value
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")

Result:

Range Time = 2.356 sec
Range Count = 1,000,000

So event with a single simple cell reference, the loop is an order of magnitude slower, and whats more, the range loop is twice as fast!

So, conclusion is what matters most is what you do inside the loop, and if speed really matters, test all the options

FWIW, tested on Excel 2010 32 bit, Win7 64 bit All tests with

  • ScreenUpdating off,
  • Calulation manual,
  • Events disabled.

Parse Json string in C#

you can try with System.Web.Script.Serialization.JavaScriptSerializer:

var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(jsonStr);

How to see top processes sorted by actual memory usage?

How to total up used memory by process name:

Sometimes even looking at the biggest single processes there is still a lot of used memory unaccounted for. To check if there are a lot of the same smaller processes using the memory you can use a command like the following which uses awk to sum up the total memory used by processes of the same name:

ps -e -orss=,args= |awk '{print $1 " " $2 }'| awk '{tot[$2]+=$1;count[$2]++} END {for (i in tot) {print tot[i],i,count[i]}}' | sort -n

e.g. output

9344 docker 1
9948 nginx: 4
22500 /usr/sbin/NetworkManager 1
24704 sleep 69
26436 /usr/sbin/sshd 15
34828 -bash 19
39268 sshd: 10
58384 /bin/su 28
59876 /bin/ksh 29
73408 /usr/bin/python 2
78176 /usr/bin/dockerd 1
134396 /bin/sh 84
5407132 bin/naughty_small_proc 1432
28061916 /usr/local/jdk/bin/java 7

Java regex capturing groups indexes

Capturing and grouping

Capturing group (pattern) creates a group that has capturing property.

A related one that you might often see (and use) is (?:pattern), which creates a group without capturing property, hence named non-capturing group.

A group is usually used when you need to repeat a sequence of patterns, e.g. (\.\w+)+, or to specify where alternation should take effect, e.g. ^(0*1|1*0)$ (^, then 0*1 or 1*0, then $) versus ^0*1|1*0$ (^0*1 or 1*0$).

A capturing group, apart from grouping, will also record the text matched by the pattern inside the capturing group (pattern). Using your example, (.*):, .* matches ABC and : matches :, and since .* is inside capturing group (.*), the text ABC is recorded for the capturing group 1.

Group number

The whole pattern is defined to be group number 0.

Any capturing group in the pattern start indexing from 1. The indices are defined by the order of the opening parentheses of the capturing groups. As an example, here are all 5 capturing groups in the below pattern:

(group)(?:non-capturing-group)(g(?:ro|u)p( (nested)inside)(another)group)(?=assertion)
|     |                       |          | |      |      ||       |     |
1-----1                       |          | 4------4      |5-------5     |
                              |          3---------------3              |
                              2-----------------------------------------2

The group numbers are used in back-reference \n in pattern and $n in replacement string.

In other regex flavors (PCRE, Perl), they can also be used in sub-routine calls.

You can access the text matched by certain group with Matcher.group(int group). The group numbers can be identified with the rule stated above.

In some regex flavors (PCRE, Perl), there is a branch reset feature which allows you to use the same number for capturing groups in different branches of alternation.

Group name

From Java 7, you can define a named capturing group (?<name>pattern), and you can access the content matched with Matcher.group(String name). The regex is longer, but the code is more meaningful, since it indicates what you are trying to match or extract with the regex.

The group names are used in back-reference \k<name> in pattern and ${name} in replacement string.

Named capturing groups are still numbered with the same numbering scheme, so they can also be accessed via Matcher.group(int group).

Internally, Java's implementation just maps from the name to the group number. Therefore, you cannot use the same name for 2 different capturing groups.

Check if MySQL table exists or not

$result = mysql_query("SHOW TABLES FROM $dbname");

while($row = mysql_fetch_row($result)) 
{
    $arr[] = $row[0];
}

if(in_array($table,$arr))
{
  echo 'Table exists';
}

mongodb count num of distinct values per field/key

I use this query:

var collection = "countries"; var field = "country"; 
db[collection].distinct(field).forEach(function(value){print(field + ", " + value + ": " + db.hosts.count({[field]: value}))})

Output:

countries, England: 3536
countries, France: 238
countries, Australia: 1044
countries, Spain: 16

This query first distinct all the values, and then count for each one of them the number of occurrences.

How to implement the Android ActionBar back button?

Android Annotations:

@OptionsItem(android.R.id.home)
void homeSelected() {
    onBackPressed();
}

Source: https://github.com/excilys/androidannotations

increment date by one month

If you want to get the date of one month from now you can do it like this

echo date('Y-m-d', strtotime('1 month'));

If you want to get the date of two months from now, you can achieve that by doing this

echo date('Y-m-d', strtotime('2 month'));

And so on, that's all.

Java - Reading XML file

One of the possible implementations:

File file = new File("userdata.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
        .newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
String usr = document.getElementsByTagName("user").item(0).getTextContent();
String pwd = document.getElementsByTagName("password").item(0).getTextContent();

when used with the XML content:

<credentials>
    <user>testusr</user>
    <password>testpwd</password>
</credentials>

results in "testusr" and "testpwd" getting assigned to the usr and pwd references above.

How do I send a POST request with PHP?

The better way of sending GET or POST requests with PHP is as below:

<?php
    $r = new HttpRequest('http://example.com/form.php', HttpRequest::METH_POST);
    $r->setOptions(array('cookies' => array('lang' => 'de')));
    $r->addPostFields(array('user' => 'mike', 'pass' => 's3c|r3t'));

    try {
        echo $r->send()->getBody();
    } catch (HttpException $ex) {
        echo $ex;
    }
?>

The code is taken from official documentation here http://docs.php.net/manual/da/httprequest.send.php

How merge two objects array in angularjs?

$scope.actions.data.concat is not a function 

same problem with me but i solve the problem by

 $scope.actions.data = [].concat($scope.actions.data , data)

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

This should solve your problem, you should try to run the following below:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 

Swift do-try-catch syntax

There are two important points to the Swift 2 error handling model: exhaustiveness and resiliency. Together, they boil down to your do/catch statement needing to catch every possible error, not just the ones you know you can throw.

Notice that you don't declare what types of errors a function can throw, only whether it throws at all. It's a zero-one-infinity sort of problem: as someone defining a function for others (including your future self) to use, you don't want to have to make every client of your function adapt to every change in the implementation of your function, including what errors it can throw. You want code that calls your function to be resilient to such change.

Because your function can't say what kind of errors it throws (or might throw in the future), the catch blocks that catch it errors don't know what types of errors it might throw. So, in addition to handling the error types you know about, you need to handle the ones you don't with a universal catch statement -- that way if your function changes the set of errors it throws in the future, callers will still catch its errors.

do {
    let sandwich = try makeMeSandwich(kitchen)
    print("i eat it \(sandwich)")
} catch SandwichError.NotMe {
    print("Not me error")
} catch SandwichError.DoItYourself {
    print("do it error")
} catch let error {
    print(error.localizedDescription)
}

But let's not stop there. Think about this resilience idea some more. The way you've designed your sandwich, you have to describe errors in every place where you use them. That means that whenever you change the set of error cases, you have to change every place that uses them... not very fun.

The idea behind defining your own error types is to let you centralize things like that. You could define a description method for your errors:

extension SandwichError: CustomStringConvertible {
    var description: String {
        switch self {
            case NotMe: return "Not me error"
            case DoItYourself: return "Try sudo"
        }
    }
}

And then your error handling code can ask your error type to describe itself -- now every place where you handle errors can use the same code, and handle possible future error cases, too.

do {
    let sandwich = try makeMeSandwich(kitchen)
    print("i eat it \(sandwich)")
} catch let error as SandwichError {
    print(error.description)
} catch {
    print("i dunno")
}

This also paves the way for error types (or extensions on them) to support other ways of reporting errors -- for example, you could have an extension on your error type that knows how to present a UIAlertController for reporting the error to an iOS user.

How can I play sound in Java?

I wrote the following code that works fine. But I think it only works with .wav format.

public static synchronized void playSound(final String url) {
  new Thread(new Runnable() {
  // The wrapper thread is unnecessary, unless it blocks on the
  // Clip finishing; see comments.
    public void run() {
      try {
        Clip clip = AudioSystem.getClip();
        AudioInputStream inputStream = AudioSystem.getAudioInputStream(
          Main.class.getResourceAsStream("/path/to/sounds/" + url));
        clip.open(inputStream);
        clip.start(); 
      } catch (Exception e) {
        System.err.println(e.getMessage());
      }
    }
  }).start();
}

Convert array of indices to 1-hot encoded numpy array

Here's a dimensionality-independent standalone solution.

This will convert any N-dimensional array arr of nonnegative integers to a one-hot N+1-dimensional array one_hot, where one_hot[i_1,...,i_N,c] = 1 means arr[i_1,...,i_N] = c. You can recover the input via np.argmax(one_hot, -1)

def expand_integer_grid(arr, n_classes):
    """

    :param arr: N dim array of size i_1, ..., i_N
    :param n_classes: C
    :returns: one-hot N+1 dim array of size i_1, ..., i_N, C
    :rtype: ndarray

    """
    one_hot = np.zeros(arr.shape + (n_classes,))
    axes_ranges = [range(arr.shape[i]) for i in range(arr.ndim)]
    flat_grids = [_.ravel() for _ in np.meshgrid(*axes_ranges, indexing='ij')]
    one_hot[flat_grids + [arr.ravel()]] = 1
    assert((one_hot.sum(-1) == 1).all())
    assert(np.allclose(np.argmax(one_hot, -1), arr))
    return one_hot

How to pass a vector to a function?

You'll have to pass the pointer to the vector, not the vector itself. Note the additional '&' here:

found = binarySearch(first, last, search4, &random);

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

Is it possible to run selenium (Firefox) web driver without a GUI?

Be aware that HtmlUnitDriver webclient is single-threaded and Ghostdriver is only at 40% of the functionalities to be a WebDriver.

Nonetheless, Ghostdriver run properly for tests and I have problems to connect it to the WebDriver hub.

How to set commands output as a variable in a batch file

I found this thread on that there Interweb thing. Boils down to:

@echo off 
setlocal enableextensions 
for /f "tokens=*" %%a in ( 
'VER' 
) do ( 
set myvar=%%a 
) 
echo/%%myvar%%=%myvar% 
pause 
endlocal 

You can also redirect the output of a command to a temporary file, and then put the contents of that temporary file into your variable, likesuchashereby. It doesn't work with multiline input though.

cmd > tmpFile 
set /p myvar= < tmpFile 
del tmpFile 

Credit to the thread on Tom's Hardware.

How can I find the first occurrence of a sub-string in a python string?

find()

>>> s = "the dude is a cool dude"
>>> s.find('dude')
4

What does this format means T00:00:00.000Z?

Please use DateTimeFormatter ISO_DATE_TIME = DateTimeFormatter.ISO_DATE_TIME; instead of DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss") or any pattern

This fixed my problem Below

java.time.format.DateTimeParseException: Text '2019-12-18T19:00:00.000Z' could not be parsed at index 10

What does $1 [QSA,L] mean in my .htaccess file?

Not the place to give a complete tutorial, but here it is in short;

RewriteCond basically means "execute the next RewriteRule only if this is true". The !-l path is the condition that the request is not for a link (! means not, -l means link)

The RewriteRule basically means that if the request is done that matches ^(.+)$ (matches any URL except the server root), it will be rewritten as index.php?url=$1 which means a request for ollewill be rewritten as index.php?url=olle).

QSA means that if there's a query string passed with the original URL, it will be appended to the rewrite (olle?p=1 will be rewritten as index.php?url=olle&p=1.

L means if the rule matches, don't process any more RewriteRules below this one.

For more complete info on this, follow the links above. The rewrite support can be a bit hard to grasp, but there are quite a few examples on stackoverflow to learn from.

Removing object properties with Lodash

Lodash unset is suitable for removing a few unwanted keys.

_x000D_
_x000D_
const myObj = {
    keyOne: "hello",
    keyTwo: "world"
}

unset(myObj, "keyTwo");

console.log(myObj); /// myObj = { keyOne: "hello" }
_x000D_
_x000D_
_x000D_

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

How do I find the index of a character in a string in Ruby?

index(substring [, offset]) ? fixnum or nil
index(regexp [, offset]) ? fixnum or nil

Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

"hello".index('e')             #=> 1
"hello".index('lo')            #=> 3
"hello".index('a')             #=> nil
"hello".index(?e)              #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4

Check out ruby documents for more information.

Is it possible to append to innerHTML without destroying descendants' event listeners?

As a slight (but related) asside, if you use a javascript library such as jquery (v1.3) to do your dom manipulation you can make use of live events whereby you set up a handler like:

 $("#myspan").live("click", function(){
  alert('hi');
});

and it will be applied to that selector at all times during any kind of jquery manipulation. For live events see: docs.jquery.com/events/live for jquery manipulation see: docs.jquery.com/manipulation

WooCommerce: Finding the products in database

Update 2020

Products are located mainly in the following tables:

  • wp_posts table with post_type like product (or product_variation),

  • wp_postmeta table with post_id as relational index (the product ID).

  • wp_wc_product_meta_lookup table with product_id as relational index (the post ID) | Allow fast queries on specific product data (since WooCommerce 3.7)

  • wp_wc_order_product_lookuptable with product_id as relational index (the post ID) | Allow fast queries to retrieve products on orders (since WooCommerce 3.7)

Product types, categories, subcategories, tags, attributes and all other custom taxonomies are located in the following tables:

  • wp_terms

  • wp_termmeta

  • wp_term_taxonomy

  • wp_term_relationships - column object_id as relational index (the product ID)

  • wp_woocommerce_termmeta

  • wp_woocommerce_attribute_taxonomies (for product attributes only)

  • wp_wc_category_lookup (for product categories hierarchy only since WooCommerce 3.7)


Product types are handled by custom taxonomy product_type with the following default terms:

  • simple
  • grouped
  • variable
  • external

Some other product types for Subscriptions and Bookings plugins:

  • subscription
  • variable-subscription
  • booking

Since Woocommerce 3+ a new custom taxonomy named product_visibility handle:

  • The product visibility with the terms exclude-from-search and exclude-from-catalog
  • The feature products with the term featured
  • The stock status with the term outofstock
  • The rating system with terms from rated-1 to rated-5

Particular feature: Each product attribute is a custom taxonomy…


References:

How to submit an HTML form on loading the page?

You can try also using below script

<html>
<head>
<script>
function load()
{
document.frm1.submit()
}
</script>
</head>

<body onload="load()">
<form action="http://www.google.com" id="frm1" name="frm1">
<input type="text" value="" />
</form>
</body>
</html> 

How to do a LIKE query with linq?

var StudentList = dbContext.Students.SqlQuery("Select * from Students where Email like '%gmail%'").ToList<Student>();

User can use this of like query in Linq and fill the student model.

How to color System.out.println output?

I created a jar library called JCDP (Java Colored Debug Printer).

For Linux it uses the ANSI escape codes that WhiteFang mentioned, but abstracts them using words instead of codes which is much more intuitive.

For Windows it actually includes the JAnsi library but creates an abstraction layer over it, maintaining the intuitive and simple interface created for Linux.

This library is licensed under the MIT License so feel free to use it.

Have a look at JCDP's github repository.

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

The two calls have different meanings that have nothing to do with performance; the fact that it speeds up the execution time is (or might be) just a side effect. You should understand what each of them does and not blindly include them in every program because they look like an optimization.

ios_base::sync_with_stdio(false);

This disables the synchronization between the C and C++ standard streams. By default, all standard streams are synchronized, which in practice allows you to mix C- and C++-style I/O and get sensible and expected results. If you disable the synchronization, then C++ streams are allowed to have their own independent buffers, which makes mixing C- and C++-style I/O an adventure.

Also keep in mind that synchronized C++ streams are thread-safe (output from different threads may interleave, but you get no data races).

cin.tie(NULL);

This unties cin from cout. Tied streams ensure that one stream is flushed automatically before each I/O operation on the other stream.

By default cin is tied to cout to ensure a sensible user interaction. For example:

std::cout << "Enter name:";
std::cin >> name;

If cin and cout are tied, you can expect the output to be flushed (i.e., visible on the console) before the program prompts input from the user. If you untie the streams, the program might block waiting for the user to enter their name but the "Enter name" message is not yet visible (because cout is buffered by default, output is flushed/displayed on the console only on demand or when the buffer is full).

So if you untie cin from cout, you must make sure to flush cout manually every time you want to display something before expecting input on cin.

In conclusion, know what each of them does, understand the consequences, and then decide if you really want or need the possible side effect of speed improvement.

How can I catch a ctrl-c event?

For a Windows console app, you want to use SetConsoleCtrlHandler to handle CTRL+C and CTRL+BREAK.

See here for an example.

Main differences between SOAP and RESTful web services in Java

  • REST stands for representational state transfer whereas SOAP stands for Simple Object Access Protocol.

  • SOAP defines its own security where as REST inherits security from the underlying transport.

  • SOAP does not support error handling, but REST has built-in error handling.

  • REST is lightweight and does not require XML parsing. REST can be consumed by any client, even a web browser with Ajax and JavaScript. REST consumes less bandwidth, it does not require a SOAP header for every message.

    • REST is useful over any protocol which provide a URI. Ignore point 5 for REST as mentioned below in the picture.

SOAP vs. REST

filedialog, tkinter and opening files

The exception you get is telling you filedialog is not in your namespace. filedialog (and btw messagebox) is a tkinter module, so it is not imported just with from tkinter import *

>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>> 

you should use for example:

>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>

or

>>> import tkinter.filedialog as fdialog

or

>>> from tkinter.filedialog import askopenfilename

So this would do for your browse button:

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror

class MyFrame(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Example")
        self.master.rowconfigure(5, weight=1)
        self.master.columnconfigure(5, weight=1)
        self.grid(sticky=W+E+N+S)

        self.button = Button(self, text="Browse", command=self.load_file, width=10)
        self.button.grid(row=1, column=0, sticky=W)

    def load_file(self):
        fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
                                           ("HTML files", "*.html;*.htm"),
                                           ("All files", "*.*") ))
        if fname:
            try:
                print("""here it comes: self.settings["template"].set(fname)""")
            except:                     # <- naked except is a bad idea
                showerror("Open Source File", "Failed to read file\n'%s'" % fname)
            return


if __name__ == "__main__":
    MyFrame().mainloop()

enter image description here

Java count occurrence of each item in an array

With , you can do it like this:

String[] array = {"name1","name2","name3","name4", "name5", "name2"};
Arrays.stream(array)
      .collect(Collectors.groupingBy(s -> s))
      .forEach((k, v) -> System.out.println(k+" "+v.size()));

Output:

name5 1
name4 1
name3 1
name2 2
name1 1

What it does is:

  • Create a Stream<String> from the original array
  • Group each element by identity, resulting in a Map<String, List<String>>
  • For each key value pair, print the key and the size of the list

If you want to get a Map that contains the number of occurences for each word, it can be done doing:

Map<String, Long> map = Arrays.stream(array)
    .collect(Collectors.groupingBy(s -> s, Collectors.counting()));

For more informations:

Hope it helps! :)

CSS3 animate border color

If you need the transition to run infinitely, try the below example:

_x000D_
_x000D_
#box {_x000D_
  position: relative;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-color: gray;_x000D_
  border: 5px solid black;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#box:hover {_x000D_
  border-color: red;_x000D_
  animation-name: flash_border;_x000D_
  animation-duration: 2s;_x000D_
  animation-timing-function: linear;_x000D_
  animation-iteration-count: infinite;_x000D_
  -webkit-animation-name: flash_border;_x000D_
  -webkit-animation-duration: 2s;_x000D_
  -webkit-animation-timing-function: linear;_x000D_
  -webkit-animation-iteration-count: infinite;_x000D_
  -moz-animation-name: flash_border;_x000D_
  -moz-animation-duration: 2s;_x000D_
  -moz-animation-timing-function: linear;_x000D_
  -moz-animation-iteration-count: infinite;_x000D_
}_x000D_
_x000D_
@keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}_x000D_
_x000D_
@-moz-keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}
_x000D_
<div id="box">roll over me</div>
_x000D_
_x000D_
_x000D_

Python 3.1.1 string to hex

In Python 3.5+, encode the string to bytes and use the hex() method, returning a string.

s = "hello".encode("utf-8").hex()
s
# '68656c6c6f'

Optionally convert the string back to bytes:

b = bytes(s, "utf-8")
b
# b'68656c6c6f'

How to escape special characters of a string with single backslashes

Simply using re.sub might also work instead of str.maketrans. And this would also work in python 2.x

>>> print(re.sub(r'(\-|\]|\^|\$|\*|\.|\\)',lambda m:{'-':'\-',']':'\]','\\':'\\\\','^':'\^','$':'\$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\\w\$arr=1

How can I get the concatenation of two lists in Python without modifying either one?

Yes: list1 + list2. This gives a new list that is the concatenation of list1 and list2.

Can you 'exit' a loop in PHP?

All of these are good answers, but I would like to suggest one more that I feel is a better code standard. You may choose to use a flag in the loop condition that indicates whether or not to continue looping and avoid using break all together.

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
$length = count($arr);
$found = false;
for ($i = 0; $i < $length && !$found; $i++) {
    $val = $arr[$i];
    if ($val == 'stop') {
        $found = true; // this will cause the code to 
                       // stop looping the next time 
                       // the condition is checked
    }
    echo "$val<br />\n";
}

I consider this to be better code practice because it does not rely on the scope that break is used. Rather, you define a variable that indicates whether or not to break a specific loop. This is useful when you have many loops that may or may not be nested or sequential.

Android 6.0 Marshmallow. Cannot write to SD Card

Android Documentation on Manifest.permission.Manifest.permission.WRITE_EXTERNAL_STORAGE states:

Starting in API level 19, this permission is not required to read/write files in your application-specific directories returned by getExternalFilesDir(String) and getExternalCacheDir().


I think that this means you do not have to code for the run-time implementation of the WRITE_EXTERNAL_STORAGE permission unless the app is writing to a directory that is not specific to your app.

You can define the max sdk version in the manifest per permission like:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="19" />

Also make sure to change the target SDK in the build.graddle and not the manifest, the gradle settings will always overwrite the manifest settings.

android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
    minSdkVersion 17
    targetSdkVersion 22
}

send/post xml file using curl command line

Here's how you can POST XML on Windows using curl command line on Windows. Better use batch/.cmd file for that:

curl -i -X POST -H "Content-Type: text/xml" -d             ^
"^<?xml version=\"1.0\" encoding=\"UTF-8\" ?^>                ^
    ^<Transaction^>                                           ^
        ^<SomeParam1^>Some-Param-01^</SomeParam1^>            ^
        ^<Password^>SomePassW0rd^</Password^>                 ^
        ^<Transaction_Type^>00^</Transaction_Type^>           ^
        ^<CardHoldersName^>John Smith^</CardHoldersName^>     ^
        ^<DollarAmount^>9.97^</DollarAmount^>                 ^
        ^<Card_Number^>4111111111111111^</Card_Number^>       ^
        ^<Expiry_Date^>1118^</Expiry_Date^>                   ^
        ^<VerificationStr2^>123^</VerificationStr2^>          ^
        ^<CVD_Presence_Ind^>1^</CVD_Presence_Ind^>            ^
        ^<Reference_No^>Some Reference Text^</Reference_No^>  ^
        ^<Client_Email^>[email protected]^</Client_Email^>       ^
        ^<Client_IP^>123.4.56.7^</Client_IP^>                 ^
        ^<Tax1Amount^>^</Tax1Amount^>                         ^
        ^<Tax2Amount^>^</Tax2Amount^>                         ^
    ^</Transaction^>                                          ^
" "http://localhost:8080"

How to rename array keys in PHP?

Talking about functional PHP, I have this more generic answer:

    array_map(function($arr){
        $ret = $arr;
        $ret['value'] = $ret['url'];
        unset($ret['url']);
        return $ret;
    }, $tag);
}

HTML to PDF with Node.js

If you want to export HTML to PDF. You have many options. without node even

Option 1: Have a button on your html page that calls window.print() function. use the browsers native html to pdf. use media queries to make your html page look good on a pdf. and you also have the print before and after events that you can use to make changes to your page before print.

Option 2. htmltocanvas or rasterizeHTML. convert your html to canvas , then call toDataURL() on the canvas object to get the image . and use a JavaScript library like jsPDF to add that image to a PDF file. Disadvantage of this approach is that the pdf doesnt become editable. If you want data extracted from PDF, there is different ways for that.

Option 3. @Jozzhard answer

How to remove time portion of date in C# in DateTime object only?

If you are converting it to string, you can easily do it like this.

I'm taking date as your DateTime object.

date.ToString("d");

This will give you only the date.

Return JSON with error status code MVC

The neatest solution I've found is to create your own JsonResult that extends the original implementation and allows you to specify a HttpStatusCode:

public class JsonHttpStatusResult : JsonResult
{
    private readonly HttpStatusCode _httpStatus;

    public JsonHttpStatusResult(object data, HttpStatusCode httpStatus)
    {
        Data = data;
        _httpStatus = httpStatus;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.RequestContext.HttpContext.Response.StatusCode = (int)_httpStatus;
        base.ExecuteResult(context);
    }
}

You can then use this in your controller action like so:

if(thereWereErrors)
{
    var errorModel = new { error = "There was an error" };
    return new JsonHttpStatusResult(errorModel, HttpStatusCode.InternalServerError);
}

Bootstrap trying to load map file. How to disable it? Do I need to do it?

.map files allow a browser to download a full version of the minified JS. It is really for debugging purposes.

In effect, the .map missing isn't a problem. You only know it is missing, as the browser has had its Developer tools opened, detected a minified file and is just informing you that the JS debugging won't be as good as it could be.

This is why libraries like jQuery have the full, the minified and the map file too.

See this article for a full explanation of .map files:

Submit HTML form on self page

You can do it using the same page on the action attribute: action='<yourpage>'

Can't choose class as main class in IntelliJ

Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"

Appending to an existing string

Yet an other way:

s.insert(-1, ' world')

How to print a float with 2 decimal places in Java?

float f = 102.236569f; 
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f)); // output is 102.24

APR based Apache Tomcat Native library was not found on the java.library.path?

My case: Seeing the same INFO message.

Centos 6.2 x86_64 Tomcat 6.0.24

This fixed the problem for me:

yum install tomcat-native

boom!

How to show empty data message in Datatables

If you want to customize the message that being shown on empty table use this:

$('#example').dataTable( {
    "oLanguage": {
        "sEmptyTable":     "My Custom Message On Empty Table"
    }
} );

Since Datatable 1.10 you can do the following:

$('#example').DataTable( {
    "language": {
        "emptyTable":     "My Custom Message On Empty Table"
    }
} );

For the complete availble datatables custom messages for the table take a look at the following link reference/option/language

Using :: in C++

look at it is informative [Qualified identifiers

A qualified id-expression is an unqualified id-expression prepended by a scope resolution operator ::, and optionally, a sequence of enumeration, (since C++11)class or namespace names or decltype expressions (since C++11) separated by scope resolution operators. For example, the expression std::string::npos is an expression that names the static member npos in the class string in namespace std. The expression ::tolower names the function tolower in the global namespace. The expression ::std::cout names the global variable cout in namespace std, which is a top-level namespace. The expression boost::signals2::connection names the type connection declared in namespace signals2, which is declared in namespace boost.

The keyword template may appear in qualified identifiers as necessary to disambiguate dependent template names]1

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

Add these 2 lines

layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0

So you have:

   // Do any additional setup after loading the view, typically from a nib.
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
        layout.itemSize = CGSize(width: screenWidth/3, height: screenWidth/3)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        collectionView!.collectionViewLayout = layout

That will remove all the spaces and give you a grid layout:

enter image description here

If you want the first column to have a width equal to the screen width then add the following function:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if indexPath.row == 0
    {
        return CGSize(width: screenWidth, height: screenWidth/3)
    }
    return CGSize(width: screenWidth/3, height: screenWidth/3);

}

Grid layout will now look like (I've also added a blue background to first cell): enter image description here

Is it good practice to use the xor operator for boolean checks?

I recently used an xor in a JavaScript project at work and ended up adding 7 lines of comments to explain what was going on. The justification for using xor in that context was that one of the terms (term1 in the example below) could take on not two but three values: undefined, true or false while the other (term2) could be true or false. I would have had to add an additional check for the undefined cases but with xor, the following was sufficient since the xor forces the first term to be first evaluated as a Boolean, letting undefined get treated as false:

if (term1 ^ term2) { ...

It was, in the end, a bit of an overkill, but I wanted to keep it in there anyway, as sort of an easter egg.

How to delete the first row of a dataframe in R?

You can use negative indexing to remove rows, e.g.:

dat <- dat[-1, ]

Here is an example:

> dat <- data.frame(A = 1:3, B = 1:3)
> dat[-1, ]
  A B
2 2 2
3 3 3
> dat2 <- dat[-1, ]
> dat2
  A B
2 2 2
3 3 3

That said, you may have more problems than just removing the labels that ended up on row 1. It is more then likely that R has interpreted the data as text and thence converted to factors. Check what str(foo), where foo is your data object, says about the data types.

It sounds like you just need header = TRUE in your call to read in the data (assuming you read it in via read.table() or one of it's wrappers.)

How to get HttpClient returning status code and response body?

If you are using Spring

return new ResponseEntity<String>("your response", HttpStatus.ACCEPTED);

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

Transaction isolation levels relation with locks on table

As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.

CUBRID (open source RDBMS) explains the idea of this two algorithms:

  • Two-phase locking (2PL)

The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).

  • Multi-version concurrency control (MVCC)

The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.

When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).

The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).

In 2PL Transaction isolation levels control the following:

  • Whether locks are taken when data is read, and what type of locks are requested.

  • How long the read locks are held.

  • Whether a read operation referencing rows modified by another transaction:

    • Block until the exclusive lock on the row is freed.

    • Retrieve the committed version of the row that existed at the time the statement or transaction started.

    • Read the uncommitted data modification.

Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.

A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.

Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)

  • READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]

  • READ_COMMITED:

    • If READ_COMMITTED_SNAPSHOT is set to OFF (the default): uses shared locks to prevent other transactions from modifying rows while the current transaction is running a read operation. The shared locks also block the statement from reading rows modified by other transactions until the other transaction is completed. [...] Row locks are released before the next row is processed. [...]
    • If READ_COMMITTED_SNAPSHOT is set to ON, the Database Engine uses row versioning to present each statement with a transactionally consistent snapshot of the data as it existed at the start of the statement. Locks are not used to protect the data from updates by other transactions.
  • REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.

  • SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.

How can I remove the extension of a filename in a shell script?

My recommendation is to use basename.
It is by default in Ubuntu, visually simple code and deal with majority of cases.

Here are some sub-cases to deal with spaces and multi-dot/sub-extension:

pathfile="../space fld/space -file.tar.gz"
echo ${pathfile//+(*\/|.*)}

It usually get rid of extension from first ., but fail in our .. path

echo **"$(basename "${pathfile%.*}")"**  
space -file.tar     # I believe we needed exatly that

Here is an important note:

I used double quotes inside double quotes to deal with spaces. Single quote will not pass due to texting the $. Bash is unusual and reads "second "first" quotes" due to expansion.

However, you still need to think of .hidden_files

hidden="~/.bashrc"
echo "$(basename "${hidden%.*}")"  # will produce "~" !!!  

not the expected "" outcome. To make it happen use $HOME or /home/user_path/
because again bash is "unusual" and don't expand "~" (search for bash BashPitfalls)

hidden2="$HOME/.bashrc" ;  echo '$(basename "${pathfile%.*}")'

Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

An other example would be on the "created_on" column where you want to let the database handle the date creation

A function to convert null to string

you can use ??"" for example:

y=x??""

if x isn't null y=x but if x is null y=""

Git add all subdirectories

You can also face problems if a subdirectory itself is a git repository - ie .has a .git directory - check with ls -a.

To remove go to the subdirectory and rm .git -rf.

Proper way to declare custom exceptions in modern Python?

To define your own exceptions correctly, there are a few best practices that you should follow:

  • Define a base class inheriting from Exception. This will allow to easily catch any exceptions related to the project:

    class MyProjectError(Exception):
        """A base class for MyProject exceptions."""
    

    Organizing the exception classes in a separate module (e.g. exceptions.py) is generally a good idea.

  • To create a specific exception, subclass the base exception class.

  • To add support for extra argument(s) to a custom exception, define a custom __init__() method with a variable number of arguments. Call the base class's __init__(), passing any positional arguments to it (remember that BaseException/Exception expect any number of positional arguments):

    class CustomError(MyProjectError):
        def __init__(self, *args, **kwargs):
            super().__init__(*args)
            self.foo = kwargs.get('foo')
    

    To raise such exception with an extra argument you can use:

     raise CustomError('Something bad happened', foo='foo')
    

This design adheres to the Liskov substitution principle, since you can replace an instance of a base exception class with an instance of a derived exception class. Also, it allows you to create an instance of a derived class with the same parameters as the parent.

Position a div container on the right side

This works for me.

<div style="position: relative;width:100%;">
    <div style="position:absolute;left:0px;background-color:red;width:25%;height:100px;">
      This will be on the left
    </div>

    <div style="position:absolute;right:0px;background-color:blue;width:25%;height:100px;">
      This will be on the right
    </div>
</div>

Setting paper size in FPDF

They say it right there in the documentation for the FPDF constructor:

FPDF([string orientation [, string unit [, mixed size]]])

This is the class constructor. It allows to set up the page size, the orientation and the unit of measure used in all methods (except for font sizes). Parameters ...

size

The size used for pages. It can be either one of the following values (case insensitive):

A3 A4 A5 Letter Legal

or an array containing the width and the height (expressed in the unit given by unit).

They even give an example with custom size:

Example with a custom 100x150 mm page size:

$pdf = new FPDF('P','mm',array(100,150));

Reading value from console, interactively

Here's a example:

const stdin = process.openStdin()

process.stdout.write('Enter name: ')

stdin.addListener('data', text => {
  const name = text.toString().trim()
  console.log('Your name is: ' + name)

  stdin.pause() // stop reading
})

Output:

Enter name: bob
Your name is: bob

JavaScript, getting value of a td with id name

For input you must have used value to grab its text but for td, you should use innerHTML to get its html/value. Example:

alert(document.getElementById("td_id_here").innerHTML);

To get its text though, use:

alert(document.getElementById("td_id_here").innerText);

AngularJS: How to make angular load script inside ng-include?

I used this method to load a script file dynamically (inside a controller).

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://maps.googleapis.com/maps/api/js";
document.body.appendChild(script);

How to avoid using Select in Excel VBA

How to avoid copy-paste?

Let's face it: this one appears a lot when recording macros:

Range("X1").Select
Selection.Copy
Range("Y9).Select
Selection.Paste

While the only thing the person wants is:

Range("Y9").Value = Range("X1").Value

Therefore, instead of using copy-paste in VBA macros, I'd advise the following simple approach:

Destination_Range.Value = Source_Range.Value

How do you specifically order ggplot2 x axis instead of alphabetical order?

It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:

#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))

In this example, the order of the factor will be the same as in the data.csv file.

If you prefer a different order, you can order them by hand:

data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))

However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.

How do I copy a string to the clipboard?

You can use module clipboard. Its simple and extremely easy to use. Works with Mac, Windows, & Linux.
Note: Its an alternative of pyperclip

After installing, import it:

import clipboard

Then you can copy like this:

clipboard.copy("This is copied")

You can also paste the copied text:

clipboard.paste()

libaio.so.1: cannot open shared object file

It looks like a 32/64 bit mismatch. The ldd output shows that mainly libraries from /lib64 are chosen. That would indicate that you have installed a 64 bit version of the Oracle client and have created a 64 bit executable. But libaio.so is probably a 32 bit library and cannot be used for your application.

So you either need a 64 bit version of libaio or you create a 32 bit version of your application.

How to get screen dimensions as pixels in Android

This function returns the approximate screen size in inches.

public double getScreenSize()
{
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width=dm.widthPixels;
        int height=dm.heightPixels;
        int dens=dm.densityDpi;
        double wi=(double)width/(double)dens;
        double hi=(double)height/(double)dens;
        double x = Math.pow(wi,2);
        double y = Math.pow(hi,2);
        double screenInches = Math.sqrt(x+y);
        return screenInches;
}

Inline style to act as :hover in CSS

If you are only debugging, you might use javascript to modify the css:

<a onmouseover="this.style.textDecoration='underline';" 
    onmouseout="this.style.textDecoration='none';">bar</a>

Remove all git files from a directory?

Unlike other source control systems like SVN or CVS, git stores all of its metadata in a single directory, rather than in every subdirectory of the project. So just delete .git from the root (or use a script like git-export) and you should be fine.

Class Diagrams in VS 2017

  1. Open Visual Studio Installer from the Windows Start menu, or by selecting Tools > Get Tools and Features from the menu bar in Visual Studio.

    Visual Studio Installer opens.

  2. Select the Individual components tab, and then scroll down to the Code tools category.

  3. Select Class Designer and then select Modify.

Visual Studio Installer Window

The Class Designer component starts installing.

For more details, visit this link: How to: Add class diagrams to projects

How to get the scroll bar with CSS overflow on iOS

I have done some testing and using CSS3 to redefine the scrollbars works and you get to keep your Overflow:scroll; or Overflow:auto

I ended up with something like this...

::-webkit-scrollbar {
    width: 15px;
    height: 15px;
    border-bottom: 1px solid #eee; 
    border-top: 1px solid #eee;
}
::-webkit-scrollbar-thumb {
    border-radius: 8px;
    background-color: #C3C3C3;
    border: 2px solid #eee;
}

::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.2); 
} 

The only down side which I have not yet been able to figure out is how to interact with the scrollbars on iProducts but you can interact with the content to scroll it

How to download source in ZIP format from GitHub?

Sometimes if the 'Download ZIP' button is not available, you can click on 'Raw' and the file should download to your system.

How do I Sort a Multidimensional Array in PHP

I know it's 2 years since this question was asked and answered, but here's another function that sorts a two-dimensional array. It accepts a variable number of arguments, allowing you to pass in more than one key (ie column name) to sort by. PHP 5.3 required.

function sort_multi_array ($array, $key)
{
  $keys = array();
  for ($i=1;$i<func_num_args();$i++) {
    $keys[$i-1] = func_get_arg($i);
  }

  // create a custom search function to pass to usort
  $func = function ($a, $b) use ($keys) {
    for ($i=0;$i<count($keys);$i++) {
      if ($a[$keys[$i]] != $b[$keys[$i]]) {
        return ($a[$keys[$i]] < $b[$keys[$i]]) ? -1 : 1;
      }
    }
    return 0;
  };

  usort($array, $func);

  return $array;
}

Try it here: http://www.exorithm.com/algorithm/view/sort_multi_array

How do I get a UTC Timestamp in JavaScript?

If you want a one liner, The UTC Unix Timestamp can be created in JavaScript as:

var currentUnixTimestap = ~~(+new Date() / 1000);

This will take in account the timezone of the system. It is basically time elapsed in Seconds since epoch.

How it works:

  • Create date object : new Date().
  • Convert to timestamp by adding unary + before object creation to convert it to timestamp integer. : +new Date().
  • Convert milliseconds to seconds: +new Date() / 1000
  • Use double tildes to round off the value to integer. : ~~(+new Date())

Sqlite convert string to date

This is for fecha(TEXT) format date YYYY-MM-dd HH:mm:ss for instance I want all the records of Ene-05-2014 (2014-01-05):

SELECT 
 fecha 
FROM 
 Mytable 
WHERE 
 DATE(substr(fecha ,1,4) ||substr(fecha ,6,2)||substr(fecha ,9,2))
BETWEEN 
 DATE(20140105) 
AND 
 DATE(20140105);

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

String.Format like functionality in T-SQL?

here's what I found with my experiments using the built-in

FORMATMESSAGE() function

sp_addmessage @msgnum=50001,@severity=1,@msgText='Hello %s you are #%d',@replace='replace'
SELECT FORMATMESSAGE(50001, 'Table1', 5)

when you call up sp_addmessage, your message template gets stored into the system table master.dbo.sysmessages (verified on SQLServer 2000).

You must manage addition and removal of template strings from the table yourself, which is awkward if all you really want is output a quick message to the results screen.

The solution provided by Kathik DV, looks interesting but doesn't work with SQL Server 2000, so i altered it a bit, and this version should work with all versions of SQL Server:

IF OBJECT_ID( N'[dbo].[FormatString]', 'FN' ) IS NOT NULL
    DROP FUNCTION [dbo].[FormatString]
GO
/***************************************************
Object Name : FormatString
Purpose : Returns the formatted string.
Original Author : Karthik D V http://stringformat-in-sql.blogspot.com/
Sample Call:
SELECT dbo.FormatString ( N'Format {0} {1} {2} {0}', N'1,2,3' )
*******************************************/
CREATE FUNCTION [dbo].[FormatString](
@Format NVARCHAR(4000) ,
@Parameters NVARCHAR(4000)
)
RETURNS NVARCHAR(4000)
AS
BEGIN
    --DECLARE @Format NVARCHAR(4000), @Parameters NVARCHAR(4000) select @format='{0}{1}', @Parameters='hello,world'
    DECLARE @Message NVARCHAR(400), @Delimiter CHAR(1)
    DECLARE @ParamTable TABLE ( ID INT IDENTITY(0,1), Parameter VARCHAR(1000) )
    Declare @startPos int, @endPos int
    SELECT @Message = @Format, @Delimiter = ','

    --handle first parameter
     set @endPos=CHARINDEX(@Delimiter,@Parameters)
    if (@endPos=0 and @Parameters is not null) --there is only one parameter
        insert into @ParamTable (Parameter) values(@Parameters)
    else begin
        insert into @ParamTable (Parameter) select substring(@Parameters,0,@endPos)
    end

    while @endPos>0
    Begin
        --insert a row for each parameter in the 
        set @startPos = @endPos + LEN(@Delimiter)
        set @endPos = CHARINDEX(@Delimiter,@Parameters, @startPos)
        if (@endPos>0)
            insert into @ParamTable (Parameter) select substring(@Parameters,@startPos,@endPos)
        else
            insert into @ParamTable (Parameter) select substring(@Parameters,@startPos,4000)            
    End

    UPDATE @ParamTable SET @Message = REPLACE ( @Message, '{'+CONVERT(VARCHAR,ID) + '}', Parameter )
    RETURN @Message
END
Go
    grant execute,references on dbo.formatString to public

Usage:

print dbo.formatString('hello {0}... you are {1}','world,good')
--result: hello world... you are good

How to change the sender's name or e-mail address in mutt?

One special case for this is if you have used a construction like the following in your ~/.muttrc:

# Reset From email to default
send-hook . "my_hdr From: Real Name <[email protected]>"

This send-hook will override either of these:

mutt -e "set [email protected]"
mutt -e "my_hdr From: Other Name <[email protected]>"

Your emails will still go out with the header:

From: Real Name <[email protected]>

In this case, the only command line solution I've found is actually overriding the send-hook itself:

mutt -e "send-hook . \"my_hdr From: Other Name <[email protected]>\""

Is try-catch like error handling possible in ASP Classic?

Been a while since I was in ASP land, but iirc there's a couple of ways:

try catch finally can be reasonably simulated in VBS (good article here here) and there's an event called class_terminate you can watch and catch exceptions globally in. Then there's the possibility of changing your scripting language...

calling another method from the main method in java

First java will not allow you to have do() method. Instead you can make it doOperation().

Second You cann't invoke directly non static methods from static function. Main is a static function. You need to instantiate the class first and then invoke method using that instance.

Third you can invoke static method directly from non static methods.

Passing in class names to react components

pill ${this.props.styleName} will get "pill undefined" when you don't set the props

I prefer

className={ "pill " + ( this.props.styleName || "") }

or

className={ "pill " + ( this.props.styleName ? this.props.styleName : "") }

Windows 7 environment variable not working in path

%M2% and %JAVA_HOME% need to be added to a PATH variable in the USER variables, not the SYSTEM variables.

Formatting a double to two decimal places

The problem is that when you are doing additions and multiplications of numbers all with two decimal places, you expect there will be no rounding errors, but remember the internal representation of double is in base 2, not in base 10 ! So a number like 0.1 in base 10 may be in base 2 : 0.101010101010110011... with an infinite number of decimals (the value stored in the double will be a number N with :

 0.1-Math.Pow(2,-64) < N < 0.1+Math.Pow(2,-64) 

As a consequence an operation like 12.3 + 0.1 may be not the same exact 64 bits double value as 12.4 (or 12.456 * 10 may be not the same as 124.56) because of rounding errors. For example if you store in a Database the result of 12.3 +0.1 into a table/column field of type double precision number and then SELECT WHERE xx=12.4 you may realize that you stored a number that is not exactly 12.4 and the Sql select will not return the record; So if you cannot use the decimal datatype (which has internal representation in base 10) and must use the 'double' datatype, you have to do some normalization after each addition or multiplication :

double freqMHz= freqkHz.MulRound(0.001); // freqkHz*0.001
double amountEuro= amountEuro.AddRound(delta); // amountEuro+delta


    public static double AddRound(this double d,double val)
    {
        return double.Parse(string.Format("{0:g14}", d+val));
    }
    public static double MulRound(this double d,double val)
    {
        return double.Parse(string.Format("{0:g14}", d*val));
    }

Difference between Visibility.Collapsed and Visibility.Hidden

Visibility : Hidden Vs Collapsed

Consider following code which only shows three Labels and has second Label visibility as Collapsed:

 <StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Center">
    <StackPanel.Resources>
        <Style TargetType="Label">
            <Setter Property="Height" Value="30" />
            <Setter Property="Margin" Value="0"/>
            <Setter Property="BorderBrush" Value="Black"/>
            <Setter Property="BorderThickness" Value="1" />
        </Style>
    </StackPanel.Resources>
    <Label Width="50" Content="First"/>
    <Label Width="50" Content="Second" Visibility="Collapsed"/>
    <Label Width="50" Content="Third"/>
</StackPanel>

Output Collapsed:

Collapsed

Now change the second Label visibility to Hiddden.

<Label Width="50" Content="Second" Visibility="Hidden"/>

Output Hidden:

Hidden

As simple as that.

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

Even though the question is too old, but I would like to share the solution that worked for me because I already checked everything when it comes to this error. It was a pain, I spent two days trying and at the end the solution was:

update the M2e plugin in eclipse

clean and build again

Python - 'ascii' codec can't decode byte

If you're using Python < 3, you'll need to tell the interpreter that your string literal is Unicode by prefixing it with a u:

Python 2.7.2 (default, Jan 14 2012, 23:14:09) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> "??".encode("utf8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'

Further reading: Unicode HOWTO.

TypeError: a bytes-like object is required, not 'str'

Whenever you encounter an error with this message use my_string.encode().

(where my_string is the string you're passing to a function/method).

The encode method of str objects returns the encoded version of the string as a bytes object which you can then use. In this specific instance, socket methods such as .send expect a bytes object as the data to be sent, not a string object.

Since you have an object of type str and you're passing it to a function/method that expects an object of type bytes, an error is raised that clearly explains that:

TypeError: a bytes-like object is required, not 'str'

So the encode method of strings is needed, applied on a str value and returning a bytes value:

>>> s = "Hello world"
>>> print(type(s))
<class 'str'>
>>> byte_s = s.encode()
>>> print(type(byte_s))
<class 'bytes'>
>>> print(byte_s)
b"Hello world"

Here the prefix b in b'Hello world' denotes that this is indeed a bytes object. You can then pass it to whatever function is expecting it in order for it to run smoothly.

Code signing is required for product type 'Application' in SDK 'iOS5.1'

One possible solution which works for me:

  1. Search "code sign" in Build settings
  2. Change everything in code signing identity to "iOS developer", which are "Don't code sign" originally.

Bravo!

C++ - unable to start correctly (0xc0150002)

I take it that is a Vista Window! I often got this when first trying to port a DirectX program from XPsp3 to Vista.

It's a .dll problem. The OpenCV runtime.dll will call upon a system.dll that will be no longer shipped Vista, so unfortunately you will have to to a bit of hunting to find which system.dll it's trying to find. (system.dll could be vc2010 or vista)

This error is also caused by incorrect installation of .dlls (i.e not rolling out) hth Happy hunting

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.

Date.prototype.getISOTimezoneOffset = function () {
    const offset = this.getTimezoneOffset();
    return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);
}

Date.prototype.toISOLocaleString = function () {
    return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
        this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
        this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +
        this.getMilliseconds().leftPad(3);
}

Number.prototype.leftPad = function (size) {
    var s = String(this);
    while (s.length < (size || 2)) {
        s = "0" + s;
    }
    return s;
}

Example usage:

var date = new Date();
console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
// Prints "2020-08-05T16:15:46.525+10:00"

I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.

(The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString for anyone without said library.)

UML diagram shapes missing on Visio 2013

Software & Database is usually not in the Standard edition of Visio, only the Pro version.

Try looking here for some templates that will work in standard edition

TransactionRequiredException Executing an update/delete query

The same exception occurred to me in a somewhat different situation. Since I've been searching here for an answer, maybe it'll help somebody.

I my case the exception has been happening because I called the (properly annotated) @Transactional method from a SERVICE CONSTRUCTOR... Since my idea was simply to make this method run at the start, I annotated it as following, and stopped calling in a wrong way. Exception is gone, and code is better :)

@EventListener(ContextRefreshedEvent.class)
@Transactional
public void methodName() {...}

@Transactional import: import org.springframework.transaction.annotation.Transactional;

Get button click inside UITableViewCell

// Add action in cell for row at index path -tableView

cell.buttonName.addTarget(self, action: #selector(ViewController.btnAction(_:)), for: .touchUpInside)

// Button Action

  @objc func btnAction(_ sender: AnyObject) {



        var position: CGPoint = sender.convert(.zero, to: self.tableView)


        let indexPath = self.tableView.indexPathForRow(at: position)
        let cell: UITableViewCell = tableView.cellForRow(at: indexPath!)! as
        UITableViewCell




}

Send text to specific contact programmatically (whatsapp)

This will first search for the specified contact and then open a chat window. And if WhatsApp is not installed then try-catch block handle this.

    String digits = "\\d+";
    String mob_num = "987654321";     
    if (mob_num.matches(digits)) 
            {
        try {
              //linking for whatsapp
              Uri uri = Uri.parse("whatsapp://send?phone=+91" + mob_num);
              Intent i = new Intent(Intent.ACTION_VIEW, uri);
              startActivity(i);
            }
            catch (ActivityNotFoundException e){
                    e.printStackTrace();
                    //if you're in anonymous class pass context like "YourActivity.this"
                    Toast.makeText(this, "WhatsApp not installed.", Toast.LENGTH_SHORT).show();
            }
        }

Java: Literal percent sign in printf statement

Escaped percent sign is double percent (%%):

System.out.printf("2 out of 10 is %d%%", 20);

How to display 3 buttons on the same line in css

Do something like this,

HTML :

<div style="width:500px;">
    <button type="submit" class="msgBtn" onClick="return false;" >Save</button>
    <button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
    <button class="msgBtnBack">Back</button>
</div>

CSS :

div button{
    display:inline-block;
}

Fiddle Demo

Or

HTML :

<div style="width:500px;" id="container">
    <div><button type="submit" class="msgBtn" onClick="return false;" >Save</button></div>
    <div><button type="submit" class="msgBtn2" onClick="return false;">Publish</button></div>
    <div><button class="msgBtnBack">Back</button></div>
</div>

CSS :

#container div{
    display:inline-block;
    width:130px;
}

Fiddle Demo

Iterate through string array in Java

You have to maintain the serial how many times you are accessing the array.Use like this

int lookUpTime=0;

    for(int i=lookUpTime;i<lookUpTime+2 && i<elements.length();i++)
     {
    // do something with elements[i]
    }

lookUpTime++;

jquery multiple checkboxes array

This way will let you add or remove values when you check or uncheck any checkbox named as options[]:

var checkedValues = [];
$("input[name='options[]']").change(function() {
    const intValue = parseInt($(this).val());
    if ($(this).is(':checked')) {
        checkedValues.push(value);
    } else {
        const index = checkedValues.indexOf(value);
        if (index > -1) {
           checkedValues.splice(index, 1);
        }
    }
 });

How to use zIndex in react-native

I finally solved this by creating a second object that imitates B.

My schema now looks like this:

enter image description here

I now have B1 (within parent of A) and B2 outside of it.

B1 and B2 are right next to one another, so to the naked eye it looks as if it's just 1 object.

JavaScript: Global variables after Ajax requests

It seems that your problem is simply a concurrency issue. The post function takes a callback argument to tell you when the post has been finished. You cannot make the alert in global scope like this and expect that the post has already been finished. You have to move it to the callback function.

CodeIgniter - File upload required validation

I found a solution that works exactly how I want.

I changed

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'required');

To

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
    $this->form_validation->set_rules('userfile', 'Document', 'required');
}

RegEx to extract all matches from string using RegExp.exec

To loop through all matches, you can use the replace function:

var re = /\s*([^[:]+):\"([^"]+)"/g;
var s = '[description:"aoeu" uuid:"123sth"]';

s.replace(re, function(match, g1, g2) { console.log(g1, g2); });

Reset the Value of a Select Box

use the .val('') setter

jsfiddle example

$('select').val('1');

How to remove elements/nodes from angular.js array

Because when you do shift() on an array, it changes the length of the array. So the for loop will be messed up. You can loop through from end to front to avoid this problem.

Btw, I assume you try to remove the element at the position i rather than the first element of the array. ($scope.items.shift(); in your code will remove the first element of the array)

for(var i = $scope.items.length - 1; i >= 0; i--){
    if($scope.items[i].name == 'ted'){
        $scope.items.splice(i,1);
    }
}

How to get the name of the current method from code

Since C# version 6 you can simply call:

string currentMethodName = nameof(MyMethod);

In C# version 5 and .NET 4.5 you can use the [CallerMemberName] attribute to have the compiler auto-generate the name of the calling method in a string argument. Other useful attributes are [CallerFilePath] to have the compiler generate the source code file path and [CallerLineNumber] to get the line number in the source code file for the statement that made the call.


Before that there were still some more convoluted ways of getting the method name, but much simpler:

void MyMethod() {
  string currentMethodName = "MyMethod";
  //etc...
}

Albeit that a refactoring probably won't fix it automatically.

If you completely don't care about the (considerable) cost of using Reflection then this helper method should be useful:

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Reflection;
//...

[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetMyMethodName() {
  var st = new StackTrace(new StackFrame(1));
  return st.GetFrame(0).GetMethod().Name;
} 

Oracle PL/SQL string compare issue

To the first question:

Probably the message wasn't print out because you have the output turned off. Use these commands to turn it back on:

set serveroutput on
exec dbms_output.enable(1000000);

On the second question:

My PLSQL is quite rusty so I can't give you a full snippet, but you'll need to loop over the result set of the SQL query and CONCAT all the strings together.

How to use the unsigned Integer in Java 8 and Java 9?

Per the documentation you posted, and this blog post - there's no difference when declaring the primitive between an unsigned int/long and a signed one. The "new support" is the addition of the static methods in the Integer and Long classes, e.g. Integer.divideUnsigned. If you're not using those methods, your "unsigned" long above 2^63-1 is just a plain old long with a negative value.

From a quick skim, it doesn't look like there's a way to declare integer constants in the range outside of +/- 2^31-1, or +/- 2^63-1 for longs. You would have to manually compute the negative value corresponding to your out-of-range positive value.

Split text with '\r\n'

This worked for me.

string stringSeparators = "\r\n";
string text = sr.ReadToEnd();
string lines = text.Replace(stringSeparators, "");
lines = lines.Replace("\\r\\n", "\r\n");
Console.WriteLine(lines);

The first replace replaces the \r\n from the text file's new lines, and the second replaces the actual \r\n text that is converted to \\r\\n when the files is read. (When the file is read \ becomes \\).

Python-equivalent of short-form "if" in C++

While a = 'foo' if True else 'bar' is the more modern way of doing the ternary if statement (python 2.5+), a 1-to-1 equivalent of your version might be:

a = (b == True and "123" or "456" )

... which in python should be shortened to:

a = b is True and "123" or "456"

... or if you simply want to test the truthfulness of b's value in general...

a = b and "123" or "456"

? : can literally be swapped out for and or

Is it safe to delete the "InetPub" folder?

As long as you go into the IIS configuration and change the default location from %SystemDrive%\InetPub to %SystemDrive%\www for each of the services (web, ftp) there shouldn't be any problems. Of course, you can't protect against other applications that might install stuff into that directory by default, instead of checking the configuration.

My recommendation? Don't change it -- it's not that hard to live with, and it reduces the confusion level for the next person who has to administrate the machine.

Creating and returning Observable from Angular 2 Service

UPDATE: 9/24/16 Angular 2.0 Stable

This question gets a lot of traffic still, so, I wanted to update it. With the insanity of changes from Alpha, Beta, and 7 RC candidates, I stopped updating my SO answers until they went stable.

This is the perfect case for using Subjects and ReplaySubjects

I personally prefer to use ReplaySubject(1) as it allows the last stored value to be passed when new subscribers attach even when late:

let project = new ReplaySubject(1);

//subscribe
project.subscribe(result => console.log('Subscription Streaming:', result));

http.get('path/to/whatever/projects/1234').subscribe(result => {
    //push onto subject
    project.next(result));

    //add delayed subscription AFTER loaded
    setTimeout(()=> project.subscribe(result => console.log('Delayed Stream:', result)), 3000);
});

//Output
//Subscription Streaming: 1234
//*After load and delay*
//Delayed Stream: 1234

So even if I attach late or need to load later I can always get the latest call and not worry about missing the callback.

This also lets you use the same stream to push down onto:

project.next(5678);
//output
//Subscription Streaming: 5678

But what if you are 100% sure, that you only need to do the call once? Leaving open subjects and observables isn't good but there's always that "What If?"

That's where AsyncSubject comes in.

let project = new AsyncSubject();

//subscribe
project.subscribe(result => console.log('Subscription Streaming:', result),
                  err => console.log(err),
                  () => console.log('Completed'));

http.get('path/to/whatever/projects/1234').subscribe(result => {
    //push onto subject and complete
    project.next(result));
    project.complete();

    //add a subscription even though completed
    setTimeout(() => project.subscribe(project => console.log('Delayed Sub:', project)), 2000);
});

//Output
//Subscription Streaming: 1234
//Completed
//*After delay and completed*
//Delayed Sub: 1234

Awesome! Even though we closed the subject it still replied with the last thing it loaded.

Another thing is how we subscribed to that http call and handled the response. Map is great to process the response.

public call = http.get(whatever).map(res => res.json())

But what if we needed to nest those calls? Yes you could use subjects with a special function:

getThing() {
    resultSubject = new ReplaySubject(1);

    http.get('path').subscribe(result1 => {
        http.get('other/path/' + result1).get.subscribe(response2 => {
            http.get('another/' + response2).subscribe(res3 => resultSubject.next(res3))
        })
    })
    return resultSubject;
}
var myThing = getThing();

But that's a lot and means you need a function to do it. Enter FlatMap:

var myThing = http.get('path').flatMap(result1 => 
                    http.get('other/' + result1).flatMap(response2 => 
                        http.get('another/' + response2)));

Sweet, the var is an observable that gets the data from the final http call.

OK thats great but I want an angular2 service!

I got you:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ReplaySubject } from 'rxjs';

@Injectable()
export class ProjectService {

  public activeProject:ReplaySubject<any> = new ReplaySubject(1);

  constructor(private http: Http) {}

  //load the project
  public load(projectId) {
    console.log('Loading Project:' + projectId, Date.now());
    this.http.get('/projects/' + projectId).subscribe(res => this.activeProject.next(res));
    return this.activeProject;
  }

 }

 //component

@Component({
    selector: 'nav',
    template: `<div>{{project?.name}}<a (click)="load('1234')">Load 1234</a></div>`
})
 export class navComponent implements OnInit {
    public project:any;

    constructor(private projectService:ProjectService) {}

    ngOnInit() {
        this.projectService.activeProject.subscribe(active => this.project = active);
    }

    public load(projectId:string) {
        this.projectService.load(projectId);
    }

 }

I'm a big fan of observers and observables so I hope this update helps!

Original Answer

I think this is a use case of using a Observable Subject or in Angular2 the EventEmitter.

In your service you create a EventEmitter that allows you to push values onto it. In Alpha 45 you have to convert it with toRx(), but I know they were working to get rid of that, so in Alpha 46 you may be able to simply return the EvenEmitter.

class EventService {
  _emitter: EventEmitter = new EventEmitter();
  rxEmitter: any;
  constructor() {
    this.rxEmitter = this._emitter.toRx();
  }
  doSomething(data){
    this.rxEmitter.next(data);
  }
}

This way has the single EventEmitter that your different service functions can now push onto.

If you wanted to return an observable directly from a call you could do something like this:

myHttpCall(path) {
    return Observable.create(observer => {
        http.get(path).map(res => res.json()).subscribe((result) => {
            //do something with result. 
            var newResultArray = mySpecialArrayFunction(result);
            observer.next(newResultArray);
            //call complete if you want to close this stream (like a promise)
            observer.complete();
        });
    });
}

That would allow you do this in the component: peopleService.myHttpCall('path').subscribe(people => this.people = people);

And mess with the results from the call in your service.

I like creating the EventEmitter stream on its own in case I need to get access to it from other components, but I could see both ways working...

Here's a plunker that shows a basic service with an event emitter: Plunkr

Eclipse error ... cannot be resolved to a type

For maven users:

  • Right click on the project
  • Maven
  • Update Project

How to resize superview to fit all subviews with autolayout?

You can do this by creating a constraint and connecting it via interface builder

See explanation: Auto_Layout_Constraints_in_Interface_Builder

raywenderlich beginning-auto-layout

AutolayoutPG Articles constraint Fundamentals

@interface ViewController : UIViewController {
    IBOutlet NSLayoutConstraint *leadingSpaceConstraint;
    IBOutlet NSLayoutConstraint *topSpaceConstraint;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leadingSpaceConstraint;

connect this Constraint outlet with your sub views Constraint or connect super views Constraint too and set it according to your requirements like this

 self.leadingSpaceConstraint.constant = 10.0;//whatever you want to assign

I hope this clarifies it.

Pass multiple complex objects to a post/put Web API method

You could try posting multipart content from the client like this:

 using (var httpClient = new HttpClient())
{
    var uri = new Uri("http://example.com/api/controller"));

    using (var formData = new MultipartFormDataContent())
    {
        //add content to form data
        formData.Add(new StringContent(JsonConvert.SerializeObject(content)), "Content");

        //add config to form data
        formData.Add(new StringContent(JsonConvert.SerializeObject(config)), "Config");

        var response = httpClient.PostAsync(uri, formData);
        response.Wait();

        if (!response.Result.IsSuccessStatusCode)
        {
            //error handling code goes here
        }
    }
}

On the server side you could read the the content like this:

public async Task<HttpResponseMessage> Post()
{
    //make sure the post we have contains multi-part data
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    //read data
    var provider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(provider);

    //declare backup file summary and file data vars
    var content = new Content();
    var config = new Config();

    //iterate over contents to get Content and Config
    foreach (var requestContents in provider.Contents)
    {
        if (requestContents.Headers.ContentDisposition.Name == "Content")
        {
            content = JsonConvert.DeserializeObject<Content>(requestContents.ReadAsStringAsync().Result);
        }
        else if (requestContents.Headers.ContentDisposition.Name == "Config")
        {
            config = JsonConvert.DeserializeObject<Config>(requestContents.ReadAsStringAsync().Result);
        }
    }

    //do something here with the content and config and set success flag
    var success = true;

    //indicate to caller if this was successful
    HttpResponseMessage result = Request.CreateResponse(success ? HttpStatusCode.OK : HttpStatusCode.InternalServerError, success);
    return result;

}

}

Lost httpd.conf file located apache

Get the path of running Apache

$ ps -ef | grep apache
apache   12846 14590  0 Oct20 ?        00:00:00 /usr/sbin/apache2

Append -V argument to the path

$ /usr/sbin/apache2 -V | grep SERVER_CONFIG_FILE
-D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"

Reference:
http://commanigy.com/blog/2011/6/8/finding-apache-configuration-file-httpd-conf-location

Prepend line to beginning of a file

The clear way to do this is as follows if you do not mind writing the file again

with open("a.txt", 'r+') as fp:
    lines = fp.readlines()     # lines is list of line, each element '...\n'
    lines.insert(0, one_line)  # you can use any index if you know the line index
    fp.seek(0)                 # file pointer locates at the beginning to write the whole file again
    fp.writelines(lines)       # write whole lists again to the same file

Note that this is not in-place replacement. It's writing a file again.

In summary, you read a file and save it to a list and modify the list and write the list again to a new file with the same filename.

Select option padding not working in chrome

Not padding but if your goal is to simply make it larger, you can increase the font-size. And using it with font-size-adjust reduces the font-size back to normal on select and not on options, so it ends up making the option larger.

Not sure if it works on all browsers, or will keep working in current.

Tested on Chrome 85 & Firefox 81.

screenshot (on Firefox)

_x000D_
_x000D_
select {
    font-size: 2em;
    font-size-adjust: 0.3;
}
_x000D_
<label>
  Select: <select>
            <option>Option 1</option>
            <option>Option 2</option>
            <option>Option 3</option>
          </select>
</label>
_x000D_
_x000D_
_x000D_

How to get second-highest salary employees in a table

Try this: This will give dynamic results irrespective of no of rows

SELECT * FROM emp WHERE salary = (SELECT max(e1.salary) 
FROM emp e1 WHERE e1.salary < (SELECT Max(e2.salary) FROM emp e2))**

Best Practices for Custom Helpers in Laravel 5

Create Helpers.php in app/Helper/Helpers.php

namespace App\Helper
class Helpers
{


}

Add in composer and composer update

 "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories",
            "database","app/Helper/Helpers.php"
        ],
        "psr-4": {
            "App\\": "app/"
        },
         "files": ["app/Helper/Helpers.php"]
    },

use in Controller

use App\Helper\Helpers

use in view change in config->app.php file

   'aliases' => [
    ...
    'Helpers'   => 'App\Helper\Helpers'
    ],

call in view

<?php echo Helpers::function_name();  ?>

What is the best way to calculate a checksum for a file that is on my machine?

Note that the above solutions will not tell you if your installation is correct only if your install.exe is correct (you can trust it to produce a correct install.)

You would need MD5 sums for each file/folder to test if the installed code has been messed with after the install completed.

WinMerg is useful to compare two installs (on two different machines perhaps) to see if one has been changed or why one is broken.

How to remove element from array in forEach loop?

The following will give you all the elements which is not equal to your special characters!

review = jQuery.grep( review, function ( value ) {
    return ( value !== '\u2022 \u2022 \u2022' );
} );

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

Run-time error '3061'. Too few parameters. Expected 1. (Access 2007)

Does the query has more than the parameter siteID, becouse if you want to run the query one parameter still isn't filled witch gives you the error

Why must wait() always be in synchronized block

This basically has to do with the hardware architecture (i.e. RAM and caches).

If you don't use synchronized together with wait() or notify(), another thread could enter the same block instead of waiting for the monitor to enter it. Moreover, when e.g. accessing an array without a synchronized block, another thread may not see the changement to it...actually another thread will not see any changements to it when it already has a copy of the array in the x-level cache (a.k.a. 1st/2nd/3rd-level caches) of the thread handling CPU core.

But synchronized blocks are only one side of the medal: If you actually access an object within a synchronized context from a non-synchronized context, the object still won't be synchronized even within a synchronized block, because it holds an own copy of the object in its cache. I wrote about this issues here: https://stackoverflow.com/a/21462631 and When a lock holds a non-final object, can the object's reference still be changed by another thread?

Furthermore, I'm convinced that the x-level caches are responsible for most non-reproducible runtime errors. That's because the developers usually don't learn the low-level stuff, like how CPU's work or how the memory hierarchy affects the running of applications: http://en.wikipedia.org/wiki/Memory_hierarchy

It remains a riddle why programming classes don't start with memory hierarchy and CPU architecture first. "Hello world" won't help here. ;)

How to scale Docker containers in production

Have a look at Rancher.com - it can manage multiple Docker hosts and much more.

How do I set the colour of a label (coloured text) in Java?

You can set the color of a JLabel by altering the foreground category:

JLabel title = new JLabel("I love stackoverflow!", JLabel.CENTER);

title.setForeground(Color.white);

As far as I know, the simplest way to create the two-color label you want is to simply make two labels, and make sure they get placed next to each other in the proper order.

Return different type of data from a method in java?

the approach you took is good. Just Implementation may need to be better. For instance ReturningValues should be well defined and Its better if you can make ReturningValues as immutable.

// this approach is better
public static ReturningValues myMethod() {
    ReturningValues rv = new ReturningValues("value", 12);
    return rv;
}


public final class ReturningValues {
    private final String value;
    private final int index;


    public ReturningValues(String value, int index) {
      this.value = value;
      this.index = index;
     }

} 

Or if you have lots of key value pairs you can use HashMap then

public static Map<String,Object> myMethod() {
  Map<String,Object> map = new HashMap<String,Object>();
  map.put(VALUE, "value");
  map.put(INDEX, 12);
  return Collections.unmodifiableMap(map); // try to use this 
}

Why cannot change checkbox color whatever I do?

I had the same issue, trying to use large inputs and had a very small checkbox. After some searching, this is good enough for my needs:

input[type='checkbox']{
  width: 30px !important;
  height: 30px !important;
  margin: 5px;
  -webkit-appearance: none;
  -moz-appearance: none;
  -o-appearance: none;
  appearance:none;
  outline: 2px solid lightblue;
  box-shadow: none;
  font-size: 2em;
}

JSFiddle

Maybe someone will find it useful.

Can I create links with 'target="_blank"' in Markdown?

With Markdown-2.5.2, you can use this:

[link](url){:target="_blank"}

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

Follow these steps:
Right click on designing part > Constraint Layout > Infer Constraints

What does LINQ return when the results are empty

.ToList returns an empty list. (same as new List() );

Spring Boot yaml configuration for a list of strings

Well, the only thing I can make it work is like so:

servers: >
    dev.example.com,
    another.example.com

@Value("${servers}")
private String[] array;

And dont forget the @Configuration above your class....

Without the "," separation, no such luck...

Works too (boot 1.5.8 versie)

servers: 
       dev.example.com,
       another.example.com

Quick way to retrieve user information Active Directory

Well, if you know where your user lives in the AD hierarchy (e.g. quite possibly in the "Users" container, if it's a small network), you could also bind to the user account directly, instead of searching for it.

DirectoryEntry deUser = new DirectoryEntry("LDAP://cn=John Doe,cn=Users,dc=yourdomain,dc=com");

if (deUser != null)
{
  ... do something with your user
}

And if you're on .NET 3.5 already, you could even use the vastly expanded System.DirectorySrevices.AccountManagement namespace with strongly typed classes for each of the most common AD objects:

// bind to your domain
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "LDAP://dc=yourdomain,dc=com");

// find the user by identity (or many other ways)
UserPrincipal user = UserPrincipal.FindByIdentity(pc, "cn=John Doe");

There's loads of information out there on System.DirectoryServices.AccountManagement - check out this excellent article on MSDN by Joe Kaplan and Ethan Wilansky on the topic.

HTML form action and onsubmit issues

Try

onsubmit="return checkRegistration()"

MySQL: Cloning a MySQL database on the same MySql instance

If you have triggers in your original database, you can avoid the "Trigger already exists" error by piping a replacement before the import:

mysqldump -u olddbuser -p -d olddbname | sed "s/`olddbname`./`newdbname`./" | mysql -u newdbuser -p -D newdbname