Programs & Examples On #Ffserver

ffserver is a streaming server for both audio and video. Questions about using ffserver that do not involve programming should be asked at Super User.

jQuery post() with serialize and extra data

$.ajax({    
    type: 'POST',  
    url: 'test.php',  
    data:$("#Test-form").serialize(),  
    dataType:'json',
     beforeSend:function(xhr, settings){
     settings.data += '&moreinfo=MoreData';
     },
    success:function(data){
            //  json response  
    },
    error: function(data) { 
        // if error occured
    }
    });

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

Real mouse position in canvas

You need to get the mouse position relative to the canvas

To do that you need to know the X/Y position of the canvas on the page.

This is called the canvas’s “offset”, and here’s how to get the offset. (I’m using jQuery in order to simplify cross-browser compatibility, but if you want to use raw javascript a quick Google will get that too).

    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

Then in your mouse handler, you can get the mouse X/Y like this:

  function handleMouseDown(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
}

Here is an illustrating code and fiddle that shows how to successfully track mouse events on the canvas:

http://jsfiddle.net/m1erickson/WB7Zu/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;

    function handleMouseDown(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#downlog").html("Down: "+ mouseX + " / " + mouseY);

      // Put your mousedown stuff here

    }

    function handleMouseUp(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#uplog").html("Up: "+ mouseX + " / " + mouseY);

      // Put your mouseup stuff here
    }

    function handleMouseOut(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#outlog").html("Out: "+ mouseX + " / " + mouseY);

      // Put your mouseOut stuff here
    }

    function handleMouseMove(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#movelog").html("Move: "+ mouseX + " / " + mouseY);

      // Put your mousemove stuff here

    }

    $("#canvas").mousedown(function(e){handleMouseDown(e);});
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
    $("#canvas").mouseup(function(e){handleMouseUp(e);});
    $("#canvas").mouseout(function(e){handleMouseOut(e);});

}); // end $(function(){});
</script>

</head>

<body>
    <p>Move, press and release the mouse</p>
    <p id="downlog">Down</p>
    <p id="movelog">Move</p>
    <p id="uplog">Up</p>
    <p id="outlog">Out</p>
    <canvas id="canvas" width=300 height=300></canvas>

</body>
</html>

How do I view / replay a chrome network debugger har file saved with content?

Edit: Harhar is now open source. I have updated the URL below.

If you use an Avalanche load generator, you can use Harhar to replay a HAR file at very high load: https://acastaner.github.io/harhar/

This tool handles the "content" you use when you "Save as HAR with content."

Solve error javax.mail.AuthenticationFailedException

The solution that works for me has two steps.

  1. First step

    package com.student.mail;
    
    import java.util.Properties;
    
    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    /**
     *
     * @author jorge santos
     */
    public class GoogleMail {
        public static void main(String[] args) {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465"); 
            Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("[email protected]","Silueta95#");
                }
            });
    
        try {
    
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("[email protected]"));
            message.setSubject("Testing Subject");
            message.setText("Test Mail");
    
            Transport.send(message);
    
            System.out.println("Done");
    
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
    
    }
    
  2. Enable the gmail security

    https://myaccount.google.com/u/2/lesssecureapps?pli=1&pageId=none
    

Set a thin border using .css() in javascript

I'd recommend using a class instead of setting css properties. So instead of this:

$(this).css({"border-color": "#C1E0FF", 
             "border-width":"1px", 
             "border-style":"solid"});

Define a css class:

.border 
{ 
  border-color: #C1E0FF; 
  border-width:1px; 
  border-style:solid; 
}

And then change your javascript to:

$(this).addClass("border");

Cannot connect to MySQL 4.1+ using old authentication

On OSX, I used MacPorts to address the same problem when connecting to my siteground database. Siteground appears to be using 5.0.77mm0.1-log, but creating a new user account didn't fix the problem. This is what did

sudo port install php5-mysql -mysqlnd +mysql5

This downgrades the mysql driver that php will use.

Delete commits from a branch in Git

Assuming you have not pushed to the remote repository, you could re-clone the repository. This has been my method of choice a few times.

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

What is the difference between a mutable and immutable string in C#?

None, actually. The String class is mutable.

unsafe
{
    string foo = string.Copy("I am immutable.");
    fixed (char* pChar = foo)
    {
        char* pFoo = pChar;

        pFoo[5] = ' ';
        pFoo[6] = ' ';
    }

    Console.WriteLine(foo); // "I am   mutable."
}

This kind of logic is done all the time in the String and StringBuilder classes, actually. They just allocate a new string each time you call Concat, Substring, etc. and use pointer arithmetic to copy over to the new string. Strings just don't mutate themselves, hence why they are considered "immutable".


By the way, do not attempt this with string literals or you will badly mess up your program:

string bar = "I am a string.";

fixed (char* pChar = bar)
{
    char* pBar = pChar;

    pBar[2] = ' ';
}

string baz = "I am a string.";

Console.WriteLine(baz); // "I  m a string."

This is because string literals are interned in the desktop .NET Framework; in other words, bar and baz point to the exact same string, so mutating one will mutate the other. This is all fine and dandy though if you're using an unmanaged platform like WinRT, which lacks string interning.

How to truncate text in Angular2?

If you want to truncate by a number of words and add an ellipsis you can use this function:

truncate(value: string, limit: number = 40, trail: String = '…'): string {
  let result = value || '';

  if (value) {
    const words = value.split(/\s+/);
    if (words.length > Math.abs(limit)) {
      if (limit < 0) {
        limit *= -1;
        result = trail + words.slice(words.length - limit, words.length).join(' ');
      } else {
        result = words.slice(0, limit).join(' ') + trail;
      }
    }
  }

  return result;
}

Example:

truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 5, '…')
> "Bacon ipsum dolor amet sirloin…"

taken from: https://github.com/yellowspot/ng2-truncate/blob/master/src/truncate-words.pipe.ts

If you want to truncate by a number of letters but don't cut words out use this:

truncate(value: string, limit = 25, completeWords = true, ellipsis = '…') {
  let lastindex = limit;
  if (completeWords) {
    lastindex = value.substr(0, limit).lastIndexOf(' ');
  }
  return `${value.substr(0, limit)}${ellipsis}`;
}

Example:

truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 19, true, '…')
> "Bacon ipsum dolor…"

truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 19, false, '…')
> "Bacon ipsum dolor a…"

How to Apply Gradient to background view of iOS Swift App

Easy to use extension on swift 3

extension CALayer {
    func addGradienBorder(colors:[UIColor] = [UIColor.red,UIColor.blue], width:CGFloat = 1) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame =  CGRect(origin: .zero, size: self.bounds.size)
        gradientLayer.startPoint = CGPoint(x:0.0, y:0.5)
        gradientLayer.endPoint = CGPoint(x:1.0, y:0.5)
        gradientLayer.colors = colors.map({$0.cgColor})

        let shapeLayer = CAShapeLayer()
        shapeLayer.lineWidth = width
        shapeLayer.path = UIBezierPath(rect: self.bounds).cgPath
        shapeLayer.fillColor = nil
        shapeLayer.strokeColor = UIColor.black.cgColor
        gradientLayer.mask = shapeLayer

        self.addSublayer(gradientLayer)
    }
}

use to your view, example

yourView.addGradienBorder(color: UIColor.black, opacity: 0.1, offset: CGSize(width:2 , height: 5), radius: 3, viewCornerRadius: 3.0)

Passing variable from Form to Module in VBA

Siddharth's answer is nice, but relies on globally-scoped variables. There's a better, more OOP-friendly way.

A UserForm is a class module like any other - the only difference is that it has a hidden VB_PredeclaredId attribute set to True, which makes VB create a global-scope object variable named after the class - that's how you can write UserForm1.Show without creating a new instance of the class.

Step away from this, and treat your form as an object instead - expose Property Get members and abstract away the form's controls - the calling code doesn't care about controls anyway:

Option Explicit
Private cancelling As Boolean

Public Property Get UserId() As String
    UserId = txtUserId.Text
End Property

Public Property Get Password() As String
    Password = txtPassword.Text
End Property

Public Property Get IsCancelled() As Boolean
    IsCancelled = cancelling
End Property

Private Sub OkButton_Click()
    Me.Hide
End Sub

Private Sub CancelButton_Click()
    cancelling = True
    Me.Hide
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        cancelling = True
        Cancel = True
        Me.Hide
    End If
End Sub

Now the calling code can do this (assuming the UserForm was named LoginPrompt):

With New LoginPrompt
    .Show vbModal
    If .IsCancelled Then Exit Sub
    DoSomething .UserId, .Password
End With

Where DoSomething would be some procedure that requires the two string parameters:

Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
    'work with the parameter values, regardless of where they came from
End Sub

How do I import an existing Java keystore (.jks) file into a Java installation?

Ok, so here was my process:

keytool -list -v -keystore permanent.jks - got me the alias.

keytool -export -alias alias_name -file certificate_name -keystore permanent.jks - got me the certificate to import.

Then I could import it with the keytool:

keytool -import -alias alias_name -file certificate_name -keystore keystore location

As @Christian Bongiorno says the alias can't already exist in your keystore.

PHP Foreach Arrays and objects

Use

//$arr should be array as you mentioned as below
foreach($arr as $key=>$value){
  echo $value->sm_id;
}

OR

//$arr should be array as you mentioned as below
foreach($arr as $value){
  echo $value->sm_id;
}

Java to Jackson JSON serialization: Money fields

I'm one of the maintainers of jackson-datatype-money, so take this answer with a grain of salt since I'm certainly biased. The module should cover your needs and it's pretty light-weight (no additional runtime dependencies). In addition it's mentioned in the Jackson docs, Spring docs and there were even some discussions already about how to integrate it into the official ecosystem of Jackson.

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

I had a similar error but with different context when I uploaded a *.p file to Google Drive. I tried to use it later in a Google Colab session, and got this error:

    1 with open("/tmp/train.p", mode='rb') as training_data:
----> 2     train = pickle.load(training_data)
UnpicklingError: invalid load key, '<'.

I solved it by compressing the file, upload it and then unzip on the session. It looks like the pickle file is not saved correctly when you upload/download it so it gets corrupted.

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

Other folks have already done a good job of explaining this ridiculus conundrum ... and I think Chris Hoffman did an even better job here: https://www.howtogeek.com/326509/whats-the-difference-between-the-system32-and-syswow64-folders-in-windows/

My two thoughts:

  1. We all make stupid short-sighted mistakes in life. When Microsoft named their (at the time) Win32 DLL directory "System32", it made sense at the time ... they just didn't take into consideration what would happen if/when a 64-bit (or 128-bit) version of their OS got developed later - and the massive backward compatibility issue such a directory name would cause. Hindsight is always 20-20, so I can't really blame them (too much) for such a mistake. ...HOWEVER... When Microsoft did later develop their 64-bit operating system, even with the benefit of hindsight, why oh why would they make not only the exact same short-sighted mistake AGAIN but make it even worse by PURPOSEFULLY giving it such a misleading name?!? Shame on them!!! Why not AT LEAST actually name the directory "SysWin32OnWin64" to avoid confusion?!? And what happens when they eventually produce a 128-bit OS ... then where are they going to put their 32-bit, 64-bit, and 128-bit DLLs?!?

  2. All of this logic still seems completely flawed to me. On 32-bit versions of Windows, System32 contains 32-bit DLLs; on 64-bit versions of Windows, System32 contains 64-bit DLLs ... so that developers wouldn't have to make code changes, correct? The problem with this logic is that those developers are either now making 64-bit apps needing 64-bit DLLs or they're making 32-bit apps needing 32-bit DLLs ... either way, aren't they still screwed? I mean, if they're still making a 32-bit app, for it to now run on a 64-bit Windows, they'll now need to make a code change to find/reference the same ol' 32-bit DLL they used before (now located in SysWOW64). Or, if they're working on a 64-bit app, they're going to need to re-write their old app for the new OS anyway ... so a recompile/rebuild was going to be needed anyway!!!

Microsoft just hurts me sometimes.

What to do about Eclipse's "No repository found containing: ..." error messages?

The updates that Eclipse has found have dependencies that need to be downloaded during the installation but which cannot currently be found. This may be a temporary network problem or some repo server being down (if you're lucky). But unfortunately, sometimes this simply means that the dependencies are not contained in the repositories that Eclipse is trying to download them from, at least that is what i have encountered every now and then (not annoyingly often though).

So either the failure is temporary and you should try again or you are out of luck and may have to use a manual installation procedure (download and unpack in plugins folder).

Maybe you can increase your success rate by adding the repositories that supposedly contain the artifacts in the 'Available Software Sites' dialogue.

I'm not 100% sure of that though. In fact, I would like to find a 'perfect' answer to this question myself.

What usually works quite well is installing plugins via the Eclipse Marketplace.

Oh and sometimes this helps: Uncheck some options (like OSGI in your case).

How to open an Excel file in C#?

For opening a file, try this:

objexcel.Workbooks.Open(@"C:\YourPath\YourExcelFile.xls",
    missing, missing, missing, missing, missing, missing, missing,
    missing, missing, missing, missing, missing,missing, missing);

You must supply those stupid looking 'missing' arguments. If you were writing the same code in VB.Net you wouldn't have needed them, but you can't avoid them in C#.

'\r': command not found - .bashrc / .bash_profile

For those who don't have dos2unix installed (and don't want to install it):

Remove trailing \r character that causes this error:

sed -i 's/\r$//' filename


Explanation:

Option -i is for in-place editing, we delete the trailing \r directly in the input file. Thus be careful to type the pattern correctly.

Ajax passing data to php script

Try sending the data like this:

var data = {};
data.album = this.title;

Then you can access it like

$_POST['album']

Notice not a 'GET'

Differences between SP initiated SSO and IDP initiated SSO

In IDP Init SSO (Unsolicited Web SSO) the Federation process is initiated by the IDP sending an unsolicited SAML Response to the SP. In SP-Init, the SP generates an AuthnRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with a SAML Response. IMHO ADFSv2 support for SAML2.0 Web SSO SP-Init is stronger than its IDP-Init support re: integration with 3rd Party Fed products (mostly revolving around support for RelayState) so if you have a choice you'll want to use SP-Init as it'll probably make life easier with ADFSv2.

Here are some simple SSO descriptions from the PingFederate 8.0 Getting Started Guide that you can poke through that may help as well -- https://documentation.pingidentity.com/pingfederate/pf80/index.shtml#gettingStartedGuide/task/idpInitiatedSsoPOST.html

Why Doesn't C# Allow Static Methods to Implement an Interface?

Conceptually there is no reason why an interface could not define a contract that includes static methods.

For the current C# language implementation, the restriction is due to the allowance of inheritance of a base class and interfaces. If "class SomeBaseClass" implements "interface ISomeInterface" and "class SomeDerivedClass : SomeBaseClass, ISomeInterface" also implements the interface, a static method to implement an interface method would fail compile because a static method cannot have same signature as an instance method (which would be present in base class to implement the interface).

A static class is functionally identical to a singleton and serves the same purpose as a singleton with cleaner syntax. Since a singleton can implement an interface, interface implementations by statics are conceptually valid.

So it simply boils down to the limitation of C# name conflict for instance and static methods of the same name across inheritance. There is no reason why C# could not be "upgraded" to support static method contracts (interfaces).

how to parse xml to java object?

For performing Unmarshall using JAXB:

1) Convert given XML to XSD(by yourself or by online convertor),

2) Create a JAXB project in eclipse,

3) Create XSD file and paste that converted XSD content in it,

4) Right click on **XSD file--> Generate--> JAXB Classes-->follow the instructions(this will create all nessasary .java files in src, i.e., one package-info, object factory and pojo class),

5) Create another .java file in src to operate unmarshall operation, and run it.

Happy Coding !!

How do I write a method to calculate total cost for all items in an array?

The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
{
   public static void main(String arg[])
   {
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(System.in);
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
     {
       a[i]=n.nextInt();
       total=total+a[i];
      }
       System.out.println("The total is :"+total);
    }
}

How do I count a JavaScript object's attributes?

For those which will read this question/answers, here is a JavaScript implementation of Dictionary collection very similar as functionality as .NET one: JavaScript Dictionary

Return different type of data from a method in java?

I create various return types using enum. It doesn't defined automatically. That implementation look like factory pattern.

public  enum  SmartReturn {

    IntegerType, DoubleType;

    @SuppressWarnings("unchecked")
    public <T> T comeback(String value) {
        switch (this) {
            case IntegerType:
                return (T) Integer.valueOf(value);
            case DoubleType:
                return (T) Double.valueOf(value);
            default:
                return null;
        }
    }
}

Unit Test:

public class MultipleReturnTypeTest {

  @Test
  public void returnIntegerOrString() {
     Assert.assertTrue(SmartReturn.IntegerType.comeback("1") instanceof Integer);
     Assert.assertTrue(SmartReturn.DoubleType.comeback("1") instanceof Double);
  }

}

How do I move an existing Git submodule within a Git repository?

[Update: 2014-11-26] As Yar summarizes nicely below, before you do anything, make sure you know the URL of the submodule. If unknown, open .git/.gitmodules and examine the keysubmodule.<name>.url.

What worked for me was to remove the old submodule using git submodule deinit <submodule> followed by git rm <submodule-folder>. Then add the submodule again with the new folder name and commit. Checking git status before committing shows the old submodule renamed to the new name and .gitmodule modified.

$ git submodule deinit foo
$ git rm foo
$ git submodule add https://bar.com/foo.git new-foo
$ git status
renamed:    foo -> new-foo
modified:   .gitmodules
$ git commit -am "rename foo submodule to new-foo"

Select from one table where not in another

You can LEFT JOIN the two tables. If there is no corresponding row in the second table, the values will be NULL.

SELECT id FROM partmaster LEFT JOIN product_details ON (...) WHERE product_details.part_num IS NULL

From a Sybase Database, how I can get table description ( field names and types)?

When finding user table, in case if want the table owner name also, you can use the following:

select su.name + '.' + so.name
from   sysobjects so,
       sysusers   su
where  so.type = 'U' and
       so.uid  = su.uid
order  by su.name,
          so.name

#1071 - Specified key was too long; max key length is 767 bytes

MySQL assumes worst case for the number of bytes per character in the string. For the MySQL 'utf8' encoding, that's 3 bytes per character since that encoding doesn't allow characters beyond U+FFFF. For the MySQL 'utf8mb4' encoding, it's 4 bytes per character, since that's what MySQL calls actual UTF-8.

So assuming you're using 'utf8', your first column will take 60 bytes of the index, and your second another 1500.

Is there a way to delete all the data from a topic or delete the topic before every run?

In manually deleting a topic from a kafka cluster , you just might check this out https://github.com/darrenfu/bigdata/issues/6 A vital step missed a lot in most solution is in deleting the /config/topics/<topic_name> in ZK.

Using arrays or std::vectors in C++, what's the performance gap?

If you compile the software in debug mode, many compilers will not inline the accessor functions of the vector. This will make the stl vector implementation much slower in circumstances where performance is an issue. It will also make the code easier to debug since you can see in the debugger how much memory was allocated.

In optimized mode, I would expect the stl vector to approach the efficiency of an array. This is since many of the vector methods are now inlined.

how to re-format datetime string in php?

You could do it like this:

<?php
$datetime = "20130409163705"; 
$format = "YmdHis";

$date = date_parse_from_format ($format, $datetime);
print_r ($date);
?>

You can look at date_parse_from_format() and the accepted format values.

Find if current time falls in a time range

Using Linq we can simplify this by this

 Enumerable.Range(0, (int)(to - from).TotalHours + 1)
            .Select(i => from.AddHours(i)).Where(date => date.TimeOfDay >= new TimeSpan(8, 0, 0) && date.TimeOfDay <= new TimeSpan(18, 0, 0))

How to log Apache CXF Soap Request and Soap Response using Log4j?

When configuring log4j.properties, putting org.apache.cxf logging level to INFO is enough to see the plain SOAP messages:

log4j.logger.org.apache.cxf=INFO

DEBUG is too verbose.

How can I listen for a click-and-hold in jQuery?

Aircoded (but tested on this fiddle)

(function($) {
    function startTrigger(e) {
        var $elem = $(this);
        $elem.data('mouseheld_timeout', setTimeout(function() {
            $elem.trigger('mouseheld');
        }, e.data));
    }

    function stopTrigger() {
        var $elem = $(this);
        clearTimeout($elem.data('mouseheld_timeout'));
    }


    var mouseheld = $.event.special.mouseheld = {
        setup: function(data) {
            // the first binding of a mouseheld event on an element will trigger this
            // lets bind our event handlers
            var $this = $(this);
            $this.bind('mousedown', +data || mouseheld.time, startTrigger);
            $this.bind('mouseleave mouseup', stopTrigger);
        },
        teardown: function() {
            var $this = $(this);
            $this.unbind('mousedown', startTrigger);
            $this.unbind('mouseleave mouseup', stopTrigger);
        },
        time: 750 // default to 750ms
    };
})(jQuery);

// usage
$("div").bind('mouseheld', function(e) {
    console.log('Held', e);
})

How to get the selected row values of DevExpress XtraGrid?

You can do this in a number of ways. You can use databinding (typical initialized after InitializeComponent();)

textBox1.DataBindings.Add(new Binding("Text", yourBindingSource, 
                    "TableName.ColumnName", true, DataSourceUpdateMode.OnPropertyChanged));

or use a DataLayoutControl (if you are going to use textbox for editing, I really recommend spending some time to learn how to use this component.

or in FocusedRowChanged by assigning from one of these methods:

textBox1.Text = gridView1.GetDataRow(e.FocusedRowHandle)["Name"].ToString();
textBox1.Text = gridView1.GetFocusedDataRow()["Name"].ToString();
textBox1.Text = (gridView1.GetFocusedRow() as DataRowView).Row["Name"].ToString();
textBox1.Text = gridView1.GetFocusedRowCellValue("Name").ToString();

Get Value of a Edit Text field

String value = YourEditText.getText().toString;

How do I display todays date on SSRS report?

  1. Inset Test box in the design area of the SSRS report.
  2. Right-click on the Textbox and scroll down and click on the Expression tab
  3. just type the given expression in the expression area: =format(Today,"dd/MM/yyyy")

The application may be doing too much work on its main thread

I got same issue while developing an app which uses a lot of drawable png files on grid layout. I also tried to optimize my code as far as possible.. but it didn't work out for me.. Then i tried to reduce the size of those png.. and guess its working absolutely fine.. So my suggestion is to reduce size of drawable resources if any..

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Split string to equal length substrings in Java

public String[] splitInParts(String s, int partLength)
{
    int len = s.length();

    // Number of parts
    int nparts = (len + partLength - 1) / partLength;
    String parts[] = new String[nparts];

    // Break into parts
    int offset= 0;
    int i = 0;
    while (i < nparts)
    {
        parts[i] = s.substring(offset, Math.min(offset + partLength, len));
        offset += partLength;
        i++;
    }

    return parts;
}

How do I remove an item from a stl vector with a certain value?

If you have an unsorted vector, then you can simply swap with the last vector element then resize().

With an ordered container, you'll be best off with ?std::vector::erase(). Note that there is a std::remove() defined in <algorithm>, but that doesn't actually do the erasing. (Read the documentation carefully).

Converting a string to a date in JavaScript

new Date(2000, 10, 1) will give you "Wed Nov 01 2000 00:00:00 GMT+0100 (CET)"

See that 0 for month gives you January

Update index after sorting data-frame

Since pandas 1.0.0 df.sort_values has a new parameter ignore_index which does exactly what you need:

In [1]: df2 = df.sort_values(by=['x','y'],ignore_index=True)

In [2]: df2
Out[2]:
   x  y
0  0  0
1  0  1
2  0  2
3  1  0
4  1  1
5  1  2
6  2  0
7  2  1
8  2  2

CSS content generation before or after 'input' elements

With :before and :after you specify which content should be inserted before (or after) the content inside of that element. input elements have no content.

E.g. if you write <input type="text">Test</input> (which is wrong) the browser will correct this and put the text after the input element.

The only thing you could do is to wrap every input element in a span or div and apply the CSS on these.

See the examples in the specification:

For example, the following document fragment and style sheet:

<h2> Header </h2>               h2 { display: run-in; }
<p> Text </p>                   p:before { display: block; content: 'Some'; }

...would render in exactly the same way as the following document fragment and style sheet:

<h2> Header </h2>            h2 { display: run-in; }
<p><span>Some</span> Text </p>  span { display: block }

This is the same reason why it does not work for <br>, <img>, etc. (<textarea> seems to be special).

Count distinct values

SELECT CUSTOMER, COUNT(*) as PETS 
FROM table_name 
GROUP BY CUSTOMER;

How to update Ruby with Homebrew?

I would use ruby-build with rbenv. The following lines install Ruby 3.0.0 and set it as your default Ruby version:

$ brew update
$ brew install ruby-build
$ brew install rbenv

$ rbenv install 3.0.0
$ rbenv global 3.0.0

Android open camera from button

You are correct about the action used in Intent but it's not the only thing you have to do. You'll also have to add

startActivityForResult(intent, YOUR_REQUEST_CODE);

To get it all done and retrieve the actual picture you could check the following thread.

Android - Capture photo

How to create a timeline with LaTeX?

Tim Storer wrote a more flexible and nicer looking timeline.sty (Internet Archive Wayback Machine link, as original is gone). In addition, the line is horizontal rather than vertical. So for instance:

\begin{timeline}{2008}{2010}{50}{250}
  \MonthAndYearEvent{4}{2008}{First Podcast}
  \MonthAndYearEvent{7}{2008}{Private Beta}
  \MonthAndYearEvent{9}{2008}{Public Beta}
  \YearEvent{2009}{IPO?}
\end{timeline}

produces a timeline that looks like this:

2008                              2010
 · · April, 2008 First Podcast    ·
       · July, 2008 Private Beta
           · September, 2008 Public Beta
                · 2009 IPO?

Personally, I find this a more pleasing solution than the other answers. But I also find myself modifying the code to get something closer to what I think a timeline should look like. So there's not definitive solution in my opinion.

How to use timeit module

simply pass your entire code as an argument of timeit:

import timeit

print(timeit.timeit(

"""   
limit = 10000
prime_list = [i for i in range(2, limit+1)]

for prime in prime_list:
    for elem in range(prime*2, max(prime_list)+1, prime):
        if elem in prime_list:
            prime_list.remove(elem)
"""   
, number=10))

Remove all special characters except space from a string using JavaScript

The first solution does not work for any UTF-8 alphabet. (It will cut text such as ??????). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.

function removeSpecials(str) {
    var lower = str.toLowerCase();
    var upper = str.toUpperCase();

    var res = "";
    for(var i=0; i<lower.length; ++i) {
        if(lower[i] != upper[i] || lower[i].trim() === '')
            res += str[i];
    }
    return res;
}

Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.

Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø == Tromso).

How to add minutes to current time in swift

You can do date arithmetic by using NSDateComponents. For example:

import Foundation

let comps = NSDateComponents()

comps.minute = 5

let cal = NSCalendar.currentCalendar()

let r = cal.dateByAddingComponents(comps, toDate: NSDate(), options: nil)

It is what you see when you try it in playground

enter image description here

ASP.NET custom error page - Server.GetLastError() is null

A combination of what NailItDown and Victor said. The preferred/easiest way is to use your Global.Asax to store the error and then redirect to your custom error page.

Global.asax:

    void Application_Error(object sender, EventArgs e) 
{
    // Code that runs when an unhandled error occurs
    Exception ex = Server.GetLastError();
    Application["TheException"] = ex; //store the error for later
    Server.ClearError(); //clear the error so we can continue onwards
    Response.Redirect("~/myErrorPage.aspx"); //direct user to error page
}

In addition, you need to set up your web.config:

  <system.web>
    <customErrors mode="RemoteOnly" defaultRedirect="~/myErrorPage.aspx">
    </customErrors>
  </system.web>

And finally, do whatever you need to with the exception you've stored in your error page:

protected void Page_Load(object sender, EventArgs e)
{

    // ... do stuff ...
    //we caught an exception in our Global.asax, do stuff with it.
    Exception caughtException = (Exception)Application["TheException"];
    //... do stuff ...
}

Spring Security with roles and permissions

The basic steps are:

  1. Use a custom authentication provider

    <bean id="myAuthenticationProvider" class="myProviderImplementation" scope="singleton">
    ...
    </bean>
    

  2. Make your custom provider return a custom UserDetails implementation. This UserDetailsImpl will have a getAuthorities() like this:

    public Collection<GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> permissions = new ArrayList<GrantedAuthority>();
        for (GrantedAuthority role: roles) {
            permissions.addAll(getPermissionsIncludedInRole(role));
        }
        return permissions;
    }
    

Of course from here you could apply a lot of optimizations/customizations for your specific requirements.

Can't connect to docker from docker-compose

I know it's silly, but in my case I just tried with sudo and it worked like a charm.

in your case, just try: $ sudo docker-compose up

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

Convert string to datetime in vb.net

Pass the decode pattern to ParseExact

Dim d as string = "201210120956"
Dim dt = DateTime.ParseExact(d, "yyyyMMddhhmm", Nothing)

ParseExact is available only from Net FrameWork 2.0.
If you are still on 1.1 you could use Parse, but you need to provide the IFormatProvider adequate to your string

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

I had a problem where it did not allow me to insert it even after setting the IDENTITY_INSERT ON.

The problem was that i did not specify the column names and for some reason it did not like it.

INSERT INTO tbl Values(vals)

So basically do the full INSERT INTO tbl(cols) Values(vals)

In Oracle SQL: How do you insert the current date + time into a table?

It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:

insert into errortable (dateupdated, table1id)
    values (sysdate, 1083);

It seems silly to convert the system date to a string just to convert it back to a date.

If you want to see the full date, then you can do:

select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;

How to scale an Image in ImageView to keep the aspect ratio

Try using android:layout_gravity for ImageView:

android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"

The example above worked for me.

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

I think this will work perfectly. I used the same:

For Android Studio:

  1. Click on Build > Generate Signed APK.
  2. You will get a message box, just click OK.
  3. Now there will be another window just copy Key Store Path.
  4. Now open a command prompt and go to C:\Program Files\Java\jdk1.6.0_39\bin> (or any installed jdk version).
  5. Type keytool -list -v -keystore and then paste your Key Store Path (Eg. C:\Program Files\Java\jdk1.6.0_39\bin>keytool -list -v -keystore "E:\My Projects \Android\android studio\signed apks\Hello World\HelloWorld.jks").
  6. Now it will Ask Key Store Password, provide yours and press Enter to get your SHA1 and MD5 Certificate keys.

Reading images in python

import matplotlib.pyplot as plt
image = plt.imread('images/my_image4.jpg')
plt.imshow(image)

Using 'matplotlib.pyplot.imread' is recommended by warning messages in jupyter.

Center text in div?

Will this work for you?

div { text-align: center; }

Error installing mysql2: Failed to build gem native extension

If still getting error then follow the steps of mysql2 gem installation on Rails 3 on -

http://rorguide.blogspot.com/2011/03/installing-mysql2-gem-on-ruby-192-and.html

where most of the user were able to install mysql2 gem.

CSS Div stretch 100% page height

Use position absolute. Note that this isn't how we are generally used to using position absolute which requires manually laying things out or having floating dialogs. This will automatically stretch when you resize the window or the content. I believe that this requires standards mode but will work in IE6 and above.

Just replace the div with id 'thecontent' with your content (the specified height there is just for illustration, you don't have to specify a height on the actual content.

<div style="position: relative; width: 100%;">
      <div style="position: absolute; left: 0px; right: 33%; bottom: 0px; top: 0px; background-color: blue; width: 33%;" id="navbar">nav bar</div>
      <div style="position: relative; left: 33%; width: 66%; background-color: yellow;" id="content">
         <div style="height: 10000px;" id="thecontent"></div>
      </div>
</div>

The way that this works is that the outer div acts as a reference point for the nav bar. The outer div is stretched out by the content of the 'content' div. The nav bar uses absolute positioning to stretch itself out to the height of its parent. For the horizontal alignment we make the content div offset itself by the same width of the navbar.

This is made much easier with CSS3 flex box model, but that's not available in IE yet and has some of it's own quirks.

Function to close the window in Tkinter

def exit(self):
    self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)

This worked for me to destroy my Tkinter frame on clicking the exit button.

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

From the documentation of SimpleDateFormat:

Letter     Date or Time Component     Presentation     Examples  
S          Millisecond                Number           978 

So it is milliseconds, or 1/1000th of a second. You just format it with on 6 digits, so you add 3 extra leading zeroes...

You can check it this way:

    Date d =new Date();
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSS").format(d));
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").format(d));

Output:

2013-10-07 12:13:27.132
2013-10-07 12:13:27.132
2013-10-07 12:13:27.132
2013-10-07 12:13:27.0132
2013-10-07 12:13:27.00132
2013-10-07 12:13:27.000132

(Ideone fiddle)

How to make child divs always fit inside parent div?

I had a similar problem, but in my case, I have content in my div that height-wise will exceed the boundaries of the parent div. When it does, I want it to auto-scroll. I was able to accomplish this by using

.vscrolling_container { height: 100%; overflow: auto; }

Loop through a Map with JSTL

You can loop through a hash map like this

<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);                            
%>

  <c:forEach items="${itemList}" var="itemrow">
   <input  type="text"  value="<c:out value='${itemrow.test}'/>"/>
  </c:forEach>               

For more JSTL functionality look here

How do I jump to a closing bracket in Visual Studio Code?

On French keyboard the default binding is : Ctrl+Shift+*

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

In my case (remote connnection) helped turning off firewall on server.

service iptables stop

How do I do logging in C# without using 3rd party libraries?

If you want your own custom Error Logging you can easily write your own code. I'll give you a snippet from one of my projects.

public void SaveLogFile(object method, Exception exception)
{
    string location = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\FolderName\";
    try
    {
        //Opens a new file stream which allows asynchronous reading and writing
        using (StreamWriter sw = new StreamWriter(new FileStream(location + @"log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
        {
            //Writes the method name with the exception and writes the exception underneath
            sw.WriteLine(String.Format("{0} ({1}) - Method: {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), method.ToString()));
            sw.WriteLine(exception.ToString()); sw.WriteLine("");
        }
    }
    catch (IOException)
    {
        if (!File.Exists(location + @"log.txt"))
        {
            File.Create(location + @"log.txt");
        }
    }
}

Then to actually write to the error log just write (q being the caught exception)

SaveLogFile(MethodBase.GetCurrentMethod(), `q`);

Command copy exited with code 4 when building - Visual Studio restart solves it

As I am writing a DLL library I used the xcopy command to copy the library where the program can find and load it. After several times of opening and closing the program there was still an open process of it in taskmanager which i did not recognized.

Look for any process from which the file may be used and close it.

Lazy Method for Reading Big File in Python?

To process line by line, this is an elegant solution:

  def stream_lines(file_name):
    file = open(file_name)
    while True:
      line = file.readline()
      if not line:
        file.close()
        break
      yield line

As long as there're no blank lines.

What is the difference between server side cookie and client side cookie?

All cookies are client and server

There is no difference. A regular cookie can be set server side or client side. The 'classic' cookie will be sent back with each request. A cookie that is set by the server, will be sent to the client in a response. The server only sends the cookie when it is explicitly set or changed, while the client sends the cookie on each request.

But essentially it's the same cookie.

But, behavior can change

A cookie is basically a name=value pair, but after the value can be a bunch of semi-colon separated attributes that affect the behavior of the cookie if it is so implemented by the client (or server). Those attributes can be about lifetime, context and various security settings.

HTTP-only (is not server-only)

One of those attributes can be set by a server to indicate that it's an HTTP-only cookie. This means that the cookie is still sent back and forth, but it won't be available in JavaScript. Do note, though, that the cookie is still there! It's only a built in protection in the browser, but if somebody would use a ridiculously old browser like IE5, or some custom client, they can actually read the cookie!

So it seems like there are 'server cookies', but there are actually not. Those cookies are still sent to the client. On the client there is no way to prevent a cookie from being sent to the server.

Alternatives to achieve 'only-ness'

If you want to store a value only on the server, or only on the client, then you'd need some other kind of storage, like a file or database on the server, or Local Storage on the client.

Getting data from selected datagridview row and which event?

You can try this click event

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0)
    {
        DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
        Eid_txt.Text = row.Cells["Employee ID"].Value.ToString();
        Name_txt.Text = row.Cells["First Name"].Value.ToString();
        Surname_txt.Text = row.Cells["Last Name"].Value.ToString();

Using Case/Switch and GetType to determine the object

You can do this:

function void PrintType(Type t) {
 var t = true;
 new Dictionary<Type, Action>{
   {typeof(bool), () => Console.WriteLine("bool")},
   {typeof(int),  () => Console.WriteLine("int")}
 }[t.GetType()]();
}

It's clear and its easy. It a bit slower than caching the dictionary somewhere.. but for lots of code this won't matter anyway..

Code for Greatest Common Divisor in Python

using recursion,

def gcd(a,b):
    return a if not b else gcd(b, a%b)

using while,

def gcd(a,b):
  while b:
    a,b = b, a%b
  return a

using lambda,

gcd = lambda a,b : a if not b else gcd(b, a%b)

>>> gcd(10,20)
>>> 10

Increasing the maximum number of TCP/IP connections in Linux

There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.

More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:

  • Check if your TCP window setting is large enough. Linux defaults are good for everything except really fast inet link (hundreds of mbps) or fast satellite links. What is your bandwidth*delay product?
  • Check for packet loss using ping with large packets (ping -s 1472 ...)
  • Check for rate limiting. On Linux, this is configured with tc
  • Confirm that the bandwidth you think exists actually exists using e.g., iperf
  • Confirm that your protocol is sane. Remember latency.
  • If this is a gigabit+ LAN, can you use jumbo packets? Are you?

Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat or lsof). If that number is substantial, you might:

  • Have a lot of bandwidth, e.g., 100mbps+. In this case, you may actually need to up the ulimit -n. Still, ~1000 connections (default on my system) is quite a few.
  • Have network problems which are slowing down your connections (e.g., packet loss)
  • Have something else slowing you down, e.g., IO bandwidth, especially if you're seeking. Have you checked iostat -x?

Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.

I hope this provides some help. You're really asking a networking question.

Create intermediate folders if one doesn't exist

A nice Java 7+ answer from Benoit Blanchon can be found here:

With Java 7, you can use Files.createDirectories().

For instance:

Files.createDirectories(Paths.get("/path/to/directory"));

HTML 5 Geo Location Prompt in Chrome

There's some sort of security restriction in place in Chrome for using geolocation from a file:/// URI, though unfortunately it doesn't seem to record any errors to indicate that. It will work from a local web server. If you have python installed try opening a command prompt in the directory where your test files are and issuing the command:

python -m SimpleHTTPServer

It should start up a web server on port 8000 (might be something else, but it'll tell you in the console what port it's listening on), then browse to http://localhost:8000/mytestpage.html

If you don't have python there are equivalent modules in Ruby, or Visual Web Developer Express comes with a built in local web server.

Use of Greater Than Symbol in XML

You can try to use CDATA to put all your symbols that don't work.

An example of something that will work in XML:

<![CDATA[
function matchwo(a,b) {
    if (a < b && a < 0) {
        return 1;
   } else {
       return 0;
   }
}
]]>

And of course you can use &lt; and &gt;.

How do I merge dictionaries together in Python?

Starting in Python 3.9, the operator | creates a new dictionary with the merged keys and values from two dictionaries:

# d1 = { 'a': 1, 'b': 2 }
# d2 = { 'b': 1, 'c': 3 }
d3 = d2 | d1
# d3: {'b': 2, 'c': 3, 'a': 1}

This:

Creates a new dictionary d3 with the merged keys and values of d2 and d1. The values of d1 take priority when d2 and d1 share keys.


Also note the |= operator which modifies d2 by merging d1 in, with priority on d1 values:

# d1 = { 'a': 1, 'b': 2 }
# d2 = { 'b': 1, 'c': 3 }
d2 |= d1
# d2: {'b': 2, 'c': 3, 'a': 1}

?

Understanding MongoDB BSON Document size limit

Perhaps storing a blog post -> comments relation in a non-relational database is not really the best design.

You should probably store comments in a separate collection to blog posts anyway.

[edit]

See comments below for further discussion.

What does it mean if a Python object is "subscriptable" or not?

A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.

For example, see: Application Scripting Framework

Now, if Alistair didn't know what he asked and really meant "subscriptable" objects (as edited by others), then (as mipadi also answered) this is the correct one:

A subscriptable object is any object that implements the __getitem__ special method (think lists, dictionaries).

Auto Increment after delete in MySQL

I came here looking for an answer to the Title question "MySQL - Auto Increment after delete" but I could only find an answer for that in the questions

By using something like:

DELETE FROM table;
ALTER TABLE table AUTO_INCREMENT = 1;

Note that Darin Dimitrov's answer explain really well AUTO_INCREMENT and it's usage. Take a look there before doing something you might regret.

PS: The question itself is more "Why you need to recycle key values?" and Dolph's answer cover that.

Call fragment from fragment

In MainActivity

private static android.support.v4.app.FragmentManager fragmentManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);                     

    fragmentManager = getSupportFragmentManager();                                                                 


    }

public void secondFragment() {

    fragmentManager
            .beginTransaction()
            .setCustomAnimations(R.anim.right_enter, R.anim.left_out)
            .replace(R.id.frameContainer, new secondFragment(), "secondFragmentTag").addToBackStack(null)
            .commit();
}

In FirstFragment call SecondFrgment Like this:

new MainActivity().secondFragment();

What is the difference between CSS and SCSS?

And this is less

@primarycolor: #ffffff;
@width: 800px;

body{
 width: @width;
 color: @primarycolor;
 .content{
  width: @width;
  background:@primarycolor;
 }
}

How to use a dot "." to access members of dictionary?

Using namedtuple allows dot access.

It is like a lightweight object which also has the properties of a tuple.

It allows to define properties and access them using the dot operator.

from collections import namedtuple
Data = namedtuple('Data', ['key1', 'key2'])

dataObj = Data(val1, key2=val2) # can instantiate using keyword arguments and positional arguments

Access using dot operator

dataObj.key1 # Gives val1
datObj.key2 # Gives val2

Access using tuple indices

dataObj[0] # Gives val1
dataObj[1] # Gives val2

But remember this is a tuple; not a dict. So the below code will give error

dataObj['key1'] # Gives TypeError: tuple indices must be integers or slices, not str

Refer: namedtuple

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

I had the exact same problem and solved it running the folowing command from the command line as an admin :

1) first stop the service with the following

net stop http /y

2) then disable the startup (optional)

sc config http start= disabled

Show hide div using codebehind

There are a few ways to handle rendering/showing controls on the page and you should take note to what happens with each method.

Rendering and Visibility

There are some instances where elements on your page don't need to be rendered for the user because of some type of logic or database value. In this case, you can prevent rendering (creating the control on the returned web page) altogether. You would want to do this if the control doesn't need to be shown later on the client side because no matter what, the user viewing the page never needs to see it.

Any controls or elements can have their visibility set from the server side. If it is a plain old html element, you just need to set the runat attribute value to server on the markup page.

<div id="myDiv" runat="server"></div>

The decision to render the div or not can now be done in the code behind class like so:

myDiv.Visible = someConditionalBool;

If set to true, it will be rendered on the page and if it's false it won't be rendered at all, not even hidden.

Client Side Hiding

Hiding an element is done on the client side only. Meaning, it's rendered but it has a display CSS style set on it which instructs your browser to not show it to the user. This is beneficial when you want to hide/show things based on user input. It's important to know that the element CAN be hidden on the server side too as long as the element/control has runat=server set just as I explained in the previous example.

Hiding in the Code Behind Class

To hide an element that you want rendered to the page but hidden is another simple single line of code:

myDiv.Style["display"] = "none";

If you have a need to remove the display style server side, it can be done by removing the display style, or setting it to a different value like inline or block (values described here).

myDiv.Style.Remove("display");
// -- or --
myDiv.Style["display"] = "inline";

Hiding on the Client Side with javascript

Using plain old javascript, you can easily hide the same element in this manner

var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";

// then to show again
myDivElem.style.display = "";

jQuery makes hiding elements a little simpler if you prefer to use jQuery:

var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();

// ... and to show 
myDiv.show();

Select option padding not working in chrome

This simple hack will indent the text. Works well.

select {
  text-indent: 5px;
}

How to close Browser Tab After Submitting a Form?

That's because the event onsubmit is triggered before the form is submitted.

Remove your onSubmit and output that JavaScript in your PHP script after you have processed the request. You are closing the window right now, and cancelling the request to your server.

Android camera android.hardware.Camera deprecated

API Documentation

According to the Android developers guide for android.hardware.Camera, they state:

We recommend using the new android.hardware.camera2 API for new applications.

On the information page about android.hardware.camera2, (linked above), it is stated:

The android.hardware.camera2 package provides an interface to individual camera devices connected to an Android device. It replaces the deprecated Camera class.

The problem

When you check that documentation you'll find that the implementation of these 2 Camera API's are very different.

For example getting camera orientation on android.hardware.camera

@Override
public int getOrientation(final int cameraId) {
    Camera.CameraInfo info = new Camera.CameraInfo();
    Camera.getCameraInfo(cameraId, info);
    return info.orientation;
}

Versus android.hardware.camera2

@Override
public int getOrientation(final int cameraId) {
    try {
        CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        String[] cameraIds = manager.getCameraIdList();
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
        return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
    } catch (CameraAccessException e) {
        // TODO handle error properly or pass it on
        return 0;
    }
}

This makes it hard to switch from one to another and write code that can handle both implementations.

Note that in this single code example I already had to work around the fact that the olde camera API works with int primitives for camera IDs while the new one works with String objects. For this example I quickly fixed that by using the int as an index in the new API. If the camera's returned aren't always in the same order this will already cause issues. Alternative approach is to work with String objects and String representation of the old int cameraIDs which is probably safer.

One away around

Now to work around this huge difference you can implement an interface first and reference that interface in your code.

Here I'll list some code for that interface and the 2 implementations. You can limit the implementation to what you actually use of the camera API to limit the amount of work.

In the next section I'll quickly explain how to load one or another.

The interface wrapping all you need, to limit this example I only have 2 methods here.

public interface CameraSupport {
    CameraSupport open(int cameraId);
    int getOrientation(int cameraId);
}

Now have a class for the old camera hardware api:

@SuppressWarnings("deprecation")
public class CameraOld implements CameraSupport {

    private Camera camera;

    @Override
    public CameraSupport open(final int cameraId) {
        this.camera = Camera.open(cameraId);
        return this;
    }

    @Override
    public int getOrientation(final int cameraId) {
       Camera.CameraInfo info = new Camera.CameraInfo();
       Camera.getCameraInfo(cameraId, info);
       return info.orientation;
    }
}

And another one for the new hardware api:

public class CameraNew implements CameraSupport {

    private CameraDevice camera;
    private CameraManager manager;

    public CameraNew(final Context context) {
        this.manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    }

    @Override
    public CameraSupport open(final int cameraId) {
        try {
            String[] cameraIds = manager.getCameraIdList();
            manager.openCamera(cameraIds[cameraId], new CameraDevice.StateCallback() {
                @Override
                public void onOpened(CameraDevice camera) {
                    CameraNew.this.camera = camera;
                }

                @Override
                public void onDisconnected(CameraDevice camera) {
                    CameraNew.this.camera = camera;
                    // TODO handle
                }

                @Override
                public void onError(CameraDevice camera, int error) {
                    CameraNew.this.camera = camera;
                    // TODO handle
                }
            }, null);
        } catch (Exception e) {
            // TODO handle
        }
        return this;
    }

    @Override
    public int getOrientation(final int cameraId) {
        try {
            String[] cameraIds = manager.getCameraIdList();
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
            return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        } catch (CameraAccessException e) {
            // TODO handle
            return 0;
        }
    }
}

Loading the proper API

Now to load either your CameraOld or CameraNew class you'll have to check the API level since CameraNew is only available from api level 21.

If you have dependency injection set up already you can do so in your module when providing the CameraSupport implementation. Example:

@Module public class CameraModule {

    @Provides
    CameraSupport provideCameraSupport(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return new CameraNew(context);
        } else {
            return new CameraOld();
        }
    } 
}

If you don't use DI you can just make a utility or use Factory pattern to create the proper one. Important part is that the API level is checked.

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

Here is dirty way:

  1. Log into a linux server using "ssh -X user@host"
  2. open rxvt-unicode or other X terminal.
  3. open tmux or screen
  4. Log back into your local computer from the server
  5. start your favourite shell such as msys or cygwin.

How to check if user input is not an int value

Maybe you can try this:

int function(){
Scanner input = new Scanner(System.in);   
System.out.print("Enter an integer between 1-100: ");   
int range;
while(true){   
    if(input.hasNextInt()){   
    range = input.nextInt();
    if(0<=range && range <= 100)
        break;
    else
        continue;
    }
    input.nextLine();  //Comsume the garbage value
    System.out.println("Enter an integer between 1-100:");
}
return range;
}

SQL "between" not inclusive

It has been assumed that the second date reference in the BETWEEN syntax is magically considered to be the "end of the day" but this is untrue.

i.e. this was expected:

SELECT * FROM Cases 
WHERE created_at BETWEEN the beginning of '2013-05-01' AND the end of '2013-05-01'

but what really happen is this:

SELECT * FROM Cases 
WHERE created_at BETWEEN '2013-05-01 00:00:00+00000' AND '2013-05-01 00:00:00+00000'

Which becomes the equivalent of:

SELECT * FROM Cases WHERE created_at = '2013-05-01 00:00:00+00000'

The problem is one of perceptions/expectations about BETWEEN which does include BOTH the lower value and the upper values in the range, but does not magically make a date the "beginning of" or "the end of".

BETWEEN should be avoided when filtering by date ranges.

Always use the >= AND < instead

SELECT * FROM Cases 
WHERE (created_at >= '20130501' AND created_at < '20130502')

the parentheses are optional here but can be important in more complex queries.

Combine GET and POST request methods in Spring

@RequestMapping(value = "/books", method = { RequestMethod.GET, 
RequestMethod.POST })
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
     HttpServletRequest request) 
    throws ParseException {

//your code 
}

This will works for both GET and POST.

For GET if your pojo(BooksFilter) have to contain the attribute which you're using in request parameter

like below

public class BooksFilter{

private String parameter1;
private String parameter2;

   //getters and setters

URl should be like below

/books?parameter1=blah

Like this way u can use it for both GET and POST

How to automatically update your docker containers, if base-images are updated

A 'docker way' would be to use docker hub automated builds. The Repository Links feature will rebuild your container when an upstream container is rebuilt, and the Webhooks feature will send you a notification.

It looks like the webhooks are limited to HTTP POST calls. You'd need to set up a service to catch them, or maybe use one of the POST to email services out there.

I haven't looked into it, but the new Docker Universal Control Plane might have a feature for detecting updated containers and re-deploying.

Text that shows an underline on hover

<span class="txt">Some Text</span>

.txt:hover {
    text-decoration: underline;
}

Global Variable from a different file Python

from file2 import * is making copies. You want to do this:

import file2
print file2.foo
print file2.SomeClass()

Git Diff with Beyond Compare

Please notice you make a wrong path of $2. because you are under Cygwin but BC3 not, so you should specify a full path for it. such as "d:/cygwin$2"

Please refer my git-diff-wrapper.sh here:

$ cat ~/git-diff-wrapper.sh
#!/bin/sh
echo $2
echo $5
/cygdrive/c/Program\ Files\ \(x86\)/Beyond\ Compare\ 3/BCompare.exe "d:/programs/cygwin$2" "$5"

Good luck.

How can I make directory writable?

To make the parent directory as well as all other sub-directories writable, just add -R

chmod -R a+w <directory>

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

Answer is YES

<html>
<head>
</head>
<body>
<script language="javascript">
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\NewFile.txt", true);
var text=document.getElementById("TextArea1").innerText;
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
</script>

<form name="abc">
<textarea name="text">FIFA</textarea>
<button onclick="WriteToFile()">Click to save</Button>  
</form> 

</body>
</html>

Any way to exit bash script, but not quitting the terminal

To write a script that is secure to be run as either a shell script or sourced as an rc file, the script can check and compare $0 and $BASH_SOURCE and determine if exit can be safely used.

Here is a short code snippet for that

[ "X$(basename $0)" = "X$(basename $BASH_SOURCE)" ] && \
    echo "***** executing $name_src as a shell script *****" || \
    echo "..... sourcing $name_src ....."

How can I use a carriage return in a HTML tooltip?

Try character 10. It won't work in Firefox though. :(

The text is displayed (if at all) in a browser dependent manner. Small tooltips work on most browsers. Long tooltips and line breaking work in IE and Safari (use &#10; or &#13; for a new newline). Firefox and Opera do not support newlines. Firefox does not support long tooltips.

http://modp.com/wiki/htmltitletooltips

Update:

As of January 2015 Firefox does support using &#13; to insert a line break in an HTML title attribute. See the snippet example below.

_x000D_
_x000D_
<a href="#" title="Line 1&#13;Line 2&#13;Line 3">Hover for multi-line title</a>
_x000D_
_x000D_
_x000D_

npm - how to show the latest version of a package

There is also another easy way to check the latest version without going to NPM if you are using VS Code.

In package.json file check for the module you want to know the latest version. Remove the current version already present there and do CTRL + space or CMD + space(mac).The VS code will show the latest versions

image shows the latest versions of modules in vscode

Show only two digit after decimal

How about String.format("%.2f", i2)?

How to put labels over geom_bar in R with ggplot2

To plot text on a ggplot you use the geom_text. But I find it helpful to summarise the data first using ddply

dfl <- ddply(df, .(x), summarize, y=length(x))
str(dfl)

Since the data is pre-summarized, you need to remember to change add the stat="identity" parameter to geom_bar:

ggplot(dfl, aes(x, y=y, fill=x)) + geom_bar(stat="identity") +
    geom_text(aes(label=y), vjust=0) +
    opts(axis.text.x=theme_blank(),
        axis.ticks=theme_blank(),
        axis.title.x=theme_blank(),
        legend.title=theme_blank(),
        axis.title.y=theme_blank()
)

enter image description here

How to kill zombie process

You can clean up a zombie process by killing its parent process with the following command:

kill -HUP $(ps -A -ostat,ppid | awk '{/[zZ]/{ print $2 }')

Send values from one form to another form

After a series of struggle for passing the data from one form to another i finally found a stable answer. It works like charm.

All you need to do is declare a variable as public static datatype 'variableName' in one form and assign the value to this variable which you want to pass to another form and call this variable in another form using directly the form name (Don't create object of this form as static variables can be accessed directly) and access this variable value.

Example of such is,

Form1

public static int quantity;
quantity=TextBox1.text; \\Value which you want to pass

Form2

TextBox2.Text=Form1.quantity;\\ Data will be placed in TextBox2

How do I start my app on startup?

Additionally you can use an app like AutoStart if you dont want to modify the code, to launch an android application at startup: AutoStart - No root

How do I format a number to a dollar amount in PHP

If you just want something simple:

'$' . number_format($money, 2);

number_format()

Static Final Variable in Java

For the primitive types, the 'final static' will be a proper declaration to declare a constant. A non-static final variable makes sense when it is a constant reference to an object. In this case each instance can contain its own reference, as shown in JLS 4.5.4.

See Pavel's response for the correct answer.

$(...).datepicker is not a function - JQuery - Bootstrap

 <script type="text/javascript">

    var options={
            format: 'mm/dd/yyyy',
            todayHighlight: true,
            autoclose: true,
        };

    $('#datetimepicker').datepicker(options);

</script>

Upload Image using POST form data in Python-requests

In case if you were to pass the image as part of JSON along with other attributes, you can use the below snippet.
client.py

import base64
import json                    

import requests

api = 'http://localhost:8080/test'
image_file = 'sample_image.png'

with open(image_file, "rb") as f:
    im_bytes = f.read()        
im_b64 = base64.b64encode(im_bytes).decode("utf8")

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
  
payload = json.dumps({"image": im_b64, "other_key": "value"})
response = requests.post(api, data=payload, headers=headers)
try:
    data = response.json()     
    print(data)                
except requests.exceptions.RequestException:
    print(response.text)

server.py

import io
import json                    
import base64                  
import logging             
import numpy as np
from PIL import Image

from flask import Flask, request, jsonify, abort

app = Flask(__name__)          
app.logger.setLevel(logging.DEBUG)
  
  
@app.route("/test", methods=['POST'])
def test_method():         
    # print(request.json)      
    if not request.json or 'image' not in request.json: 
        abort(400)
             
    # get the base64 encoded string
    im_b64 = request.json['image']

    # convert it into bytes  
    img_bytes = base64.b64decode(im_b64.encode('utf-8'))

    # convert bytes data to PIL Image object
    img = Image.open(io.BytesIO(img_bytes))

    # PIL image object to numpy array
    img_arr = np.asarray(img)      
    print('img shape', img_arr.shape)

    # process your img_arr here    
    
    # access other keys of json
    # print(request.json['other_key'])

    result_dict = {'output': 'output_key'}
    return result_dict
  
  
def run_server_api():
    app.run(host='0.0.0.0', port=8080)
  
  
if __name__ == "__main__":     
    run_server_api()

How to generate a Makefile with source in sub-directories using just one makefile

Usually, you create a Makefile in each subdirectory, and write in the top-level Makefile to call make in the subdirectories.

This page may help: http://www.gnu.org/software/make/

Find (and kill) process locking port 3000 on Mac

You can use lsof -i:3000.

That is "List Open Files". This gives you a list of the processes and which files and ports they use.

Writing handler for UIAlertAction

  1. In Swift

    let alertController = UIAlertController(title:"Title", message: "Message", preferredStyle:.alert)
    
    let Action = UIAlertAction.init(title: "Ok", style: .default) { (UIAlertAction) in
        // Write Your code Here
    }
    
    alertController.addAction(Action)
    self.present(alertController, animated: true, completion: nil)
    
  2. In Objective C

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *OK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
    {
    }];
    
    [alertController addAction:OK];
    
    [self presentViewController:alertController animated:YES completion:nil];
    

What issues should be considered when overriding equals and hashCode in Java?

One gotcha I have found is where two objects contain references to each other (one example being a parent/child relationship with a convenience method on the parent to get all children).
These sorts of things are fairly common when doing Hibernate mappings for example.

If you include both ends of the relationship in your hashCode or equals tests it's possible to get into a recursive loop which ends in a StackOverflowException.
The simplest solution is to not include the getChildren collection in the methods.

Decode HTML entities in Python string?

Beautiful Soup handles entity conversion. In Beautiful Soup 3, you'll need to specify the convertEntities argument to the BeautifulSoup constructor (see the 'Entity Conversion' section of the archived docs). In Beautiful Soup 4, entities get decoded automatically.

Beautiful Soup 3

>>> from BeautifulSoup import BeautifulSoup
>>> BeautifulSoup("<p>&pound;682m</p>", 
...               convertEntities=BeautifulSoup.HTML_ENTITIES)
<p>£682m</p>

Beautiful Soup 4

>>> from bs4 import BeautifulSoup
>>> BeautifulSoup("<p>&pound;682m</p>")
<html><body><p>£682m</p></body></html>

C++ [Error] no matching function for call to

You are trying to call DeckOfCards::shuffle with a deckOfCards parameter:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck

But the method takes a vector<Card>&:

void deckOfCards::shuffle(vector<Card>& deck)

The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.

Error:

[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'

Paraphrased:

Hey, pal. You're trying to call a function called shuffle which apparently takes a single parameter of type reference-to-deckOfCards, but there is no such function.

Error:

[Note] candidate is:

In file included from main.cpp

[Note] void deckOfCards::shuffle(std::vector&)

Paraphrased:

I mean, maybe you meant this other function called shuffle, but that one takes a reference-tovector<something>.

Error:

[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'

Which I'd be happy to call if I knew how to convert from a deckOfCards to a vector; but I don't. So I won't.

Download file from web in Python 3

You can use wget which is popular downloading shell tool for that. https://pypi.python.org/pypi/wget This will be the simplest method since it does not need to open up the destination file. Here is an example.

import wget
url = 'https://i1.wp.com/python3.codes/wp-content/uploads/2015/06/Python3-powered.png?fit=650%2C350'  
wget.download(url, '/Users/scott/Downloads/cat4.jpg') 

Dealing with multiple Python versions and PIP?

Other answers show how to use pip with both 2.X and 3.X Python, but does not show how to handle the case of multiple Python distributions (eg. original Python and Anaconda Python).

I have a total of 3 Python versions: original Python 2.7 and Python 3.5 and Anaconda Python 3.5.

Here is how I install a package into:

  1. Original Python 3.5:

    /usr/bin/python3 -m pip install python-daemon
    
  2. Original Python 2.7:

    /usr/bin/python -m pip install python-daemon
    
  3. Anaconda Python 3.5:

    python3 -m pip install python-daemon
    

    or

    pip3 install python-daemon
    

    Simpler, as Anaconda overrides original Python binaries in user environment.

    Of course, installing in anaconda should be done with conda command, this is just an example.


Also, make sure that pip is installed for that specific python.You might need to manually install pip. This works in Ubuntu 16.04:

sudo apt-get install python-pip 

or

sudo apt-get install python3-pip

How to access the correct `this` inside a callback?

First, you need to have a clear understanding of scope and behaviour of this keyword in the context of scope.

this & scope :


there are two types of scope in javascript. They are :

   1) Global Scope

   2) Function Scope

in short, global scope refers to the window object.Variables declared in a global scope are accessible from anywhere.On the other hand function scope resides inside of a function.variable declared inside a function cannot be accessed from outside world normally.this keyword in global scope refers to the window object.this inside function also refers to the window object.So this will always refer to the window until we find a way to manipulate this to indicate a context of our own choosing.

--------------------------------------------------------------------------------
-                                                                              -
-   Global Scope                                                               -
-   ( globally "this" refers to window object)                                 -     
-                                                                              -
-         function outer_function(callback){                                   -
-                                                                              -
-               // outer function scope                                        -
-               // inside outer function"this" keyword refers to window object -                                                                              -
-              callback() // "this" inside callback also refers window object  -

-         }                                                                    -
-                                                                              -
-         function callback_function(){                                        -
-                                                                              -
-                //  function to be passed as callback                         -
-                                                                              -
-                // here "THIS" refers to window object also                   -
-                                                                              -
-         }                                                                    -
-                                                                              -
-         outer_function(callback_function)                                    -
-         // invoke with callback                                              -
--------------------------------------------------------------------------------

Different ways to manipulate this inside callback functions:

Here I have a constructor function called Person. It has a property called name and four method called sayNameVersion1,sayNameVersion2,sayNameVersion3,sayNameVersion4. All four of them has one specific task.Accept a callback and invoke it.The callback has a specific task which is to log the name property of an instance of Person constructor function.

function Person(name){

    this.name = name

    this.sayNameVersion1 = function(callback){
        callback.bind(this)()
    }
    this.sayNameVersion2 = function(callback){
        callback()
    }

    this.sayNameVersion3 = function(callback){
        callback.call(this)
    }

    this.sayNameVersion4 = function(callback){
        callback.apply(this)
    }

}

function niceCallback(){

    // function to be used as callback

    var parentObject = this

    console.log(parentObject)

}

Now let's create an instance from person constructor and invoke different versions of sayNameVersionX ( X refers to 1,2,3,4 ) method with niceCallback to see how many ways we can manipulate the this inside callback to refer to the person instance.

var p1 = new Person('zami') // create an instance of Person constructor

bind :

What bind do is to create a new function with the this keyword set to the provided value.

sayNameVersion1 and sayNameVersion2 use bind to manipulate this of the callback function.

this.sayNameVersion1 = function(callback){
    callback.bind(this)()
}
this.sayNameVersion2 = function(callback){
    callback()
}

first one bind this with callback inside the method itself.And for the second one callback is passed with the object bound to it.

p1.sayNameVersion1(niceCallback) // pass simply the callback and bind happens inside the sayNameVersion1 method

p1.sayNameVersion2(niceCallback.bind(p1)) // uses bind before passing callback

call :

The first argument of the call method is used as this inside the function that is invoked with call attached to it.

sayNameVersion3 uses call to manipulate the this to refer to the person object that we created, instead of the window object.

this.sayNameVersion3 = function(callback){
    callback.call(this)
}

and it is called like the following :

p1.sayNameVersion3(niceCallback)

apply :

Similar to call, first argument of apply refers to the object that will be indicated by this keyword.

sayNameVersion4 uses apply to manipulate this to refer to person object

this.sayNameVersion4 = function(callback){
    callback.apply(this)
}

and it is called like the following.Simply the callback is passed,

p1.sayNameVersion4(niceCallback)

Setting the height of a DIV dynamically

If I understand what you're asking, this should do the trick:

// the more standards compliant browsers (mozilla/netscape/opera/IE7) use 
// window.innerWidth and window.innerHeight

var windowHeight;

if (typeof window.innerWidth != 'undefined')
{
    windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first 
// line in the document)
else if (typeof document.documentElement != 'undefined'
        && typeof document.documentElement.clientWidth != 'undefined' 
        && document.documentElement.clientWidth != 0)
{
    windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
    windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}

document.getElementById("yourDiv").height = windowHeight - 300 + "px";

Print text instead of value from C enum

I like this to have enum in the dayNames. To reduce typing, we can do the following:

#define EP(x) [x] = #x  /* ENUM PRINT */

const char* dayNames[] = { EP(Sunday), EP(Monday)};

Android selector & text color

I always used the above solution without searching more after this. ;-)

However, today I came across something and thought of sharing it. :)

This feature is indeed available from API 1 and is called as ColorStateList, where we can supply a color to various states of Widgets (as we already know).

It is also very well documented, here.

Java - Writing strings to a CSV file

 private static final String FILE_HEADER ="meter_Number,latestDate";
    private static final String COMMA_DELIMITER = ",";
    private static final String NEW_LINE_SEPARATOR = "\n";
    static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:m m:ss");

    private void writeToCsv(Map<String, Date> meterMap) {
        try {
            Iterator<Map.Entry<String, Date>> iter = meterMap.entrySet().iterator();
            FileWriter fw = new FileWriter("smaple.csv");
            fw.append(FILE_HEADER.toString());
            fw.append(NEW_LINE_SEPARATOR);
            while (iter.hasNext()) {
                Map.Entry<String, Date> entry = iter.next();
                try {
                    fw.append(entry.getKey());
                    fw.append(COMMA_DELIMITER);
                    fw.append(formatter.format(entry.getValue()));
                    fw.append(NEW_LINE_SEPARATOR);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    iter.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Getting The ASCII Value of a character in a C# string

Here's an alternative since you don't like the cast to int:

foreach(byte b in System.Text.Encoding.UTF8.GetBytes(str.ToCharArray()))
    Console.Write(b.ToString());

Delete empty rows

I believe that your problem is that you're checking for an empty string using double quotes instead of single quotes. Try just changing to:

DELETE FROM table WHERE edit_user=''

Show which git tag you are on?

Edit: Jakub Narebski has more git-fu. The following much simpler command works perfectly:

git describe --tags

(Or without the --tags if you have checked out an annotated tag. My tag is lightweight, so I need the --tags.)

original answer follows:

git describe --exact-match --tags $(git log -n1 --pretty='%h')

Someone with more git-fu may have a more elegant solution...

This leverages the fact that git-log reports the log starting from what you've checked out. %h prints the abbreviated hash. Then git describe --exact-match --tags finds the tag (lightweight or annotated) that exactly matches that commit.

The $() syntax above assumes you're using bash or similar.

Android Studio - Device is connected but 'offline'

On windows--> Launch your terminal from the platform-tools folder inside android sdk.

Then use the following commands

adb kill server
adb start server

it should work

Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.

Encountered a similar error, this how I resolved it:

  1. Access Project explorer view on Netbeans IDE 8.2. Proceed to your project under Dependencies hover the cursor over the log4j-over-slf4j.jar to view the which which dependencies have indirectly imported as shown below. enter image description here

  2. Right click an import jar file and select Exclude Dependency enter image description here

  3. To confirm, open your pom.xml file you will notice the exclusion element as below.

enter image description here 4. Initiate maven clean install and run your project. Good luck!

Compile Views in ASP.NET MVC

I frankly would recommend the RazorGenerator nuget package. That way your views have a .designer.cs file generated when you save them and on top of getting compile time errors for you views, they are also precompiled into the assembly (= faster warmup) and Resharper provides some additional help as well.

To use this include the RazorGenerator nuget package in you ASP.NET MVC project and install the "Razor Generator" extension under item under Tools ? Extensions and Updates.

We use this and the overhead per compile with this approach is much less. On top of this I would probably recommend .NET Demon by RedGate which further reduces compile time impact substantially.

Hope this helps.

How do you delete a column by name in data.table?

I simply do it in the data frame kind of way:

DT$col = NULL

Works fast and as far as I could see doesn't cause any problems.

UPDATE: not the best method if your DT is very large, as using the $<- operator will lead to object copying. So better use:

DT[, col:=NULL]

PivotTable's Report Filter using "greater than"

I can't say how much this might help you, but just found a solution to something similar problem which I faced. In the Pivot-

  1. Right click and choose Pivot table options
  2. Choose the display option
  3. uncheck the first 'Show expand/Collapse buttons'
  4. check the 'Classic PivotTable Layout(enables dragging of fields in the grid)
  5. click ok.

This would refine the data. Then, I had just copy and pasted this data in a new tab wherein I had applied the filters to my Total column with values greater than certain percentage.

This did work in my case and hope it helps you too.

Catching FULL exception message

The following worked well for me

try {
    asdf
} catch {
    $string_err = $_ | Out-String
}

write-host $string_err

The result of this is the following as a string instead of an ErrorRecord object

asdf : The term 'asdf' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\TASaif\Desktop\tmp\catch_exceptions.ps1:2 char:5
+     asdf
+     ~~~~
    + CategoryInfo          : ObjectNotFound: (asdf:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

UILabel font size?

**You can set font size by these properties **

timedisplayLabel= [[UILabel alloc]initWithFrame:CGRectMake(70, 194, 180, 60)];

[timedisplayLabel setTextAlignment:NSTextAlignmentLeft];

[timedisplayLabel setBackgroundColor:[UIColor clearColor]];

[timedisplayLabel setAdjustsFontSizeToFitWidth:YES];

[timedisplayLabel setTextColor:[UIColor blackColor]];

[timedisplayLabel setUserInteractionEnabled:NO];

[timedisplayLabel setFont:[UIFont fontWithName:@"digital-7" size:60]];

timedisplayLabel.layer.shadowColor =[[UIColor whiteColor ]CGColor ];

timedisplayLabel.layer.shadowOffset=(CGSizeMake(0, 0));

timedisplayLabel.layer.shadowOpacity=1;

timedisplayLabel.layer.shadowRadius=3.0;

timedisplayLabel.layer.masksToBounds=NO;

timedisplayLabel.shadowColor=[UIColor darkGrayColor];

timedisplayLabel.shadowOffset=CGSizeMake(0, 2);

Using different Web.config in development and production environment

You can also use the extension "Configuration Transform" works the same as "SlowCheetah",

Execution failed for task ':app:processDebugResources' even with latest build tools

Error:Execution failed for task com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException:

finished with non-zero exit value 1

One reason for this error to occure is that the file path to a resource file is to long:

Error: File path too long on Windows, keep below 240 characters 

Fix: Move your project folder closer to the root of your disk

Don't:// folder/folder/folder/folder/very_long_folder_name/MyProject...

Do://folder/short_name/MyProject


Another reason could be duplicated resources or name spaces

Example:

  <style name="MyButton" parent="android:Widget.Button">
      <item name="android:textColor">@color/accent_color</item>
      <item name="android:textColor">#000000</item>
  </style>

And make sure all file names and extensions are in lowercase

Wrong

myimage.PNG
myImage.png

Correct

my_image.png

Make sure to Clean/Rebuild project

(delete the 'build' folder)

Reading a text file in MATLAB line by line

If you really want to process your file line by line, a solution might be to use fgetl:

  1. Open the data file with fopen
  2. Read the next line into a character array using fgetl
  3. Retreive the data you need using sscanf on the character array you just read
  4. Perform any relevant test
  5. Output what you want to another file
  6. Back to point 2 if you haven't reached the end of your file.

Unlike the previous answer, this is not very much in the style of Matlab but it might be more efficient on very large files.

Hope this will help.

What is the Swift equivalent to Objective-C's "@synchronized"?

Details

Xcode 8.3.1, Swift 3.1

Task

Read write value from different threads (async).

Code

class AsyncObject<T>:CustomStringConvertible {
    private var _value: T
    public private(set) var dispatchQueueName: String
   
    let dispatchQueue: DispatchQueue
    
    init (value: T, dispatchQueueName: String) {
        _value = value
        self.dispatchQueueName = dispatchQueueName
        dispatchQueue = DispatchQueue(label: dispatchQueueName)
    }
    
    func setValue(with closure: @escaping (_ currentValue: T)->(T) ) {
        dispatchQueue.sync { [weak self] in
            if let _self = self {
                _self._value = closure(_self._value)
            }
        }
    }
    
    func getValue(with closure: @escaping (_ currentValue: T)->() ) {
        dispatchQueue.sync { [weak self] in
            if let _self = self {
                closure(_self._value)
            }
        }
    }
    
    
    var value: T {
        get {
            return dispatchQueue.sync { _value }
        }
        
        set (newValue) {
            dispatchQueue.sync { _value = newValue }
        }
    }

    var description: String {
        return "\(_value)"
    }
}

Usage

print("Single read/write action")
// Use it when when you need to make single action
let obj = AsyncObject<Int>(value: 0, dispatchQueueName: "Dispatch0")
obj.value = 100
let x = obj.value
print(x)

print("Write action in block")
// Use it when when you need to make many action
obj.setValue{ (current) -> (Int) in
    let newValue = current*2
    print("previous: \(current), new: \(newValue)")
    return newValue
}

Full Sample

extension DispatchGroup

extension DispatchGroup {
    
    class func loop(repeatNumber: Int, action: @escaping (_ index: Int)->(), completion: @escaping ()->()) {
        let group = DispatchGroup()
        for index in 0...repeatNumber {
            group.enter()
            DispatchQueue.global(qos: .utility).async {
                action(index)
                group.leave()
            }
        }
        
        group.notify(queue: DispatchQueue.global(qos: .userInitiated)) {
            completion()
        }
    }
}

class ViewController

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //sample1()
        sample2()
    }
    
    func sample1() {
        print("=================================================\nsample with variable")
        
        let obj = AsyncObject<Int>(value: 0, dispatchQueueName: "Dispatch1")
        
        DispatchGroup.loop(repeatNumber: 5, action: { index in
            obj.value = index
        }) {
            print("\(obj.value)")
        }
    }
    
    func sample2() {
        print("\n=================================================\nsample with array")
        let arr = AsyncObject<[Int]>(value: [], dispatchQueueName: "Dispatch2")
        DispatchGroup.loop(repeatNumber: 15, action: { index in
            arr.setValue{ (current) -> ([Int]) in
                var array = current
                array.append(index*index)
                print("index: \(index), value \(array[array.count-1])")
                return array
            }
        }) {
            print("\(arr.value)")
        }
    }
}

Android. Fragment getActivity() sometimes returns null

The best to get rid of this is to keep activity reference when onAttach is called and use the activity reference wherever needed, for e.g.

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
    mContext = null;
}

Edited, since onAttach(Activity) is depreciated & now onAttach(Context) is being used

npm ERR! network getaddrinfo ENOTFOUND

Step 1: Set the proxy npm set proxy http://username:password@companyProxy:8080

npm set https-proxy http://username:password@companyProxy:8080

npm config set strict-ssl false -g

NOTES: No special characters in password except @ allowed.

Decreasing for loops in Python impossible?

>>> range(6, 0, -1)
[6, 5, 4, 3, 2, 1]

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

Another solution you can try that worked for me when I received this error is to clean the solution, then do a rebuild. As the other solutions did not help me, I thought this might help someone else in the same boat.

Get DataKey values in GridView RowCommand

I managed to get the value of the DataKeys using this code:

In the GridView I added:

DataKeyNames="ID" OnRowCommand="myRowCommand"

Then in my row command function:

protected void myRowCommand(object sender, GridViewCommandEventArgs e) 
{
    LinkButton lnkBtn = (LinkButton)e.CommandSource;    // the button
    GridViewRow myRow = (GridViewRow)lnkBtn.Parent.Parent;  // the row
    GridView myGrid = (GridView)sender; // the gridview
    string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString(); // value of the datakey 

    switch (e.CommandName)
    {
      case "cmd1":
      // do something using the ID
      break;
      case "cmd2":
      // do something else using the ID
      break;
    }
 }

How to increment a variable on a for loop in jinja template?

Came searching for Django's way of doing this and found this post. Maybe someone else need the django solution who come here.

{% for item in item_list %}
    {{ forloop.counter }} {# starting index 1 #}
    {{ forloop.counter0 }} {# starting index 0 #}

    {# do your stuff #}
{% endfor %}

Read more here: https://docs.djangoproject.com/en/1.11/ref/templates/builtins/

LEFT JOIN in LINQ to entities?

May be I come later to answer but right now I'm facing with this... if helps there are one more solution (the way i solved it).

    var query2 = (
    from users in Repo.T_Benutzer
    join mappings in Repo.T_Benutzer_Benutzergruppen on mappings.BEBG_BE equals users.BE_ID into tmpMapp
    join groups in Repo.T_Benutzergruppen on groups.ID equals mappings.BEBG_BG into tmpGroups
    from mappings in tmpMapp.DefaultIfEmpty()
    from groups in tmpGroups.DefaultIfEmpty()
    select new
    {
         UserId = users.BE_ID
        ,UserName = users.BE_User
        ,UserGroupId = mappings.BEBG_BG
        ,GroupName = groups.Name
    }

);

By the way, I tried using the Stefan Steiger code which also helps but it was slower as hell.

Why both no-cache and no-store should be used in HTTP response?

I must clarify that no-cache does not mean do not cache. In fact, it means "revalidate with server" before using any cached response you may have, on every request.

must-revalidate, on the other hand, only needs to revalidate when the resource is considered stale.

If the server says that the resource is still valid then the cache can respond with its representation, thus alleviating the need for the server to resend the entire resource.

no-store is effectively the full do not cache directive and is intended to prevent storage of the representation in any form of cache whatsoever.

I say whatsoever, but note this in the RFC 2616 HTTP spec:

History buffers MAY store such responses as part of their normal operation

But this is omitted from the newer RFC 7234 HTTP spec in potentially an attempt to make no-store stronger, see:

http://tools.ietf.org/html/rfc7234#section-5.2.1.5

WPF Databinding: How do I access the "parent" data context?

This will also work:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView will inherit its DataContext from Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Binding for such controls will work perfectly.

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

        combo1.DisplayMember = "Text";
        combo1.ValueMember = "Value";   
        combo1.Items.Add(new { Text = "someText"), Value = "someValue") });
        dynamic item = combo1.Items[combo1.SelectedIndex];
        var itemValue = item.Value;
        var itemText = item.Text;

Unfortunatly "combo1.SelectedValue" does not work, i did not want to bind my combobox with any source, so i came up with this solution. Maybe it will help someone.

Add an image in a WPF button

You can set the button's background to the image if you then want to overlay text.

<Button>
   <Button.Background>
     <ImageBrush ImageSource="/AssemblyName;component/Pictures/img.jpg"/>
   </Button.Background>
   <TextBlock>Blablabla</TextBlock>
</Button>

Watch out for the image source syntax. See this question for help.

How To Add An "a href" Link To A "div"?

Try creating a class named overlay and apply the following css to it:

a.overlay { width: 100%; height:100%; position: absolute; }

Make sure it is placed in a positioned element.

Now simply place an <a> tag with that class inside the div you want to be linkable:

<div id="buttonOne">
  <a class="overlay" href="......."></a>
    <div id="linkedinB">
       <img src="img/linkedinB.png" alt="never forget the alt tag" width="40" height="40"/>
    </div>
 </div>

PhilipK's suggestion might work but it won't validate because you can't place a block element (div) inside an inline element (a). And when your website doesn't validate the W3C Ninja's will come for you!

An other advice would be to try avoiding inline styling.

How can I check if a date is the same day as datetime.today()?

If you want to just compare dates,

yourdatetime.date() < datetime.today().date()

Or, obviously,

yourdatetime.date() == datetime.today().date()

If you want to check that they're the same date.

The documentation is usually helpful. It is also usually the first google result for python thing_i_have_a_question_about. Unless your question is about a function/module named "snake".

Basically, the datetime module has three types for storing a point in time:

  • date for year, month, day of month
  • time for hours, minutes, seconds, microseconds, time zone info
  • datetime combines date and time. It has the methods date() and time() to get the corresponding date and time objects, and there's a handy combine function to combine date and time into a datetime.

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

Create a .reg file containing your proxy settings for your users. Create a batch file setting it to setting it to run the .reg file with the extension /s

On a server using a logon script, tell the logon to run the batch file. Jason

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

How to set ObjectId as a data type in mongoose

My solution on using ObjectId

// usermodel.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId


let UserSchema = new Schema({
   username: {
     type: String
   },
   events: [{
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }]
})

UserSchema.set('autoIndex', true)

module.exports = mongoose.model('User', UserSchema)

Using mongoose's populate method

// controller.js

const mongoose = require('mongoose')
const User = require('./usermodel.js')

let query = User.findOne({ name: "Person" })

query.exec((err, user) => {
  if (err) {
     console.log(err)
  }

  user.events = events
  // user.events is now an array of events
})

Bootstrap 3 offset on right not left

Here is the same solution than Rukshan but in sass (in order to keep your grid configuration) for special case that don't work with Ross Allen solution (when you can't have a parent div.row)

@mixin make-grid-offset-right($class) {
    @for $index from 0 through $grid-columns {
        .col-#{$class}-offset-right-#{$index} {
            margin-right: percentage(($index / $grid-columns));
        }
    }
}

@include make-grid-offset-right(xs);

@media (min-width: $screen-sm-min) {
  @include make-grid-offset-right(sm);
}

@media (min-width: $screen-md-min) {
  @include make-grid-offset-right(md);
}

@media (min-width: $screen-lg-min) {
  @include make-grid-offset-right(lg);
}

Docker container will automatically stop after "docker run -d"

I had the same issue, just opening another terminal with a bash on it worked for me :

create container:

docker run -d mcr.microsoft.com/mssql/server:2019-CTP3.0-ubuntu
containerid=52bbc9b30557

start container:

docker start 52bbc9b30557

start bash to keep container running:

docker exec -it 52bbc9b30557 bash

start process you need:

docker exec -it 52bbc9b30557 /path_to_cool_your_app

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

You should execute the next query:

GRANT ALL ON TABLE mytable TO myuser;

Or if your error is in a view then maybe the table does not have permission, so you should execute the next query:

GRANT ALL ON TABLE tbm_grupo TO myuser;

How to consume a SOAP web service in Java

As some sugested you can use apache or jax-ws. You can also use tools that generate code from WSDL such as ws-import but in my opinion the best way to consume web service is to create a dynamic client and invoke only operations you want not everything from wsdl. You can do this by creating a dynamic client: Sample code:

String endpointUrl = ...;

QName serviceName = new QName("http://com/ibm/was/wssample/echo/",
 "EchoService");
QName portName = new QName("http://com/ibm/was/wssample/echo/",
 "EchoServicePort");

/** Create a service and add at least one port to it. **/ 
Service service = Service.create(serviceName);
service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointUrl);

/** Create a Dispatch instance from a service.**/ 
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, 
SOAPMessage.class, Service.Mode.MESSAGE);

/** Create SOAPMessage request. **/
// compose a request message
MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);

// Create a message.  This example works with the SOAPPART.
SOAPMessage request = mf.createMessage();
SOAPPart part = request.getSOAPPart();

// Obtain the SOAPEnvelope and header and body elements.
SOAPEnvelope env = part.getEnvelope();
SOAPHeader header = env.getHeader();
SOAPBody body = env.getBody();

// Construct the message payload.
SOAPElement operation = body.addChildElement("invoke", "ns1",
 "http://com/ibm/was/wssample/echo/");
SOAPElement value = operation.addChildElement("arg0");
value.addTextNode("ping");
request.saveChanges();

/** Invoke the service endpoint. **/
SOAPMessage response = dispatch.invoke(request);

/** Process the response. **/

python mpl_toolkits installation issue

It doesn't work on Ubuntu 16.04, it seems that some libraries have been forgotten in the python installation package on this one. You should use package manager instead.

Solution

Uninstall matplotlib from pip then install it again with apt-get

python 2:

sudo pip uninstall matplotlib
sudo apt-get install python-matplotlib

python 3:

sudo pip3 uninstall matplotlib
sudo apt-get install python3-matplotlib

Object of class stdClass could not be converted to string

Most likely, the userdata() function is returning an object, not a string. Look into the documentation (or var_dump the return value) to find out which value you need to use.

Regex: match word that ends with "Id"

Gumbo gets my vote, however, the OP doesn't specify whether just "Id" is an allowable word, which means I'd make a minor modification:

\w+Id\b

1 or more word characters followed by "Id" and a breaking space. The [a-zA-Z] variants don't take into account non-English alphabetic characters. I might also use \s instead of \b as a space rather than a breaking space. It would depend if you need to wrap over multiple lines.

vertical-align: middle doesn't work

You should set a fixed value to your span's line-height property:

.float, .twoline {
    line-height: 100px;
}

How to increase the distance between table columns in HTML?

If I understand correctly, you want this fiddle.

_x000D_
_x000D_
table {_x000D_
  background: gray;_x000D_
}_x000D_
td {    _x000D_
  display: block;_x000D_
  float: left;_x000D_
  padding: 10px 0;_x000D_
  margin-right:50px;_x000D_
  background: white;_x000D_
}_x000D_
td:last-child {_x000D_
  margin-right: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Hello HTML!</td>_x000D_
    <td>Hello CSS!</td>_x000D_
    <td>Hello JS!</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to strip HTML tags from string in JavaScript?

cleanText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");

Distilled from this website (web.achive).

This regex looks for <, an optional slash /, one or more characters that are not >, then either > or $ (the end of the line)

Examples:

'<div>Hello</div>' ==> 'Hello'
 ^^^^^     ^^^^^^
'Unterminated Tag <b' ==> 'Unterminated Tag '
                  ^^

But it is not bulletproof:

'If you are < 13 you cannot register' ==> 'If you are '
            ^^^^^^^^^^^^^^^^^^^^^^^^
'<div data="score > 42">Hello</div>' ==> ' 42">Hello'
 ^^^^^^^^^^^^^^^^^^          ^^^^^^

If someone is trying to break your application, this regex will not protect you. It should only be used if you already know the format of your input. As other knowledgable and mostly sane people have pointed out, to safely strip tags, you must use a parser.

If you do not have acccess to a convenient parser like the DOM, and you cannot trust your input to be in the right format, you may be better off using a package like sanitize-html, and also other sanitizers are available.

Install a Windows service using a Windows command prompt?

Follow these steps when deploying the Windows Service, don't lose time:

  1. Run command prompt by the Admin right

  2. Insure about release mode when compilling in your IDE

  3. Give a type to your project installer on design view

  4. Select authentication type in accordance the case

  5. Insure about software dependencies: If you are using a certificate install it correctly

  6. Go your console write this:

    C:\Windows\Microsoft.NET\Framework\yourRecentVersion\installutil.exe c:\yourservice.exe

there is a hidden -i argument before the exe path -i c:\ you can use -u for uninstallling

  1. Look your .exe path to seem log file. You can use event viewer to observing in the feature

Difference between java.exe and javaw.exe

The difference is in the subsystem that each executable targets.

  • java.exe targets the CONSOLE subsystem.
  • javaw.exe targets the WINDOWS subsystem.

How do I get time of a Python program's execution?

If you want to measure time in microseconds, then you can use the following version, based completely on the answers of Paul McGuire and Nicojo - it's Python 3 code. I've also added some colour to it:

import atexit
from time import time
from datetime import timedelta, datetime


def seconds_to_str(elapsed=None):
    if elapsed is None:
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    else:
        return str(timedelta(seconds=elapsed))


def log(txt, elapsed=None):
    colour_cyan = '\033[36m'
    colour_reset = '\033[0;0;39m'
    colour_red = '\033[31m'
    print('\n ' + colour_cyan + '  [TIMING]> [' + seconds_to_str() + '] ----> ' + txt + '\n' + colour_reset)
    if elapsed:
        print("\n " + colour_red + " [TIMING]> Elapsed time ==> " + elapsed + "\n" + colour_reset)


def end_log():
    end = time()
    elapsed = end-start
    log("End Program", seconds_to_str(elapsed))


start = time()
atexit.register(end_log)
log("Start Program")

log() => function that prints out the timing information.

txt ==> first argument to log, and its string to mark timing.

atexit ==> Python module to register functions that you can call when the program exits.

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

How to execute 16-bit installer on 64-bit Win7?

You can't run 16-bit applications (or components) on 64-bit versions of Windows. That emulation layer no longer exists. The 64-bit versions already have to provide a compatibility layer for 32-bit applications.

Support for 16-bit had to be dropped eventually, even in a culture where backwards-compatibility is of sacred import. The transition to 64-bit seemed like as good a time as any. It's hard to imagine anyone out there in the wild that is still using 16-bit applications and seeking to upgrade to 64-bit OSes.

What would be the best way to get round this problem?

If the component itself is 16-bit, then using a virtual machine running a 32-bit version of Windows is your only real choice. Oracle's VirtualBox is free, and a perennial favorite.

If only the installer is 16-bit (and it installs a 32-bit component), then you might be able to use a program like 7-Zip to extract the contents of the installer and install them manually. Let's just say this "solution" is high-risk and you should have few, if any, expectations.

It's high time to upgrade away from 16-bit stuff, like Turbo C++ and Sheridan controls. I've yet to come across anything that the Sheridan controls can do that the built-in controls can't do and haven't been able to do since Windows 95.

MySQL export into outfile : CSV escaping chars

What happens if you try the following?

Instead of your double REPLACE statement, try:

REPLACE(IFNULL(ts.description, ''),'\r\n', '\n')

Also, I think it should be LINES TERMINATED BY '\r\n' instead of just '\n'

How do I add Git version control (Bitbucket) to an existing source code folder?

User johannes told you how to do add existing files to a Git repository in a general situation. Because you talk about Bitbucket, I suggest you do the following:

  1. Create a new repository on Bitbucket (you can see a Create button on the top of your profile page) and you will go to this page:

    Create repository on Bitbucket

  2. Fill in the form, click next and then you automatically go to this page:

    Create repository from scratch or add existing files

  3. Choose to add existing files and you go to this page:

    Enter image description here

  4. You use those commands and you upload the existing files to Bitbucket. After that, the files are online.

How do I break a string across more than one line of code in JavaScript?

In your example, you can break the string into two pieces:

alert ( "Please Select file"
 + " to delete");

Or, when it's a string, as in your case, you can use a backslash as @Gumbo suggested:

alert ( "Please Select file\
 to delete");

Note that this backslash approach is not necessarily preferred, and possibly not universally supported (I had trouble finding hard data on this). It is not in the ECMA 5.1 spec.

When working with other code (not in quotes), line breaks are ignored, and perfectly acceptable. For example:

if(SuperLongConditionWhyIsThisSoLong
  && SuperLongConditionOnAnotherLine
  && SuperLongConditionOnThirdLineSheesh)
{
    // launch_missiles();
}

INNER JOIN vs INNER JOIN (SELECT . FROM)

You are correct. You did exactly the right thing, checking the query plan rather than trying to second-guess the optimiser. :-)

Plot different DataFrames in the same figure

To do this for multiple dataframes, you can do a for loop over them:

fig = plt.figure(num=None, figsize=(10, 8))
ax = dict_of_dfs['FOO'].column.plot()
for BAR in dict_of_dfs.keys():
    if BAR == 'FOO':
        pass
    else:
        dict_of_dfs[BAR].column.plot(ax=ax)

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

I found my problem. The issue was that my integers were actually type numpy.int64.

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

You can have a different goroutine that detects syscall.SIGINT and syscall.SIGTERM signals and relay them to a channel using signal.Notify. You can send a hook to that goroutine using a channel and save it in a function slice. When the shutdown signal is detected on the channel, you can execute those functions in the slice. This can be used to clean up the resources, wait for running goroutines to finish, persist data, or print partial run totals.

I wrote a small and simple utility to add and run hooks at shutdown. Hope it can be of help.

https://github.com/ankit-arora/go-utils/blob/master/go-shutdown-hook/shutdown-hook.go

You can do this in a 'defer' fashion.

example for shutting down a server gracefully :

srv := &http.Server{}

go_shutdown_hook.ADD(func() {
    log.Println("shutting down server")
    srv.Shutdown(nil)
    log.Println("shutting down server-done")
})

l, err := net.Listen("tcp", ":3090")

log.Println(srv.Serve(l))

go_shutdown_hook.Wait()

warning: implicit declaration of function

If you have the correct headers defined & are using a non GlibC library (such as Musl C) gcc will also throw error: implicit declaration of function when GNU extensions such as malloc_trim are encountered.

The solution is to wrap the extension & the header:

#if defined (__GLIBC__)
  malloc_trim(0);
#endif

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

Delete both Android SDK Tools and Android SDK PLatform-tools; then download both packages again. Now, create a new emulator and start it; it will work. You might be able to run your old emulators.

Clearing state es6 React

The solutions that involve setting this.state directly aren't working for me in React 16, so here is what I did to reset each key:

  const initialState = { example: 'example' }
  ...
  constructor() {
      super()
      this.state = initialState
  }
  ...
  reset() {
    const keys = Object.keys(this.state)
    const stateReset = keys.reduce((acc, v) => ({ ...acc, [v]: undefined }), {})
    this.setState({ ...stateReset, ...initialState })
  }

Calculating Time Difference

The datetime module will do all the work for you:

>>> import datetime
>>> a = datetime.datetime.now()
>>> # ...wait a while...
>>> b = datetime.datetime.now()
>>> print(b-a)
0:03:43.984000

If you don't want to display the microseconds, just use (as gnibbler suggested):

>>> a = datetime.datetime.now().replace(microsecond=0)
>>> b = datetime.datetime.now().replace(microsecond=0)
>>> print(b-a)
0:03:43

Remove a file from the list that will be committed

if you have already pushed your commit then. do

git checkout origin/<remote-branch> <filename>
git commit --amend

AND If you have not pushed the changes on the server you can use

git reset --soft HEAD~1

Nginx 403 forbidden for all files

I solved this problem by adding user settings.

in nginx.conf

worker_processes 4;
user username;

change the 'username' with linux user name.

How to extract file name from path?

The simplest approach if you are sure the file physically exists on the disk:

Dim fileName, filePath As String
filePath = "C:\Documents\myfile.pdf"
fileName = Dir(filePath)

If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:

fileName = Mid(filePath, InStrRev(filePath, "\") + 1)

What to return if Spring MVC controller method doesn't return value?

But as your system grows in size and functionality... i think that returning always a json is not a bad idea at all. Is more a architectural / "big scale design" matter.

You can think about returing always a JSON with two know fields : code and data. Where code is a numeric code specifying the success of the operation to be done and data is any aditional data related with the operation / service requested.

Come on, when we use a backend a service provider, any service can be checked to see if it worked well.

So i stick, to not let spring manage this, exposing hybrid returning operations (Some returns data other nothing...).. instaed make sure that your server expose a more homogeneous interface. Is more simple at the end of the day.

Testing two JSON objects for equality ignoring child order in Java

Try Skyscreamer's JSONAssert.

Its non-strict mode has two major advantages that make it less brittle:

  • Object extensibility (e.g. With an expected value of {id:1}, this would still pass: {id:1,moredata:'x'}.)
  • Loose array ordering (e.g. ['dog','cat']==['cat','dog'])

In strict mode it behaves more like json-lib's test class.

A test looks something like this:

@Test
public void testGetFriends() {
    JSONObject data = getRESTData("/friends/367.json");
    String expected = "{friends:[{id:123,name:\"Corby Page\"}"
        + ",{id:456,name:\"Solomon Duskis\"}]}";
    JSONAssert.assertEquals(expected, data, false);
}

The parameters in the JSONAssert.assertEquals() call are expectedJSONString, actualDataString, and isStrict.

The result messages are pretty clear, which is important when comparing really big JSON objects.

Jquery: Checking to see if div contains text, then action

Your code contains two problems:

  • The equality operator in JavaScript is ==, not =.
  • jQuery.text() joins all text nodes of matched elements into a single string. If you have two successive elements, of which the first contains 'some' and the second contains 'Text', then your code will incorrectly think that there exists an element that contains 'someText'.

I suggest the following instead:

if ($('#field > div.field-item:contains("someText")').length > 0) {
    $("#somediv").addClass("thisClass");
}

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

Not all at once. But you can press

Alt + Enter

People assume it only works when you are at the particular item. But it actually works for "next missing type". So if you keep pressing Alt + Enter, IDEA fixes one after another until all are fixed.

Default value for field in Django model

Set editable to False and default to your default value.

http://docs.djangoproject.com/en/stable/ref/models/fields/#editable

b = models.CharField(max_length=7, default='0000000', editable=False)

Also, your id field is unnecessary. Django will add it automatically.

Deleting Row in SQLite in Android

Guys if above solutions don't work for you then try this one also because it worked for me.

public boolean deleteRow(String name) 
{
    return db.delete(DATABASE_TABLE, KEY_NAME + "='" + name +"' ;", null) > 0;
}