Programs & Examples On #Slidetoggle

slidetoggle is a function of jQuery which displays or hides the matched elements with a sliding motion.

How to toggle font awesome icon on click?

Generally and simply it works like this:

_x000D_
_x000D_
<script>_x000D_
            $(document).ready(function () {_x000D_
                $('i').click(function () {_x000D_
                    $(this).toggleClass('fa-plus-square fa-minus-square');_x000D_
                });_x000D_
            });_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to set time delay in javascript

There are two (mostly used) types of timer function in javascript setTimeout and setInterval (other)

Both these methods have same signature. They take a call back function and delay time as parameter.

setTimeout executes only once after the delay whereas setInterval keeps on calling the callback function after every delay milisecs.

both these methods returns an integer identifier that can be used to clear them before the timer expires.

clearTimeout and clearInterval both these methods take an integer identifier returned from above functions setTimeout and setInterval

Example:

setTimeout

alert("before setTimeout");

setTimeout(function(){
        alert("I am setTimeout");
   },1000); //delay is in milliseconds 

  alert("after setTimeout");

If you run the the above code you will see that it alerts before setTimeout and then after setTimeout finally it alerts I am setTimeout after 1sec (1000ms)

What you can notice from the example is that the setTimeout(...) is asynchronous which means it doesn't wait for the timer to get elapsed before going to next statement i.e alert("after setTimeout");

Example:

setInterval

alert("before setInterval"); //called first

 var tid = setInterval(function(){
        //called 5 times each time after one second  
      //before getting cleared by below timeout. 
        alert("I am setInterval");
   },1000); //delay is in milliseconds 

  alert("after setInterval"); //called second

setTimeout(function(){
     clearInterval(tid); //clear above interval after 5 seconds
},5000);

If you run the the above code you will see that it alerts before setInterval and then after setInterval finally it alerts I am setInterval 5 times after 1sec (1000ms) because the setTimeout clear the timer after 5 seconds or else every 1 second you will get alert I am setInterval Infinitely.

How browser internally does that?

I will explain in brief.

To understand that you have to know about event queue in javascript. There is a event queue implemented in browser. Whenever an event get triggered in js, all of these events (like click etc.. ) are added to this queue. When your browser has nothing to execute it takes an event from queue and executes them one by one.

Now, when you call setTimeout or setInterval your callback get registered to an timer in browser and it gets added to the event queue after the given time expires and eventually javascript takes the event from the queue and executes it.

This happens so, because javascript engine are single threaded and they can execute only one thing at a time. So, they cannot execute other javascript and keep track of your timer. That is why these timers are registered with browser (browser are not single threaded) and it can keep track of timer and add an event in the queue after the timer expires.

same happens for setInterval only in this case the event is added to the queue again and again after the specified interval until it gets cleared or browser page refreshed.

Note

The delay parameter you pass to these functions is the minimum delay time to execute the callback. This is because after the timer expires the browser adds the event to the queue to be executed by the javascript engine but the execution of the callback depends upon your events position in the queue and as the engine is single threaded it will execute all the events in the queue one by one.

Hence, your callback may sometime take more than the specified delay time to be called specially when your other code blocks the thread and not giving it time to process what's there in the queue.

And as I mentioned javascript is single thread. So, if you block the thread for long.

Like this code

while(true) { //infinite loop 
}

Your user may get a message saying page not responding.

slideToggle JQuery right to left

I would suggest you use the below css

.showhideoverlay { 
  width: 100%;
  height: 100%;
  right: 0px;
  top: 0px;
  position: fixed;
  background: #000;
  opacity: 0.75;
}

You can then use a simple toggle function:

$('a.open').click(function() {
  $('div.showhideoverlay').toggle("slow");
});

This will display the overlay menu from right to left. Alternatively, you can use the positioning for changing the effect from top or bottom, i.e. use bottom: 0; instead of top: 0; - you will see menu sliding from right-bottom corner.

jquery toggle slide from left to right and back

See this: Demo

$('#cat_icon,.panel_title').click(function () {
   $('#categories,#cat_icon').stop().slideToggle('slow');
});

Update : To slide from left to right: Demo2

Note: Second one uses jquery-ui also

jQuery hide and show toggle div with plus and minus icon

Here is an example of how to do it with an arrow instead of a + and -. This uses jQuery to change classes on the element, and CSS to style the arrow.

_x000D_
_x000D_
$(".toggleHide").click(function() {_x000D_
  $(".elementToHide").slideToggle("fast");_x000D_
  $(this).find("i").toggleClass("down up");_x000D_
});
_x000D_
i {_x000D_
  border: solid black;_x000D_
  border-width: 0 5px 5px 0;_x000D_
  display: inline-block;_x000D_
  padding: 5px;_x000D_
  -webkit-transition-duration: 1s;_x000D_
  /* Safari */_x000D_
  transition-duration: 1s;_x000D_
}_x000D_
_x000D_
.up {_x000D_
  transform: rotate(-135deg);_x000D_
  -webkit-transform: rotate(-135deg);_x000D_
}_x000D_
_x000D_
.down {_x000D_
  transform: rotate(45deg);_x000D_
  -webkit-transform: rotate(45deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<h3 class="toggleHide"><i class="down"></i></h3>_x000D_
<aside class="elementToHide">_x000D_
  Content to hide_x000D_
</aside>
_x000D_
_x000D_
_x000D_

Toggle show/hide on click with jQuery

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js</script>        <script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").toggle();
  });
});
</script>
</head>
<body>
<p>Welcome !!!</p>
<button>Toggle between hide() and show()</button>
</body>
</html>

jQuery if statement to check visibility

After fixing a performance issue related to the use of .is(":visible"), I would recommend against the above answers and instead use jQuery's code for deciding whether a single element is visible:

$.expr.filters.visible($("#singleElementID")[0]);

What .is does is check whether a set of elements is within another set of elements. So you will looking for your element within the entire set of visible elements on your page. Having 100 elements is pretty normal and might take a few milliseconds to search through the array of visible elements. If you're building a web app you probably have hundreds or possibly thousands. Our app was sometimes taking 100ms for $("#selector").is(":visible") since it was checking if an element was in an array of 5000 other elements.

click() event is calling twice in jquery

When I use this method on load page with jquery, I write $('#obj').off('click'); before set the click function, so the bubble not occurs. Works for me.

preventDefault() on an <a> tag

Try something like:

$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
    event.preventDefault();
    $(this).next('div').slideToggle(200);
});

Here is the page about that in the jQuery documentation

Select 2 columns in one and combine them

Yes, just like you did:

select something + somethingElse as onlyOneColumn from someTable

If you queried the database, you would have gotten the right answer.

What happens is you ask for an expression. A very simple expression is just a column name, a more complicated expression can have formulas etc in it.

How to run Spring Boot web application in Eclipse itself?

Just run the main method which is in the class SampleWebJspApplication. Spring Boot will take care of all the rest (starting the embedded tomcat which will host your sample application).

Best way to verify string is empty or null

Just to show java 8's stance to remove null values.

String s = Optional.ofNullable(myString).orElse("");
if (s.trim().isEmpty()) {
    ...
}

Makes sense if you can use Optional<String>.

What is setBounds and how do I use it?

This is a method of the java.awt.Component class. It is used to set the position and size of a component:

setBounds

public void setBounds(int x,
                  int y,
                  int width,
                  int height) 

Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height. Parameters:

  • x - the new x-coordinate of this component
  • y - the new y-coordinate of this component
  • width - the new width of this component
  • height - the new height of this component

x and y as above correspond to the upper left corner in most (all?) cases.

It is a shortcut for setLocation and setSize.

This generally only works if the layout/layout manager are non-existent, i.e. null.

String.Replace(char, char) method in C#

If you use

string temp = mystring.Replace("\r\n", "").Replace("\n", "");

then you won't have to worry about where your string is coming from.

Check if MySQL table exists or not

$query = mysqli_query('SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME IN ("table1","table2","table3") AND TABLE_SCHEMA="yourschema"');
$tablesExists = array();
while( null!==($row=mysqli_fetch_row($query)) ){
    $tablesExists[] = $row[0];
}

What does file:///android_asset/www/index.html mean?

it's file:///android_asset/... not file:///android_assets/... notice the plural of assets is wrong even if your file name is assets

How to remove .html from URL?

Resorting to using .htaccess to rewrite the URLs for static HTML is generally not only unnecessary, but also bad for you website's performance. Enabling .htaccess is also an unnecessary security vulnerability - turning it off eliminates a significant number of potential issues. The same rules for each .htaccess file can instead go in a <Directory> section for that directory, and it will be more performant if you then set AllowOverride None because it won't need to check each directory for a .htaccess file, and more secure because an attacker can't change the vhost config without root access.

If you don't need .htaccess in a VPS environment, you can disable it entirely and get better performance from your web server.

All you need to do is move your individual files from a structure like this:

index.html
about.html
products.html
terms.html

To a structure like this:

index.html
about/index.html
products/index.html
terms/index.html

Your web server will then render the appropriate pages - if you load /about/, it will treat that as /about/index.html.

This won't rewrite the URL if anyone visits the old one, though, so it would need redirects to be in place if it was retroactively applied to an existing site.

What does this GCC error "... relocation truncated to fit..." mean?

On Cygwin -mcmodel=medium is already default and doesn't help. To me adding -Wl,--image-base -Wl,0x10000000 to GCC linker did fixed the error.

What are 'get' and 'set' in Swift?

A simple question should be followed by a short, simple and clear answer.

  • When we are getting a value of the property it fires its get{} part.

  • When we are setting a value to the property it fires its set{} part.

PS. When setting a value to the property, SWIFT automatically creates a constant named "newValue" = a value we are setting. After a constant "newValue" becomes accessible in the property's set{} part.

Example:

var A:Int = 0
var B:Int = 0

var C:Int {
get {return 1}
set {print("Recived new value", newValue, " and stored into 'B' ")
     B = newValue
     }
}

//When we are getting a value of C it fires get{} part of C property
A = C 
A            //Now A = 1

//When we are setting a value to C it fires set{} part of C property
C = 2
B            //Now B = 2

How to POST JSON data with Python Requests?

It turns out I was missing the header information. The following works:

url = "http://localhost:8080"
data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

The correct syntax is:

FOR EACH ROW SET NEW.bname = CONCAT( UCASE( LEFT( NEW.bname, 1 ) )
                                   , LCASE( SUBSTRING( NEW.bname, 2 ) ) )

How to make matrices in Python?

you can do it short like this:

matrix = [["A, B, C, D, E"]*5]
print(matrix)


[['A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E']]

How is length implemented in Java Arrays?

According to the Java Language Specification (specifically §10.7 Array Members) it is a field:

  • The public final field length, which contains the number of components of the array (length may be positive or zero).

Internally the value is probably stored somewhere in the object header, but that is an implementation detail and depends on the concrete JVM implementation.

The HotSpot VM (the one in the popular Oracle (formerly Sun) JRE/JDK) stores the size in the object-header:

[...] arrays have a third header field, for the array size.

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

You need to add JQuery js before adding bootstrap js file, because BootStrap use jqueries function. So make sure to load first jquery js and then bootstap js file.

<!-- JQuery Core JavaScript -->
<script src="app/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="app/js/bootstrap.min.js"></script>

Content is not allowed in Prolog SAXParserException

This error is probably related to a byte order mark (BOM) prior to the actual XML content. You need to parse the returned String and discard the BOM, so SAXParser can process the document correctly.

You will find a possible solution here.

Rails update_attributes without save?

For mass assignment of values to an ActiveRecord model without saving, use either the assign_attributes or attributes= methods. These methods are available in Rails 3 and newer. However, there are minor differences and version-related gotchas to be aware of.

Both methods follow this usage:

@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }

@user.attributes = { model: "Sierra", year: "2012", looks: "Sexy" }

Note that neither method will perform validations or execute callbacks; callbacks and validation will happen when save is called.

Rails 3

attributes= differs slightly from assign_attributes in Rails 3. attributes= will check that the argument passed to it is a Hash, and returns immediately if it is not; assign_attributes has no such Hash check. See the ActiveRecord Attribute Assignment API documentation for attributes=.

The following invalid code will silently fail by simply returning without setting the attributes:

@user.attributes = [ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ]

attributes= will silently behave as though the assignments were made successfully, when really, they were not.

This invalid code will raise an exception when assign_attributes tries to stringify the hash keys of the enclosing array:

@user.assign_attributes([ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ])

assign_attributes will raise a NoMethodError exception for stringify_keys, indicating that the first argument is not a Hash. The exception itself is not very informative about the actual cause, but the fact that an exception does occur is very important.

The only difference between these cases is the method used for mass assignment: attributes= silently succeeds, and assign_attributes raises an exception to inform that an error has occurred.

These examples may seem contrived, and they are to a degree, but this type of error can easily occur when converting data from an API, or even just using a series of data transformation and forgetting to Hash[] the results of the final .map. Maintain some code 50 lines above and 3 functions removed from your attribute assignment, and you've got a recipe for failure.

The lesson with Rails 3 is this: always use assign_attributes instead of attributes=.

Rails 4

In Rails 4, attributes= is simply an alias to assign_attributes. See the ActiveRecord Attribute Assignment API documentation for attributes=.

With Rails 4, either method may be used interchangeably. Failure to pass a Hash as the first argument will result in a very helpful exception: ArgumentError: When assigning attributes, you must pass a hash as an argument.

Validations

If you're pre-flighting assignments in preparation to a save, you might be interested in validating before save, as well. You can use the valid? and invalid? methods for this. Both return boolean values. valid? returns true if the unsaved model passes all validations or false if it does not. invalid? is simply the inverse of valid?

valid? can be used like this:

@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }.valid?

This will give you the ability to handle any validations issues in advance of calling save.

What is the difference between null=True and blank=True in Django?

null is for database and blank is for fields validation that you want to show on user interface like textfield to get the last name of person. If lastname=models.charfield (blank=true) it didnot ask user to enter last name as this is the optional field now. If lastname=models.charfield (null=true) then it means that if this field doesnot get any value from user then it will store in database as an empty string " ".

How to call a vue.js function on page load

Beware that when the mounted event is fired on a component, not all Vue components are replaced yet, so the DOM may not be final yet.

To really simulate the DOM onload event, i.e. to fire after the DOM is ready but before the page is drawn, use vm.$nextTick from inside mounted:

mounted: function () {
  this.$nextTick(function () {
    // Will be executed when the DOM is ready
  })
}

Sending XML data using HTTP POST with PHP

you can use cURL library for posting data: http://www.php.net/curl

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);

where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects

How can I bind to the change event of a textarea in jQuery?

After some experimentation I came up with this implementation:

$('.detect-change')
    .on('change cut paste', function(e) {
        console.log("Change detected.");
        contentModified = true;
    })
    .keypress(function(e) {
        if (e.which !== 0 && e.altKey == false && e.ctrlKey == false && e.metaKey == false) {
            console.log("Change detected.");
            contentModified = true;
        }
    });

Handles changes to any kind of input and select as well as textareas ignoring arrow keys and things like ctrl, cmd, function keys, etc.

Note: I've only tried this in FF since it's for a FF add-on.

$.ajax - dataType

jQuery Ajax loader is not working well when you call two APIs simultaneously. To resolve this problem you have to call the APIs one by one using the isAsync property in Ajax setting. You also need to make sure that there should not be any error in the setting. Otherwise, the loader will not work. E.g undefined content-type, data-type for POST/PUT/DELETE/GET call.

How do I monitor all incoming http requests?

I would install Microsoft Network Monitor, configure the tool so it would only see HTTP packets (filter the port) and start capturing packets.

You could download it here

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I didn't have control over the security configuration for the service I was calling into, but got the same error. I was able to fix my client as follows.

  1. In the config, set up the security mode:

    <security mode="TransportCredentialOnly">
      <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
      <message clientCredentialType="UserName" algorithmSuite="Default" />
    </security>
    
  2. In the code, set the proxy class to allow impersonation (I added a reference to a service called customer):

    Customer_PortClient proxy = new Customer_PortClient();
    proxy.ClientCredentials.Windows.AllowedImpersonationLevel =    
             System.Security.Principal.TokenImpersonationLevel.Impersonation;
    

Sort array of objects by object fields

if you're using php oop you might need to change to:

public static function cmp($a, $b) 
{
    return strcmp($a->name, $b->name);
}

//in this case FUNCTION_NAME would be cmp
usort($your_data, array('YOUR_CLASS_NAME','FUNCTION_NAME')); 

Delete ActionLink with confirm dialog

I wanted the same thing; a delete button on my Details view. I eventually realised I needed to post from that view:

@using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
            @Html.HiddenFor(model => model.Id)
            @Html.ActionLink("Edit", "Edit", new { id = Model.Id }, new { @class = "btn btn-primary", @style="margin-right:30px" })

            <input type="submit" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this record?');" />
        }

And, in the Controller:

 // this action deletes record - called from the Delete button on Details view
    [HttpPost]
    public ActionResult Details(MainPlus mainPlus)
    {
        if (mainPlus != null)
        {
            try
            {
                using (IDbConnection db = new SqlConnection(PCALConn))
                {
                    var result = db.Execute("DELETE PCAL.Main WHERE Id = @Id", new { Id = mainPlus.Id });
                }
                return RedirectToAction("Calls");
            } etc

Create Excel files from C# without office

If you're interested in making .xlsx (Office 2007 and beyond) files, you're in luck. Office 2007+ uses OpenXML which for lack of a more apt description is XML files inside of a zip named .xlsx

Take an excel file (2007+) and rename it to .zip, you can open it up and take a look. If you're using .NET 3.5 you can use the System.IO.Packaging library to manipulate the relationships & zipfile itself, and linq to xml to play with the xml (or just DOM if you're more comfortable).

Otherwise id reccomend DotNetZip, a powerfull library for manipulation of zipfiles.

OpenXMLDeveloper has lots of resources about OpenXML and you can find more there.

If you want .xls (2003 and below) you're going to have to look into 3rd party libraries or perhaps learn the file format yourself to achieve this without excel installed.

ASP.NET MVC controller actions that return JSON or partial html

Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the

public ActionResult SomeActionMethod(int id) 
{ 
    return Json(new {foo="bar", baz="Blech"});
}

Method from the jquery getJSON method by simply...

$.getJSON("../SomeActionMethod", { id: someId },
    function(data) {
        alert(data.foo);
        alert(data.baz);
    }
);

twitter bootstrap text-center when in xs mode

html

<div class="text-lg-right text-center">
  center in xs and right in lg devices
</div>

Save image from url with curl PHP

Improved version of Komang answer (add referer and user agent, check if you can write the file), return true if it's ok, false if there is an error :

public function downloadImage($url,$filename){
    if(file_exists($filename)){
        @unlink($filename);
    }
    $fp = fopen($filename,'w');
    if($fp){
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $result = parse_url($url);
        curl_setopt($ch, CURLOPT_REFERER, $result['scheme'].'://'.$result['host']);
        curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0');
        $raw=curl_exec($ch);
        curl_close ($ch);
        if($raw){
            fwrite($fp, $raw);
        }
        fclose($fp);
        if(!$raw){
            @unlink($filename);
            return false;
        }
        return true;
    }
    return false;
}

NTFS performance and large volumes of files and directories

I am building a File-Structure to host up to 2 billion (2^32) files and performed the following tests that show a sharp drop in Navigate + Read Performance at about 250 Files or 120 Directories per NTFS Directory on a Solid State Drive (SSD):

  • The File Performance drops by 50% between 250 and 1000 Files.
  • The Directory Performance drops by 60% between 120 and 1000 Directories.
  • Values for Numbers > 1000 remain relatively stable

Interestingly the Number of Directories and Files do NOT significantly interfere.

So the Lessons are:

  • File Numbers above 250 cost a Factor of 2
  • Directories above 120 cost a Factor of 2.5
  • The File-Explorer in Windows 7 can handle large #Files or #Dirs, but Usability is still bad.
  • Introducing Sub-Directories is not expensive

This is the Data (2 Measurements for each File and Directory):

(FOPS = File Operations per Second)
(DOPS = Directory Operations per Second)

#Files  lg(#)   FOPS    FOPS2   DOPS    DOPS2
   10   1.00    16692   16692   16421   16312
  100   2.00    16425   15943   15738   16031
  120   2.08    15716   16024   15878   16122
  130   2.11    15883   16124   14328   14347
  160   2.20    15978   16184   11325   11128
  200   2.30    16364   16052   9866    9678
  210   2.32    16143   15977   9348    9547
  220   2.34    16290   15909   9094    9038
  230   2.36    16048   15930   9010    9094
  240   2.38    15096   15725   8654    9143
  250   2.40    15453   15548   8872    8472
  260   2.41    14454   15053   8577    8720
  300   2.48    12565   13245   8368    8361
  400   2.60    11159   11462   7671    7574
  500   2.70    10536   10560   7149    7331
 1000   3.00    9092    9509    6569    6693
 2000   3.30    8797    8810    6375    6292
10000   4.00    8084    8228    6210    6194
20000   4.30    8049    8343    5536    6100
50000   4.70    7468    7607    5364    5365

And this is the Test Code:

[TestCase(50000, false, Result = 50000)]
[TestCase(50000, true, Result = 50000)]
public static int TestDirPerformance(int numFilesInDir, bool testDirs) {
    var files = new List<string>();
    var dir = Path.GetTempPath() + "\\Sub\\" + Guid.NewGuid() + "\\";
    Directory.CreateDirectory(dir);
    Console.WriteLine("prepare...");
    const string FILE_NAME = "\\file.txt";
    for (int i = 0; i < numFilesInDir; i++) {
        string filename = dir + Guid.NewGuid();
        if (testDirs) {
            var dirName = filename + "D";
            Directory.CreateDirectory(dirName);
            using (File.Create(dirName + FILE_NAME)) { }
        } else {
            using (File.Create(filename)) { }
        }
        files.Add(filename);
    }
    //Adding 1000 Directories didn't change File Performance
    /*for (int i = 0; i < 1000; i++) {
        string filename = dir + Guid.NewGuid();
        Directory.CreateDirectory(filename + "D");
    }*/
    Console.WriteLine("measure...");
    var r = new Random();
    var sw = new Stopwatch();
    sw.Start();
    int len = 0;
    int count = 0;
    while (sw.ElapsedMilliseconds < 5000) {
        string filename = files[r.Next(files.Count)];
        string text = File.ReadAllText(testDirs ? filename + "D" + FILE_NAME : filename);
        len += text.Length;
        count++;
    }
    Console.WriteLine("{0} File Ops/sec ", count / 5);
    return numFilesInDir; 
}

How do you set the title color for the new Toolbar?

I struggled with this for a few hours today because all of these answers are kind of out of date now what with MDC and the new theming capabilities I just could not see how to override app:titleTextColor app wide as a style.

The answer is that titleTextColor is available in the styles.xml is you are overriding something that inherits from Widget.AppCompat.Toolbar. Today I think the best choice is supposed to be Widget.MaterialComponents.Toolbar:

<style name="Widget.LL.Toolbar" parent="@style/Widget.MaterialComponents.Toolbar">
     <item name="titleTextAppearance">@style/TextAppearance.LL.Toolbar</item>
     <item name="titleTextColor">@color/white</item>
     <item name="android:background">?attr/colorSecondary</item>
</style>

<style name="TextAppearance.LL.Toolbar" parent="@style/TextAppearance.Widget.AppCompat.Toolbar.Title">
     <item name="android:textStyle">bold</item>
</style>

And in your app theme, specify the toolbarStyle:

<item name="toolbarStyle">@style/Widget.LL.Toolbar</item>

Now you can leave the xml where you specify the tool bar unchanged. For a long time I thought changing the android:textColor in the toolbar title text appearance should be working, but for some reason it does not.

How do I increase the capacity of the Eclipse output console?

Window > Preferences, go to the Run/Debug > Console section >> "Limit console output.>>Console buffer size(characters):" (This option can be seen in Eclipse Indigo ,but it limits buffer size at 1,000,000 )

What does "Could not find or load main class" mean?

If it's a Maven project:

  1. Go to the POM file.
  2. Remove all the dependencies.
  3. Save the POM file.
  4. Again import only the necessary dependencies.
  5. Save the POM file.

The issue should go away.

Best way to use PHP to encrypt and decrypt passwords?

Security warning: This code is not secure.

working example

define('SALT', 'whateveryouwant'); 

function encrypt($text) 
{ 
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 
} 

function decrypt($text) 
{ 
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 
} 

$encryptedmessage = encrypt("your message"); 
echo decrypt($encryptedmessage); 

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

In the ActionListener Class you can simply add

public void actionPerformed(ActionEvent event) {
    if (event.getSource()==textField){
        textButton.doClick();
    }
    else if (event.getSource()==textButton) {
        //do something
    }
}

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

I use this method:

var results = this.Database.SqlQuery<yourEntity>("EXEC [ent].[GetNextExportJob] {0}", ProcessorID);

I like it because I just drop in Guids and Datetimes and SqlQuery performs all the formatting for me.

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

In my case, none of these solutions worked. I had to go to

Tools -> Import and Export Settings -> Reset all settings.

and then debugging started working without any issues.

Change the Bootstrap Modal effect

I copied model code from w3school bootstrap model and added following css. This code provides beautiful animation. You can try it.

.modal.fade .modal-dialog {
     -webkit-transform: scale(0.1);
     -moz-transform: scale(0.1);
     -ms-transform: scale(0.1);
     transform: scale(0.1);
     top: 300px;
     opacity: 0;
     -webkit-transition: all 0.3s;
     -moz-transition: all 0.3s;
     transition: all 0.3s;
}

.modal.fade.in .modal-dialog {
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -ms-transform: scale(1);
    transform: scale(1);
    -webkit-transform: translate3d(0, -300px, 0);
    transform: translate3d(0, -300px, 0);
    opacity: 1;
}

How do I test a website using XAMPP?

The webpages on an online server reside in a location which looks somewhat like this: http://www.somerandomsite.com/index.php

Since xampp is Offline, it sets up a local server whose address is like this http://localhost/

Basically, xampp sets up a server (apache and others) in your system. And all the files such as index.php, somethingelse.php, etc., reside in the xampp\htdocs\ folder.

The browser locates the server in localhost and will search through the above folder for any resources available in there.

So create any number of folders inside the "xampp\htdocs\" each folder thus forming a website (as you build it).

Sometimes apache won't even start. This is due to the clashing of ports with some applications. Some of them I commonly encounter is Skype. See to that it is killed completely and restart apache

I want to truncate a text or line with ellipsis using JavaScript

For preventing the dots in the middle of a word or after a punctuation symbol.

_x000D_
_x000D_
let parseText = function(text, limit){_x000D_
  if (text.length > limit){_x000D_
      for (let i = limit; i > 0; i--){_x000D_
          if(text.charAt(i) === ' ' && (text.charAt(i-1) != ','||text.charAt(i-1) != '.'||text.charAt(i-1) != ';')) {_x000D_
              return text.substring(0, i) + '...';_x000D_
          }_x000D_
      }_x000D_
       return text.substring(0, limit) + '...';_x000D_
  }_x000D_
  else_x000D_
      return text;_x000D_
};_x000D_
    _x000D_
    _x000D_
console.log(parseText("1234567 890",5))  // >> 12345..._x000D_
console.log(parseText("1234567 890",8))  // >> 1234567..._x000D_
console.log(parseText("1234567 890",15)) // >> 1234567 890
_x000D_
_x000D_
_x000D_

PHP - check if variable is undefined

An another way is simply :

if($test){
    echo "Yes 1";
}
if(!is_null($test)){
    echo "Yes 2";
}

$test = "hello";

if($test){
    echo "Yes 3";
}

Will return :

"Yes 3"

The best way is to use isset(), otherwise you can have an error like "undefined $test".

You can do it like this :

if( isset($test) && ($test!==null) )

You'll not have any error because the first condition isn't accepted.

How to run Spyder in virtual environment?

There is an option to create virtual environments in Anaconda with required Python version.

conda create -n myenv python=3.4

To activate it :

source activate myenv   # (in linux, you can use . as a shortcut for "source")
activate myenv          # (in windows - note that you should be in your c:\anaconda2 directory)

UPDATE. I have tested it with Ubuntu 18.04. Now you have to install spyder additionally for the new environment with this command (after the activation of the environment with the command above):

conda install spyder

(I have also tested the installation with pip, but for Python 3.4 or older versions, it breaks with the library dependencies error that requires manual installation.)

And now to run Spyder with Python 3.4 just type:

spyder

Spyder with Python 3.4

EDIT from a reader:

For a normal opening, use "Anaconda Prompt" > activate myenv > spyder (then the "Anaconda Prompt" must stay open, you cannot use it for other commands, and a force-close will shut down Spyder). This is of course faster than the long load of "Anaconda Navigator" > switch environment > launch Spyder (@adelriosantiago's answer).

JSLint says "missing radix parameter"

Just put an empty string in the radix place, because parseInt() take two arguments:

parseInt(string, radix);

string The value to parse. If the string argument is not a string, then it is converted to a string (using the ToString abstract operation). Leading whitespace in the string argument is ignored.

radix An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above-mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10.

imageIndex = parseInt(id.substring(id.length - 1))-1;
imageIndex = parseInt(id.substring(id.length - 1), '')-1;

SQL Server : How to test if a string has only digit characters

There is a system function called ISNUMERIC for SQL 2008 and up. An example:

SELECT myCol
FROM mTable
WHERE ISNUMERIC(myCol)<> 1;

I did a couple of quick tests and also looked further into the docs:

ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.

Which means it is fairly predictable for example

-9879210433 would pass but 987921-0433 does not. $9879210433 would pass but 9879210$433 does not.

So using this information you can weed out based on the list of valid currency symbols and + & - characters.

php codeigniter count rows

This is what is did that solved the same problem. I solved it by creating a function that returns the query result thus:

function getUsers(){
$query = $this->db->get('users');
return $query->result();
}

//The above code can go in the user_model or whatever your model is.

This allows me to use one function for the result and number of returned rows.

Use this code below in your contoller where you need the count as well as the result array().

//This gives you the user count using the count function which returns and integer of the exact rows returned from the query.
$this->data['user_count'] = count($this->user_model->getUsers());

//This gives you the returned result array.
$this->data['users'] = $this->user_model->getUsers();

I hope this helps.

Java BigDecimal: Round to the nearest whole value

I don't think you can round it like that in a single command. Try

    ArrayList<BigDecimal> list = new ArrayList<BigDecimal>();
    list.add(new BigDecimal("100.12"));
    list.add(new BigDecimal("100.44"));
    list.add(new BigDecimal("100.50"));
    list.add(new BigDecimal("100.75"));

    for (BigDecimal bd : list){
        System.out.println(bd+" -> "+bd.setScale(0,RoundingMode.HALF_UP).setScale(2));
    }

Output:
100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00

I tested for the rest of your examples and it returns the wanted values, but I don't guarantee its correctness.

Uploading file using POST request in Node.js

An undocumented feature of the formData field that request implements is the ability to pass options to the form-data module it uses:

request({
  url: 'http://example.com',
  method: 'POST',
  formData: {
    'regularField': 'someValue',
    'regularFile': someFileStream,
    'customBufferFile': {
      value: fileBufferData,
      options: {
        filename: 'myfile.bin'
      }
    }
  }
}, handleResponse);

This is useful if you need to avoid calling requestObj.form() but need to upload a buffer as a file. The form-data module also accepts contentType (the MIME type) and knownLength options.

This change was added in October 2014 (so 2 months after this question was asked), so it should be safe to use now (in 2017+). This equates to version v2.46.0 or above of request.

Is there a way to define a min and max value for EditText in Android?

If you are only concerned about max limit then just add below line in

android:maxLength="10" 

If you need to add min limit then you can do like this way in this case min limit is 7. user is restricted to enter character between min and max limit (in between 8 and 10)

public final static boolean isValidCellPhone(String number){
        if (number.length() < 8 || number.length() >10 ) {
            return false;
        } else {

           return android.util.Patterns.PHONE.matcher(number).matches();
        }
    }

If you also need to restrict user to enter 01 at start then modify if condition like this way

if (!(number.startsWith("01")) || number.length() < 8 || number.length() >10 ) {  
.
.
.
}

At the end call method like

   ....else if (!(Helper.isValidMobilePhone(textMobileNo))){
                        Helper.setEditTextError(etMobileNo,"Invalid Mobile Number");
                    }......

How do I manage MongoDB connections in a Node.js web application?

The primary committer to node-mongodb-native says:

You open do MongoClient.connect once when your app boots up and reuse the db object. It's not a singleton connection pool each .connect creates a new connection pool.

So, to answer your question directly, reuse the db object that results from MongoClient.connect(). This gives you pooling, and will provide a noticeable speed increase as compared with opening/closing connections on each db action.

How to import or copy images to the "res" folder in Android Studio?

If you want to do this easily from within Android Studio then on the left side, right above your file directory you will see a dropdown with options on how to view your files like:

Project, Android, and Packages, plus a list of Scopes.

If you are on Android it makes it hard to see when you add new folders or assets to your project - BUT if you change the dropdown to PROJECT then the file directory will match the file system on your computer, then go to:

app > src > main > res

From here you can find the conventional Eclipse type files like drawable/drawable-hdpi/drawable-mdpi and so on where you can easily drag and drop files into or import into and instantly see them. As soon as you see your files here they will be available when going to assign image src's and so on.

Good luck Android Warriors in a strange new world!

Install pip in docker

Try this:

  1. Uncomment the following line in /etc/default/docker DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"
  2. Restart the Docker service sudo service docker restart
  3. Delete any images which have cached the invalid DNS settings.
  4. Build again and the problem should be solved.

From this question.

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

In my case it was something else: the object I was saving should first have an id(e.g. save() should be called) before I could set any kind of relationship with it.

Unknown SSL protocol error in connection

I was getting that behind a corporate proxy.

Solved by:

git config http.sslVerify "false"

Place a button right aligned

To keep the button in the page flow:

<input type="button" value="Click Me" style="margin-left: auto; display: block;" />

(put that style in a .css file, do not use this html inline, for better maintenance)

Javascript - Track mouse position

onmousemove = function(e){console.log("mouse location:", e.clientX, e.clientY)}

Open your console (Ctrl+Shift+J), copy-paste the code above and move your mouse on browser window.

HTML / CSS How to add image icon to input type="button"?

What it looks like

This works well for me, and I'm handling hover and click CSS as well (by changing background color):

HTML (here showing 2 images, image1 on top of image2):

<button class="iconButton" style="background-image: url('image1.png'), url('image2.png')"
  onclick="alert('clicked');"></button>

CSS (my images are 32px X 32px, so I gave them 4px for padding and a 5px border rounding):

.iconButton {
    width: 36px;
    height: 36px;
    background-color: #000000;
    background-position: center;
    background-repeat: no-repeat;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    outline: none;
}

.iconButton:hover {
    background-color: #303030;
}

.iconButton:active {
    background-color: #606060;
}

button::-moz-focus-inner {
    border: 0;
}

How to see the values of a table variable at debug time in T-SQL?

If you are using SQL Server 2016 or newer, you can also select it as JSON result and display it in JSON Visualizer, it's much easier to read it than in XML and allows you to filter results.

DECLARE @v nvarchar(max) = (SELECT * FROM Suppliers FOR JSON AUTO)

enter image description here

Fixed header, footer with scrollable content

Approach 1 - flexbox

It works great for both known and unknown height elements. Make sure to set the outer div to height: 100%; and reset the default margin on body. See the browser support tables.

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
.header, .footer {_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  flex: 1;_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 2 - CSS table

For both known and unknown height elements. It also works in legacy browsers including IE8.

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: table;_x000D_
}_x000D_
.header, .content, .footer {_x000D_
  display: table-row;_x000D_
}_x000D_
.header, .footer {_x000D_
  background: silver;_x000D_
}_x000D_
.inner {_x000D_
  display: table-cell;_x000D_
}_x000D_
.content .inner {_x000D_
  height: 100%;_x000D_
  position: relative;_x000D_
  background: pink;_x000D_
}_x000D_
.scrollable {_x000D_
  position: absolute;_x000D_
  left: 0; right: 0;_x000D_
  top: 0; bottom: 0;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">_x000D_
    <div class="inner">Header</div>_x000D_
  </div>_x000D_
  <div class="content">_x000D_
    <div class="inner">_x000D_
      <div class="scrollable">_x000D_
        <div style="height:1000px;">Content</div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="footer">_x000D_
    <div class="inner">Footer</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 3 - calc()

If header and footer are fixed height, you can use CSS calc().

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
  height: 50px;_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  height: calc(100% - 100px);_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 4 - % for all

If the header and footer are known height, and they are also percentage you can just do the simple math making them together of 100% height.

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
  height: 10%;_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  height: 80%;_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle

Controlling Spacing Between Table Cells

Use border-collapse and border-spacing to get spaces between the table cells. I would not recommend using floating cells as suggested by QQping.

JSFiddle

How to add a Java Properties file to my Java Project in Eclipse

If you have created a Java Project in eclipse by using the 'from existing source' option then it should work as it did before. To be more precise File > New Java Project. In the Contents section select 'Create project from existing source' and then select your existing project folder. The wizard will take care of the rest.

Checking for empty queryset in Django

If you have a huge number of objects, this can (at times) be much faster:

try:
    orgs[0]
    # If you get here, it exists...
except IndexError:
    # Doesn't exist!

On a project I'm working on with a huge database, not orgs is 400+ ms and orgs.count() is 250ms. In my most common use cases (those where there are results), this technique often gets that down to under 20ms. (One case I found, it was 6.)

Could be much longer, of course, depending on how far the database has to look to find a result. Or even faster, if it finds one quickly; YMMV.

EDIT: This will often be slower than orgs.count() if the result isn't found, particularly if the condition you're filtering on is a rare one; as a result, it's particularly useful in view functions where you need to make sure the view exists or throw Http404. (Where, one would hope, people are asking for URLs that exist more often than not.)

Generate .pem file used to set up Apple Push Notifications

Apple have changed the name of the certificate that is issued. You can now use the same certificate for both development and production. While you can still request a development only certificate you can no longer request a production only certificate.

please see below screnshot

How do I create and store md5 passwords in mysql

you have to reason in terms of hased password:

store the password as md5('bob123'); when bob is register to your app

$query = "INSERT INTO users (username,password) VALUES('bob','".md5('bob123')."');

then, when bob is logging-in:

$query = "SELECT * FROM users WHERE username = 'bob' AND password = '".md5('bob123')."';

obvioulsy use variables for username and password, these queries are generated by php and then you can execute them on mysql

Java maximum memory on Windows XP

Keep in mind that Windows has virtual memory management and the JVM only needs memory that is contiguous in its address space. So, other programs running on the system shouldn't necessarily impact your heap size. What will get in your way are DLL's that get loaded in to your address space. Unfortunately optimizations in Windows that minimize the relocation of DLL's during linking make it more likely you'll have a fragmented address space. Things that are likely to cut in to your address space aside from the usual stuff include security software, CBT software, spyware and other forms of malware. Likely causes of the variances are different security patches, C runtime versions, etc. Device drivers and other kernel bits have their own address space (the other 2GB of the 4GB 32-bit space).

You could try going through your DLL bindings in your JVM process and look at trying to rebase your DLL's in to a more compact address space. Not fun, but if you are desperate...

Alternatively, you can just switch to 64-bit Windows and a 64-bit JVM. Despite what others have suggested, while it will chew up more RAM, you will have much more contiguous virtual address space, and allocating 2GB contiguously would be trivial.

What is the difference between a generative and a discriminative algorithm?

Let's say you have input data x and you want to classify the data into labels y. A generative model learns the joint probability distribution p(x,y) and a discriminative model learns the conditional probability distribution p(y|x) - which you should read as "the probability of y given x".

Here's a really simple example. Suppose you have the following data in the form (x,y):

(1,0), (1,0), (2,0), (2, 1)

p(x,y) is

      y=0   y=1
     -----------
x=1 | 1/2   0
x=2 | 1/4   1/4

p(y|x) is

      y=0   y=1
     -----------
x=1 | 1     0
x=2 | 1/2   1/2

If you take a few minutes to stare at those two matrices, you will understand the difference between the two probability distributions.

The distribution p(y|x) is the natural distribution for classifying a given example x into a class y, which is why algorithms that model this directly are called discriminative algorithms. Generative algorithms model p(x,y), which can be transformed into p(y|x) by applying Bayes rule and then used for classification. However, the distribution p(x,y) can also be used for other purposes. For example, you could use p(x,y) to generate likely (x,y) pairs.

From the description above, you might be thinking that generative models are more generally useful and therefore better, but it's not as simple as that. This paper is a very popular reference on the subject of discriminative vs. generative classifiers, but it's pretty heavy going. The overall gist is that discriminative models generally outperform generative models in classification tasks.

Difference between return and exit in Bash functions

First of all, return is a keyword and exit is a function.

That said, here's a simplest of explanations.

return

It returns a value from a function.

exit

It exits out of or abandons the current shell.

What does "Changes not staged for commit" mean

when you change a file which is already in the repository, you have to git add it again if you want it to be staged.

This allows you to commit only a subset of the changes you made since the last commit. For example, let's say you have file a, file b and file c. You modify file a and file b but the changes are very different in nature and you don't want all of them to be in one single commit. You issue

git add a
git commit a -m "bugfix, in a"
git add b
git commit b -m "new feature, in b"

As a side note, if you want to commit everything you can just type

git commit -a

Hope it helps.

What is the best way to implement "remember me" for a website?

Store their UserId and a RememberMeToken. When they login with remember me checked generate a new RememberMeToken (which invalidate any other machines which are marked are remember me).

When they return look them up by the remember me token and make sure the UserId matches.

C# DLL config file

if you want to read settings from the DLL's config file but not from the the root applications web.config or app.config use below code to read configuration in the dll.

var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
string dllConfigData = appConfig.AppSettings.Settings["dllConfigData"].Value;

C++ sorting and keeping track of indexes

For this type of question Store the orignal array data into a new data and then binary search the first element of the sorted array into the duplicated array and that indice should be stored into a vector or array.

input array=>a
duplicate array=>b
vector=>c(Stores the indices(position) of the orignal array
Syntax:
for(i=0;i<n;i++)
c.push_back(binarysearch(b,n,a[i]));`

Here binarysearch is a function which takes the array,size of array,searching item and would return the position of the searched item

How to convert java.sql.timestamp to LocalDate (java8) java.time?

The accepted answer is not ideal, so I decided to add my 2 cents

timeStamp.toLocalDateTime().toLocalDate();

is a bad solution in general, I'm not even sure why they added this method to the JDK as it makes things really confusing by doing an implicit conversion using the system timezone. Usually when using only java8 date classes the programmer is forced to specify a timezone which is a good thing.

The good solution is

timestamp.toInstant().atZone(zoneId).toLocalDate()

Where zoneId is the timezone you want to use which is typically either ZoneId.systemDefault() if you want to use your system timezone or some hardcoded timezone like ZoneOffset.UTC

The general approach should be

  1. Break free to the new java8 date classes using a class that is directly related, e.g. in our case java.time.Instant is directly related to java.sql.Timestamp, i.e. no timezone conversions are needed between them.
  2. Use the well-designed methods in this java8 class to do the right thing. In our case atZone(zoneId) made it explicit that we are doing a conversion and using a particular timezone for it.

How to read a HttpOnly cookie using JavaScript

Different Browsers enable different security measures when the HTTPOnly flag is set. For instance Opera and Safari do not prevent javascript from writing to the cookie. However, reading is always forbidden on the latest version of all major browsers.

But more importantly why do you want to read an HTTPOnly cookie? If you are a developer, just disable the flag and make sure you test your code for xss. I recommend that you avoid disabling this flag if at all possible. The HTTPOnly flag and "secure flag" (which forces the cookie to be sent over https) should always be set.

If you are an attacker, then you want to hijack a session. But there is an easy way to hijack a session despite the HTTPOnly flag. You can still ride on the session without knowing the session id. The MySpace Samy worm did just that. It used an XHR to read a CSRF token and then perform an authorized task. Therefore, the attacker could do almost anything that the logged user could do.

People have too much faith in the HTTPOnly flag, XSS can still be exploitable. You should setup barriers around sensitive features. Such as the change password filed should require the current password. An admin's ability to create a new account should require a captcha, which is a CSRF prevention technique that cannot be easily bypassed with an XHR.

How to convert a ruby hash object to JSON?

One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).

So, take a look here:

car = {:make => "bmw", :year => "2003"}
# => {:make=>"bmw", :year=>"2003"}
car.to_json
# NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
#   from (irb):11
#   from /usr/bin/irb:12:in `<main>'
require 'json'
# => true
car.to_json
# => "{"make":"bmw","year":"2003"}"

As you can see, requiring json has magically brought method to_json to our Hash.

How to change collation of database, table, column?

I was surprised to learn, and so I had to come back here and report, that the excellent and well maintained Interconnect/it SAFE SEARCH AND REPLACE ON DATABASE script has some options for converting tables to utf8 / unicode, and even to convert to innodb. It's a script commonly used to migrate a database driven website (Wordpress, Drupal, Joomla, etc) from one domain to another.

interconnect script buttons

How can I check for "undefined" in JavaScript?

Personally, I always use the following:

var x;
if( x === undefined) {
    //Do something here
}
else {
   //Do something else here
}

The window.undefined property is non-writable in all modern browsers (JavaScript 1.8.5 or later). From Mozilla's documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined, I see this: One reason to use typeof() is that it does not throw an error if the variable has not been defined.

I prefer to have the approach of using

x === undefined 

because it fails and blows up in my face rather than silently passing/failing if x has not been declared before. This alerts me that x is not declared. I believe all variables used in JavaScript should be declared.

React js onClick can't pass value to method

class extends React.Component {
    onClickDiv = (column) => {
        // do stuff
    }
    render() {
        return <div onClick={() => this.onClickDiv('123')} />
    }
}

Is there a good JSP editor for Eclipse?

Bravo JSP Editor (Can't comment on how good it is, i haven't tried it) http://marketplace.eclipse.org/content/bravo-jsp-editor

Eclipse "Invalid Project Description" when creating new project from existing source

Today I accidentally solved the issue:

Below 2 steps may not be involved but not sure:

  1. Call from (Eclipse menu)* "/Window/Android SDK Manager" and update a) "Android SDK Tools" b) "Android SDK Platform-tools" packages
  2. Call from Eclipse menu "/Help/Check for Updates" and update Eclipse. Restart Eclipse.

Steps below are necessary:

  1. From eclipse menu "/File/Import/Android/Existing Android Code Into Workspace"
  2. Browse and select problematic project/or problematic projectS parent directory.
  3. Check "Copy projects into workspace".
  4. Check "Add projects into working sets".
  5. Press finish.

  6. [Optional scenario]: If project(s) and their containing folders have been renamed with the fully qualified package names then simply click on project node parent (where you see project package name instead of project's old name) in Eclipse and rename project with old name. Eclipse will rename folder too.

P.S. Tested on Eclipse Juno.

Edit: Many times have passed since this answer and new Eclipse and Android SDK arrived. They have no much more problems during importing existing projects. The only thing one has to consider before importing is to move project folders(those ones one is willing to import) outside of eclipse workspace dir and then check checkboxes ("copy projects into working sets", "add projects into wokring sets") in import wizard dialog. Also I recommend doing this with latest Android SDK because it no more imports projects with dummy names and does not rename folders as it did in some custom cases.

How can I get a value from a map?

The main problem is that operator [] is used to insert and read a value into and from the map, so it cannot be const. If the key does not exist, it will create a new entry with a default value in it, incrementing the size of the map, that will contain a new key with an empty string ,in this particular case, as a value if the key does not exist yet. You should avoid operator[] when reading from a map and use, as was mention before, "map.at(key)" to ensure bound checking. This is one of the most common mistakes people often do with maps. You should use "insert" and "at" unless your code is aware of this fact. Check this talk about common bugs Curiously Recurring C++ Bugs at Facebook

PHP foreach change original array values

Try this

function checkForm($fields){
        foreach($fields as $field){
            if($field['required'] && strlen($_POST[$field['name']]) <= 0){
                $field['value'] = "Some error";
            }
        }
        return $field;
    }

Run bash script from Windows PowerShell

If you add the extension .SH to the environment variable PATHEXT, you will be able to run shell scripts from PowerShell by only using the script name with arguments:

PS> .\script.sh args

If you store your scripts in a directory that is included in your PATH environment variable, you can run it from anywhere, and omit the extension and path:

PS> script args

Note: sh.exe or another *nix shell must be associated with the .sh extension.

Netbeans - class does not have a main method

This happens when you move your main class location manually because Netbeans doesn't refresh one of its property files. Open nbproject/project.properties and change the value of main.class to the correct package location.

What is the difference between String.slice and String.substring?

slice() works like substring() with a few different behaviors.

Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);

What they have in common:

  1. If start equals stop: returns an empty string
  2. If stop is omitted: extracts characters to the end of the string
  3. If either argument is greater than the string's length, the string's length will be used instead.

Distinctions of substring():

  1. If start > stop, then substring will swap those 2 arguments.
  2. If either argument is negative or is NaN, it is treated as if it were 0.

Distinctions of slice():

  1. If start > stop, slice() will return the empty string. ("")
  2. If start is negative: sets char from the end of string, exactly like substr() in Firefox. This behavior is observed in both Firefox and IE.
  3. If stop is negative: sets stop to: string.length – Math.abs(stop) (original value), except bounded at 0 (thus, Math.max(0, string.length + stop)) as covered in the ECMA specification.

Source: Rudimentary Art of Programming & Development: Javascript: substr() v.s. substring()

Sorting HTML table with JavaScript

Sorting table rows by cell. 1. Little simpler and has some features. 2. Distinguish 'number' and 'string' on sorting 3. Add toggle to sort by ASC, DESC

var index;      // cell index
var toggleBool; // sorting asc, desc 
function sorting(tbody, index){
    this.index = index;
    if(toggleBool){
        toggleBool = false;
    }else{
        toggleBool = true;
    }

    var datas= new Array();
    var tbodyLength = tbody.rows.length;
    for(var i=0; i<tbodyLength; i++){
        datas[i] = tbody.rows[i];
    }

    // sort by cell[index] 
    datas.sort(compareCells);
    for(var i=0; i<tbody.rows.length; i++){
        // rearrange table rows by sorted rows
        tbody.appendChild(datas[i]);
    }   
}

function compareCells(a,b) {
    var aVal = a.cells[index].innerText;
    var bVal = b.cells[index].innerText;

    aVal = aVal.replace(/\,/g, '');
    bVal = bVal.replace(/\,/g, '');

    if(toggleBool){
        var temp = aVal;
        aVal = bVal;
        bVal = temp;
    } 

    if(aVal.match(/^[0-9]+$/) && bVal.match(/^[0-9]+$/)){
        return parseFloat(aVal) - parseFloat(bVal);
    }
    else{
          if (aVal < bVal){
              return -1; 
          }else if (aVal > bVal){
                return 1; 
          }else{
              return 0;       
          }         
    }
}

below is html sample

            <table summary="Pioneer">

                <thead>
                    <tr>
                        <th scope="col"  onclick="sorting(tbody01, 0)">No.</th>
                        <th scope="col"  onclick="sorting(tbody01, 1)">Name</th>
                        <th scope="col"  onclick="sorting(tbody01, 2)">Belong</th>
                        <th scope="col"  onclick="sorting(tbody01, 3)">Current Networth</th>
                        <th scope="col"  onclick="sorting(tbody01, 4)">BirthDay</th>
                        <th scope="col"  onclick="sorting(tbody01, 5)">Just Number</th>
                    </tr>
                </thead>

                <tbody id="tbody01">
                    <tr>
                        <td>1</td>
                        <td>Gwanshic Yi</td>
                        <td>Gwanshic Home</td>
                        <td>120000</td>
                        <td>1982-03-20</td>
                        <td>124,124,523</td>
                    </tr>
                    <tr>
                        <td>2</td>
                        <td>Steve Jobs</td>
                        <td>Apple</td>
                        <td>19000000000</td>
                        <td>1955-02-24</td>
                        <td>194,523</td>
                    </tr>
                    <tr>
                        <td>3</td>
                        <td>Bill Gates</td>
                        <td>MicroSoft</td>
                        <td>84300000000</td>
                        <td>1955-10-28</td>
                        <td>1,524,124,523</td>
                    </tr>
                    <tr>
                        <td>4</td>
                        <td>Larry Page</td>
                        <td>Google</td>
                        <td>39100000000</td>
                        <td>1973-03-26</td>
                        <td>11,124,523</td>
                    </tr>
                </tbody>
            </table>

Print series of prime numbers in python

The fastest & best implementation of omitting primes:

def PrimeRanges2(a, b):
    arr = range(a, b+1)
    up = int(math.sqrt(b)) + 1
    for d in range(2, up):
        arr = omit_multi(arr, d)

Using $_POST to get select option value from HTML

Depends on if the form that the select is contained in has the method set to "get" or "post".

If <form method="get"> then the value of the select will be located in the super global array $_GET['taskOption'].

If <form method="post"> then the value of the select will be located in the super global array $_POST['taskOption'].

To store it into a variable you would:

$option = $_POST['taskOption']

A good place for more information would be the PHP manual: http://php.net/manual/en/tutorial.forms.php

How to deserialize a JObject to .NET object

According to this post, it's much better now:

// pick out one album
JObject jalbum = albums[0] as JObject;

// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();

Documentation: Convert JSON to a Type

SFTP Libraries for .NET

I've used IP*Works SSH and it is great. Easy to setup and use. Plus, their support is top-notch when you run into questions or problems.

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

If the shell scripts start with #!/bin/bash, they will always run with bash from /bin. If they however start with #!/usr/bin/env bash, they will search for bash in $PATH and then start with the first one they can find.

Why would this be useful? Assume you want to run bash scripts, that require bash 4.x or newer, yet your system only has bash 3.x installed and currently your distribution doesn't offer a newer version or you are no administrator and cannot change what is installed on that system.

Of course, you can download bash source code and build your own bash from scratch, placing it to ~/bin for example. And you can also modify your $PATH variable in your .bash_profile file to include ~/bin as the first entry (PATH=$HOME/bin:$PATH as ~ will not expand in $PATH). If you now call bash, the shell will first look for it in $PATH in order, so it starts with ~/bin, where it will find your bash. Same thing happens if scripts search for bash using #!/usr/bin/env bash, so these scripts would now be working on your system using your custom bash build.

One downside is, that this can lead to unexpected behavior, e.g. same script on the same machine may run with different interpreters for different environments or users with different search paths, causing all kind of headaches.

The biggest downside with env is that some systems will only allow one argument, so you cannot do this #!/usr/bin/env <interpreter> <arg>, as the systems will see <interpreter> <arg> as one argument (they will treat it as if the expression was quoted) and thus env will search for an interpreter named <interpreter> <arg>. Note that this is not a problem of the env command itself, which always allowed multiple parameters to be passed through but with the shebang parser of the system that parses this line before even calling env. Meanwhile this has been fixed on most systems but if your script wants to be ultra portable, you cannot rely that this has been fixed on the system you will be running.

It can even have security implications, e.g. if sudo was not configured to clean environment or $PATH was excluded from clean up. Let me demonstrate this:

Usually /bin is a well protected place, only root is able to change anything there. Your home directory is not, though, any program you run is able to make changes to it. That means malicious code could place a fake bash into some hidden directory, modify your .bash_profile to include that directory in your $PATH, so all scripts using #!/usr/bin/env bash will end up running with that fake bash. If sudo keeps $PATH, you are in big trouble.

E.g. consider a tool creates a file ~/.evil/bash with the following content:

#!/bin/bash

if [ $EUID -eq 0 ]; then
  echo "All your base are belong to us..."
  # We are root - do whatever you want to do
fi

/bin/bash "$@"

Let's make a simple script sample.sh:

#!/usr/bin/env bash

echo "Hello World"

Proof of concept (on a system where sudo keeps $PATH):

$ ./sample.sh
Hello World

$ sudo ./sample.sh
Hello World

$ export PATH="$HOME/.evil:$PATH"

$ ./sample.sh
Hello World

$ sudo ./sample.sh
All your base are belong to us...
Hello World

Usually the classic shells should all be located in /bin and if you don't want to place them there for whatever reason, it's really not an issue to place a symlink in /bin that points to their real locations (or maybe /bin itself is a symlink), so I would always go with #!/bin/sh and #!/bin/bash. There's just too much that would break if these wouldn't work anymore. It's not that POSIX would require these position (POSIX does not standardize path names and thus it doesn't even standardize the shebang feature at all) but they are so common, that even if a system would not offer a /bin/sh, it would probably still understand #!/bin/sh and know what to do with it and may it only be for compatibility with existing code.

But for more modern, non standard, optional interpreters like Perl, PHP, Python, or Ruby, it's not really specified anywhere where they should be located. They may be in /usr/bin but they may as well be in /usr/local/bin or in a completely different hierarchy branch (/opt/..., /Applications/..., etc.). That's why these often use the #!/usr/bin/env xxx shebang syntax.

How to choose multiple files using File Upload Control?

here is the complete example of how you can select and upload multiple files in asp.net using file upload control....

write this code in .aspx file..

<head runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<div>
    <input type="file" id="myfile" multiple="multiple" name="myfile" runat="server" size="100" />
    <br />
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    <br />
    <asp:Label ID="Span1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>

after that write this code in .aspx.cs file..

   protected void Button1_Click(object sender,EventArgs e) {
          string filepath = Server.MapPath("\\Upload");
          HttpFileCollection uploadedFiles = Request.Files;
          Span1.Text = string.Empty;

          for(int i = 0;i < uploadedFiles.Count;i++) {
              HttpPostedFile userPostedFile = uploadedFiles[i];

              try {
                  if (userPostedFile.ContentLength > 0) {
                     Span1.Text += "<u>File #" + (i + 1) +  "</u><br>";
                     Span1.Text += "File Content Type: " +  userPostedFile.ContentType      + "<br>";
                     Span1.Text += "File Size: " + userPostedFile.ContentLength           + "kb<br>";
                     Span1.Text += "File Name: " + userPostedFile.FileName + "<br>";

                     userPostedFile.SaveAs(filepath + "\\" +    Path.GetFileName(userPostedFile.FileName));                  
                     Span1.Text += "Location where saved: " +   filepath + "\\" +   Path.GetFileName(userPostedFile.FileName) + "<p>";
                  }
              } catch(Exception Ex) {
                  Span1.Text += "Error: <br>" + Ex.Message;
              }
           }
        }
    }

and here you go...your multiple file upload control is ready..have a happy day.

What is InputStream & Output Stream? Why and when do we use them?

InputStream is used for reading, OutputStream for writing. They are connected as decorators to one another such that you can read/write all different types of data from all different types of sources.

For example, you can write primitive data to a file:

File file = new File("C:/text.bin");
file.createNewFile();
DataOutputStream stream = new DataOutputStream(new FileOutputStream(file));
stream.writeBoolean(true);
stream.writeInt(1234);
stream.close();

To read the written contents:

File file = new File("C:/text.bin");
DataInputStream stream = new DataInputStream(new FileInputStream(file));
boolean isTrue = stream.readBoolean();
int value = stream.readInt();
stream.close();
System.out.printlin(isTrue + " " + value);

You can use other types of streams to enhance the reading/writing. For example, you can introduce a buffer for efficiency:

DataInputStream stream = new DataInputStream(
    new BufferedInputStream(new FileInputStream(file)));

You can write other data such as objects:

MyClass myObject = new MyClass(); // MyClass have to implement Serializable
ObjectOutputStream stream = new ObjectOutputStream(
    new FileOutputStream("C:/text.obj"));
stream.writeObject(myObject);
stream.close();

You can read from other different input sources:

byte[] test = new byte[] {0, 0, 1, 0, 0, 0, 1, 1, 8, 9};
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(test));
int value0 = stream.readInt();
int value1 = stream.readInt();
byte value2 = stream.readByte();
byte value3 = stream.readByte();
stream.close();
System.out.println(value0 + " " + value1 + " " + value2 + " " + value3);

For most input streams there is an output stream, also. You can define your own streams to reading/writing special things and there are complex streams for reading complex things (for example there are Streams for reading/writing ZIP format).

Python: json.loads returns items prefixing with 'u'

The u prefix means that those strings are unicode rather than 8-bit strings. The best way to not show the u prefix is to switch to Python 3, where strings are unicode by default. If that's not an option, the str constructor will convert from unicode to 8-bit, so simply loop recursively over the result and convert unicode to str. However, it is probably best just to leave the strings as unicode.

RegEx to match stuff between parentheses

var getMatchingGroups = function(s) {
  var r=/\((.*?)\)/g, a=[], m;
  while (m = r.exec(s)) {
    a.push(m[1]);
  }
  return a;
};

getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]

Unable to import a module that is definitely installed

In my case it was a problem with a missing init.py file in the module, that I wanted to import in a Python 2.7 environment.

Python 3.3+ has Implicit Namespace Packages that allow it to create a packages without an init.py file.

How to include bootstrap css and js in reactjs app?

Somehow the accepted answer is only talking about including css file from bootstrap.

But I think this question is related to the one here - Bootstrap Dropdown not working in React

There are couple of answers that can help -

  1. https://stackoverflow.com/a/52251319/4266842
  2. https://stackoverflow.com/a/54188034/4266842

Multiple distinct pages in one HTML file

Twine is an open-source tool for telling interactive, nonlinear stories. It generates a single html with multiples pages. Maybe it is not the right tool for you but it could be useful for someone else looking for something similar.

Lost connection to MySQL server during query?

This was happening to me with mariadb because I made a varchar(255) column a unique key.. guess that's too heavy for a unique, as the insert was timing out.

Shortcut for changing font size

You can chnage font size by ctrl + mousewheel.

OR

tools --> options --> environment --> font and color.

Detail with screenshot is mentonied here

How to set child process' environment variable in Makefile

As MadScientist pointed out, you can export individual variables with:

export MY_VAR = foo  # Available for all targets

Or export variables for a specific target (target-specific variables):

my-target: export MY_VAR_1 = foo
my-target: export MY_VAR_2 = bar
my-target: export MY_VAR_3 = baz

my-target: dependency_1 dependency_2
  echo do something

You can also specify the .EXPORT_ALL_VARIABLES target to—you guessed it!—EXPORT ALL THE THINGS!!!:

.EXPORT_ALL_VARIABLES:

MY_VAR_1 = foo
MY_VAR_2 = bar
MY_VAR_3 = baz

test:
  @echo $$MY_VAR_1 $$MY_VAR_2 $$MY_VAR_3

see .EXPORT_ALL_VARIABLES

Python: For each list element apply a function across the list

Doing it the mathy way...

nums = [1, 2, 3, 4, 5]
min_combo = (min(nums), max(nums))

Unless, of course, you have negatives in there. In that case, this won't work because you actually want the min and max absolute values - the numerator should be close to zero, and the denominator far from it, in either direction. And double negatives would break it.

Add one year in current date PYTHON

This is what I do when I need to add months or years and don't want to import more libraries. Just create a datetime.date() object, call add_month(date) to add a month and add_year(date) to add a year.

import datetime
__author__ = 'Daniel Margarido'


# Check if the int given year is a leap year
# return true if leap year or false otherwise
def is_leap_year(year):
    if (year % 4) == 0:
        if (year % 100) == 0:
            if (year % 400) == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False


THIRTY_DAYS_MONTHS = [4, 6, 9, 11]
THIRTYONE_DAYS_MONTHS = [1, 3, 5, 7, 8, 10, 12]

# Inputs -> month, year Booth integers
# Return the number of days of the given month
def get_month_days(month, year):
    if month in THIRTY_DAYS_MONTHS:   # April, June, September, November
        return 30
    elif month in THIRTYONE_DAYS_MONTHS:   # January, March, May, July, August, October, December
        return 31
    else:   # February
        if is_leap_year(year):
            return 29
        else:
            return 28

# Checks the month of the given date
# Selects the number of days it needs to add one month
# return the date with one month added
def add_month(date):
    current_month_days = get_month_days(date.month, date.year)
    next_month_days = get_month_days(date.month + 1, date.year)

    delta = datetime.timedelta(days=current_month_days)
    if date.day > next_month_days:
        delta = delta - datetime.timedelta(days=(date.day - next_month_days) - 1)

    return date + delta


def add_year(date):
    if is_leap_year(date.year):
        delta = datetime.timedelta(days=366)
    else:
        delta = datetime.timedelta(days=365)

    return date + delta


# Validates if the expected_value is equal to the given value
def test_equal(expected_value, value):
    if expected_value == value:
        print "Test Passed"
        return True

    print "Test Failed : " + str(expected_value) + " is not equal to " str(value)
    return False

# Test leap year
print "---------- Test leap year ----------"
test_equal(True, is_leap_year(2012))
test_equal(True, is_leap_year(2000))
test_equal(False, is_leap_year(1900))
test_equal(False, is_leap_year(2002))
test_equal(False, is_leap_year(2100))
test_equal(True, is_leap_year(2400))
test_equal(True, is_leap_year(2016))

# Test add month
print "---------- Test add month ----------"
test_equal(datetime.date(2016, 2, 1), add_month(datetime.date(2016, 1, 1)))
test_equal(datetime.date(2016, 6, 16), add_month(datetime.date(2016, 5, 16)))
test_equal(datetime.date(2016, 3, 15), add_month(datetime.date(2016, 2, 15)))
test_equal(datetime.date(2017, 1, 12), add_month(datetime.date(2016, 12, 12)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 31)))
test_equal(datetime.date(2015, 3, 1), add_month(datetime.date(2015, 1, 31)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 30)))
test_equal(datetime.date(2016, 4, 30), add_month(datetime.date(2016, 3, 30)))
test_equal(datetime.date(2016, 5, 1), add_month(datetime.date(2016, 3, 31)))

# Test add year
print "---------- Test add year ----------"
test_equal(datetime.date(2016, 2, 2), add_year(datetime.date(2015, 2, 2)))
test_equal(datetime.date(2001, 2, 2), add_year(datetime.date(2000, 2, 2)))
test_equal(datetime.date(2100, 2, 2), add_year(datetime.date(2099, 2, 2)))
test_equal(datetime.date(2101, 2, 2), add_year(datetime.date(2100, 2, 2)))
test_equal(datetime.date(2401, 2, 2), add_year(datetime.date(2400, 2, 2)))

MySQL query to get column names?

Not sure if this is what you were looking for, but this worked for me:

$query = query("DESC YourTable");  
$col_names = array_column($query, 'Field');

That returns a simple array of the column names / variable names in your table or array as strings, which is what I needed to dynamically build MySQL queries. My frustration was that I simply don't know how to index arrays in PHP very well, so I wasn't sure what to do with the results from DESC or SHOW. Hope my answer is helpful to beginners like myself!

To check result: print_r($col_names);

Returning from a void function

The only reason to have a return in a void function would be to exit early due to some conditional statement:

void foo(int y)
{
    if(y == 0) return;

    // do stuff with y
}

As unwind said: when the code ends, it ends. No need for an explicit return at the end.

In angular $http service, How can I catch the "status" of error?

Since $http.get returns a 'promise' with the extra convenience methods success and error (which just wrap the result of then) you should be able to use (regardless of your Angular version):

$http.get('/someUrl')
    .then(function success(response) {
        console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText
    }, function error(response) {
        console.log('failed', response); // supposed to have: data, status, headers, config, statusText
    })

Not strictly an answer to the question, but if you're getting bitten by the "my version of Angular is different than the docs" issue you can always dump all of the arguments, even if you don't know the appropriate method signature:

$http.get('/someUrl')
  .success(function(data, foo, bar) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  })
  .error(function(baz, foo, bar, idontknow) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  });

Then, based on whatever you find, you can 'fix' the function arguments to match.

How to finish Activity when starting other activity in Android?

The best - and simplest - solution might be this:

Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
finishAndRemoveTask();

Documentation for finishAndRemoveTask():

Call this when your activity is done and should be closed and the task should be completely removed as a part of finishing the root activity of the task.

Is that what you're looking for?

What are enums and why are they useful?

ENum stands for "Enumerated Type". It is a data type having a fixed set of constants which you define yourself.

Date minus 1 year?

On my website, to check if registering people is 18 years old, I simply used the following :

$legalAge = date('Y-m-d', strtotime('-18 year'));

After, only compare the the two dates.

Hope it could help someone.

How to get selected option using Selenium WebDriver with Java

In Selenium Python it is:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select

def get_selected_value_from_drop_down(self):
    try:
        select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.ID, 'data_configuration_edit_data_object_tab_details_lb_use_for_match'))))
        return select.first_selected_option.get_attribute("value")
    except NoSuchElementException, e:
        print "Element not found "
        print e

How to create streams from string in Node.Js?

Edit: Garth's answer is probably better.

My old answer text is preserved below.


To convert a string to a stream, you can use a paused through stream:

through().pause().queue('your string').end()

Example:

var through = require('through')

// Create a paused stream and buffer some data into it:
var stream = through().pause().queue('your string').end()

// Pass stream around:
callback(null, stream)

// Now that a consumer has attached, remember to resume the stream:
stream.resume()

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.

Why are Python lambdas useful?

Lambdas are actually very powerful constructs that stem from ideas in functional programming, and it is something that by no means will be easily revised, redefined or removed in the near future of Python. They help you write code that is more powerful as it allows you to pass functions as parameters, thus the idea of functions as first-class citizens.

Lambdas do tend to get confusing, but once a solid understanding is obtained, you can write clean elegant code like this:

squared = map(lambda x: x*x, [1, 2, 3, 4, 5])

The above line of code returns a list of the squares of the numbers in the list. Ofcourse, you could also do it like:

def square(x):
    return x*x

squared = map(square, [1, 2, 3, 4, 5])

It is obvious the former code is shorter, and this is especially true if you intend to use the map function (or any similar function that takes a function as a parameter) in only one place. This also makes the code more intuitive and elegant.

Also, as @David Zaslavsky mentioned in his answer, list comprehensions are not always the way to go especially if your list has to get values from some obscure mathematical way.

From a more practical standpoint, one of the biggest advantages of lambdas for me recently has been in GUI and event-driven programming. If you take a look at callbacks in Tkinter, all they take as arguments are the event that triggered them. E.g.

def define_bindings(widget):
    widget.bind("<Button-1>", do-something-cool)

def do-something-cool(event):
    #Your code to execute on the event trigger

Now what if you had some arguments to pass? Something as simple as passing 2 arguments to store the coordinates of a mouse-click. You can easily do it like this:

def main():
    # define widgets and other imp stuff
    x, y = None, None
    widget.bind("<Button-1>", lambda event: do-something-cool(x, y))

def do-something-cool(event, x, y):
    x = event.x
    y = event.y
    #Do other cool stuff

Now you can argue that this can be done using global variables, but do you really want to bang your head worrying about memory management and leakage especially if the global variable will just be used in one particular place? That would be just poor programming style.

In short, lambdas are awesome and should never be underestimated. Python lambdas are not the same as LISP lambdas though (which are more powerful), but you can really do a lot of magical stuff with them.

SQL Column definition : default value and not null redundant?

DEFAULT is the value that will be inserted in the absence of an explicit value in an insert / update statement. Lets assume, your DDL did not have the NOT NULL constraint:

ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT 'MyDefault'

Then you could issue these statements

-- 1. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B) VALUES (NULL, NULL);

-- 2. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, DEFAULT);

-- 3. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) DEFAULT VALUES;

-- 4. This will insert NULL into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, NULL);

Alternatively, you can also use DEFAULT in UPDATE statements, according to the SQL-1992 standard:

-- 5. This will update 'MyDefault' into tbl.col
UPDATE tbl SET col = DEFAULT;

-- 6. This will update NULL into tbl.col
UPDATE tbl SET col = NULL;

Note, not all databases support all of these SQL standard syntaxes. Adding the NOT NULL constraint will cause an error with statements 4, 6, while 1-3, 5 are still valid statements. So to answer your question: No, they're not redundant.

Local Storage vs Cookies

Cookies:

  1. Introduced prior to HTML5.
  2. Has expiration date.
  3. Cleared by JS or by Clear Browsing Data of browser or after expiration date.
  4. Will sent to the server per each request.
  5. The capacity is 4KB.
  6. Only strings are able to store in cookies.
  7. There are two types of cookies: persistent and session.

Local Storage:

  1. Introduced with HTML5.
  2. Does not have expiration date.
  3. Cleared by JS or by Clear Browsing Data of the browser.
  4. You can select when the data must be sent to the server.
  5. The capacity is 5MB.
  6. Data is stored indefinitely, and must be a string.
  7. Only have one type.

Function to get yesterday's date in Javascript in format DD/MM/YYYY

The problem here seems to be that you're reassigning $today by assigning a string to it:

$today = $dd+'/'+$mm+'/'+$yyyy;

Strings don't have getDate.

Also, $today.getDate()-1 just gives you the day of the month minus one; it doesn't give you the full date of 'yesterday'. Try this:

$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1); //setDate also supports negative values, which cause the month to rollover.

Then just apply the formatting code you wrote:

var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1; //January is 0!

var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+$dd} if($mm<10){$mm='0'+$mm} $yesterday = $dd+'/'+$mm+'/'+$yyyy;

Because of the last statement, $yesterday is now a String (not a Date) containing the formatted date.

What is the Swift equivalent of respondsToSelector?

Currently (Swift 2.1) you can check it using 3 ways:

  1. Using respondsToSelector answered by @Erik_at_Digit
  2. Using '?' answered by @Sulthan

  3. And using as? operator:

    if let delegateMe = self.delegate as? YourCustomViewController
    {
       delegateMe.onSuccess()
    }
    

Basically it depends on what you are trying to achieve:

  • If for example your app logic need to perform some action and the delegate isn't set or the pointed delegate didn't implement the onSuccess() method (protocol method) so option 1 and 3 are the best choice, though I'd use option 3 which is Swift way.
  • If you don't want to do anything when delegate is nil or method isn't implemented then use option 2.

Android: How to change CheckBox size?

Assume your original xml is:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
        android:drawable="@drawable/tick_img" />
    <item android:state_checked="false"
        android:drawable="@drawable/untick_img" />
</selector>

then simply remove android:button="@drawable/xml_above" in your checkbox xml, and do drawable scaling programmatically in java (decrease the 150 big size to your desired dp):

CheckBox tickRememberPasswd = findViewById(R.id.remember_tick);

//custom selector size
Drawable drawableTick = ContextCompat.getDrawable(this, R.drawable.tick_img);
Drawable drawableUntick = ContextCompat.getDrawable(this, R.drawable.untick_img);
Bitmap bitmapTick = null;
if (drawableTick != null && drawableUntick != null) {
    int desiredPixels = Math.round(convertDpToPixel(150, this));

    bitmapTick = ((BitmapDrawable) drawableTick).getBitmap();
    Drawable dTick = new BitmapDrawable(getResources()
            , Bitmap.createScaledBitmap(bitmapTick, desiredPixels, desiredPixels, true));

    Bitmap bitmapUntick = ((BitmapDrawable) drawableUntick).getBitmap();
    Drawable dUntick = new BitmapDrawable(getResources()
            , Bitmap.createScaledBitmap(bitmapUntick, desiredPixels, desiredPixels, true));

    final StateListDrawable statesTick = new StateListDrawable();
    statesTick.addState(new int[] {android.R.attr.state_checked},
            dTick);
    statesTick.addState(new int[] { }, //else state_checked false
            dUntick);
    tickRememberPasswd.setButtonDrawable(statesTick);
}

the convertDpToPixel method:

public static float convertDpToPixel(float dp, Context context) {
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return px;
}

static function in C

C programmers use the static attribute to hide variable and function declarations inside modules, much as you would use public and private declarations in Java and C++. C source files play the role of modules. Any global variable or function declared with the static attribute is private to that module. Similarly, any global variable or function declared without the static attribute is public and can be accessed by any other module. It is good programming practice to protect your variables and functions with the static attribute wherever possible.

How do I set up CLion to compile and run?

I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.

The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.

SHORT ANSWER (should be similar for MinGW too but I haven't tried it):

  1. Install Cygwin with GCC, G++, GDB and CMake (the required versions)
  2. Add full path to Cygwin 'bin' directory to Windows Environment variables
  3. Restart CLion and check 'Settings' -> 'Build, Execution, Deployment' to make sure CLion has picked up the right versions of Cygwin, make and gdb
  4. Check the project configuration ('Run' -> 'Edit configuration') to make sure your project name appears there and you can select options in 'Target', 'Configuration' and 'Executable' fields.
  5. Build and then Run
  6. Enjoy

LONG ANSWER:

Below are the detailed steps that solved this issue for me:

  1. Uninstall/delete the previous version of Cygwin (MinGW in your case)

  2. Make sure that CLion is up-to-date

  3. Run Cygwin setup (x64 for my 64-bit OS)

  4. Install at least the following packages for Cygwin: gcc g++ make Cmake gdb Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).

  5. Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows

[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']

  1. Add the 'bin' folder to the Path variable. For Cygwin, I added: D:\cygwin64\bin

  2. Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings

  3. Select 'Build, Execution, Deployment' and then click on 'Toolchains'

  4. Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)

  5. For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)

  6. 'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]

  7. Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'

See screenshot: Check all paths to the compiler, make and gdb

  1. Now go to 'Run' -> 'Edit configuration'. You should see your project name in the left-side panel and the configurations on the right side

See screenshot: Check the configuration to run the project

  1. There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active

  2. Build your project and then run the project. You should see the output in the terminal window

Hope this helps! Good luck and enjoy CLion.

Create a file if one doesn't exist - C

If fptr is NULL, then you don't have an open file. Therefore, you can't freopen it, you should just fopen it.

FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
    fptr = fopen("scores.dat", "wb");
}

note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.

A complete example

int main()
{
    FILE *fptr;
    char there_was_error = 0;
    char opened_in_read  = 1;
    fptr = fopen("scores.dat", "rb+");
    if(fptr == NULL) //if file does not exist, create it
    {
        opened_in_read = 0;
        fptr = fopen("scores.dat", "wb");
        if (fptr == NULL)
            there_was_error = 1;
    }
    if (there_was_error)
    {
        printf("Disc full or no permission\n");
        return EXIT_FAILURE;
    }
    if (opened_in_read)
        printf("The file is opened in read mode."
               " Let's read some cached data\n");
    else
        printf("The file is opened in write mode."
               " Let's do some processing and cache the results\n");
    return EXIT_SUCCESS;
}

Using CSS in Laravel views?

We can do this by the following way.

<link href="{{ asset('/css/style.css') }}" rel="stylesheet">

{{ HTML::style('css/style.css', array('media' => 'print')) }}

It will search the style file in the public folder of Laravel and then will render it.

Why is my Button text forced to ALL CAPS on Lollipop?

I do not know why the answer of @user1010160 got rating of 0. I would have given it +1 if I had enough reputations.

Since my app is designed for API less than 14 and I did not want to add code to my program I did not find a solution until I read his answer. What he said was that even though you have done what is needed in the Application styles it will not work unless you add a style to your activity and there you set textAllCaps to false.

It is not enough to have a style for the activity (my activity had a style), because the style might defaults to the AllCaps property. You have to set explicitly, in the activity too, that property to false.

I now have it both in the Application and in the Activity parts of the manifest file.

Remove duplicates from an array of objects in JavaScript

let data = [
  {
    'name': 'Amir',
    'surname': 'Rahnama'
  }, 
  {
    'name': 'Amir',
    'surname': 'Stevens'
  }
];
let non_duplicated_data = _.uniqBy(data, 'name');

append to url and refresh page

location.href = location.href + "&parameter=" + value;

How do I make JavaScript beep?

It's not possible to do directly in JavaScript. You'll need to embed a short WAV file in the HTML, and then play that via code.

An Example:

<script>
function PlaySound(soundObj) {
  var sound = document.getElementById(soundObj);
  sound.Play();
}
</script>

<embed src="success.wav" autostart="false" width="0" height="0" id="sound1"
enablejavascript="true">

You would then call it from JavaScript code as such:

PlaySound("sound1");

This should do exactly what you want - you'll just need to find/create the beep sound yourself, which should be trivial.

How can I extract a predetermined range of lines from a text file on Unix?

I wanted to do the same thing from a script using a variable and achieved it by putting quotes around the $variable to separate the variable name from the p:

sed -n "$first","$count"p imagelist.txt >"$imageblock"

I wanted to split a list into separate folders and found the initial question and answer a useful step. (split command not an option on the old os I have to port code to).

Apache default VirtualHost

The other answers here didn't work for me, but I found a pretty simple solution that did work.

I made the default one the last one listed, and I gave it ServerAlias *.

For example:

NameVirtualHost *:80

<VirtualHost *:80>
    ServerName www.secondwebsite.com
    ServerAlias secondwebsite.com *.secondwebsite.com
    DocumentRoot /home/secondwebsite/web
</VirtualHost>

<VirtualHost *:80>
    ServerName www.defaultwebsite.com
    ServerAlias *
    DocumentRoot /home/defaultwebsite/web
</VirtualHost>

If the visitor didn't explicitly choose to go to something ending in secondwebsite.com, they get the default website.

Convert SVG to PNG in Python

Another solution I've just found here How to render a scaled SVG to a QImage?

from PySide.QtSvg import *
from PySide.QtGui import *


def convertSvgToPng(svgFilepath,pngFilepath,width):
    r=QSvgRenderer(svgFilepath)
    height=r.defaultSize().height()*width/r.defaultSize().width()
    i=QImage(width,height,QImage.Format_ARGB32)
    p=QPainter(i)
    r.render(p)
    i.save(pngFilepath)
    p.end()

PySide is easily installed from a binary package in Windows (and I use it for other things so is easy for me).

However, I noticed a few problems when converting country flags from Wikimedia, so perhaps not the most robust svg parser/renderer.

How to import a class from default package

There is a workaround for your problem. You can use reflection to achieve it.

First, create an interface for your target class Calculatons :

package mypackage;

public interface CalculationsInterface {  
    int Calculate(int contextId);  
    double GetProgress(int contextId);  

}

Next, make your target class implements that interface:

public class Calculations implements mypackage.CalculationsInterface {
    @Override
    native public int Calculate(int contextId);
    @Override
    native public double GetProgress(int contextId);
    static  {
        System.loadLibrary("Calc");
    }
}

Finally, use reflection to create an instance of Calculations class and assign it to a variable of type CalculationsInterface :

Class<?> calcClass = Class.forName("Calculations");
CalculationsInterface api = (CalculationsInterface)calcClass.newInstance();
// Use it 
double res = api.GetProgress(10);

Access camera from a browser

Video Tutorial: Accessing the Camera with HTML5 & appMobi API will be helpful for you.

Also, you may try the getUserMedia method (supported by Opera 12)

enter image description here

How do I run a docker instance from a DockerFile?

Download the file and from the same directory run docker build -t nodebb .

This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb (you can change nodebb to your own name).

Could someone explain this for me - for (int i = 0; i < 8; i++)

for(<first part>; <second part>; <third part>)
{
    DoStuff();
}

This code is evaluated like this:

  1. Run <first part>
  2. If <second part> is false, skip to the end
  3. DoStuff();
  4. Run <third part>
  5. Goto 2

So for your example:

for (int i = 0; i < 8; i++)
{
    DoStuff();
}
  1. Set i to 0.
  2. If i is not less than 8, skip to the end.
  3. DoStuff();
  4. i++
  5. Goto 2

So the loop runs one time with i set to each value from 0 to 7. Note that i is incremented to 8, but then the loop ends immediately afterwards; it does not run with i set to 8.

How to delete object?

You cannot delete an managed object in C# . That's why is called MANAGED language. So you don't have to troble yourself with delete (just like in c++).

It is true that you can set it's instance to null. But that is not going to help you that much because you have no control of your GC (Garbage collector) to delete some objects apart from Collect. And this is not what you want because this will delete all your collection from a generation.

So how is it done then ? So : GC searches periodically objects that are not used anymore and it deletes the object with an internal mechanism that should not concern you.

When you set an instance to null you just notify that your object has no referene anymore ant that could help CG to collect it faster !!!

python dictionary sorting in descending order based on values

List

dict = {'Neetu':22,'Shiny':21,'Poonam':23}
print sorted(dict.items())
sv = sorted(dict.values())
print sv

Dictionary

d = []
l = len(sv)
while l != 0 :
    d.append(sv[l - 1])
    l = l - 1
print d`

Difference between __getattr__ vs __getattribute__

This is just an example based on Ned Batchelder's explanation.

__getattr__ example:

class Foo(object):
    def __getattr__(self, attr):
        print "looking up", attr
        value = 42
        self.__dict__[attr] = value
        return value

f = Foo()
print f.x 
#output >>> looking up x 42

f.x = 3
print f.x 
#output >>> 3

print ('__getattr__ sets a default value if undefeined OR __getattr__ to define how to handle attributes that are not found')

And if same example is used with __getattribute__ You would get >>> RuntimeError: maximum recursion depth exceeded while calling a Python object

How do I automatically resize an image for a mobile site?

if you use bootstrap 3 , just add img-responsive class in your img tag

<img class="img-responsive"  src="...">

if you use bootstrap 4, add img-fluid class in your img tag

<img class="img-fluid"  src="...">

which does the staff: max-width: 100%, height: auto, and display:block to the image

How to write an XPath query to match two attributes?

or //div[@id='id-74385'][@class='guest clearfix']

Opacity of div's background without affecting contained element in IE 8?

opacity on parent element sets it for the whole sub DOM tree

You can't really set opacity for certain element that wouldn't cascade to descendants as well. That's not how CSS opacity works I'm afraid.

What you can do is to have two sibling elements in one container and set transparent one's positioning:

<div id="container">
    <div id="transparent"></div>
    <div id="content"></div>
</div>

then you have to set transparent position: absolute/relative so its content sibling will be rendered over it.

rgba can do background transparency of coloured backgrounds

rgba colour setting on element's background-color will of course work, but it will limit you to only use colour as background. No images I'm afraid. You can of course use CSS3 gradients though if you provide gradient stop colours in rgba. That works as well.

But be advised that rgba may not be supported by your required browsers.

Alert-free modal dialog functionality

But if you're after some kind of masking the whole page, this is usually done by adding a separate div with this set of styles:

position: fixed;
width: 100%;
height: 100%;
z-index: 1000; /* some high enough value so it will render on top */
opacity: .5;
filter: alpha(opacity=50);

Then when you display the content it should have a higher z-index. But these two elements are not related in terms of siblings or anything. They're just displayed as they should be. One over the other.

SQL Server Configuration Manager not found

Paste this line in folder path url in file explore: C:\Windows\SysWOW64\SQLServerManager11.msc then press enter.

enter image description here

How do you create nested dict in Python?

For arbitrary levels of nestedness:

In [2]: def nested_dict():
   ...:     return collections.defaultdict(nested_dict)
   ...:

In [3]: a = nested_dict()

In [4]: a
Out[4]: defaultdict(<function __main__.nested_dict>, {})

In [5]: a['a']['b']['c'] = 1

In [6]: a
Out[6]:
defaultdict(<function __main__.nested_dict>,
            {'a': defaultdict(<function __main__.nested_dict>,
                         {'b': defaultdict(<function __main__.nested_dict>,
                                      {'c': 1})})})

Running interactive commands in Paramiko

The full paramiko distribution ships with a lot of good demos.

In the demos subdirectory, demo.py and interactive.py have full interactive TTY examples which would probably be overkill for your situation.

In your example above ssh_stdin acts like a standard Python file object, so ssh_stdin.write should work so long as the channel is still open.

I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard stdin.write method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the SSHClient.exec_command method is implemented for all the gory details.

How to print out more than 20 items (documents) in MongoDB's shell?

Could always do:

db.foo.find().forEach(function(f){print(tojson(f, '', true));});

To get that compact view.

Also, I find it very useful to limit the fields returned by the find so:

db.foo.find({},{name:1}).forEach(function(f){print(tojson(f, '', true));});

which would return only the _id and name field from foo.

Best /Fastest way to read an Excel Sheet into a DataTable?

You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy read excel file to DataTable and you can import excel file to sql server database (use SqlBulkCopy). ExcelDataReader reads very fast. On my machine 10000 records less 3 sec and 60000 less 8 sec.

Read to DataTable example:

class Program
{
    static void Main(string[] args)
    {
        var dt = new DataTable();
        using (var reader = new ExcelDataReader(@"data.xlsx"))
            dt.Load(reader);

        Console.WriteLine("done: " + dt.Rows.Count);
        Console.ReadKey();
   }
}

Where could I buy a valid SSL certificate?

You are really asking a couple of questions here:

1) Why does the price of SSL certificates vary so much

2) Where can I get good, cheap SSL certificates?

The first question is a good one. For example, the type of SSL certificate you buy is important. Many SSL certificates are domain verified only - that is, the company issuing the certificate only validate that you own the domain. They don't validate your identity, so people visiting your site might know that the domain has a SSL certificate, but that doesn't mean the person behing the website isn't a scammer or phisher, for example. This is why the Verisign solution is much more expensive - you are getting a cert that not only secures your site, but validates the identity of the owner of the site (well, that's the claim).

You can read more on this subject here

For your second question, I can personally recommend RapidSSL. I've bought several certificates from them in the past and they are, well, rapid. However, you should always do your research first. A company based in France might be better for you to deal with as you can get support in your local hours, etc.

Understanding INADDR_ANY for socket programming

INADDR_ANY is a constant, that contain 0 in value . this will used only when you want connect from all active ports you don't care about ip-add . so if you want connect any particular ip you should mention like as my_sockaddress.sin_addr.s_addr = inet_addr("192.168.78.2")

Make: how to continue after a command fails?

make -k (or --keep-going on gnumake) will do what you are asking for, I think.

You really ought to find the del or rm line that is failing and add a -f to it to keep that error from happening to others though.

Edittext change border color with shape.xml

Use this code on xml . i hope it will be work

<?xml version="1.0" encoding="utf-8" ?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
           android:thickness="0dp"
           android:shape="rectangle">
      <stroke android:width="3dp"
             android:color="#4799E8"/>
      <corners android:radius="5dp" />
      <gradient
       android:startColor="#C8C8C8"
       android:endColor="#FFFFFF"
       android:type="linear"
       android:angle="270"/>
    </shape>

How to destroy a JavaScript object?

Structure your code so that all your temporary objects are located inside closures instead of global namespace / global object properties and go out of scope when you've done with them. GC will take care of the rest.

HTML table with horizontal scrolling (first column fixed)

Take a look at this JQuery plugin:

http://fixedheadertable.com

It adds vertical (fixed header row) or horizontal (fixed first column) scrolling to an existing HTML table. There is a demo you can check for both cases of scrolling.

How to do SQL Like % in Linq?

Way late, but I threw this together to be able to do String comparisons using SQL Like style wildcards:

public static class StringLikeExtensions
{
    /// <summary>
    /// Tests a string to be Like another string containing SQL Like style wildcards
    /// </summary>
    /// <param name="value">string to be searched</param>
    /// <param name="searchString">the search string containing wildcards</param>
    /// <returns>value.Like(searchString)</returns>
    /// <example>value.Like("a")</example>
    /// <example>value.Like("a%")</example>
    /// <example>value.Like("%b")</example>
    /// <example>value.Like("a%b")</example>
    /// <example>value.Like("a%b%c")</example>
    /// <remarks>base author -- Ruard van Elburg from StackOverflow, modifications by dvn</remarks>
    /// <remarks>converted to a String extension by sja</remarks>
    /// <seealso cref="https://stackoverflow.com/questions/1040380/wildcard-search-for-linq"/>
    public static bool Like(this String value, string searchString)
    {
        bool result = false;

        var likeParts = searchString.Split(new char[] { '%' });

        for (int i = 0; i < likeParts.Length; i++)
        {
            if (likeParts[i] == String.Empty)
            {
                continue;   // "a%"
            }

            if (i == 0)
            {
                if (likeParts.Length == 1) // "a"
                {
                    result = value.Equals(likeParts[i], StringComparison.OrdinalIgnoreCase);
                }
                else // "a%" or "a%b"
                {
                    result = value.StartsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
                }
            }
            else if (i == likeParts.Length - 1) // "a%b" or "%b"
            {
                result &= value.EndsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
            }
            else // "a%b%c"
            {
                int current = value.IndexOf(likeParts[i], StringComparison.OrdinalIgnoreCase);
                int previous = value.IndexOf(likeParts[i - 1], StringComparison.OrdinalIgnoreCase);
                result &= previous < current;
            }
        }

        return result;
    }

    /// <summary>
    /// Tests a string containing SQL Like style wildcards to be ReverseLike another string 
    /// </summary>
    /// <param name="value">search string containing wildcards</param>
    /// <param name="compareString">string to be compared</param>
    /// <returns>value.ReverseLike(compareString)</returns>
    /// <example>value.ReverseLike("a")</example>
    /// <example>value.ReverseLike("abc")</example>
    /// <example>value.ReverseLike("ab")</example>
    /// <example>value.ReverseLike("axb")</example>
    /// <example>value.ReverseLike("axbyc")</example>
    /// <remarks>reversed logic of Like String extension</remarks>
    public static bool ReverseLike(this String value, string compareString)
    {
        bool result = false;

        var likeParts = value.Split(new char[] {'%'});

        for (int i = 0; i < likeParts.Length; i++)
        {
            if (likeParts[i] == String.Empty)
            {
                continue;   // "a%"
            }

            if (i == 0)
            {
                if (likeParts.Length == 1) // "a"
                {
                    result = compareString.Equals(likeParts[i], StringComparison.OrdinalIgnoreCase);
                }
                else // "a%" or "a%b"
                {
                    result = compareString.StartsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
                }
            }
            else if (i == likeParts.Length - 1) // "a%b" or "%b"
            {
                result &= compareString.EndsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
            }
            else // "a%b%c"
            {
                int current = compareString.IndexOf(likeParts[i], StringComparison.OrdinalIgnoreCase);
                int previous = compareString.IndexOf(likeParts[i - 1], StringComparison.OrdinalIgnoreCase);
                result &= previous < current;
            }
        }

        return result;
    }
}

Function not defined javascript

There are a couple of things to check:

  • In FireBug, see if there are any loading errors that would indicate that your script is badly formatted and the functions do not get registered.
  • You can also try typing "proceedToSecond" into the FireBug console to see if the function gets defined
  • One thing you may try is removing the space around the @type attribute to the script tag: it should be <script type="text/javascript"> instead of <script type = "text/javascript">

Does JavaScript guarantee object property order?

YES (for non-integer keys).

Most Browsers iterate object properties as:

  1. Integer keys in ascending order (and strings like "1" that parse as ints)
  2. String keys, in insertion order (ES2015 guarantees this and all browsers comply)
  3. Symbol names, in insertion order (ES2015 guarantees this and all browsers comply)

Some older browsers combine categories #1 and #2, iterating all keys in insertion order. If your keys might parse as integers, it's best not to rely on any specific iteration order.

Current Language Spec (since ES2015) insertion order is preserved, except in the case of keys that parse as integers (eg "7" or "99"), where behavior varies between browsers. For example, Chrome/V8 does not respect insertion order when the keys are parse as numeric.

Old Language Spec (before ES2015): Iteration order was technically undefined, but all major browsers complied with the ES2015 behavior.

Note that the ES2015 behavior was a good example of the language spec being driven by existing behavior, and not the other way round. To get a deeper sense of that backwards-compatibility mindset, see http://code.google.com/p/v8/issues/detail?id=164, a Chrome bug that covers in detail the design decisions behind Chrome's iteration order behavior. Per one of the (rather opinionated) comments on that bug report:

Standards always follow implementations, that's where XHR came from, and Google does the same thing by implementing Gears and then embracing equivalent HTML5 functionality. The right fix is to have ECMA formally incorporate the de-facto standard behavior into the next rev of the spec.

Using DateTime in a SqlParameter for Stored Procedure, format error

How are you setting up the SqlParameter? You should set the SqlDbType property to SqlDbType.DateTime and then pass the DateTime directly to the parameter (do NOT convert to a string, you are asking for a bunch of problems then).

You should be able to get the value into the DB. If not, here is a very simple example of how to do it:

static void Main(string[] args)
{
    // Create the connection.
    using (SqlConnection connection = new SqlConnection(@"Data Source=..."))
    {
        // Open the connection.
        connection.Open();

        // Create the command.
        using (SqlCommand command = new SqlCommand("xsp_Test", connection))
        {
            // Set the command type.
            command.CommandType = System.Data.CommandType.StoredProcedure;

            // Add the parameter.
            SqlParameter parameter = command.Parameters.Add("@dt",
                System.Data.SqlDbType.DateTime);

            // Set the value.
            parameter.Value = DateTime.Now;

            // Make the call.
            command.ExecuteNonQuery();
        }
    }
}

I think part of the issue here is that you are worried that the fact that the time is in UTC is not being conveyed to SQL Server. To that end, you shouldn't, because SQL Server doesn't know that a particular time is in a particular locale/time zone.

If you want to store the UTC value, then convert it to UTC before passing it to SQL Server (unless your server has the same time zone as the client code generating the DateTime, and even then, that's a risk, IMO). SQL Server will store this value and when you get it back, if you want to display it in local time, you have to do it yourself (which the DateTime struct will easily do).

All that being said, if you perform the conversion and then pass the converted UTC date (the date that is obtained by calling the ToUniversalTime method, not by converting to a string) to the stored procedure.

And when you get the value back, call the ToLocalTime method to get the time in the local time zone.

Aligning rotated xticklabels with their respective xticks

You can set the horizontal alignment of ticklabels, see the example below. If you imagine a rectangular box around the rotated label, which side of the rectangle do you want to be aligned with the tickpoint?

Given your description, you want: ha='right'

n=5

x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Ticklabel %i' % i for i in range(n)]

fig, axs = plt.subplots(1,3, figsize=(12,3))

ha = ['right', 'center', 'left']

for n, ax in enumerate(axs):
    ax.plot(x,y, 'o-')
    ax.set_title(ha[n])
    ax.set_xticks(x)
    ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])

enter image description here

How do you set, clear, and toggle a single bit?

Here are some macros I use:

SET_FLAG(Status, Flag)            ((Status) |= (Flag))
CLEAR_FLAG(Status, Flag)          ((Status) &= ~(Flag))
INVALID_FLAGS(ulFlags, ulAllowed) ((ulFlags) & ~(ulAllowed))
TEST_FLAGS(t,ulMask, ulBit)       (((t)&(ulMask)) == (ulBit))
IS_FLAG_SET(t,ulMask)             TEST_FLAGS(t,ulMask,ulMask)
IS_FLAG_CLEAR(t,ulMask)           TEST_FLAGS(t,ulMask,0)

What is the difference between XAMPP or WAMP Server & IIS?

In addition to the above, WAMP supports 64 bit PHP on Windows systems while XAMPP only offers 32 bit versions. This actually made me switch to WAMP on my Windows machine since you need 64 bit PHP 7 to get bigint numbers correctly from MySQL

Android Webview gives net::ERR_CACHE_MISS message

To Solve this Error in Webview Android, First Check the Permissions in Manifest.xml, if not define there,then define as like this. <uses-permission android:name="android.permission.INTERNET"/>

App.Config Transformation for projects which are not Web Projects in Visual Studio?

If you use a TFS online(Cloud version) and you want to transform the App.Config in a project, you can do the following without installing any extra tools. From VS => Unload the project => Edit project file => Go to the bottom of the file and add the following:

<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="AfterBuild" Condition="Exists('App.$(Configuration).config')">
<TransformXml Source="App.config" Transform="App.$(Configuration).config" Destination="$(OutDir)\$(AssemblyName).dll.config" />

AssemblyFile and Destination works for local use and TFS online(Cloud) server.

input type=file show only button

Another easy way of doing this. Make a "input type file" tag in html and hide it. Then click a button and format it according to need. After this use javascript/jquery to programmatically click the input tag when the button is clicked.

HTML :-

<input id="file" type="file" style="display: none;">
<button id="button">Add file</button>

JavaScript :-

document.getElementById('button').addEventListener("click", function() {
    document.getElementById('file').click();
});

jQuery :-

$('#button').click(function(){
    $('#file').click();
});

CSS :-

#button
{
    background-color: blue;
    color: white;
}

Here is a working JS fiddle for the same :- http://jsfiddle.net/32na3/

Extracting jar to specified directory

It's better to do this.

Navigate to the folder structure you require

Use the command

jar -xvf  'Path_to_ur_Jar_file'

hidden field in php

You absolutely can, I use this approach a lot w/ both JavaScript and PHP.

Field definition:

<input type="hidden" name="foo" value="<?php echo $var;?>" />

Access w/ PHP:

$_GET['foo'] or $_POST['foo']

Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine: https://github.com/niczak/PHP-Sanitize-Post/blob/master/sanitize.php

Cheers!

How to force a WPF binding to refresh?

MultiBinding friendly version...

private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
    BindingOperations.GetBindingExpressionBase((ComboBox)sender, ComboBox.ItemsSourceProperty).UpdateTarget();
}

When to use IList and when to use List

If you're working within a single method (or even in a single class or assembly in some cases) and no one outside is going to see what you're doing, use the fullness of a List. But if you're interacting with outside code, like when you're returning a list from a method, then you only want to declare the interface without necessarily tying yourself to a specific implementation, especially if you have no control over who compiles against your code afterward. If you started with a concrete type and you decided to change to another one, even if it uses the same interface, you're going to break someone else's code unless you started off with an interface or abstract base type.

How can I run an EXE program from a Windows Service using C#?

System.Diagnostics.Process.Start("Exe Name");

Which regular expression operator means 'Don't' match this character?

^ used at the beginning of a character range, or negative lookahead/lookbehind assertions.

>>> re.match('[^f]', 'foo')
>>> re.match('[^f]', 'bar')
<_sre.SRE_Match object at 0x7f8b102ad6b0>
>>> re.match('(?!foo)...', 'foo')
>>> re.match('(?!foo)...', 'bar')
<_sre.SRE_Match object at 0x7f8b0fe70780>

How can a LEFT OUTER JOIN return more records than exist in the left table?

In response to your postscript, that depends on what you would like.

You are getting (possible) multiple rows for each row in your left table because there are multiple matches for the join condition. If you want your total results to have the same number of rows as there is in the left part of the query you need to make sure your join conditions cause a 1-to-1 match.

Alternatively, depending on what you actually want you can use aggregate functions (if for example you just want a string from the right part you could generate a column that is a comma delimited string of the right side results for that left row.

If you are only looking at 1 or 2 columns from the outer join you might consider using a scalar subquery since you will be guaranteed 1 result.

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

I was facing the same issue while publishing my 1'st web services. I resolved it by simply doing this:

  1. Open IIS

  2. Click on Application Pools

  3. Right Click on DefaultAppPool => Set Application Pool Default => Change .Net Version to V 4.0. (You can also change .Net Framework Version of your application specifically)

Hope, it'll work.

Stretch Image to Fit 100% of Div Height and Width

Or you can put in the CSS,

<style>
div#img {
  background-image: url(“file.png");
  color:yellow (this part doesn't matter;
  height:100%;
  width:100%;
}
</style>

How to get the selected item from ListView?

Though I am using kotlin, the following code answered your question. This return selected item:

val item = myListView.adapter.getItem(i).toString()

The following is the whole selecteditem Listener

myListView.setOnItemClickListener(object : OnItemClickListener {
       override fun onItemClick(parent: AdapterView<*>, view: View, i: Int,
                        id: Long) {
           val item = myListView.adapter.getItem(i).toString()

       }
    })

The code returns the item clicked by its index i as shown in the code

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

In case you need the [] syntax, useful for "edit forms" when you need to pass parameters like id with the route, you would do something like:

[routerLink]="['edit', business._id]"

As for an "about page" with no parameters like yours,

[routerLink]="/about"

or

[routerLink]=['about']

will do the trick.

Is it possible to write data to file using only JavaScript?

In the case it is not possibile to use the new Blob solution, that is for sure the best solution in modern browser, it is still possible to use this simpler approach, that has a limit in the file size by the way:

function download() {
                var fileContents=JSON.stringify(jsonObject, null, 2);
                var fileName= "data.json";

                var pp = document.createElement('a');
                pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
                pp.setAttribute('download', fileName);
                pp.click();
            }
            setTimeout(function() {download()}, 500);

_x000D_
_x000D_
$('#download').on("click", function() {_x000D_
  function download() {_x000D_
    var jsonObject = {_x000D_
      "name": "John",_x000D_
      "age": 31,_x000D_
      "city": "New York"_x000D_
    };_x000D_
    var fileContents = JSON.stringify(jsonObject, null, 2);_x000D_
    var fileName = "data.json";_x000D_
_x000D_
    var pp = document.createElement('a');_x000D_
    pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));_x000D_
    pp.setAttribute('download', fileName);_x000D_
    pp.click();_x000D_
  }_x000D_
  setTimeout(function() {_x000D_
    download()_x000D_
  }, 500);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="download">Download me</button>
_x000D_
_x000D_
_x000D_

How do you clear the console screen in C?

There is no C portable way to do this. Although various cursor manipulation libraries like curses are relatively portable. conio.h is portable between OS/2 DOS and Windows, but not to *nix variants.

The entire notion of a "console" is a concept outside of the scope of standard C.

If you are looking for a pure Win32 API solution, There is no single call in the Windows console API to do this. One way is to FillConsoleOutputCharacter of a sufficiently large number of characters. Or WriteConsoleOutput You can use GetConsoleScreenBufferInfo to find out how many characters will be enough.

You can also create an entirely new Console Screen Buffer and make the current one.

Using $window or $location to Redirect in AngularJS

Not sure from what version, but I use 1.3.14 and you can just use:

window.location.href = '/employee/1';

No need to inject $location or $window in the controller and no need to get the current host address.

Converting dd/mm/yyyy formatted string to Datetime

use DateTime.ParseExact

string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)

null will use the current culture, which is somewhat dangerous. Try to supply a specific culture

DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)

how to get value of selected item in autocomplete

I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.

(function() {
    var lastText = '';

    $('#MyTextBox'), {
        source: MyData
    })
    .on('autocompleteselect autocompletefocus', function(ev, ui) {
        lastText = ui.item.label;
        jqTag.data('autocomplete-item', ui.item);
    })
    .keyup(function(ev) {
        if (lastText != jqTag.val()) {
            // Clear when they stop typing
            jqTag.data('autocomplete-item', null);

            // Pass the event on as autocompleteclear so callers can listen for select/clear
            var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
            return jqTag.trigger(clearEv);
    });
})();

With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.

How do I download the Android SDK without downloading Android Studio?

To download the SDK over command line, the link has changed slightly than previously mentioned:

wget --quiet --output-document=/tmp/sdk-tools-linux.zip https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_SDK_TOOLS}.zip

Latest version listed on the downloads page.

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

Here are shortcuts for the IPython Notebook.

Ctrl-m i interrupts the kernel. (that is, the sole letter i after Ctrl-m)

According to this answer, I twice works as well.

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

In my case. I had the error because I forgot to make a commit after create a repository on github into an existing project. So I solved:

git add .
git commit -m"commentary"

Then I was able to type:

git push -u origin master

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

Basically this happened with me, when i tried to change the package name of the app.

So, in emulator, same app was installed before. When i tried to install app after changing package name, it said, authority already used by older application in device.

Simply after uninstalling the application, it solved my problem.

Also, Authority name should always be : your.package.name.UNIQUENAME;

example :

  <provider
        android:name="com.aviary.android.feather.cds.AviaryCdsProvider"
        android:authorities="your.package.name.AviaryCdsProvider"
       />

Laravel: Using try...catch with DB::transaction()

In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction() but instead wrap your code in DB::beginTransaction and DB::commit/DB::rollback():

DB::beginTransaction();

try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}

See the transaction docs.

Decimal to Hexadecimal Converter in Java

The following converts decimal to Hexa Decimal with Time Complexity : O(n) Linear Time with out any java inbuilt function

private static String decimalToHexaDecimal(int N) {
    char hexaDecimals[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    StringBuilder builder = new StringBuilder();
    int base= 16;
    while (N != 0) {
        int reminder = N % base;
        builder.append(hexaDecimals[reminder]);
        N = N / base;
    }

    return builder.reverse().toString();
}

Split string with string as delimiter

I expanded Magoos answer to get both desired strings:

@ECHO OFF
SETLOCAL enabledelayedexpansion
SET "string=string1 by string2.txt"
SET "s2=%string:* by =%"
set "s1=!string: by %s2%=!"
set "s2=%s2:.txt=%"
ECHO +%s1%+%s2%+

EDIT: just to prove, my solution also works with the additional requirements:

@ECHO OFF
SETLOCAL enabledelayedexpansion
SET "string=string&1 more words by string&2 with spaces.txt"
SET "s2=%string:* by =%"
set "s1=!string: by %s2%=!"
set "s2=%s2:.txt=%"
ECHO "+%s1%+%s2%+"
set s1
set s2

Output:

"+string&1 more words+string&2 with spaces+"
s1=string&1 more words
s2=string&2 with spaces

Copy multiple files from one directory to another from Linux shell

Use wildcards:

cp /home/ankur/folder/* /home/ankur/dest

If you don't want to copy all the files, you can use braces to select files:

cp /home/ankur/folder/{file{1,2},xyz,abc} /home/ankur/dest

This will copy file1, file2, xyz, and abc.

You should read the sections of the bash man page on Brace Expansion and Pathname Expansion for all the ways you can simplify this.

Another thing you can do is cd /home/ankur/folder. Then you can type just the filenames rather than the full pathnames, and you can use filename completion by typing Tab.

UICollectionView cell selection and cell reuse

Changing the cell property such as the cell's background colors shouldn't be done on the UICollectionViewController itself, it should be done inside you CollectionViewCell class. Don't use didSelect and didDeselect, just use this:

class MyCollectionViewCell: UICollectionViewCell 
{
     override var isSelected: Bool
     {
         didSet
         {
            // Your code
         }
     } 
}

Iterating through list of list in Python

Create a method to recursively iterate through nested lists. If the current element is an instance of list, then call the same method again. If not, print the current element. Here's an example:

data = [1,2,3,[4,[5,6,7,[8,9]]]]

def print_list(the_list):

    for each_item in the_list:
        if isinstance(each_item, list):
            print_list(each_item)
        else:
            print(each_item)

print_list(data)

Matplotlib legends in subplot

This should work:

ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")

PyCharm import external library

In order to reference an external library in a project File -> Settings -> Project -> Project structure -> select the folder and mark as a source

How can I select an element by name with jQuery?

You can get the name value from an input field using name element in jQuery by:

_x000D_
_x000D_
var firstname = jQuery("#form1 input[name=firstname]").val(); //Returns ABCD_x000D_
var lastname = jQuery("#form1 input[name=lastname]").val(); //Returns XYZ _x000D_
console.log(firstname);_x000D_
console.log(lastname);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form name="form1" id="form1">_x000D_
  <input type="text" name="firstname" value="ABCD"/>_x000D_
  <input type="text" name="lastname" value="XYZ"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Printing image with PrintDocument. how to adjust the image to fit paper size

You can use my code here

//Print Button Event Handeler
private void btnPrint_Click(object sender, EventArgs e)
{
    PrintDocument pd = new PrintDocument();
    pd.PrintPage += PrintPage;
    //here to select the printer attached to user PC
    PrintDialog printDialog1 = new PrintDialog();
    printDialog1.Document = pd;
    DialogResult result = printDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        pd.Print();//this will trigger the Print Event handeler PrintPage
    }
}

//The Print Event handeler
private void PrintPage(object o, PrintPageEventArgs e)
{
    try
    {
        if (File.Exists(this.ImagePath))
        {
            //Load the image from the file
            System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\myimage.jpg");

            //Adjust the size of the image to the page to print the full image without loosing any part of it
            Rectangle m = e.MarginBounds;

            if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
            {
                m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
            }
            else
            {
                m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
            }
            e.Graphics.DrawImage(img, m);
        }
    }
    catch (Exception)
    {

    }
}

Why is the use of alloca() not considered good practice?

alloca () is nice and efficient... but it is also deeply broken.

  • broken scope behavior (function scope instead of block scope)
  • use inconsistant with malloc (alloca()-ted pointer shouldn't be freed, henceforth you have to track where you pointers are coming from to free() only those you got with malloc())
  • bad behavior when you also use inlining (scope sometimes goes to the caller function depending if callee is inlined or not).
  • no stack boundary check
  • undefined behavior in case of failure (does not return NULL like malloc... and what does failure means as it does not check stack boundaries anyway...)
  • not ansi standard

In most cases you can replace it using local variables and majorant size. If it's used for large objects, putting them on the heap is usually a safer idea.

If you really need it C you can use VLA (no vla in C++, too bad). They are much better than alloca() regarding scope behavior and consistency. As I see it VLA are a kind of alloca() made right.

Of course a local structure or array using a majorant of the needed space is still better, and if you don't have such majorant heap allocation using plain malloc() is probably sane. I see no sane use case where you really really need either alloca() or VLA.

How to copy directories in OS X 10.7.3?

tl;dr

cp -R "/src/project 1/App" "/src/project 2"

Explanation:

Using quotes will cater for spaces in the directory names

cp -R "/src/project 1/App" "/src/project 2"

If the App directory is specified in the destination directory:

cp -R "/src/project 1/App" "/src/project 2/App"

and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"

Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.

Inside a bash script:

cp -R "${1}/App" "${2}"

Extract a substring from a string in Ruby using a regular expression

You can use a regular expression for that pretty easily…

Allowing spaces around the word (but not keeping them):

str.match(/< ?([^>]+) ?>\Z/)[1]

Or without the spaces allowed:

str.match(/<([^>]+)>\Z/)[1]

How do I format a date as ISO 8601 in moment.js?

Use format with no parameters:

var date = moment();
date.format(); // "2014-09-08T08:02:17-05:00"

(http://jsfiddle.net/8gvhL1dz/)

Why Is `Export Default Const` invalid?

To me this is just one of many idiosyncracies (emphasis on the idio(t) ) of typescript that causes people to pull out their hair and curse the developers. Maybe they could work on coming up with more understandable error messages.

How to sort multidimensional array by column?

The optional key parameter to sort/sorted is a function. The function is called for each item and the return values determine the ordering of the sort

>>> lst = [['John', 2], ['Jim', 9], ['Jason', 1]]
>>> def my_key_func(item):
...     print("The key for {} is {}".format(item, item[1]))
...     return item[1]
... 
>>> sorted(lst, key=my_key_func)
The key for ['John', 2] is 2
The key for ['Jim', 9] is 9
The key for ['Jason', 1] is 1
[['Jason', 1], ['John', 2], ['Jim', 9]]

taking the print out of the function leaves

>>> def my_key_func(item):
...     return item[1]

This function is simple enough to write "inline" as a lambda function

>>> sorted(lst, key=lambda item: item[1])
[['Jason', 1], ['John', 2], ['Jim', 9]]