Programs & Examples On #Data extraction

How to extract a floating number from a string

I think that you'll find interesting stuff in the following answer of mine that I did for a previous similar question:

https://stackoverflow.com/q/5929469/551449

In this answer, I proposed a pattern that allows a regex to catch any kind of number and since I have nothing else to add to it, I think it is fairly complete

If hasClass then addClass to parent

If anyone is using WordPress, you can use something like:

if (jQuery('.dropdown-menu li').hasClass('active')) {
    jQuery('.current-menu-parent').addClass('current-menu-item');
}

Show a number to two decimal places

Number without round

$double = '21.188624';
echo intval($double) . '.' . substr(end(explode('.', $double)), 0, 2);

Exception: There is already an open DataReader associated with this Connection which must be closed first

You are trying to to an Insert (with ExecuteNonQuery()) on a SQL connection that is used by this reader already:

while (myReader.Read())

Either read all the values in a list first, close the reader and then do the insert, or use a new SQL connection.

Is there an easy way to check the .NET Framework version?

Thank you for this post which was quite useful. I had to tweak it a little in order to check for framework 2.0 because the registry key cannot be converted straightaway to a double. Here is the code:

string[] version_names = rk.GetSubKeyNames();
//version names start with 'v', eg, 'v3.5'
//we also need to take care of strings like v2.0.50727...
string sCurrent = version_names[version_names.Length - 1].Remove(0, 1);
if (sCurrent.LastIndexOf(".") > 1)
{
    string[] sSplit = sCurrent.Split('.');
    sCurrent = sSplit[0] + "." + sSplit[1] + sSplit[2];
}
double dCurrent = Convert.ToDouble(sCurrent, System.Globalization.CultureInfo.InvariantCulture);
double dExpected = Convert.ToDouble(sExpectedVersion);
if (dCurrent >= dExpected)

Python Turtle, draw text with on screen with larger font

Use the optional font argument to turtle.write(), from the docs:

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
 Parameters:

  • arg – object to be written to the TurtleScreen
  • move – True/False
  • align – one of the strings “left”, “center” or right”
  • font – a triple (fontname, fontsize, fonttype)

So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal")) to change the font size to 16 (default is 8).

How to change default timezone for Active Record in Rails?

I had to add this block to my environment.rb file and all was well :)

Rails.application.configure do
    config.time_zone = "Pacific Time (US & Canada)"
    config.active_record.default_timezone = :local
end
  • I added it before the line Rails.application.initialize!

SQL: How to to SUM two values from different tables

For your current structure, you could also try the following:

select cash.Country, cash.Value, cheque.Value, cash.Value + cheque.Value as [Total]
from Cash
join Cheque
on cash.Country = cheque.Country

I think I prefer a union between the two tables, and a group by on the country name as mentioned above.

But I would also recommend normalising your tables. Ideally you'd have a country table, with Id and Name, and a payments table with: CountryId (FK to countries), Total, Type (cash/cheque)

How to compress image size?

Use Compressor (Image compression library). Visit zetbaitsu/Compressor for code and documentation.

  1. add dependency in gradle (app level)

    dependencies {
        implementation 'id.zelory:compressor:3.0.0'
    }
    
  2. To Compress Image use one of these approaches:

  • Compress Image File:

          val compressedImageFile = Compressor.compress(context, actualImageFile)
    
  • Compress Image File to Bitmap:

          val compressedImageFile = Compressor.compress(context, actualImageFile)
          val bitmap = BitmapFactory.decodeFile(compressedImageFile.path)
    

Auto-click button element on page load using jQuery

You can use that and adjust the time you want to launch 1= onload 2000= 2 sec

_x000D_
_x000D_
$(document).ready(function(){
 $('#click').click(function(){
        alert('button clicked');
    });
  // set time out 2 sec
     setTimeout(function(){
        $('#click').trigger('click');
    }, 2000);
});
_x000D_
.container{
padding-top:50px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="col text-center">
<button id="click" class="btn btn-danger">Jquery Auto Click</button>
  </div>
   </div>
_x000D_
_x000D_
_x000D_

Removing path and extension from filename in PowerShell

Starting with PowerShell 6, you get the filename without extension like so:

split-path c:\temp\myfile.txt -leafBase

What are the best practices for using a GUID as a primary key, specifically regarding performance?

This link says it better than I could and helped in my decision making. I usually opt for an int as a primary key, unless I have a specific need not to and I also let SQL server auto-generate/maintain this field unless I have some specific reason not to. In reality, performance concerns need to be determined based on your specific app. There are many factors at play here including but not limited to expected db size, proper indexing, efficient querying, and more. Although people may disagree, I think in many scenarios you will not notice a difference with either option and you should choose what is more appropriate for your app and what allows you to develop easier, quicker, and more effectively (If you never complete the app what difference does the rest make :).

https://web.archive.org/web/20120812080710/http://databases.aspfaq.com/database/what-should-i-choose-for-my-primary-key.html

P.S. I'm not sure why you would use a Composite PK or what benefit you believe that would give you.

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

  1. If Data Consistency is highly important - Use Hashtable or Collections.synchronizedMap(Map).
  2. If speed/performance is highly important and Data Updating can be compromised- Use ConcurrentHashMap.

Change image source with JavaScript

Hi i tried to integrate with your code.

Can you have a look at this?

Thanks M.S

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<!--TODO: need to integrate this code into the project to change images added 05/21/2016:-->_x000D_
_x000D_
<script type="text/javascript">_x000D_
    function changeImage(a) {_x000D_
        document.getElementById("img").src=a;_x000D_
    }_x000D_
</script>_x000D_
_x000D_
_x000D_
 _x000D_
<title> Fluid Selection </title>_x000D_
<!-- css -->_x000D_
 <link rel="stylesheet" href="bootstrap-3/css/bootstrap.min.css">_x000D_
 <link rel="stylesheet" href="css/main.css">_x000D_
<!-- end css -->_x000D_
<!-- Java script files -->_x000D_
<!-- Date.js date os javascript helper -->_x000D_
    <script src="js/date.js"> </script>_x000D_
_x000D_
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->_x000D_
 <script src="js/jquery-2.1.1.min.js"></script>_x000D_
_x000D_
<!-- Include all compiled plugins (below), or include individual files as needed -->_x000D_
 <script src="bootstrap-3/js/bootstrap.min.js"> </script>_x000D_
 <script src="js/library.js"> </script>_x000D_
 <script src="js/sfds.js"> </script>_x000D_
 <script src="js/main.js"> </script>_x000D_
_x000D_
<!-- End Java script files -->_x000D_
_x000D_
<!--added on 05/28/2016-->_x000D_
_x000D_
<style>_x000D_
/* The Modal (background) */_x000D_
.modal {_x000D_
    display: none; /* Hidden by default */_x000D_
    position: fixed; /* Stay in place */_x000D_
    z-index:40001; /* High z-index to ensure it appears above all content */ _x000D_
    padding-top: 100px; /* Location of the box */_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    width: 100%; /* Full width */_x000D_
    height: 100%; /* Full height */_x000D_
    overflow: auto; /* Enable scroll if needed */_x000D_
   _x000D_
    background-color: rgba(0,0,0,0.9); /* Black w/ opacity */_x000D_
}_x000D_
_x000D_
/* Modal Content */_x000D_
.modal-content {_x000D_
    position: relative;_x000D_
    background-color: #fefefe;_x000D_
    margin: auto;_x000D_
    padding: 0;_x000D_
    border: 1px solid #888;_x000D_
    width: 40%;_x000D_
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);_x000D_
    -webkit-animation-name: animatetop;_x000D_
    -webkit-animation-duration: 0.4s;_x000D_
    animation-name: animatetop;_x000D_
    animation-duration: 0.4s_x000D_
 opacity:.5; /* Sets opacity so it's partly transparent */ -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; _x000D_
 /* IE     _x000D_
 transparency */ filter:alpha(opacity=50); /* More IE transparency */ z-index:40001; } _x000D_
}_x000D_
_x000D_
/* Add Animation */_x000D_
@-webkit-keyframes animatetop {_x000D_
    from {top:-300px; opacity:0} _x000D_
    to {top:0; opacity:1}_x000D_
}_x000D_
_x000D_
@keyframes animatetop {_x000D_
    from {top:-300px; opacity:0}_x000D_
    to {top:0; opacity:1}_x000D_
}_x000D_
_x000D_
/* The Close Button */_x000D_
.close {_x000D_
    _x000D_
}_x000D_
_x000D_
.close:hover,_x000D_
.close:focus {_x000D_
    color: #000;_x000D_
    text-decoration: none;_x000D_
    cursor:pointer;_x000D_
}_x000D_
_x000D_
/* The Close Button */_x000D_
.close2 {_x000D_
    _x000D_
}_x000D_
_x000D_
_x000D_
.close2:focus {_x000D_
    color: #000;_x000D_
    text-decoration: none;_x000D_
    cursor:pointer;_x000D_
}_x000D_
_x000D_
.modal-header {_x000D_
 color: #000;_x000D_
    padding: 2px 16px;_x000D_
 }_x000D_
_x000D_
.modal-body {padding: 2px 16px;}_x000D_
 _x000D_
 _x000D_
}_x000D_
_x000D_
.modal-footer {_x000D_
    padding: 2px 16px;_x000D_
    background-color: #000099;_x000D_
    color: white;_x000D_
}_x000D_
_x000D_
_x000D_
</style>_x000D_
_x000D_
<script>_x000D_
 $(document).ready(function() {_x000D_
 _x000D_
 _x000D_
  $("#water").click(function(event){_x000D_
   var $this= $(this);_x000D_
   if($this.hasClass('clicked')){_x000D_
    $this.removeClass('clicked');_x000D_
    SFDS.setFluidType(0);_x000D_
    $this.find('h3').text('Select the H20 Fluid Type');_x000D_
    }else{_x000D_
     SFDS.setFluidType(1);_x000D_
     $this.addClass('clicked');_x000D_
     $this.find('h3').text('H20 Selected');_x000D_
_x000D_
   }_x000D_
  });_x000D_
  _x000D_
  $("#saline").click(function(event){_x000D_
   var $this= $(this);_x000D_
   if($this.hasClass('clicked')){_x000D_
    $this.removeClass('clicked');_x000D_
    SFDS.setFluidType(0);_x000D_
    $this.find('h3').text('Select the NaCL Fluid Type');_x000D_
    }else{_x000D_
     SFDS.setFluidType(1);_x000D_
     $this.addClass('clicked');_x000D_
     $this.find('h3').text('NaCL Selected');_x000D_
     _x000D_
  _x000D_
  _x000D_
   }_x000D_
  });_x000D_
  _x000D_
 });_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<div class="container-fluid">_x000D_
 <header>_x000D_
  <div class="row">_x000D_
   <div class="col-xs-6">_x000D_
    <div id="date"><span class="date_time"></span></div>_x000D_
   </div>_x000D_
   <div class="col-xs-6">_x000D_
    <div id="time" class="text-right"><span class="date_time"></span></div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </header>_x000D_
_x000D_
 <div class="row">_x000D_
  <div class="col-md-offset-1 col-sm-3 col-xs-8 col-xs-offset-2 col-sm-offset-0">_x000D_
   <div id="fluid" class="main_button center-block">_x000D_
    <div class="large_circle_button, main_img"> _x000D_
     <h2>Select<br>Fluid</h2>_x000D_
     <img class="center-block large_button_image" src="images/dropwater.png" alt=""/> _x000D_
    </div>_x000D_
    <h1></h1>_x000D_
   </div>_x000D_
  </div>_x000D_
  <div class=" col-md-6 col-sm-offset-1 col-sm-8 col-xs-12">_x000D_
   <div class="row">_x000D_
    <div class="col-xs-12">_x000D_
     <div id="water" class="large_rectangle_button">_x000D_
      <div class="label_wrapper">_x000D_
       <h3>Sterile<br>Water</h3>_x000D_
      </div>_x000D_
      <div id="thumb_img" class="image_wrapper">_x000D_
       <img src="images/dropsterilewater.png" alt="Sterile Water" class="sterile_water_image" onclick='changeImage("images/dropsterilewater.png");'>_x000D_
      </div>_x000D_
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
     </div>_x000D_
    </div>_x000D_
    <div class="col-xs-12">_x000D_
     <div id="saline" class="large_rectangle_button">_x000D_
      <div class="label_wrapper">_x000D_
       <h3>Sterile<br>0.9% NaCL</h3>_x000D_
      </div>_x000D_
      <div class="image_wrapper">_x000D_
       <img src="images/cansterilesaline.png" alt= "Sterile Saline" class="sterile_salt_image" onclick='changeImage("images/imagecansterilesaline.png");'>_x000D_
      </div>_x000D_
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
     </div>_x000D_
    </div>_x000D_
    <div class="col-xs-12">_x000D_
     <div class="small_rectangle_button">_x000D_
      _x000D_
      <!-- Trigger/Open The Modal -->_x000D_
      <div id="myBtn" class="label_wrapper">_x000D_
       <h3>Change<br>Cartridge</h3>_x000D_
      </div>_x000D_
      <div class="image_wrapper">_x000D_
       <img src="images/changecartridge.png" alt="" class="change_cartrige_image" />_x000D_
      </div>_x000D_
     </div>_x000D_
    </div>_x000D_
    _x000D_
     <!-- The Modal -->_x000D_
     <div id="myModal" class="modal">_x000D_
_x000D_
       <!-- Modal content -->_x000D_
       <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <span class="close"><img src="images/x-icon.png"></span>_x000D_
        <h2>Change Cartridge Instructions</h2>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <h4>Lorem ipsum dolor sit amet, dicant nonumes volutpat cu eum, in nulla molestie vim, nec probo option iracundia ut. Tale inermis scripserit ne cum, his no errem minimum commune, usu accumsan omnesque in. Eu has nihil dolor debitis, ad nobis impedit per. Dicat mnesarchum quo at, debet abhorreant consectetuer sea te, postea adversarium et eos. At alii dicit his, liber tantas suscipit sea in, id pri erat probatus. Vel nostro periculis dissentiet te, ut ubique noster vix. Id honestatis disputationi vel, ne vix assum constituam.</h4>                                                   _x000D_
                           <a href="#"><img src="images/video-icon.png" alt="click here for video"> </a>_x000D_
                           <a href="#close2" title="Close" class="close2"><img src="images/cancel-icon.png" alt="Cancel"></a>_x000D_
_x000D_
                          _x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <h4></h4>_x000D_
      </div>_x000D_
       </div>_x000D_
_x000D_
     </div>_x000D_
     _x000D_
     <!--for comparison-->_x000D_
_x000D_
_x000D_
     _x000D_
_x000D_
     _x000D_
     <script>_x000D_
     // Get the modal_x000D_
     var modal = document.getElementById('myModal');_x000D_
_x000D_
     // Get the button that opens the modal_x000D_
     var btn = document.getElementById("myBtn");_x000D_
_x000D_
     // Get the <span> element that closes the modal_x000D_
     var span = document.getElementsByClassName("close")[0];_x000D_
     _x000D_
_x000D_
     // When the user clicks the button, open the modal _x000D_
     btn.onclick = function() {_x000D_
      modal.style.display = "block";_x000D_
     }_x000D_
_x000D_
     // When the user clicks on <span> (x), close the modal_x000D_
     span.onclick = function() {_x000D_
      modal.style.display = "none";_x000D_
     }_x000D_
_x000D_
     // When the user clicks anywhere outside of the modal, close it_x000D_
     window.onclick = function(event) {_x000D_
      if (event.target == modal) {_x000D_
       modal.style.display = "none";_x000D_
      }_x000D_
      _x000D_
      _x000D_
     }_x000D_
     </script>_x000D_
                    _x000D_
_x000D_
    _x000D_
    _x000D_
    _x000D_
    _x000D_
    _x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
</div>_x000D_
<footer class="footer navbar-fixed-bottom">_x000D_
 <div class="container-fluid">_x000D_
  <div class="row cols-bottom">_x000D_
   <div class="col-sm-3">_x000D_
    <a href="main.html">_x000D_
    <div class="small_circle_button">     _x000D_
     <img src="images/buttonback.png" alt="back to home" class="settings"/> <!--  width="49" height="48" -->_x000D_
    </div>_x000D_
   </div></a><div class=" col-sm-6">_x000D_
    <div id="stop_button" >_x000D_
     <img src="images/stop.png" alt="stop" class="center-block stop_button" /> <!-- width="140" height="128" -->_x000D_
    </div>_x000D_
     _x000D_
   </div><div class="col-sm-3">_x000D_
    <div id="parker" class="pull-right">_x000D_
     <img src="images/parkerlogo.png" alt="parkerlogo" /> <!-- width="131" height="65" -->_x000D_
    </div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
</footer>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

JUnit Testing Exceptions

@Test(expected = Exception.class)  

Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.

For

@Test

Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.

Android SeekBar setOnSeekBarChangeListener

Override all methods

    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {


    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {


    }

    @Override
    public void onStopTrackingTouch(SeekBar arg0) {


    }

Check date with todays date

Using Joda Time this can be simplified to:

DateMidnight startDate = new DateMidnight(startYear, startMonth, startDay);
if (startDate.isBeforeNow())
{
    // startDate is before now
    // do something...
}

How to start/stop/restart a thread in Java?

If your task is performing some kind of action in a loop there is a way to pause/restart processing, but I think it would have to be outside what the Thread API currently offers. If its a single shot process I am not aware of any way to suspend/restart without running into API that has been deprecated or is no longer allowed.

As for looped processes, the easiest way I could think of is that the code that spawns the Task instantiates a ReentrantLock and passes it to the task, as well as keeping a reference itself. Every time the Task enters its loop it attempts a lock on the ReentrantLock instance and when the loop completes it should unlock. You may want to encapsulate all this try/finally, making sure you let go of the lock at the end of the loop, even if an exception is thrown.

If you want to pause the task simply attempt a lock from the main code (since you kept a reference handy). What this will do is wait for the loop to complete and not let it start another iteration (since the main thread is holding a lock). To restart the thread simply unlock from the main code, this will allow the task to resume its loops.

To permanently stop the thread I would use the normal API or leave a flag in the Task and a setter for the flag (something like stopImmediately). When the loop encountered a true value for this flag it stops processing and completes the run method.

How do I download/extract font from chrome developers tools?

If you are on a unixoid operating system and want to extract just a single file you can try the following. The structure of the chrome://cache pages is URL, parsed HTTP header, hex dump of the HTTP header and then hex dump of the payload.

To extract a file copy all payload lines from a Chrome cache page to the clipboard (starting at the second 00000000: ... line), paste them into a text editor and save them as a plain text file (e.g. file.txt). If the payload is a gzipped WOFF file use xxd -r file.txt > file.woff.gz to convert it back to a binary file and gunzip file.woff.gz for decompression.

You can then use woff2otf to convert WOFF files to the OTF format or woff2 to convert WOFF 2.0 files to the TTF format. For batch processing this workflow should obviously be scripted.

__proto__ VS. prototype in JavaScript

In JavaScript, a function can be used as a constructor. That means we can create objects out of them using the new keyword. Every constructor function comes with a built-in object chained with them. This built-in object is called a prototype. Instances of a constructor function use __proto__ to access the prototype property of its constructor function.

prototype diagram

  1. First we created a constructor: function Foo(){}. To be clear, Foo is just another function. But we can create an object from it with the new keyword. That's why we call it the constructor function

  2. Every function has a unique property which is called the prototype property. So, Constructor function Foo has a prototype property which points to its prototype, which is Foo.prototype (see image).

  3. Constructor functions are themselves a function which is an instance of a system constructor called the [[Function]] constructor. So we can say that function Foo is constructed by a [[Function]] constructor. So, __proto__ of our Foo function will point to the prototype of its constructor, which is Function.prototype.

  4. Function.prototype is itself is nothing but an object which is constructed from another system constructor called [[Object]]. So, [[Object]] is the constructor of Function.prototype. So, we can say Function.prototype is an instance of [[Object]]. So __proto__ of Function.prototype points to Object.prototype.

  5. Object.prototype is the last man standing in the prototype chain. I mean it has not been constructed. It's already there in the system. So its __proto__ points to null.

  6. Now we come to instances of Foo. When we create an instance using new Foo(), it creates a new object which is an instance of Foo. That means Foo is the constructor of these instances. Here we created two instances (x and y). __proto__ of x and y thus points to Foo.prototype.

How to find a text inside SQL Server procedures / triggers?

-- Declare the text we want to search for
DECLARE @Text nvarchar(4000);
SET @Text = 'employee';

-- Get the schema name, table name, and table type for:

-- Table names
SELECT
       TABLE_SCHEMA  AS 'Object Schema'
      ,TABLE_NAME    AS 'Object Name'
      ,TABLE_TYPE    AS 'Object Type'
      ,'Table Name'  AS 'TEXT Location'
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%'+@Text+'%'
UNION
 --Column names
SELECT
      TABLE_SCHEMA   AS 'Object Schema'
      ,COLUMN_NAME   AS 'Object Name'
      ,'COLUMN'      AS 'Object Type'
      ,'Column Name' AS 'TEXT Location'
FROM  INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%'+@Text+'%'
UNION
-- Function or procedure bodies
SELECT
      SPECIFIC_SCHEMA     AS 'Object Schema'
      ,ROUTINE_NAME       AS 'Object Name'
      ,ROUTINE_TYPE       AS 'Object Type'
      ,ROUTINE_DEFINITION AS 'TEXT Location'
FROM  INFORMATION_SCHEMA.ROUTINES 
WHERE ROUTINE_DEFINITION LIKE '%'+@Text+'%'
      AND (ROUTINE_TYPE = 'function' OR ROUTINE_TYPE = 'procedure');

Generating a Random Number between 1 and 10 Java

This will work for generating a number 1 - 10. Make sure you import Random at the top of your code.

import java.util.Random;

If you want to test it out try something like this.

Random rn = new Random();

for(int i =0; i < 100; i++)
{
    int answer = rn.nextInt(10) + 1;
    System.out.println(answer);
}

Also if you change the number in parenthesis it will create a random number from 0 to that number -1 (unless you add one of course like you have then it will be from 1 to the number you've entered).

Pretty-Print JSON Data to a File using Python

import json

with open("twitterdata.json", "w") as twitter_data_file:
    json.dump(output, twitter_data_file, indent=4, sort_keys=True)

You don't need json.dumps() if you don't want to parse the string later, just simply use json.dump(). It's faster too.

Select all text inside EditText when it gets focus

I know you've found a solution, but really the proper way to do what you're asking is to just use the android:hint attribute in your EditText. This text shows up when the box is empty and not focused, but disappears upon selecting the EditText box.

What does T&& (double ampersand) mean in C++11?

The term for T&& when used with type deduction (such as for perfect forwarding) is known colloquially as a forwarding reference. The term "universal reference" was coined by Scott Meyers in this article, but was later changed.

That is because it may be either r-value or l-value.

Examples are:

// template
template<class T> foo(T&& t) { ... }

// auto
auto&& t = ...;

// typedef
typedef ... T;
T&& t = ...;

// decltype
decltype(...)&& t = ...;

More discussion can be found in the answer for: Syntax for universal references

How to undo 'git reset'?

Old question, and the posted answers work great. I'll chime in with another option though.

git reset ORIG_HEAD

ORIG_HEAD references the commit that HEAD previously referenced.

Laravel - Pass more than one variable to view

Passing multiple variables to a Laravel view

//Passing variable to view using compact method    
$var1=value1;
$var2=value2;
$var3=value3;
return view('viewName', compact('var1','var2','var3'));

//Passing variable to view using with Method
return view('viewName')->with(['var1'=>value1,'var2'=>value2,'var3'=>'value3']);

//Passing variable to view using Associative Array
return view('viewName', ['var1'=>value1,'var2'=>value2,'var3'=>value3]);

Read here about Passing Data to Views in Laravel

ReactJS - .JS vs .JSX

In most of the cases it’s only a need for the transpiler/bundler, which might not be configured to work with JSX files, but with JS! So you are forced to use JS files instead of JSX.

And since react is just a library for javascript, it makes no difference for you to choose between JSX or JS. They’re completely interchangeable!

In some cases users/developers might also choose JSX over JS, because of code highlighting, but the most of the newer editors are also viewing the react syntax correctly in JS files.

GitLab remote: HTTP Basic: Access denied and fatal Authentication

   git config --system --unset credential.helper

then enter new password for Git remote server.

Calculate last day of month in JavaScript

This works for me. Will provide last day of given year and month:

var d = new Date(2012,02,0);
var n = d.getDate();
alert(n);

Determine the number of lines within a text file

If by easy you mean a lines of code that are easy to decipher but per chance inefficient?

string[] lines = System.IO.File.RealAllLines($filename);
int cnt = lines.Count();

That's probably the quickest way to know how many lines.

You could also do (depending on if you are buffering it in)

#for large files
while (...reads into buffer){
string[] lines = Regex.Split(buffer,System.Enviorment.NewLine);
}

There are other numerous ways but one of the above is probably what you'll go with.

how to overwrite css style

instead of overwriting, create it as different css and call it in your element as other css(multiple css).
Something like:

.flex-control-thumbs li 
{ margin: 0; }

Internal CSS:

.additional li
{width: 25%; float: left;}

<ul class="flex-control-thumbs additional"> </ul> /* assuming parent is ul */

How to get all of the IDs with jQuery?

My suggestion?

var arr = $.map($("#mydiv [id]"), function(n, i) {
  return n.id;
});

you could also do this as:

var arr = $.map($("#mydiv span"), function(n, i) {

or

var arr = $.map($("#mydiv span[id]"), function(n, i) {

or even just:

var arr = $("#mydiv [id]").map(function() {
  return this.id;
});

Lots of ways basically.

How to change the datetime format in pandas

You can use dt.strftime if you need to convert datetime to other formats (but note that then dtype of column will be object (string)):

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
         DOB
0  26/1/2016 
1  26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
         DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-26  01/26/2016

Trigger insert old values- values that was updated

    createTRIGGER [dbo].[Table] ON [dbo].[table] 
FOR UPDATE
AS
    declare @empid int;
    declare @empname varchar(100);
    declare @empsal decimal(10,2);
    declare @audit_action varchar(100);
    declare @old_v varchar(100)

    select @empid=i.Col_Name1 from inserted i;  
    select @empname=i.Col_Name2  from inserted i;   
    select @empsal=i.Col_Name2 from inserted i;
    select @old_v=d.Col_Name from deleted d

    if update(Col_Name1)
        set @audit_action='Updated Record -- After Update Trigger.';
    if update(Col_Name2)
        set @audit_action='Updated Record -- After Update Trigger.';

    insert into Employee_Test_Audit1(Col_name1,Col_name2,Col_name3,Col_name4,Col_name5,Col_name6(Old_values)) 
    values(@empid,@empname,@empsal,@audit_action,getdate(),@old_v);

    PRINT '----AFTER UPDATE Trigger fired-----.'

Regex to check whether a string contains only numbers

\d will not match the decimal point. Use the following for the decimal.

const re = /^\d*(\.\d+)?$/
'123'.match(re)       // true
'123.3'.match(re)     // true
'123!3'.match(re)     // false

How do I extract the contents of an rpm?

Sometimes you can encounter an issue with intermediate RPM archive:

cpio: Malformed number
cpio: Malformed number
cpio: Malformed number
. . .
cpio: premature end of archive

That means it could be packed, these days it is LZMA2 compression as usual, by xz:

rpm2cpio <file>.rpm | xz -d | cpio -idmv

otherwise you could try:

rpm2cpio <file>.rpm | lzma -d | cpio -idmv

How can I create directory tree in C++/Linux?

This is similar to the previous but works forward through the string instead of recursively backwards. Leaves errno with the right value for last failure. If there's a leading slash, there's an extra time through the loop which could have been avoided via one find_first_of() outside the loop or by detecting the leading / and setting pre to 1. The efficiency is the same whether we get set up by a first loop or a pre loop call, and the complexity would be (slightly) higher when using the pre-loop call.

#include <iostream>
#include <string>
#include <sys/stat.h>

int
mkpath(std::string s,mode_t mode)
{
    size_t pos=0;
    std::string dir;
    int mdret;

    if(s[s.size()-1]!='/'){
        // force trailing / so we can handle everything in loop
        s+='/';
    }

    while((pos=s.find_first_of('/',pos))!=std::string::npos){
        dir=s.substr(0,pos++);
        if(dir.size()==0) continue; // if leading / first time is 0 length
        if((mdret=mkdir(dir.c_str(),mode)) && errno!=EEXIST){
            return mdret;
        }
    }
    return mdret;
}

int main()
{
    int mkdirretval;
    mkdirretval=mkpath("./foo/bar",0755);
    std::cout << mkdirretval << '\n';

}

How to use ConfigurationManager

Okay, it took me a while to see this, but there's no way this compiles:

return String.(ConfigurationManager.AppSettings[paramName]);

You're not even calling a method on the String type. Just do this:

return ConfigurationManager.AppSettings[paramName];

The AppSettings KeyValuePair already returns a string. If the name doesn't exist, it will return null.


Based on your edit you have not yet added a Reference to the System.Configuration assembly for the project you're working in.

How to select option in drop down using Capybara

In Capybara you can use only find with xpath

find(:xpath, "//*[@id='organizationSelect']/option[2]").click

and method click

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

php how to go one level up on dirname(__FILE__)

If you happen to have php 7.0+ you could use levels.

dirname( __FILE__, 2 ) with the second parameter you can define the amount of levels you want to go back.

http://php.net/manual/en/function.dirname.php

HTML table with fixed headers and a fixed column?

I have created something which has fixed header, fixed footer, fixed left column and also fixed right column. This only works fine in IE. As most of the users are still using IE this can be helpful. Please find the code here in Scrollable Table. Please let me your suggestions.

Meanwhile I am working to fix columns in other browser. I will keep you posted. :-)

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

This worked for me:

    import re
    text = 'how are u? umberella u! u. U. U@ U# u '
    rex = re.compile(r'\bu\b', re.IGNORECASE)
    print(rex.sub('you', text))

It pre-compiles the regular expression and makes use of re.IGNORECASE so that we don't have to worry about case in our regular expression! BTW, I love the funky spelling of umbrella! :-)

Which data type for latitude and longitude?

In PostGIS, for points with latitude and longitude there is geography datatype.

To add a column:

alter table your_table add column geog geography;

To insert data:

insert into your_table (geog) values ('SRID=4326;POINT(longitude latitude)');

4326 is Spatial Reference ID that says it's data in degrees longitude and latitude, same as in GPS. More about it: http://epsg.io/4326

Order is Longitude, Latitude - so if you plot it as the map, it is (x, y).

To find closest point you need first to create spatial index:

create index on your_table using gist (geog);

and then request, say, 5 closest to a given point:

select * 
from your_table 
order by geog <-> 'SRID=4326;POINT(lon lat)' 
limit 5;

Use string.Contains() with switch()

Some custom swtich can be created like this. Allows multiple case execution as well

public class ContainsSwitch
{

    List<ContainsSwitch> actionList = new List<ContainsSwitch>();
    public string Value { get; set; }
    public Action Action { get; set; }
    public bool SingleCaseExecution { get; set; }
    public void Perform( string target)
    {
        foreach (ContainsSwitch act in actionList)
        {
            if (target.Contains(act.Value))
            {
                act.Action();
                if(SingleCaseExecution)
                    break;
            }
        }
    }
    public void AddCase(string value, Action act)
    {
        actionList.Add(new ContainsSwitch() { Action = act, Value = value });
    }
}

Call like this

string m = "abc";
ContainsSwitch switchAction = new ContainsSwitch();
switchAction.SingleCaseExecution = true;
switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
switchAction.AddCase("d", delegate() { Console.WriteLine("matched d"); });
switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });

switchAction.Perform(m);

Replace multiple characters in a C# string

You may also simply write these string extension methods, and put them somewhere in your solution:

using System.Text;

public static class StringExtensions
{
    public static string ReplaceAll(this string original, string toBeReplaced, string newValue)
    {
        if (string.IsNullOrEmpty(original) || string.IsNullOrEmpty(toBeReplaced)) return original;
        if (newValue == null) newValue = string.Empty;
        StringBuilder sb = new StringBuilder();
        foreach (char ch in original)
        {
            if (toBeReplaced.IndexOf(ch) < 0) sb.Append(ch);
            else sb.Append(newValue);
        }
        return sb.ToString();
    }

    public static string ReplaceAll(this string original, string[] toBeReplaced, string newValue)
    {
        if (string.IsNullOrEmpty(original) || toBeReplaced == null || toBeReplaced.Length <= 0) return original;
        if (newValue == null) newValue = string.Empty;
        foreach (string str in toBeReplaced)
            if (!string.IsNullOrEmpty(str))
                original = original.Replace(str, newValue);
        return original;
    }
}


Call them like this:

"ABCDE".ReplaceAll("ACE", "xy");

xyBxyDxy


And this:

"ABCDEF".ReplaceAll(new string[] { "AB", "DE", "EF" }, "xy");

xyCxyF

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

Had to add the service in the calling App.config file to have it work. Make sure that you but it after all . This seemed to work for me.

Convert NVARCHAR to DATETIME in SQL Server 2008

SELECT CONVERT(NVARCHAR, LoginDate, 105)+' '+CONVERT(NVARCHAR, LoginDate, 108) AS LoginDate FROM YourTable

Output
-------------------
29-08-2013 13:55:48

Loop over html table and get checked checkboxes (JQuery)

use .filter(':has(:checkbox:checked)' ie:

$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
 $('#out').append(this.id);
});

Configure cron job to run every 15 minutes on Jenkins

It should be,

*/15 * * * *  your_command_or_whatever

MAX function in where clause mysql

The syntax you have used is incorrect. The query should be something like:

SELECT column_name(s) FROM tablename WHERE id = (SELECT MAX(id) FROM tablename)

Loading scripts after page load?

The second approach is right to execute JavaScript code after the page has finished loading - but you don't actually execute JavaScript code there, you inserted plain HTML.
The first thing works, but loads the JavaScript immediately and clears the page (so your tag will be there - but nothing else).
(Plus: language="javascript" has been deprecated for years, use type="text/javascript" instead!)

To get that working, you have to use the DOM manipulating methods included in JavaScript. Basically you'll need something like this:

var scriptElement=document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = filename;
document.head.appendChild(scriptElement);

Not connecting to SQL Server over VPN

Make sure SQL Server is enabled for TCP/IP (someone may have disabled it)?

This will also help you to check/verify the port number the SQL instance is using (in case someone changed it from the default of port 1433).

Obviously port 1433 (or whatever port SQL is listening on) needs to be unblocked by any firewalls between your machine and the box SQL is running on.

To check SQL's network configuration (requires SQL Server Client Tools installed): Start -> Programs -> SQL Server 200x -> Configuration Tools -> SQL Server Configuration Manager

Connect to the machine you need then expand the Tree Item (LHS) "SQL Server Network Configuration", then pick instance. You should have four options - Shared Memory, Named Pipes, TCP/IP and VIA. You can check that TCP/IP is enabled in the RHS window.

If you double click TCP/IP and hit the "Advanced" tab, you can also view the Port number.

Other thoughts.. Are you using SQL Authentication or Windows (Domain) authentication?

  • If SQL Authentication (which I assume you are using given you said username and password), are you sure the SQL instance you're connecting to has mixed mode authentication enabled? If not, you have to connect as Administrator and change the default security settings to allow SQL authentication.

  • If Windows Authentication, could your network be using Kerberos potentially? One would think the VPN credentials would be used for the handshake. I'd check your account has appropriate login rights.

How to set a value for a span using jQuery

Syntax:

$(selector).text() returns the text content.

$(selector).text(content) sets the text content.

$(selector).text(function(index, curContent)) sets text content using a function.

kaynak: https://www.geeksforgeeks.org/jquery-change-the-text-of-a-span-element/

Why use Gradle instead of Ant or Maven?

We use Gradle and chose it over Maven and Ant. Ant gave us total flexibility, and Ivy gives better dependency management than Maven, but there isn't great support for multi-project builds. You end up doing a lot of coding to support multi-project builds. Also having some build-by-convention is nice and makes build scripts more concise. With Maven, it takes build by convention too far, and customizing your build process becomes a hack. Also, Maven promotes every project publishing an artifact. Sometimes you have a project split up into subprojects but you want all of the subprojects to be built and versioned together. Not really something Maven is designed for.

With Gradle you can have the flexibility of Ant and build by convention of Maven. For example, it is trivial to extend the conventional build lifecycle with your own task. And you aren't forced to use a convention if you don't want to. Groovy is much nicer to code than XML. In Gradle, you can define dependencies between projects on the local file system without the need to publish artifacts for each to a repository. Finally, Gradle uses Ivy, so it has excellent dependency management. The only real downside for me thus far is the lack of mature Eclipse integration, but the options for Maven aren't really much better.

How to terminate script execution when debugging in Google Chrome?

If you are encountering this while using the debugger statement,

debugger;

... then I think the page will continue running forever until the js runtime yields, or the next break. Assuming you're in break-on-error mode (the pause-icon toggle), you can ensure a break happens by instead doing something like:

debugger;throw 1;

or maybe call a non-existent function:

debugger;z();

(Of course this doesn't help if you are trying to step through functions, though perhaps you could dynamically add in a throw 1 or z() or somesuch in the Sources panel, ctrl-S to save, and then ctrl-R to refresh... this may however skip one breakpoint, but may work if you're in a loop.)

If you are doing a loop and expect to trigger the debugger statement again, you could just type throw 1 instead.

throw 1;

Then when you hit ctrl-R, the next throw will be hit, and the page will refresh.

(tested with Chrome v38, circa Apr 2017)

How do you read a file into a list in Python?

hdl = open("C:/name/MyDocuments/numbers", 'r')
milist = hdl.readlines()
hdl.close()

Jackson serialization: ignore empty values (or null)

For jackson 2.x

@JsonInclude(JsonInclude.Include.NON_NULL)

just before the field.

How can I send a file document to the printer and have it print?

I know the tag says Windows Forms... but, if anyone is interested in a WPF application method, System.Printing works like a charm.

var file = File.ReadAllBytes(pdfFilePath);
var printQueue = LocalPrintServer.GetDefaultPrintQueue();

using (var job = printQueue.AddJob())
using (var stream = job.JobStream)
{
    stream.Write(file, 0, file.Length);
}

Just remember to include System.Printing reference, if it's not already included. Now, this method does not play well with ASP.NET or Windows Service. It should not be used with Windows Forms, as it has System.Drawing.Printing. I don't have a single issue with my PDF printing using the above code.

I should mention, however, that if your printer does not support Direct Print for PDF file format, you're out of luck with this method.

How to remove focus around buttons on click

If you're using a webkit browser (and potentially a browser compatible with webkit vendor prefixing), that outline belongs to the button's -webkit-focus-ring pseudoclass. Simply set it's outline to none:

*:-webkit-focus-ring {
  outline: none;
}

Chrome is such a webkit browser, and this effect happens on Linux too (not just a macOS thing, although some Chrome styles are macOS only)

Detect rotation of Android phone in the browser with JavaScript

To detect an orientation change on an Android browser, attach a listener to the orientationchange or resize event on window:

// Detect whether device supports orientationchange event, otherwise fall back to
// the resize event.
var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
    alert('HOLY ROTATING SCREENS BATMAN:' + window.orientation + " " + screen.width);
}, false);

Check the window.orientation property to figure out which way the device is oriented. With Android phones, screen.width or screen.height also updates as the device is rotated. (this is not the case with the iPhone).

Dropping a connected user from an Oracle 10g database schema

To find the sessions, as a DBA use

select sid,serial# from v$session where username = '<your_schema>'

If you want to be sure only to get the sessions that use SQL Developer, you can add and program = 'SQL Developer'. If you only want to kill sessions belonging to a specific developer, you can add a restriction on os_user

Then kill them with

alter system kill session '<sid>,<serial#>'

(e.g. alter system kill session '39,1232')

A query that produces ready-built kill-statements could be

select 'alter system kill session ''' || sid || ',' || serial# || ''';' from v$session where username = '<your_schema>'

This will return one kill statement per session for that user - something like:

alter system kill session '375,64855';

alter system kill session '346,53146';

How to set DialogFragment's width and height?

To get a Dialog that covers almost the entire scree: First define a ScreenParameter class

public class ScreenParameters
{
    public static int Width;
    public static  int Height;

    public ScreenParameters()
    {
        LayoutParams l = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
        Width= l.width;
        Height = l.height;
    }
}

Then you have to call the ScreenParamater before your getDialog.getWindow().setLayout() method

@Override
public void onResume()
{
    super.onResume();
    ScreenParameters s = new ScreenParameters();
    getDialog().getWindow().setLayout(s.Width , s.Height);
}

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

For anytone who has worked in ASP as well as more modern languages, the question will provoke a chuckle. In my experience using a custom error handler (set up in IIS to handle the 500;100 errors) is the best option for ASP error handling. This article describes the approach and even gives you some sample code / database table definition.

http://www.15seconds.com/issue/020821.htm

Here is a link to Archive.org's version

How to detect Adblock on my website?

I have implemented many methods to detect adblock in the browser and all solutions failed except below one in javascript:

window.onload = function() {
    setTimeout(function() {
        var ad = document.querySelector("ins.adsbygoogle");
        if (ad && ad.innerHTML.replace(/\s/g, "").length == 0) {
            console.log('You seem to blocking Google AdSense ads in your browser.');
        }
    }, 2000);
};

I hope this javascript solution will help you. Thanks for asking this question.

How to get POSTed JSON in Flask?

For all those whose issue was from the ajax call, here is a full example :

Ajax call : the key here is to use a dict and then JSON.stringify

    var dict = {username : "username" , password:"password"};

    $.ajax({
        type: "POST", 
        url: "http://127.0.0.1:5000/", //localhost Flask
        data : JSON.stringify(dict),
        contentType: "application/json",
    });

And on server side :

from flask import Flask
from flask import request
import json

app = Flask(__name__)

@app.route("/",  methods = ['POST'])
def hello():
    print(request.get_json())
    return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 

if __name__ == "__main__":
    app.run()

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

Process all arguments except the first one (in a bash script)

http://wiki.bash-hackers.org/scripting/posparams

It explains the use of shift (if you want to discard the first N parameters) and then implementing Mass Usage

Angularjs how to upload multipart form data and a file?

You can check out this method for sending image and form data altogether

<div class="form-group ml-5 mt-4" ng-app="myApp" ng-controller="myCtrl">
                    <label for="image_name">Image Name:</label>
                    <input type="text"   placeholder="Image name" ng-model="fileName" class="form-control" required>
                    <br>

                    <br>
                    <input id="file_src" type="file"   accept="image/jpeg" file-input="files"   >
                    <br>
                        {{file_name}}
            <img class="rounded mt-2 mb-2 " id="prvw_img" width="150" height="100" >
                    <hr>
                      <button class="btn btn-info" ng-click="uploadFile()">Upload</button>
                        <br>

                       <div ng-show = "IsVisible" class="alert alert-info w-100 shadow mt-2" role="alert">
              <strong> {{response_msg}} </strong>
            </div>
                            <div class="alert alert-danger " id="filealert"> <strong> File Size should be less than 4 MB </strong></div>
                    </div>

Angular JS Code

    var app = angular.module("myApp", []);
 app.directive("fileInput", function($parse){
      return{
           link: function($scope, element, attrs){
                element.on("change", function(event){
                     var files = event.target.files;


                     $parse(attrs.fileInput).assign($scope, element[0].files);
                     $scope.$apply();
                });
           }
      }
 });
 app.controller("myCtrl", function($scope, $http){
      $scope.IsVisible = false;
      $scope.uploadFile = function(){
           var form_data = new FormData();
           angular.forEach($scope.files, function(file){
                form_data.append('file', file); //form file
                                form_data.append('file_Name',$scope.fileName); //form text data
           });
           $http.post('upload.php', form_data,
           {
                //'file_Name':$scope.file_name;
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined,'Process-Data': false}
           }).success(function(response){
             $scope.IsVisible = $scope.IsVisible = true;
                      $scope.response_msg=response;
               // alert(response);
               // $scope.select();
           });
      }

 });

What is the Swift equivalent of respondsToSelector?

The equivalent is the ? operator:

var value: NSNumber? = myQuestionableObject?.importantMethod()

importantMethod will only be called if myQuestionableObject exists and implements it.

Java ByteBuffer to String

Convert a String to ByteBuffer, then from ByteBuffer back to String using Java:

import java.nio.charset.Charset;
import java.nio.*;

String babel = "obufscate thdé alphebat and yolo!!";
System.out.println(babel);
//Convert string to ByteBuffer:
ByteBuffer babb = Charset.forName("UTF-8").encode(babel);
try{
    //Convert ByteBuffer to String
    System.out.println(new String(babb.array(), "UTF-8"));
}
catch(Exception e){
    e.printStackTrace();
}

Which prints the printed bare string first, and then the ByteBuffer casted to array():

obufscate thdé alphebat and yolo!!
obufscate thdé alphebat and yolo!!

Also this was helpful for me, reducing the string to primitive bytes can help inspect what's going on:

String text = "?????";
//convert utf8 text to a byte array
byte[] array = text.getBytes("UTF-8");
//convert the byte array back to a string as UTF-8
String s = new String(array, Charset.forName("UTF-8"));
System.out.println(s);
//forcing strings encoded as UTF-8 as an incorrect encoding like
//say ISO-8859-1 causes strange and undefined behavior
String sISO = new String(array, Charset.forName("ISO-8859-1"));
System.out.println(sISO);

Prints your string interpreted as UTF-8, and then again as ISO-8859-1:

?????
ããã«ã¡ã¯

How to open a second activity on click of button in android app

Try this

  Button button;

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

button=(Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent i = new Intent(getApplicationContext(),SendPhotos.class);
                        startActivity(i);
                    }
                });

 }

How to Extract Year from DATE in POSTGRESQL

answer is;

select date_part('year', timestamp '2001-02-16 20:38:40') as year,
       date_part('month', timestamp '2001-02-16 20:38:40') as month,
       date_part('day', timestamp '2001-02-16 20:38:40') as day,
       date_part('hour', timestamp '2001-02-16 20:38:40') as hour,
       date_part('minute', timestamp '2001-02-16 20:38:40') as minute

Uncaught TypeError: .indexOf is not a function

I was getting e.data.indexOf is not a function error, after debugging it, I found that it was actually a TypeError, which meant, indexOf() being a function is applicable to strings, so I typecasted the data like the following and then used the indexOf() method to make it work

e.data.toString().indexOf('<stringToBeMatchedToPosition>')

Not sure if my answer was accurate to the question, but yes shared my opinion as i faced a similar kind of situation.

Android Imagebutton change Image OnClick

It is very simple

public void onClick(View v) {

        imgButton.setImageResource(R.drawable.ic_launcher);

    }

Using set Background image resource will chanage the background of the button

Java reverse an int value without using array

You can use recursion to solve this.

first get the length of an integer number by using following recursive function.

int Length(int num,int count){
    if(num==0){
        return count;
    }
    else{
        count++;
        return Lenght(num/10,count);
    }
}

and then you can simply multiply remainder of a number by 10^(Length of integer - 1).

int ReturnReverse(int num,int Length,int reverse){
    if(Length!=0){
        reverse = reverse + ((num%10) * (int)(Math.pow(10,Length-1)));
        return ReturnReverse(num/10,Length-1,reverse);
    }
    return reverse;
}

The whole Source Code :

import java.util.Scanner;

public class ReverseNumbers {

    int Length(int num, int count) {
        if (num == 0) {
            return count;
        } else {
            return Length(num / 10, count + 1);
        }
    }

    int ReturnReverse(int num, int Length, int reverse) {
        if (Length != 0) {
            reverse = reverse + ((num % 10) * (int) (Math.pow(10, Length - 1)));
            return ReturnReverse(num / 10, Length - 1, reverse);
        }
        return reverse;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int N = scanner.nextInt();

        ReverseNumbers reverseNumbers = new ReverseNumbers();
        reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), 0));

        scanner.close();
    }
}

Adding a 'share by email' link to website

Something like this might be the easiest way.

<a href="mailto:?subject=I wanted you to see this site&amp;body=Check out this site http://www.website.com."
   title="Share by Email">
  <img src="http://png-2.findicons.com/files/icons/573/must_have/48/mail.png">
</a>

You could find another email image and add that if you wanted.

Pass Method as Parameter using C#

You can use the Func delegate in .net 3.5 as the parameter in your RunTheMethod method. The Func delegate allows you to specify a method that takes a number of parameters of a specific type and returns a single argument of a specific type. Here is an example that should work:

public class Class1
{
    public int Method1(string input)
    {
        //... do something
        return 0;
    }

    public int Method2(string input)
    {
        //... do something different
        return 1;
    }

    public bool RunTheMethod(Func<string, int> myMethodName)
    {
        //... do stuff
        int i = myMethodName("My String");
        //... do more stuff
        return true;
    }

    public bool Test()
    {
        return RunTheMethod(Method1);
    }
}

Renew Provisioning Profile

They've changed it now. (Oct 2010)

  1. Log into iPhone developer website: http://developer.apple.com/

  2. Then click on "Provisioning Portal" on the right hand sidebar menu (right at the top).

  3. On the next page click "Provisioning" in the left sidebar menu

  4. Then you'll see your provisioning profile/s, and the 'renew' button/s - Press it :)

Malformed String ValueError ast.literal_eval() with String representation of Tuple

Use eval() instead of ast.literal_eval() if the input is trusted (which it is in your case).

raw_data = userfile.read().split('\n')
for a in raw_data : 
    print a
    btc_history.append(eval(a))

This works for me in Python 3.6.0

Android Studio Rendering Problems : The following classes could not be found

I have faced this issue when I introduced additional supporting libraries in my project IntelliJ IDEA

So for me "File" -> "Invalidate Caches...", and select "Invalidate and Restart" option to fix this.

How do I parse command line arguments in Bash?

Simple and easy to modify, parameters can be in any order. this can be modified to take parameters in any form (-a, --a, a, etc).

for arg in "$@"
do
   key=$(echo $arg | cut -f1 -d=)`
   value=$(echo $arg | cut -f2 -d=)`
   case "$key" in
        name|-name)      read_name=$value;;
        id|-id)          read_id=$value;;
        *)               echo "I dont know what to do with this"
   ease
done

How to Troubleshoot Intermittent SQL Timeout Errors

I had an issue similar to this and found out is was due to a default .Net framework setting

Sqlcommand.Timeout

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout(v=VS.100).aspx

The default is 30 seconds as sated in the above url by Microsoft, try setting this to a higher number of seconds or maybe -1 before opening the connection to see if this solves the issue.

It maybe a setting in your web.config or app.config files or on you applicaiton / web server config files.

CAST to DECIMAL in MySQL

An alternative, I think for your purpose, is to use the round() function:

select round((10 * 1.5),2) // prints 15.00

You can try it here:

How to use SearchView in Toolbar Android

If you want to add it directly in the toolbar.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <SearchView
            android:id="@+id/searchView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:iconifiedByDefault="false"
            android:queryHint="Search"
            android:layout_centerHorizontal="true" />

    </android.support.v7.widget.Toolbar>

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

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

add your default theme this line;

   <item name="colorControlNormal">@color/my_color</item>

How to insert a value that contains an apostrophe (single quote)?

You need to escape the apostrophe. In T-SQL this is with a double apostrophe, so your insert statement becomes:

Insert into Person
(First, Last)
Values
'Joe', 'O''Brien'

Virtualbox "port forward" from Guest to Host

Network communication Host -> Guest

Connect to the Guest and find out the ip address:

ifconfig 

example of result (ip address is 10.0.2.15):

eth0      Link encap:Ethernet  HWaddr 08:00:27:AE:36:99
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0

Go to Vbox instance window -> Menu -> Network adapters:

  • adapter should be NAT
  • click on "port forwarding"
  • insert new record (+ icon)
    • for host ip enter 127.0.0.1, and for guest ip address you got from prev. step (in my case it is 10.0.2.15)
    • in your case port is 8000 - put it on both, but you can change host port if you prefer

Go to host system and try it in browser:

http://127.0.0.1:8000

or your network ip address (find out on the host machine by running: ipconfig).

Network communication Guest -> Host

In this case port forwarding is not needed, the communication goes over the LAN back to the host.

On the host machine - find out your netw ip address:

ipconfig

example of result:

IP Address. . . . . . . . . . . . : 192.168.5.1

On the guest machine you can communicate directly with the host, e.g. check it with ping:

# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...

Firewall issues?

@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):

sudo ufw allow 8000 

How do you decrease navbar height in Bootstrap 3?

In Bootstrap 4

In my case I have just changed the .navbar min-height and the links font-size and it decreased the navbar.

For example:

.navbar{
    min-height:12px;
}
.navbar  a {
    font-size: 11.2px;
}

And this also worked for increasing the navbar height.

This also helps to change the navbar size when scrolling down the browser.

How can I create 2 separate log files with one log4j config file?

Try the following configuration:

log4j.rootLogger=TRACE, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.category.debugLogger=TRACE, debugLog
log4j.additivity.debugLogger=false

log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false

Then configure the loggers in the Java code accordingly:

static final Logger debugLog = Logger.getLogger("debugLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");

Do you want output to go to stdout? If not, change the first line of log4j.properties to:

log4j.rootLogger=OFF

and get rid of the stdout lines.

How do I search a Perl array for a matching string?

Perl 5.10+ contains the 'smart-match' operator ~~, which returns true if a certain element is contained in an array or hash, and false if it doesn't (see perlfaq4):

The nice thing is that it also supports regexes, meaning that your case-insensitive requirement can easily be taken care of:

use strict;
use warnings;
use 5.010;

my @array  = qw/aaa bbb/;
my $wanted = 'aAa';

say "'$wanted' matches!" if /$wanted/i ~~ @array;   # Prints "'aAa' matches!"

How do I remove duplicate items from an array in Perl?

Try this, seems the uniq function needs a sorted list to work properly.

use strict;

# Helper function to remove duplicates in a list.
sub uniq {
  my %seen;
  grep !$seen{$_}++, @_;
}

my @teststrings = ("one", "two", "three", "one");

my @filtered = uniq @teststrings;
print "uniq: @filtered\n";
my @sorted = sort @teststrings;
print "sort: @sorted\n";
my @sortedfiltered = uniq sort @teststrings;
print "uniq sort : @sortedfiltered\n";

Unzip files programmatically in .net

Standard zip files normally use the deflate algorithm.

To extract files without using third party libraries use DeflateStream. You'll need a bit more information about the zip file archive format as Microsoft only provides the compression algorithm.

You may also try using zipfldr.dll. It is Microsoft's compression library (compressed folders from the Send to menu). It appears to be a com library but it's undocumented. You may be able to get it working for you through experimentation.

Populating a ListView using an ArrayList?

public class Example extends Activity
{
    private ListView lv;
    ArrayList<String> arrlist=new ArrayList<String>();
    //let me assume that you are putting the values in this arraylist
    //Now convert your arraylist to array

    //You will get an exmaple here

    //http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html 

    private String arr[]=convert(arrlist);
    @Override
    public void onCreate(Bundle bun)
    {
        super.onCreate(bun);
        setContentView(R.layout.main);
        lv=(ListView)findViewById(R.id.lv);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
        }
    }

PySpark: withColumn() with two conditions and three outcomes

You'll want to use a udf as below

from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf

def func(fruit1, fruit2):
    if fruit1 == None or fruit2 == None:
        return 3
    if fruit1 == fruit2:
        return 1
    return 0

func_udf = udf(func, IntegerType())
df = df.withColumn('new_column',func_udf(df['fruit1'], df['fruit2']))

How to remove symbols from a string with Python?

Sometimes it takes longer to figure out the regex than to just write it out in python:

import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
    s = s.replace(char, ' ')

If you need other characters you can change it to use a white-list or extend your black-list.

Sample white-list:

whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
    if char in whitelist:
        new_s += char
    else:
        new_s += ' '

Sample white-list using a generator-expression:

whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)

HttpServletRequest get JSON POST data

Are you posting from a different source (so different port, or hostname)? If so, this very very recent topic I just answered might be helpful.

The problem was the XHR Cross Domain Policy, and a useful tip on how to get around it by using a technique called JSONP. The big downside is that JSONP does not support POST requests.

I know in the original post there is no mention of JavaScript, however JSON is usually used for JavaScript so that's why I jumped to that conclusion

How to set min-height for bootstrap container

Two things are happening here.

  1. You are not using the container class properly.
  2. You are trying to override Bootstrap's CSS for the container class

Bootstrap uses a grid system and the .container class is defined in its own CSS. The grid has to exist within a container class DIV. The container DIV is just an indication to Bootstrap that the grid within has that parent. Therefore, you cannot set the height of a container.

What you want to do is the following:

<div class="container-fluid"> <!-- this is to make it responsive to your screen width -->
    <div class="row">
        <div class="col-md-4 myClassName">  <!-- myClassName is defined in my CSS as you defined your container -->
            <img src="#.jpg" height="200px" width="300px">
        </div>
    </div>
</div>

Here you can find more info on the Bootstrap grid system.

That being said, if you absolutely MUST override the Bootstrap CSS then I would try using the "!important" clause to my CSS definition as such...

.container {
   padding-right: 15px;
   padding-left: 15px;
   margin-right: auto;
   margin-left: auto;
   max-width: 900px;
   overflow:hidden;
   min-height:0px !important;
}

But I have always found that the "!important" clause just makes for messy CSS.

How can I provide multiple conditions for data trigger in WPF?

Use MultiDataTrigger type

<Style TargetType="ListBoxItem">
    <Style.Triggers>
      <DataTrigger Binding="{Binding Path=State}" Value="WA">
        <Setter Property="Foreground" Value="Red" />
      </DataTrigger>    
      <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
          <Condition Binding="{Binding Path=Name}" Value="Portland" />
          <Condition Binding="{Binding Path=State}" Value="OR" />
        </MultiDataTrigger.Conditions>
        <Setter Property="Background" Value="Cyan" />
      </MultiDataTrigger>
    </Style.Triggers>
  </Style>

How to convert string to integer in UNIX

Any of these will work from the shell command line. bc is probably your most straight forward solution though.

Using bc:

$ echo "$d1 - $d2" | bc

Using awk:

$ echo $d1 $d2 | awk '{print $1 - $2}'

Using perl:

$ perl -E "say $d1 - $d2"

Using Python:

$ python -c "print $d1 - $d2"

all return

4

How can I search for a commit message on GitHub?

Update (2017/01/05):

GitHub has published an update that allows you now to search within commit messages from within their UI. See blog post for more information.


I had the same question and contacted someone GitHub yesterday:

Since they switched their search engine to Elasticsearch it's not possible to search for commit messages using the GitHub UI. But that feature is on the team's wishlist.

Unfortunately there's no release date for that function right now.

Easy way of running the same junit test over and over?

Anything wrong with:

@Test
void itWorks() {
    // stuff
}

@Test
void itWorksRepeatably() {
    for (int i = 0; i < 10; i++) {
        itWorks();
    }
}

Unlike the case where you are testing each of an array of values, you don't particularly care which run failed.

No need to do in configuration or annotation what you can do in code.

How to install pip for Python 3.6 on Ubuntu 16.10?

Let's suppose that you have a system running Ubuntu 16.04, 16.10, or 17.04, and you want Python 3.6 to be the default Python.

If you're using Ubuntu 16.04 LTS, you'll need to use a PPA:

sudo add-apt-repository ppa:jonathonf/python-3.6  # (only for 16.04 LTS)

Then, run the following (this works out-of-the-box on 16.10 and 17.04):

sudo apt update
sudo apt install python3.6
sudo apt install python3.6-dev
sudo apt install python3.6-venv
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
sudo ln -s /usr/bin/python3.6 /usr/local/bin/python3
sudo ln -s /usr/local/bin/pip /usr/local/bin/pip3

# Do this only if you want python3 to be the default Python
# instead of python2 (may be dangerous, esp. before 2020):
# sudo ln -s /usr/bin/python3.6 /usr/local/bin/python

When you have completed all of the above, each of the following shell commands should indicate Python 3.6.1 (or a more recent version of Python 3.6):

python --version   # (this will reflect your choice, see above)
python3 --version
$(head -1 `which pip` | tail -c +3) --version
$(head -1 `which pip3` | tail -c +3) --version

node.js string.replace doesn't work?

According to the Javascript standard, String.replace isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.

You can always just set the string to the modified value:

variableABC = variableABC.replace('B', 'D')

Edit: The code given above is to only replace the first occurrence.

To replace all occurrences, you could do:

 variableABC = variableABC.replace(/B/g, "D");  

To replace all occurrences and ignore casing

 variableABC = variableABC.replace(/B/gi, "D");  

Is there a goto statement in Java?

James Gosling created the original JVM with support of goto statements, but then he removed this feature as needless. The main reason goto is unnecessary is that usually it can be replaced with more readable statements (like break/continue) or by extracting a piece of code into a method.

Source: James Gosling, Q&A session

What are the different types of indexes, what are the benefits of each?

PostgreSQL allows partial indexes, where only rows that match a predicate are indexed. For instance, you might want to index the customer table for only those records which are active. This might look something like:

create index i on customers (id, name, whatever) where is_active is true;

If your index many columns, and you have many inactive customers, this can be a big win in terms of space (the index will be stored in fewer disk pages) and thus performance. To hit the index you need to, at a minimum, specify the predicate:

select name from customers where is_active is true;

PermissionError: [Errno 13] Permission denied

Here is how I encountered the error:

import os

path = input("Input file path: ")

name, ext = os.path.basename(path).rsplit('.', 1)
dire = os.path.dirname(path)

with open(f"{dire}\\{name} temp.{ext}", 'wb') as file:
    pass

It works great if the user inputs a file path with more than one element, like

C:\\Users\\Name\\Desktop\\Folder

But I thought that it would work with an input like

file.txt

as long as file.txt is in the same directory of the python file. But nope, it gave me that error, and I realized that the correct input should've been

.\\file.txt

Postgres "psql not recognized as an internal or external command"

Enter this path in your System environment variable.

C:\Program Files\PostgreSQL\[YOUR PG VERSION]\bin

In this case i'm using version 10. If you check the postgres folder you are going to see your current versions.

In my own case i used the following on separate lines:

C:\Program Files\PostgreSQL\10\bin
C:\Program Files\PostgreSQL\10\lib

How to format an inline code in Confluence?

To format code in-line within your text, use the '`' character to surround your code. Usually located to the left of the '1' key on your keyboard.

Example:

`printf("Hello World");`

Same delimiter as Stack Exchange!

How do I revert an SVN commit?

svn merge -c -M PATH

This saved my life.

I was having the same issue, after reverting back also I was not seeing old code. After running the above command I got a clean old version code.

How to register ASP.NET 2.0 to web server(IIS7)?

If you installed IIS after the .Net framework you can solve the porblem by re-installing the .Net framework. Part of its install detects whether IIS is present and updates IIS accordingly.

How to list installed packages from a given repo using yum

Try

yum list installed | grep reponame

On one of my servers:

yum list installed | grep remi
ImageMagick2.x86_64                       6.6.5.10-1.el5.remi          installed
memcache.x86_64                          1.4.5-2.el5.remi             installed
mysql.x86_64                              5.1.54-1.el5.remi            installed
mysql-devel.x86_64                        5.1.54-1.el5.remi            installed
mysql-libs.x86_64                         5.1.54-1.el5.remi            installed
mysql-server.x86_64                       5.1.54-1.el5.remi            installed
mysqlclient15.x86_64                      5.0.67-1.el5.remi            installed
php.x86_64                                5.3.5-1.el5.remi             installed
php-cli.x86_64                            5.3.5-1.el5.remi             installed
php-common.x86_64                         5.3.5-1.el5.remi             installed
php-domxml-php4-php5.noarch               1.21.2-1.el5.remi            installed
php-fpm.x86_64                            5.3.5-1.el5.remi             installed
php-gd.x86_64                             5.3.5-1.el5.remi             installed
php-mbstring.x86_64                       5.3.5-1.el5.remi             installed
php-mcrypt.x86_64                         5.3.5-1.el5.remi             installed
php-mysql.x86_64                          5.3.5-1.el5.remi             installed
php-pdo.x86_64                            5.3.5-1.el5.remi             installed
php-pear.noarch                           1:1.9.1-6.el5.remi           installed
php-pecl-apc.x86_64                       3.1.6-1.el5.remi             installed
php-pecl-imagick.x86_64                   3.0.1-1.el5.remi.1           installed
php-pecl-memcache.x86_64                  3.0.5-1.el5.remi             installed
php-pecl-xdebug.x86_64                    2.1.0-1.el5.remi             installed
php-soap.x86_64                           5.3.5-1.el5.remi             installed
php-xml.x86_64                            5.3.5-1.el5.remi             installed
remi-release.noarch                       5-8.el5.remi                 installed

It works.

"The page has expired due to inactivity" - Laravel 5.5

set mbstring.func_overload = 2

it helped me

Reading PDF documents in .Net

aspose pdf works pretty well. then again, you have to pay for it

Adding n hours to a date in Java?

Using the newish java.util.concurrent.TimeUnit class you can do it like this

Date oldDate = new Date(); // oldDate == current time
Date newDate = new Date(oldDate.getTime() + TimeUnit.HOURS.toMillis(2)); // Add 2 hours

Difference between a Seq and a List in Scala

Seq is a trait that List implements.

If you define your container as Seq, you can use any container that implements Seq trait.

scala> def sumUp(s: Seq[Int]): Int = { s.sum }
sumUp: (s: Seq[Int])Int

scala> sumUp(List(1,2,3))
res41: Int = 6

scala> sumUp(Vector(1,2,3))
res42: Int = 6

scala> sumUp(Seq(1,2,3))
res44: Int = 6

Note that

scala> val a = Seq(1,2,3)
a: Seq[Int] = List(1, 2, 3)

Is just a short hand for:

scala> val a: Seq[Int] = List(1,2,3)
a: Seq[Int] = List(1, 2, 3)

if the container type is not specified, the underlying data structure defaults to List.

AWS S3: how do I see how much disk space is using

Well, you can do it also through an S3 client if you prefer a human friendly UI.

I use CrossFTP, which is free and cross-platform, and there you can right-click on the folder directory -> select "Properties..." -> click on "Calculate" button next to Size and voila.

Overlapping elements in CSS

You can try using the transform: translate property by passing the appropriate values inside the parenthesis using the inspect element in Google chrome.

You have to set translate property in such way that both the <div> overlap each other then You can use JavaScript to show and hide both the <div> according to your requirements

How do I create a dynamic key to be added to a JavaScript object variable

Square brackets:

jsObj['key' + i] = 'example' + 1;

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ] operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

Thus, the way the [ ] operator works in a for loop iterating through an array:

for (var i = 0; i < myArray.length; ++i) {
  var value = myArray[i]; // property access
  // ...
}

is really no different from the way [ ] works when accessing a property whose name is some computed string:

var value = jsObj["key" + i];

The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

When setting property values using [ ], the story is the same except for the special behavior around maintaining the length property. If you set a property with a numeric key on an array instance:

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the length property will be updated to 201 as a side-effect of the property assignment. If the same thing is done to a plain object, however:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5 in otherwise the exact same way.

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.

ES2015:

If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:

var key = 'DYNAMIC_KEY',
    obj = {
        [key]: 'ES6!'
    };

console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }

How to determine equality for two JavaScript objects?

A simple solution to this issue that many people don't realize is to sort the JSON strings (per character). This is also usually faster than the other solutions mentioned here:

function areEqual(obj1, obj2) {
    var a = JSON.stringify(obj1), b = JSON.stringify(obj2);
    if (!a) a = '';
    if (!b) b = '';
    return (a.split('').sort().join('') == b.split('').sort().join(''));
}

Another useful thing about this method is you can filter comparisons by passing a "replacer" function to the JSON.stringify functions (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Example_of_using_replacer_parameter). The following will only compare all objects keys that are named "derp":

function areEqual(obj1, obj2, filter) {
    var a = JSON.stringify(obj1, filter), b = JSON.stringify(obj2, filter);
    if (!a) a = '';
    if (!b) b = '';
    return (a.split('').sort().join('') == b.split('').sort().join(''));
}
var equal = areEqual(obj1, obj2, function(key, value) {
    return (key === 'derp') ? value : undefined;
});

DateTime.TryParse issue with dates of yyyy-dd-MM format

You need to use the ParseExact method. This takes a string as its second argument that specifies the format the datetime is in, for example:

// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
try
{
   result = DateTime.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

If the user can specify a format in the UI, then you need to translate that to a string you can pass into this method. You can do that by either allowing the user to enter the format string directly - though this means that the conversion is more likely to fail as they will enter an invalid format string - or having a combo box that presents them with the possible choices and you set up the format strings for these choices.

If it's likely that the input will be incorrect (user input for example) it would be better to use TryParseExact rather than use exceptions to handle the error case:

// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
DateTime result;
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out result))
{
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
else
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

A better alternative might be to not present the user with a choice of date formats, but use the overload that takes an array of formats:

// A list of possible American date formats - swap M and d for European formats
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                   "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                   "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                   "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                   "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
                   "MM/d/yyyy HH:mm:ss.ffffff" };
string dateString; // The string the date gets read into

try
{
    dateValue = DateTime.ParseExact(dateString, formats, 
                                    new CultureInfo("en-US"), 
                                    DateTimeStyles.None);
    Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
}
catch (FormatException)
{
    Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}                                               

If you read the possible formats out of a configuration file or database then you can add to these as you encounter all the different ways people want to enter dates.

SQL Server Operating system error 5: "5(Access is denied.)"

In linux, I went to /var/opt/mssql/data/ folder and opened a terminal with sudo then, changed my *.mdf and *.ldf file permissions as below in which you replace yourDB with your Database file name and myUser to currently logged username:

chmod 755 yourDB.mdf
chown myUser yourDB.mdf

chmod 755 yourDB.ldf
chown myUser yourDB.ldf

After that, it was reconnected without any issue.

Returning the product of a list

One option is to use numba and the @jit or @njit decorator. I also made one or two little tweaks to your code (at least in Python 3, "list" is a keyword that shouldn't be used for a variable name):

@njit
def njit_product(lst):
    p = lst[0]  # first element
    for i in lst[1:]:  # loop over remaining elements
        p *= i
    return p

For timing purposes, you need to run once to compile the function first using numba. In general, the function will be compiled the first time it is called, and then called from memory after that (faster).

njit_product([1, 2])  # execute once to compile

Now when you execute your code, it will run with the compiled version of the function. I timed them using a Jupyter notebook and the %timeit magic function:

product(b)  # yours
# 32.7 µs ± 510 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

njit_product(b)
# 92.9 µs ± 392 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Note that on my machine, running Python 3.5, the native Python for loop was actually the fastest. There may be a trick here when it comes to measuring numba-decorated performance with Jupyter notebooks and the %timeit magic function. I am not sure that the timings above are correct, so I recommend trying it out on your system and seeing if numba gives you a performance boost.

How to "pretty" format JSON output in Ruby on Rails

Here's my solution which I derived from other posts during my own search.

This allows you to send the pp and jj output to a file as needed.

require "pp"
require "json"

class File
  def pp(*objs)
    objs.each {|obj|
      PP.pp(obj, self)
    }
    objs.size <= 1 ? objs.first : objs
  end
  def jj(*objs)
    objs.each {|obj|
      obj = JSON.parse(obj.to_json)
      self.puts JSON.pretty_generate(obj)
    }
    objs.size <= 1 ? objs.first : objs
  end
end

test_object = { :name => { first: "Christopher", last: "Mullins" }, :grades => [ "English" => "B+", "Algebra" => "A+" ] }

test_json_object = JSON.parse(test_object.to_json)

File.open("log/object_dump.txt", "w") do |file|
  file.pp(test_object)
end

File.open("log/json_dump.txt", "w") do |file|
  file.jj(test_json_object)
end

_tkinter.TclError: no display name and no $DISPLAY environment variable

I had this same issue trying to run a simple tkinter app remotely on a Raspberry Pi. In my case I did want to display the tkinter GUI on the pi display, but I want to be able to execute it over SSH from my host machine. I was also not using matplotlib, so that wasn't the cause of my issue. I was able to resolve the issue by setting the DISPLAY environment variable as the error suggests with the command:

export DISPLAY=:0.0

A good explanation of what the display environment variable is doing and why the syntax is so odd can be found here: https://askubuntu.com/questions/432255/what-is-display-environment-variable

android - How to get view from context?

In your broadcast receiver you could access a view via inflation a root layout from XML resource and then find all your views from this root layout with findViewByid():

View view = View.inflate(context, R.layout.ROOT_LAYOUT, null);

Now you can access your views via 'view' and cast them to your view type:

myImage = (ImageView) view.findViewById(R.id.my_image);

How do I get the latest version of my code?

You have to merge your files first. Do a git status to see what are the files that need to be merged (means you need to resolve the conflicts first). Once this is done, do git add file_merged and do your pull again.

displayname attribute vs display attribute

I think the current answers are neglecting to highlight the actual important and significant differences and what that means for the intended usage. While they might both work in certain situations because the implementer built in support for both, they have different usage scenarios. Both can annotate properties and methods but here are some important differences:

DisplayAttribute

  • defined in the System.ComponentModel.DataAnnotations namespace in the System.ComponentModel.DataAnnotations.dll assembly
  • can be used on parameters and fields
  • lets you set additional properties like Description or ShortName
  • can be localized with resources

DisplayNameAttribute

  • DisplayName is in the System.ComponentModel namespace in System.dll
  • can be used on classes and events
  • cannot be localized with resources

The assembly and namespace speaks to the intended usage and localization support is the big kicker. DisplayNameAttribute has been around since .NET 2 and seems to have been intended more for naming of developer components and properties in the legacy property grid, not so much for things visible to end users that may need localization and such.

DisplayAttribute was introduced later in .NET 4 and seems to be designed specifically for labeling members of data classes that will be end-user visible, so it is more suitable for DTOs, entities, and other things of that sort. I find it rather unfortunate that they limited it so it can't be used on classes though.

EDIT: Looks like latest .NET Core source allows DisplayAttribute to be used on classes now as well.

How do I expand the output display to see more columns of a pandas DataFrame?

pd.options.display.max_columns = 100

You can specify the numbers of columns as per your requirement in max_columns.

How to put sshpass command inside a bash script?

1 - You can script sshpass's ssh command like this:

#!/bin/bash

export SSHPASS=password
sshpass -e ssh -oBatchMode=no user@host

2 - You can script sshpass's sftp commandlike this:

#!/bin/bash

export SSHPASS=password

sshpass -e sftp -oBatchMode=no -b - user@host << !
   put someFile
   get anotherFile
   bye
!

Using NSLog for debugging

Try this piece of code:

NSString *digit = [[sender titlelabel] text];
NSLog(@"%@", digit);

The message means that you have incorrect syntax for using the digit variable. If you're not sending it any message - you don't need any brackets.

How do I get the last character of a string?

Try this:

if (s.charAt(0) == s.charAt(s.length() - 1))

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

This works for me...

  • go to GenyMotion settings -> ADB tab
  • instead of Use Genymotion Android tools, choose custom Android SDK Tools and then browse your installed SDK.

PivotTable to show values, not sum of values

I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.

Assuming your data is in ColumnA:C and has column labels in Row 1, also that Month is formatted mmm(this last for ease of sorting):

  1. Sort the data by Name then Month
  2. Enter in D2 =IF(AND(A2=A1,C2=C1),D1+1,1) (One way to deal with what is the tricky issue of multiple entries for the same person for the same month).
  3. Create a pivot table from A1:D(last occupied row no.)
  4. Say insert in F1.
  5. Layout as in screenshot.

SO12803305 example

I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.

  1. Copy pivot table and Paste Special/Values to, say, L1.
  2. Delete top row of copied range with shift cells up.
  3. Insert new cell at L1 and shift down.
  4. Key 'Name' into L1.
  5. Filter copied range and for ColumnL, select Row Labels and numeric values.
  6. Delete contents of L2:L(last selected cell)
  7. Delete blank rows in copied range with shift cells up (may best via adding a column that counts all 12 months). Hopefully result should be as highlighted in yellow.

Happy to explain further/try again (I've not really tested this) if does not suit.

EDIT (To avoid second block of steps above and facilitate updating for source data changes)

.0. Before first step 2. add a blank row at the very top and move A2:D2 up.
.2. Adjust cell references accordingly (in D3 =IF(AND(A3=A2,C3=C2),D2+1,1).
.3. Create pivot table from A:D

.6. Overwrite Row Labels with Name.
.7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
.8. Hide Row1, ColumnG and rows and columns that show (blank).

additional example

Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).

Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank) into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.

extract the date part from DateTime in C#

When comparing only the date of the datatimes, use the Date property. So this should work fine for you

datetime1.Date == datetime2.Date

How to choose an AWS profile when using boto3 to connect to CloudFront

Do this to use a profile with name 'dev':

session = boto3.session.Session(profile_name='dev')
s3 = session.resource('s3')
for bucket in s3.buckets.all():
    print(bucket.name)

Difference between a script and a program?

IMO Script - is the kind of instruction that program supposed to run Program - is kind of instruction that hardware supposed to run

Though i guess .NET/JAVA byte codes are scripts by this definition

Angular - "has no exported member 'Observable'"

My resolution was adding the following import: import { of } from 'rxjs/observable/of';

So the overall code of hero.service.ts after the change is:

import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { of } from 'rxjs/observable/of';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class HeroService {

  constructor() { }

  getHeroes(): Observable<Hero[]> {
    return of(HEROES);
  }
}

How to add line breaks to an HTML textarea?

If you just need to send the value of the testarea to server with line breaks use nl2br

Copying from one text file to another using Python

readlines() reads the entire input file into a list and is not a good performer. Just iterate through the lines in the file. I used 'with' on output.txt so that it is automatically closed when done. That's not needed on 'list1.txt' because it will be closed when the for loop ends.

#!/usr/bin/env python
with open('output.txt', 'a') as f1:
    for line in open('list1.txt'):
        if 'tests/file/myword' in line:
            f1.write(line)

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

How to create a fix size list in python?

(tl;dr: The exact answer to your question is numpy.empty or numpy.empty_like, but you likely don't care and can get away with using myList = [None]*10000.)

Simple methods

You can initialize your list to all the same element. Whether it semantically makes sense to use a non-numeric value (that will give an error later if you use it, which is a good thing) or something like 0 (unusual? maybe useful if you're writing a sparse matrix or the 'default' value should be 0 and you're not worried about bugs) is up to you:

>>> [None for _ in range(10)]
[None, None, None, None, None, None, None, None, None, None]

(Here _ is just a variable name, you could have used i.)

You can also do so like this:

>>> [None]*10
[None, None, None, None, None, None, None, None, None, None]

You probably don't need to optimize this. You can also append to the array every time you need to:

>>> x = []
>>> for i in range(10):
>>>    x.append(i)

Performance comparison of simple methods

Which is best?

>>> def initAndWrite_test():
...  x = [None]*10000
...  for i in range(10000):
...   x[i] = i
... 
>>> def initAndWrite2_test():
...  x = [None for _ in range(10000)]
...  for i in range(10000):
...   x[i] = i
... 
>>> def appendWrite_test():
...  x = []
...  for i in range(10000):
...   x.append(i)

Results in python2.7:

>>> import timeit
>>> for f in [initAndWrite_test, initAndWrite2_test, appendWrite_test]:
...  print('{} takes {} usec/loop'.format(f.__name__, timeit.timeit(f, number=1000)*1000))
... 
initAndWrite_test takes 714.596033096 usec/loop
initAndWrite2_test takes 981.526136398 usec/loop
appendWrite_test takes 908.597946167 usec/loop

Results in python 3.2:

initAndWrite_test takes 641.3581371307373 usec/loop
initAndWrite2_test takes 1033.6499214172363 usec/loop
appendWrite_test takes 895.9040641784668 usec/loop

As we can see, it is likely better to do the idiom [None]*10000 in both python2 and python3. However, if one is doing anything more complicated than assignment (such as anything complicated to generate or process every element in the list), then the overhead becomes a meaninglessly small fraction of the cost. That is, such optimization is premature to worry about if you're doing anything reasonable with the elements of your list.


Uninitialized memory

These are all however inefficient because they go through memory, writing something in the process. In C this is different: an uninitialized array is filled with random garbage memory (sidenote: that has been reallocated from the system, and can be a security risk when you allocate or fail to mlock and/or fail to delete memory when closing the program). This is a design choice, designed for speedup: the makers of the C language thought that it was better not to automatically initialize memory, and that was the correct choice.

This is not an asymptotic speedup (because it's O(N)), but for example you wouldn't need to first initialize your entire memory block before you overwrite with stuff you actually care about. This, if it were possible, is equivalent to something like (pseudo-code) x = list(size=10000).

If you want something similar in python, you can use the numpy numerical matrix/N-dimensional-array manipulation package. Specifically, numpy.empty or numpy.empty_like

That is the real answer to your question.

Linux command to print directory structure in the form of a tree

Adding the below function in bashrc lets you run the command without any arguments which displays the current directory structure and when run with any path as argument, will display the directory structure of that path. This avoids the need to switch to a particular directory before running the command.

function tree() {
    find ${1:-.} | sed -e "s/[^-][^\/]*\//  |/g" -e "s/|\([^ ]\)/|-\1/"
}

This works in gitbash too.

Source: Comment from @javasheriff here

How to get the public IP address of a user in C#

That code gets you the IP address of your server not the address of the client who is accessing your website. Use the HttpContext.Current.Request.UserHostAddress property to the client's IP address.

Datatables - Search Box outside datatable

You can use the DataTables api to filter the table. So all you need is your own input field with a keyup event that triggers the filter function to DataTables. With css or jquery you can hide/remove the existing search input field. Or maybe DataTables has a setting to remove/not-include it.

Checkout the Datatables API documentation on this.

Example:

HTML

<input type="text" id="myInputTextField">

JS

oTable = $('#myTable').DataTable();   //pay attention to capital D, which is mandatory to retrieve "api" datatables' object, as @Lionel said
$('#myInputTextField').keyup(function(){
      oTable.search($(this).val()).draw() ;
})

Use string in switch case in java

Java does not support Switch-case with String. I guess this link can help you. :)

What is a thread exit code?

There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0 tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.

The closest link I could find to be useful for more information is this

Quote from above link:

What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.


From the Documentation for GetEXitCodeThread

Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.


My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.

Code for best fit straight line of a scatter plot in python

Have implemented @Micah 's solution to generate a trendline with a few changes and thought I'd share:

  • Coded as a function
  • Option for a polynomial trendline (input order=2)
  • Function can also just return the coefficient of determination (R^2, input Rval=True)
  • More Numpy array optimisations

Code:

def trendline(xd, yd, order=1, c='r', alpha=1, Rval=False):
    """Make a line of best fit"""

    #Calculate trendline
    coeffs = np.polyfit(xd, yd, order)

    intercept = coeffs[-1]
    slope = coeffs[-2]
    power = coeffs[0] if order == 2 else 0

    minxd = np.min(xd)
    maxxd = np.max(xd)

    xl = np.array([minxd, maxxd])
    yl = power * xl ** 2 + slope * xl + intercept

    #Plot trendline
    plt.plot(xl, yl, c, alpha=alpha)

    #Calculate R Squared
    p = np.poly1d(coeffs)

    ybar = np.sum(yd) / len(yd)
    ssreg = np.sum((p(xd) - ybar) ** 2)
    sstot = np.sum((yd - ybar) ** 2)
    Rsqr = ssreg / sstot

    if not Rval:
        #Plot R^2 value
        plt.text(0.8 * maxxd + 0.2 * minxd, 0.8 * np.max(yd) + 0.2 * np.min(yd),
                 '$R^2 = %0.2f$' % Rsqr)
    else:
        #Return the R^2 value:
        return Rsqr

Generating a WSDL from an XSD file

we can generate wsdl file from xsd but you have to use oracle enterprise pack of eclipse(OEPE). simply create xsd and then right click->new->wsdl...

node.js, socket.io with SSL

If your server certificated file is not trusted, (for example, you may generate the keystore by yourself with keytool command in java), you should add the extra option rejectUnauthorized

var socket = io.connect('https://localhost', {rejectUnauthorized: false});

String strip() for JavaScript?

For jquery users, how about $.trim(s)

How to put a symbol above another in LaTeX?

Use \overset{above}{main} in math mode. In your case, \overset{a}{\#}.

Inserting a value into all possible locations in a list

Coming from JavaScript, this was something I was used to having "built-in" via Array.prototype.splice(), so I made a Python function that does the same:

def list_splice(target, start, delete_count=None, *items):
    """Remove existing elements and/or add new elements to a list.

    target        the target list (will be changed)
    start         index of starting position
    delete_count  number of items to remove (default: len(target) - start)
    *items        items to insert at start index

    Returns a new list of removed items (or an empty list)
    """
    if delete_count == None:
        delete_count = len(target) - start

    # store removed range in a separate list and replace with *items
    total = start + delete_count
    removed = target[start:total]
    target[start:total] = items

    return removed

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +
   geom_point()
)

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()    
p0+guides(colour=FALSE)

UPDATE

Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

HTML5 and frameborder

style="border:none; scrolling:no; frameborder:0;  marginheight:0; marginwidth:0; "

Row count with PDO

Answering this because I trapped myself with it by now knowing this and maybe it will be useful.

Keep in mind that you cant fetch results twice. You have to save fetch result into array, get row count by count($array), and output results with foreach. For example:

$query = "your_query_here";
$STH = $DBH->prepare($query);
$STH->execute();
$rows = $STH->fetchAll();
//all your results is in $rows array
$STH->setFetchMode(PDO::FETCH_ASSOC);           
if (count($rows) > 0) {             
    foreach ($rows as $row) {
        //output your rows
    }                       
}

Prevent Android activity dialog from closing on outside touch

This could help you. It is a way to handle the touch outside event:

How to cancel an Dialog themed like Activity when touched outside the window?

By catching the event and doing nothing, I think you can prevent the closing. But what is strange though, is that the default behavior of your activity dialog should be not to close itself when you touch outside.

(PS: the code uses WindowManager.LayoutParams)

Bootstrap 3 panel header with buttons wrong position

I'm a little late to the game here, but the simple answer is to move the H4 AFTER the button div. This is a common issue when floating, always have your floats defined BEFORE the rest of the contents or you'll have that extra line-break problem.

<div class="panel-heading">
    <div class="btn-group pull-right">
        <a href="#" class="btn btn-default btn-sm">## Lock</a>
        <a href="#" class="btn btn-default btn-sm">## Delete</a>
        <a href="#" class="btn btn-default btn-sm">## Move</a>
    </div>
    <h4>Panel header</h4>
</div>

The issue here is that when your floats are defined after other items, the float's top will start at the last line-position of the element immediately before it. So, if the previous item wraps to line 3, your float will start at line 3 too.

Moving the float to the TOP of the list eliminates the issue because there are no previous elements to push it down and anything after the float will be rendered at the top line (assuming there is room on the line for all items)

Example of correct and incorrect ordering and the effects: http://www.bootply.com/HkDlNIKv9g

If else embedding inside html

<?php if ($foo) { ?>
    <div class="mydiv">Condition is true</div>
<?php } else { ?>
    <div class="myotherdiv">Condition is false</div>
<?php } ?>

Get the first N elements of an array?

In the current order? I'd say array_slice(). Since it's a built in function it will be faster than looping through the array while keeping track of an incrementing index until N.

What is the correct way to write HTML using Javascript?

  1. DOM methods, as outlined by Tom.

  2. innerHTML, as mentioned by iHunger.

DOM methods are highly preferable to strings for setting attributes and content. If you ever find yourself writing innerHTML= '<a href="'+path+'">'+text+'</a>' you're actually creating new cross-site-scripting security holes on the client side, which is a bit sad if you've spent any time securing your server-side.

DOM methods are traditionally described as ‘slow’ compared to innerHTML. But this isn't really the whole story. What is slow is inserting a lot of child nodes:

 for (var i= 0; i<1000; i++)
     div.parentNode.insertBefore(document.createElement('div'), div);

This translates to a load of work for the DOM finding the right place in its nodelist to insert the element, moving the other child nodes up, inserting the new node, updating the pointers, and so on.

Setting an existing attribute's value, or a text node's data, on the other hand, is very fast; you just change a string pointer and that's it. This is going to be much faster than serialising the parent with innerHTML, changing it, and parsing it back in (and won't lose your unserialisable data like event handlers, JS references and form values).

There are techniques to do DOM manipulations without so much slow childNodes walking. In particular, be aware of the possibilities of cloneNode, and using DocumentFragment. But sometimes innerHTML really is quicker. You can still get the best of both worlds by using innerHTML to write your basic structure with placeholders for attribute values and text content, which you then fill in afterwards using DOM. This saves you having to write your own escapehtml() function to get around the escaping/security problems mentioned above.

jQuery ajax call to REST service

From the use of 8080 I'm assuming you are using a tomcat servlet container to serve your rest api. If this is the case you can also consider to have your webserver proxy the requests to the servlet container.

With apache you would typically use mod_jk (although there are other alternatives) to serve the api trough the web server behind port 80 instead of 8080 which would solve the cross domain issue.

This is common practice, have the 'static' content in the webserver and dynamic content in the container, but both served from behind the same domain.

The url for the rest api would be http://localhost/restws/json/product/get

Here a description on how to use mod_jk to connect apache to tomcat: http://tomcat.apache.org/connectors-doc/webserver_howto/apache.html

HttpClient does not exist in .net 4.0: what can I do?

read this...

Portable HttpClient for .NET Framework and Windows Phone

see paragraph Using HttpClient on .NET Framework 4.0 or Windows Phone 7.5 http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx

Cannot set some HTTP headers when using System.Net.WebRequest

I had the same exception when my code tried to set the "Accept" header value like this:

WebRequest request = WebRequest.Create("http://someServer:6405/biprws/logon/long");
request.Headers.Add("Accept", "application/json");

The solution was to change it to this:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://someServer:6405/biprws/logon/long");
request.Accept = "application/json";

Why do we have to normalize the input for an artificial neural network?

In neural networks, it is good idea not just to normalize data but also to scale them. This is intended for faster approaching to global minima at error surface. See the following pictures: error surface before and after normalization

error surface before and after scaling

Pictures are taken from the coursera course about neural networks. Author of the course is Geoffrey Hinton.

What is the difference between SQL and MySQL?

SQL stands for Structured Query Language, and is the basis for which all Relational Database Management Systems allow the user to add, remove, update, or select records. Things like MySQ are the actual Management Systems which allow you to store and retrieve your data, whereas SQL is the actual language to do so.

The basic SQL is somewhat universal - Selects usually look the same, Inserts, Updates, Deletes, etc. Once you get beyond the basics, the commands and abilities of your individual Databases vary, and this is where you get people who are Oracle experts, MySQL, SQL Server, etc.

Basically, MySQL is one of many books holding everything, and SQL is how you go about reading that book.

PHP mail function doesn't complete sending of e-mail

This will only affect a small handful of users, but I'd like it documented for that small handful. This member of that small handful spent 6 hours troubleshooting a working PHP mail script because of this issue.

If you're going to a university that runs XAMPP from www.AceITLab.com, you should know what our professor didn't tell us: The AceITLab firewall (not the Windows firewall) blocks MercuryMail in XAMPP. You'll have to use an alternative mail client, pear is working for us. You'll have to send to a Gmail account with low security settings.

Yes, I know, this is totally useless for real world email. However, from what I've seen, academic settings and the real world often have precious little in common.

Insert/Update/Delete with function in SQL Server

Yes, you can.

However, it requires SQL CLR with EXTERNAL_ACCESS or UNSAFE permission and specifying a connection string. This is obviously not recommended.

For example, using Eval SQL.NET (a SQL CLR which allow to add C# syntax in SQL)

CREATE FUNCTION [dbo].[fn_modify_table_state]
    (
      @conn VARCHAR(8000) ,
      @sql VARCHAR(8000)
    )
RETURNS INT
AS
    BEGIN
        RETURN SQLNET::New('
using(var connection = new SqlConnection(conn))
{
    connection.Open();

    using(var command = new SqlCommand(sql, connection))
    {
        return command.ExecuteNonQuery();
    }
}
').ValueString('conn', @conn).ValueString('sql', @sql).EvalReadAccessInt()

    END

    GO

DECLARE @conn VARCHAR(8000) = 'Data Source=XPS8700;Initial Catalog=SqlServerEval_Debug;Integrated Security=True'
DECLARE @sql VARCHAR(8000) = 'UPDATE [Table_1] SET Value = -1 WHERE Name = ''zzz'''

DECLARE @rowAffecteds INT =  dbo.fn_modify_table_state(@conn, @sql)

Documentation: Modify table state within a SQL Function

Disclaimer: I'm the owner of the project Eval SQL.NET

ORA-01882: timezone region not found

Happens when you use the wrong version of OJDBC jar.

You need to use 11.2.0.4

How to handle iframe in Selenium WebDriver using java

Selenium Web Driver Handling Frames
It is impossible to click iframe directly through XPath since it is an iframe. First we have to switch to the frame and then we can click using xpath.

driver.switchTo().frame() has multiple overloads.

  1. driver.switchTo().frame(name_or_id)
    Here your iframe doesn't have id or name, so not for you.

  2. driver.switchTo().frame(index)
    This is the last option to choose, because using index is not stable enough as you could imagine. If this is your only iframe in the page, try driver.switchTo().frame(0)

  3. driver.switchTo().frame(iframe_element)
    The most common one. You locate your iframe like other elements, then pass it into the method.

driver.switchTo().defaultContent(); [parentFrame, defaultContent, frame]

// Based on index position:
int frameIndex = 0;
List<WebElement> listFrames = driver.findElements(By.tagName("iframe"));
System.out.println("list frames   "+listFrames.size());
driver.switchTo().frame(listFrames.get( frameIndex ));

// XPath|CssPath Element:
WebElement frameCSSPath = driver.findElement(By.cssSelector("iframe[title='Fill Quote']"));
WebElement frameXPath = driver.findElement(By.xpath(".//iframe[1]"));
WebElement frameTag = driver.findElement(By.tagName("iframe"));

driver.switchTo().frame( frameCSSPath ); // frameXPath, frameTag


driver.switchTo().frame("relative=up"); // focus to parent frame.
driver.switchTo().defaultContent(); // move to the most parent or main frame

// For alert's
Alert alert = driver.switchTo().alert(); // Switch to alert pop-up
alert.accept();
alert.dismiss();

XML Test:

<html>
    <IFame id='1'>...       parentFrame() « context remains unchanged. <IFame1>
    |
     -> <IFrame id='2'>...  parentFrame() « Change focus to the parent context. <IFame1>
</html>

</html>
<frameset cols="50%,50%">
    <Fame id='11'>...     defaultContent() « driver focus to top window/first frame. <html>
    |
     -> <Frame id='22'>... defaultContent() « driver focus to top window/first frame. <Fame11> 
                           frame("relative=up") « focus to parent frame. <Fame11>
</frameset>
</html>

Conversion of RC to Web-Driver Java commands. link.


<frame> is an HTML element which defines a particular area in which another HTML document can be displayed. A frame should be used within a <frameset>. « Deprecated. Not for use in new websites.

How do I revert my changes to a git submodule?

Move into the submodule's directory, then do a git reset --hard to reset all modified files to their last committed state. Be aware that this will discard all non-committed changes.

Lazy Loading vs Eager Loading

Eager Loading: Eager Loading helps you to load all your needed entities at once. i.e. related objects (child objects) are loaded automatically with its parent object.

When to use:

  1. Use Eager Loading when the relations are not too much. Thus, Eager Loading is a good practice to reduce further queries on the Server.
  2. Use Eager Loading when you are sure that you will be using related entities with the main entity everywhere.

Lazy Loading: In case of lazy loading, related objects (child objects) are not loaded automatically with its parent object until they are requested. By default LINQ supports lazy loading.

When to use:

  1. Use Lazy Loading when you are using one-to-many collections.
  2. Use Lazy Loading when you are sure that you are not using related entities instantly.

NOTE: Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.

How to fix "could not find a base address that matches schema http"... in WCF

If you want to use baseAddressPrefixFilters in web.config, you must setup IIS (6) too. This helped me:

1/ In IIS find your site. 2/ Properties / Web site (tab) / IP address -> Advanced button 3/ Add new host header on the same port which you will use in web.config.

Convert a Unicode string to a string in Python (containing extra symbols)

>>> text=u'abcd'
>>> str(text)
'abcd'

If the string only contains ascii characters.

Exception Error c0000005 in VC++

I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.

I assume it was something to do with iostream manipulations in the constructor.

Here is the fix:

// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
    cout << "Some text I was printing.." << endl;
};


// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {

};

Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.

Python + Django page redirect

page_path = define in urls.py

def deletePolls(request):
    pollId = deletePool(request.GET['id'])
    return HttpResponseRedirect("/page_path/")

python convert list to dictionary

If you are still thinking what the! You would not be alone, its actually not that complicated really, let me explain.

How to turn a list into a dictionary using built-in functions only

We want to turn the following list into a dictionary using the odd entries (counting from 1) as keys mapped to their consecutive even entries.

l = ["a", "b", "c", "d", "e"]

dict()

To create a dictionary we can use the built in dict function for Mapping Types as per the manual the following methods are supported.

dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])

The last option suggests that we supply a list of lists with 2 values or (key, value) tuples, so we want to turn our sequential list into:

l = [["a", "b"], ["c", "d"], ["e",]]

We are also introduced to the zip function, one of the built-in functions which the manual explains:

returns a list of tuples, where the i-th tuple contains the i-th element from each of the arguments

In other words if we can turn our list into two lists a, c, e and b, d then zip will do the rest.

slice notation

Slicings which we see used with Strings and also further on in the List section which mainly uses the range or short slice notation but this is what the long slice notation looks like and what we can accomplish with step:

>>> l[::2]
['a', 'c', 'e']

>>> l[1::2]
['b', 'd']

>>> zip(['a', 'c', 'e'], ['b', 'd'])
[('a', 'b'), ('c', 'd')]

>>> dict(zip(l[::2], l[1::2]))
{'a': 'b', 'c': 'd'}

Even though this is the simplest way to understand the mechanics involved there is a downside because slices are new list objects each time, as can be seen with this cloning example:

>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]

>>> b is a
True

>>> b = a[:]
>>> b
[1, 2, 3]

>>> b is a
False

Even though b looks like a they are two separate objects now and this is why we prefer to use the grouper recipe instead.

grouper recipe

Although the grouper is explained as part of the itertools module it works perfectly fine with the basic functions too.

Some serious voodoo right? =) But actually nothing more than a bit of syntax sugar for spice, the grouper recipe is accomplished by the following expression.

*[iter(l)]*2

Which more or less translates to two arguments of the same iterator wrapped in a list, if that makes any sense. Lets break it down to help shed some light.

zip for shortest

>>> l*2
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']

>>> [l]*2
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]

>>> [iter(l)]*2
[<listiterator object at 0x100486450>, <listiterator object at 0x100486450>]

>>> zip([iter(l)]*2)
[(<listiterator object at 0x1004865d0>,),(<listiterator object at 0x1004865d0>,)]

>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd')]

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd'}

As you can see the addresses for the two iterators remain the same so we are working with the same iterator which zip then first gets a key from and then a value and a key and a value every time stepping the same iterator to accomplish what we did with the slices much more productively.

You would accomplish very much the same with the following which carries a smaller What the? factor perhaps.

>>> it = iter(l)     
>>> dict(zip(it, it))
{'a': 'b', 'c': 'd'}

What about the empty key e if you've noticed it has been missing from all the examples which is because zip picks the shortest of the two arguments, so what are we to do.

Well one solution might be adding an empty value to odd length lists, you may choose to use append and an if statement which would do the trick, albeit slightly boring, right?

>>> if len(l) % 2:
...     l.append("")

>>> l
['a', 'b', 'c', 'd', 'e', '']

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': ''}

Now before you shrug away to go type from itertools import izip_longest you may be surprised to know it is not required, we can accomplish the same, even better IMHO, with the built in functions alone.

map for longest

I prefer to use the map() function instead of izip_longest() which not only uses shorter syntax doesn't require an import but it can assign an actual None empty value when required, automagically.

>>> l = ["a", "b", "c", "d", "e"]
>>> l
['a', 'b', 'c', 'd', 'e']

>>> dict(map(None, *[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': None} 

Comparing performance of the two methods, as pointed out by KursedMetal, it is clear that the itertools module far outperforms the map function on large volumes, as a benchmark against 10 million records show.

$ time python -c 'dict(map(None, *[iter(range(10000000))]*2))'
real    0m3.755s
user    0m2.815s
sys     0m0.869s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(10000000))]*2, fillvalue=None))'
real    0m2.102s
user    0m1.451s
sys     0m0.539s

However the cost of importing the module has its toll on smaller datasets with map returning much quicker up to around 100 thousand records when they start arriving head to head.

$ time python -c 'dict(map(None, *[iter(range(100))]*2))'
real    0m0.046s
user    0m0.029s
sys     0m0.015s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100))]*2, fillvalue=None))'
real    0m0.067s
user    0m0.042s
sys     0m0.021s

$ time python -c 'dict(map(None, *[iter(range(100000))]*2))'
real    0m0.074s
user    0m0.050s
sys     0m0.022s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100000))]*2, fillvalue=None))'
real    0m0.075s
user    0m0.047s
sys     0m0.024s

See nothing to it! =)

nJoy!

How to get the list of files in a directory in a shell script?

The accepted answer will not return files prefix with a . To do that use

for entry in "$search_dir"/* "$search_dir"/.[!.]* "$search_dir"/..?*
do
  echo "$entry"
done

How to sort a list of lists by a specific index of the inner list?

Itemgetter lets you to sort by multiple criteria / columns:

sorted_list = sorted(list_to_sort, key=itemgetter(2,0,1))

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

Returning string from C function

I came across this thread while working on my understanding of Cython. My extension to the original question might be of use to others working at the C / Cython interface. So this is the extension of the original question: how do I return a string from a C function, making it available to Cython & thus to Python?

For those not familiar with it, Cython allows you to statically type Python code that you need to speed up. So the process is, enjoy writing Python :), find its a bit slow somewhere, profile it, calve off a function or two and cythonize them. Wow. Close to C speed (it compiles to C) Fixed. Yay. The other use is importing C functions or libraries into Python as done here.

This will print a string and return the same or another string to Python. There are 3 files, the c file c_hello.c, the cython file sayhello.pyx, and the cython setup file sayhello.pyx. When they are compiled using python setup.py build_ext --inplace they generate a shared library file that can be imported into python or ipython and the function sayhello.hello run.

c_hello.c

#include <stdio.h>

char *c_hello() {
  char *mystr = "Hello World!\n";
  return mystr;
  // return "this string";  // alterative
}

sayhello.pyx

cdef extern from "c_hello.c":
    cdef char* c_hello()

def hello():
    return c_hello()

setup.py

from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize


ext_modules = cythonize([Extension("sayhello", ["sayhello.pyx"])])


setup(
name = 'Hello world app',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)

Git SSH error: "Connect to host: Bad file number"

I had the problem when I had an open FileZilla-Connection on Windows. Closed FileZilla -> Problem solved.

Create a directory if it does not exist and then create the files in that directory as well

Java 8+ version:

Files.createDirectories(Paths.get("/Your/Path/Here"));

The Files.createDirectories() creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists.

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

R has gotten to the point where the OS cannot allocate it another 75.1Mb chunk of RAM. That is the size of memory chunk required to do the next sub-operation. It is not a statement about the amount of contiguous RAM required to complete the entire process. By this point, all your available RAM is exhausted but you need more memory to continue and the OS is unable to make more RAM available to R.

Potential solutions to this are manifold. The obvious one is get hold of a 64-bit machine with more RAM. I forget the details but IIRC on 32-bit Windows, any single process can only use a limited amount of RAM (2GB?) and regardless Windows will retain a chunk of memory for itself, so the RAM available to R will be somewhat less than the 3.4Gb you have. On 64-bit Windows R will be able to use more RAM and the maximum amount of RAM you can fit/install will be increased.

If that is not possible, then consider an alternative approach; perhaps do your simulations in batches with the n per batch much smaller than N. That way you can draw a much smaller number of simulations, do whatever you wanted, collect results, then repeat this process until you have done sufficient simulations. You don't show what N is, but I suspect it is big, so try smaller N a number of times to give you N over-all.

How can I change the default width of a Twitter Bootstrap modal box?

.Size(ModalSize.Large)

sample:
 using (var modal = Html.Bootstrap().Begin(new Modal().Id("modalProject_" + modelItem.id).Closeable().Size(ModalSize.Large)))
                {
}

postgresql duplicate key violates unique constraint

Intro

I also encountered this problem and the solution proposed by @adamo was basically the right solution. However, I had to invest a lot of time in the details, which is why I am now writing a new answer in order to save this time for others.

Case

My case was as follows: There was a table that was filled with data using an app. Now a new entry had to be inserted manually via SQL. After that the sequence was out of sync and no more records could be inserted via the app.

Solution

As mentioned in the answer from @adamo, the sequence must be synchronized manually. For this purpose the name of the sequence is needed. For Postgres, the name of the sequence can be determined with the command PG_GET_SERIAL_SEQUENCE. Most examples use lower case table names. In my case the tables were created by an ORM middleware (like Hibernate or Entity Framework Core etc.) and their names all started with a capital letter.

In an e-mail from 2004 (link) I got the right hint.

(Let's assume for all examples, that Foo is the table's name and Foo_id the related column.)

Command to get the sequence name:

SELECT PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id');

So, the table name must be in double quotes, surrounded by single quotes.

1. Validate, that the sequence is out-of-sync

SELECT CURRVAL(PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id')) AS "Current Value", MAX("Foo_id") AS "Max Value" FROM "Foo";

When the Current Value is less than Max Value, your sequence is out-of-sync.

2. Correction

SELECT SETVAL((SELECT PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id')), (SELECT (MAX("Foo_id") + 1) FROM "Foo"), FALSE);

Transfer data between iOS and Android via Bluetooth?

You could use p2pkit, or the free solution it was based on: https://github.com/GitGarage. Doesn't work very well, and its a fixer-upper for sure, but its, well, free. Works for small amounts of data transfer right now.

How to move an entire div element up x pixels?

you can also do this

margin-top:-30px; 
min-height:40px;

this "help" to stop the div yanking everything up a bit.

Escaping ampersand character in SQL string

Instead of

node_name = 'Geometric Vectors \& Matrices'

use

node_name = 'Geometric Vectors ' || chr(38) || ' Matrices' 

38 is the ascii code for ampersand, and in this form it will be interpreted as a string, nothing else. I tried it and it worked.

Another way could be using LIKE and an underline instead the '&' character:

node_name LIKE 'Geometric Vectors _ Matrices' 

The chance that you'll find some other record too, which is different in only this one character, is quite low.

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

If using Spring Boot this works well. Even with Spring Reactive Mongo.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

and validation config:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@Configuration
public class MongoValidationConfig {

    @Bean
    public ValidatingMongoEventListener validatingMongoEventListener() {
        return new ValidatingMongoEventListener(validator());
    }

    @Bean
    public LocalValidatorFactoryBean validator() {
        return new LocalValidatorFactoryBean();
    }
}

Standard Android Button with a different color

This is my solution which perfectly works starting from API 15. This solution keeps all default button click effects, like material RippleEffect. I have not tested it on lower APIs, but it should work.

All you need to do, is:

1) Create a style which changes only colorAccent:

<style name="Facebook.Button" parent="ThemeOverlay.AppCompat">
    <item name="colorAccent">@color/com_facebook_blue</item>
</style>

I recommend using ThemeOverlay.AppCompat or your main AppTheme as parent, to keep the rest of your styles.

2) Add these two lines to your button widget:

style="@style/Widget.AppCompat.Button.Colored"
android:theme="@style/Facebook.Button"

Sometimes your new colorAccent isn't showing in Android Studio Preview, but when you launch your app on the phone, the color will be changed.


Sample Button widget

<Button
    android:id="@+id/sign_in_with_facebook"
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="@string/sign_in_facebook"
    android:textColor="@android:color/white"
    android:theme="@style/Facebook.Button" />

Sample Button with custom color

Prevent users from submitting a form by hitting Enter

Not putting a submit button could do. Just put a script to the input (type=button) or add eventListener if you want it to submit the data in the form.

Rather use this

<input type="button">

than using this

<input type="submit">

Case statement with multiple values in each 'when' block

In a case statement, a , is the equivalent of || in an if statement.

case car
   when 'toyota', 'lexus'
      # code
end

Some other things you can do with a Ruby case statement

Unable to execute dex: Multiple dex files define

ULTRA simple solution and finest:

Remove everything in Right Click Main Project's Folder -> Properties -> Java Build Path except Android X.Y (where X.Y is the version in android). Clean, and Build. Done!

Make sure before of that to have a single android-support-v4.jar.

What are the parameters for the number Pipe - Angular 2

From the DOCS

Formats a number as text. Group sizing and separator and other locale-specific configurations are based on the active locale.

SYNTAX:

number_expression | number[:digitInfo[:locale]]

where expression is a number:

digitInfo is a string which has a following format:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
  • minIntegerDigits is the minimum number of integer digits to use.Defaults to 1
  • minFractionDigits is the minimum number of digits
  • after fraction. Defaults to 0. maxFractionDigits is the maximum number of digits after fraction. Defaults to 3.
  • locale is a string defining the locale to use (uses the current LOCALE_ID by default)

DEMO

IsNull function in DB2 SQL?

In DB2 there is a function NVL(field, value if null).

Example:

SELECT ID, NVL(NAME, "Internal) AS NAME, NVL(PRICE,0) AS PRICE FROM PRODUCT WITH UR;