Programs & Examples On #Microsoft.mshtml

ActiveX component can't create object

Check your browser settings.

For me, using IE, the fix was to go into Tools/Internet Options, Security tab, for the relevant zone, "custom level" and check the ActiveX settings. Setting "Initialize and script ActiveX controls not marked as safe for scripting" to "Enable" fixed this problem for me.

A simple algorithm for polygon intersection

You could use a Polygon Clipping algorithm to find the intersection between two polygons. However these tend to be complicated algorithms when all of the edge cases are taken into account.

One implementation of polygon clipping that you can use your favorite search engine to look for is Weiler-Atherton. wikipedia article on Weiler-Atherton

Alan Murta has a complete implementation of a polygon clipper GPC.

Edit:

Another approach is to first divide each polygon into a set of triangles, which are easier to deal with. The Two-Ears Theorem by Gary H. Meisters does the trick. This page at McGill does a good job of explaining triangle subdivision.

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

Genymotion Android emulator - adb access?

Simply do this, with genymotion device running you can open Virtual Box , and see that there is a VM for you device , then go to network Settings of the VM, NAT and do port forwarding of local 5555 to remote 5555 screen attachedVirtual Box Nat Network Port forwarding

Convert double to float in Java

Converting from double to float will be a narrowing conversion. From the doc:

A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.

A narrowing primitive conversion from double to float is governed by the IEEE 754 rounding rules (§4.2.4). This conversion can lose precision, but also lose range, resulting in a float zero from a nonzero double and a float infinity from a finite double. A double NaN is converted to a float NaN and a double infinity is converted to the same-signed float infinity.

So it is not a good idea. If you still want it you can do it like:

double d = 3.0;
float f = (float) d;

What is the "double tilde" (~~) operator in JavaScript?

That ~~ is a double NOT bitwise operator.

It is used as a faster substitute for Math.floor() for positive numbers. It does not return the same result as Math.floor() for negative numbers, as it just chops off the part after the decimal (see other answers for examples of this).

How can I get a list of all open named pipes in Windows?

I stumbled across a feature in Chrome that will list out all open named pipes by navigating to "file://.//pipe//"

Since I can't seem to find any reference to this and it has been very helpful to me, I thought I might share.

Why do we need C Unions?

I'd say it makes it easier to reuse memory that might be used in different ways, i.e. saving memory. E.g. you'd like to do some "variant" struct that's able to save a short string as well as a number:

struct variant {
    int type;
    double number;
    char *string;
};

In a 32 bit system this would result in at least 96 bits or 12 bytes being used for each instance of variant.

Using an union you can reduce the size down to 64 bits or 8 bytes:

struct variant {
    int type;
    union {
        double number;
        char *string;
    } value;
};

You're able to save even more if you'd like to add more different variable types etc. It might be true, that you can do similar things casting a void pointer - but the union makes it a lot more accessible as well as type safe. Such savings don't sound massive, but you're saving one third of the memory used for all instances of this struct.

Invalid date in safari

convert string to Date fromat (you have to know server timezone)

new Date('2015-06-16 11:00:00'.replace(/\s+/g, 'T').concat('.000+08:00')).getTime()  

where +08:00 = timeZone from server

Making a POST call instead of GET using urllib2

Have a read of the urllib Missing Manual. Pulled from there is the following simple example of a POST request.

url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe', 'age'  : '10'})
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
print response.read()

As suggested by @Michael Kent do consider requests, it's great.

EDIT: This said, I do not know why passing data to urlopen() does not result in a POST request; It should. I suspect your server is redirecting, or misbehaving.

Reducing MongoDB database file size

We need solve 2 ways, based on StorageEngine.

1. MMAP() engine:

command: db.repairDatabase()

NOTE: repairDatabase requires free disk space equal to the size of your current data set plus 2 gigabytes. If the volume that holds dbpath lacks sufficient space, you can mount a separate volume and use that for the repair. When mounting a separate volume for repairDatabase you must run repairDatabase from the command line and use the --repairpath switch to specify the folder in which to store temporary repair files. eg: Imagine DB size is 120 GB means, (120*2)+2 = 242 GB Hard Disk space required.

another way you do collection wise, command: db.runCommand({compact: 'collectionName'})

2. WiredTiger: Its automatically resolved it-self.

C# cannot convert method to non delegate type

As mentioned you need to use obj.getTile()

But, in this case I think you are looking to use a Property.

public class Pin
{
    private string title;

    public Pin() { }

    public setTitle(string title) {
        this.title = title;
    }

    public String Title
    {
        get { return title; }
    }
}

This will allow you to use

foreach (Pin obj in ClassListPin.pins)
{
     string t = obj.Title;
}

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

This error is mainly due to processor architecture incompatibility with Framework installed ei x86 vs x64 The solution: Go to solution explorer>project properties>Compile tab>Advanced Compile Options There you have to change Target CPU from X64 to X86 Save new setting and recompile your solution. I tried it and it worked very fine. Hope this will help you out. Malek

Dynamically add item to jQuery Select2 control that uses AJAX

To get dynamic tagging to work with ajax, here's what I did.

Select2 version 3.5

This is easy in version 3.5 because it offers the createSearchChoice hook. It even works for multiple select, as long as multiple: true and tags: true are set.

HTML

<input type="hidden" name="locations" value="Whistler, BC" />

JS

$('input[name="locations"]').select2({
  tags: true,
  multiple: true,
  createSearchChoice: function(term, data) {
    if (!data.length)
      return { id: term, text: term };
    },
  ajax: {
    url: '/api/v1.1/locations',
    dataType: 'json'
  }
});

The idea here is to use select2's createSearchChoice hook which passes you both the term that the user entered and the ajax response (as data). If ajax returns an empty list, then tell select2 to offer the user-entered term as an option.

Demo: https://johnny.netlify.com/select2-examples/version3


Select2 version 4.X

Version 4.X doesn't have a createSearchChoice hook anymore, but here's how I did the same thing.

HTML

  <select name="locations" multiple>
    <option value="Whistler, BC" selected>Whistler, BC</option>
  </select>

JS

$('select[name="locations"]').select2({
  ajax: {
    url: '/api/v1.1/locations',
    dataType: 'json',
    data: function(params) {
      this.data('term', params.term);
      return params;
    },
    processResults: function(data) {
      if (data.length)
        return {
          results: data
        };
      else
        return {
          results: [{ id: this.$element.data('term'), text: this.$element.data('term') }]
        };
    }
  }
});

The ideas is to stash the term that the user typed into jQuery's data store inside select2's data hook. Then in select2's processResults hook, I check if the ajax response is empty. If it is, I grab the stashed term that the user typed and return it as an option to select2.

Demo: https://johnny.netlify.com/select2-examples/version4

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

I had issues getting through a form because of this error.

I used Ctrl+Click to click the submit button and navigate through the form as usual.

How to display an alert box from C# in ASP.NET?

Hey Try This Code.

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "Data has been saved", true);

Cheers

Jquery bind double click and single click separately

(function($){

$.click2 = function (elm, o){
    this.ao = o;
    var DELAY = 700, clicks = 0;
    var timer = null;
    var self = this;

    $(elm).on('click', function(e){
        clicks++;
        if(clicks === 1){
            timer = setTimeout(function(){
                self.ao.click(e);
            }, DELAY);
        } else {
            clearTimeout(timer);
            self.ao.dblclick(e);
        }
    }).on('dblclick', function(e){
        e.preventDefault();
    });

};

$.click2.defaults = { click: function(e){}, dblclick: function(e){} };

$.fn.click2 = function(o){
    o = $.extend({},$.click2.defaults, o);
    this.each(function(){ new $.click2(this, o); });
    return this;
};

})(jQuery);

And finally we use as.

$("a").click2({
    click : function(e){
        var cid = $(this).data('cid');
        console.log("Click : "+cid);
    },
    dblclick : function(e){
        var cid = $(this).data('cid');
        console.log("Double Click : "+cid);
    }
});

Unexpected token < in first line of HTML

I had this problem in an ASP.NET application, specifically a Web Forms.

I was forcing a redirect in Global.asax, but I forgot to check if the request was for resources like css, javascript, etc. I just had to add the following checks:

VB.NET

If Not Response.IsRequestBeingRedirected _
    And Not Request.Url.AbsoluteUri.Contains(".WebResource") _
    And Not Request.Url.AbsoluteUri.Contains(".css") _
    And Not Request.Url.AbsoluteUri.Contains(".js") _
    And Not Request.Url.AbsoluteUri.Contains("images/") _
    And Not Request.Url.AbsoluteUri.Contains("favicon") Then
        Response.Redirect("~/change-password.aspx")
End If

I was forcing logged users which hadn't change their passwords for a long time, to be redirected to the change-password.aspx page. I believe there is a better way to check this, but for now, this worked. Should I find a better solution, I edit my answer.

Usage of MySQL's "IF EXISTS"

You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.

Turn the EXISTS clause into a subquery instead within an IF function

SELECT IF( EXISTS(
             SELECT *
             FROM gdata_calendars
             WHERE `group` =  ? AND id = ?), 1, 0)

In fact, booleans are returned as 1 or 0

SELECT EXISTS(
         SELECT *
         FROM gdata_calendars
         WHERE `group` =  ? AND id = ?)

Convert ArrayList<String> to String[] array

Try this

String[] arr = list.toArray(new String[list.size()]);

Put text at bottom of div

Thanks @Harry the following code works for me:

.your-div{
   vertical-align: bottom;
   display: table-cell;
}

using wildcards in LDAP search filters/queries

This should work, at least according to the Search Filter Syntax article on MSDN network.

The "hang-up" you have noticed is probably just a delay. Try running the same query with narrower scope (for example the specific OU where the test object is located), as it may take very long time for processing if you run it against all AD objects.

You may also try separating the filter into two parts:

(|(displayName=*searchstring)(displayName=searchstring*))

Pushing to Git returning Error Code 403 fatal: HTTP request failed

None of the above answers worked for my enterprise GitHub account. Follow these steps for pushing via ssh key generation way.

Create a repo by visiting your git account.

Generate ssh key:

ssh-keygen -t rsa -C "[email protected]"

Copy the contents of the file ~/.ssh/id_rsa.pub to your SSH keys in your GitHub account settings. Test SSH key:

ssh -T [email protected]
clone the repo:
git clone git://github.com/username/your-repository

Now cd to your git clone folder and do:

git remote set-url origin [email protected]:username/your-repository.git

Now try editing a file (try the README) and then do:

git add -A
git commit -am "my update msg"
git push -u origin master

Update: new git version seems to recommend not to have any file while new repo is created. Hence make aa blank repo.

Detecting scroll direction

  1. Initialize an oldValue
  2. Get the newValue by listening to the event
  3. Subtract the two
  4. Conclude from the result
  5. Update oldValue with the newValue

// Initialization

let oldValue = 0;

//Listening on the event

window.addEventListener('scroll', function(e){

    // Get the new Value
    newValue = window.pageYOffset;

    //Subtract the two and conclude
    if(oldValue - newValue < 0){
        console.log("Up");
    } else if(oldValue - newValue > 0){
        console.log("Down");
    }

    // Update the old value
    oldValue = newValue;
});

Write values in app.config file

Try the following code:

    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Add("YourKey", "YourValue");
    config.Save(ConfigurationSaveMode.Minimal);

It worked for me :-)

How to return a custom object from a Spring Data JPA GROUP BY query

This SQL query return List< Object[] > would.

You can do it this way:

 @RestController
 @RequestMapping("/survey")
 public class SurveyController {

   @Autowired
   private SurveyRepository surveyRepository;

     @RequestMapping(value = "/find", method =  RequestMethod.GET)
     public Map<Long,String> findSurvey(){
       List<Object[]> result = surveyRepository.findSurveyCount();
       Map<Long,String> map = null;
       if(result != null && !result.isEmpty()){
          map = new HashMap<Long,String>();
          for (Object[] object : result) {
            map.put(((Long)object[0]),object[1]);
          }
       }
     return map;
     }
 }

Python - abs vs fabs

math.fabs() converts its argument to float if it can (if it can't, it throws an exception). It then takes the absolute value, and returns the result as a float.

In addition to floats, abs() also works with integers and complex numbers. Its return type depends on the type of its argument.

In [7]: type(abs(-2))
Out[7]: int

In [8]: type(abs(-2.0))
Out[8]: float

In [9]: type(abs(3+4j))
Out[9]: float

In [10]: type(math.fabs(-2))
Out[10]: float

In [11]: type(math.fabs(-2.0))
Out[11]: float

In [12]: type(math.fabs(3+4j))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/npe/<ipython-input-12-8368761369da> in <module>()
----> 1 type(math.fabs(3+4j))

TypeError: can't convert complex to float

Can you use if/else conditions in CSS?

Below is my old answer which is still valid but I have a more opinionated approach today:

One of the reasons why CSS sucks so much is exactly that it doesn't have conditional syntax. CSS is per se completely unusable in the modern web stack. Use SASS for just a little while and you'll know why I say that. SASS has conditional syntax... and a LOT of other advantages over primitive CSS too.


Old answer (still valid):

It cannot be done in CSS in general!

You have the browser conditionals like:

/*[if IE]*/ 
body {height:100%;} 
/*[endif]*/

But nobody keeps you from using Javascript to alter the DOM or assigning classes dynamically or even concatenating styles in your respective programming language.

I sometimes send css classes as strings to the view and echo them into the code like that (php):

<div id="myid" class="<?php echo $this->cssClass; ?>">content</div>

Applying an ellipsis to multiline text

After looking all over the internet and trying a lot of these options, the only way to make sure that it is covered correctly with support for i.e is through javascript, i created a loop function to go over post items that require multi line truncation.

*note i used Jquery, and requires your post__items class to have a fixed max-height.

// loop over post items
$('.post__items').each(function(){
    var textArray = $(this).text().split(' ');
    while($(this).prop('scrollHeight') > $(this).prop('offsetHeight')) {
        textArray.pop();
        $(this).text(textArray.join(' ') + '...');
     }
});

How to find out the username and password for mysql database

In your local system right,

   go to this url : http://localhost/phpmyadmin/

   In this click mysql default db, after that browser user table to get existing username and password.

How to get the background color of an HTML element?

Using JQuery:

var color = $('#myDivID').css("background-color");

When to use DataContract and DataMember attributes?

Also when you call from http request it will work properly but when your try to call from net.tcp that time you get all this kind stuff

Issue with adding common code as git submodule: "already exists in the index"

I got it working by doing it the other way around. Starting with an empty repo, adding the submodule in a new folder called "projectfolder/common_code". After that it was possible to add the project code in projectfolder. The details are shown below.

In an empty repo type:

git submodule add url_to_repo projectfolder/common_code

That will create the desired folder structure:

repo
|-- projectfolder
    |-- common_code

It is now possible to add more submodules, and the project code can be added to projectfolder.

I can't yet say why it worked this way around and not the other.

Calling a function of a module by using its name (a string)

The answer (I hope) no one ever wanted

Eval like behavior

getattr(locals().get("foo") or globals().get("foo"), "bar")()

Why not add auto-importing

getattr(
    locals().get("foo") or 
    globals().get("foo") or
    __import__("foo"), 
"bar")()

In case we have extra dictionaries we want to check

getattr(next((x for x in (f("foo") for f in 
                          [locals().get, globals().get, 
                           self.__dict__.get, __import__]) 
              if x)),
"bar")()

We need to go deeper

getattr(next((x for x in (f("foo") for f in 
              ([locals().get, globals().get, self.__dict__.get] +
               [d.get for d in (list(dd.values()) for dd in 
                                [locals(),globals(),self.__dict__]
                                if isinstance(dd,dict))
                if isinstance(d,dict)] + 
               [__import__])) 
        if x)),
"bar")()

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

I had this error when i was using the azure storage as a static website, the js files that are copied had the content type as text/plain; charset=utf-8 and i changed the content type to application/javascript

It started working.

.toLowerCase not working, replacement function?

It is a number, not a string. Numbers don't have a toLowerCase() function because numbers do not have case in the first place.

To make the function run without error, run it on a string.

var ans = "334";

Of course, the output will be the same as the input since, as mentioned, numbers don't have case in the first place.

How do I create a shortcut via command-line in Windows?

I created a VB script and run it either from command line or from a Java process. I also tried to catch errors when creating the shortcut so I can have a better error handling.

Set oWS = WScript.CreateObject("WScript.Shell")
shortcutLocation = Wscript.Arguments(0)

'error handle shortcut creation
On Error Resume Next
Set oLink = oWS.CreateShortcut(shortcutLocation)
If Err Then WScript.Quit Err.Number

'error handle setting shortcut target
On Error Resume Next
oLink.TargetPath = Wscript.Arguments(1)
If Err Then WScript.Quit Err.Number

'error handle setting start in property
On Error Resume Next
oLink.WorkingDirectory = Wscript.Arguments(2)
If Err Then WScript.Quit Err.Number

'error handle saving shortcut
On Error Resume Next
oLink.Save
If Err Then WScript.Quit Err.Number

I run the script with the following commmand:

cscript /b script.vbs shortcutFuturePath targetPath startInProperty

It is possible to have it working even without setting the 'Start in' property in some cases.

ng-mouseover and leave to toggle item using mouse in angularjs

Angular solution

You can fix it like this:

$scope.hoverIn = function(){
    this.hoverEdit = true;
};

$scope.hoverOut = function(){
    this.hoverEdit = false;
};

Inside of ngMouseover (and similar) functions context is a current item scope, so this refers to the current child scope.

Also you need to put ngRepeat on li:

<ul>
    <li ng-repeat="task in tasks" ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">
        {{task.name}}
        <span ng-show="hoverEdit">
            <a>Edit</a>
        </span>
    </li>
</ul>

Demo

CSS solution

However, when possible try to do such things with CSS only, this would be the optimal solution and no JS required:

ul li span {display: none;}
ul li:hover span {display: inline;}

Corrupted Access .accdb file: "Unrecognized Database Format"

Sometimes it might depend on whether you are using code to access the database or not. If you are using "DriverJet" in your code instead of "DriverACE" (or an older version of the DAO library) such a problem is highly probable to happen. You just need to replace "DriverJet" with "DriverACE" and test.

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

For what it's worth, I do this:

    <!-- Favicon - Generic -->
    <link rel="icon" href="path/favicon-32_x_32.png" sizes="32x32">
    <link rel="icon" href="path/favicon-57_x_57.png" sizes="57x57">
    <link rel="icon" href="path/favicon-76_x_76.png" sizes="76x76">
    <link rel="icon" href="path/favicon-96_x_96.png" sizes="96x96">
    <link rel="icon" href="path/favicon-128_x_128.png" sizes="128x128">
    <link rel="icon" href="path/favicon-192_x_192.png" sizes="192x192">
    <link rel="icon" href="path/favicon-228_x_228.png" sizes="228x228">
    <!-- Favicon - Android -->
    <link rel="shortcut icon" href="path/favicon-196_x_196.png" sizes="196x196">
    <!-- Favicon - iOS -->
    <link rel="apple-touch-icon" href="path/favicon-120_x_120.png" sizes="120x120">
    <link rel="apple-touch-icon" href="path/favicon-152_x_152.png" sizes="152x152">
    <link rel="apple-touch-icon" href="path/favicon-180_x_180.png" sizes="180x180">

And I still keep the favicon.ico in root.

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
response = client.execute(httppost, localContext);

doesn't work in 4.5 version without

cookie.setDomain(".domain.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");

How to create a Calendar table for 100 years in Sql

 declare @date int
 WITH CTE_DatesTable
AS
(
  SELECT CAST('20000101' as date) AS [date]
  UNION ALL
  SELECT   DATEADD(dd, 1, [date])
  FROM CTE_DatesTable
  WHERE DATEADD(dd, 1, [date]) <= '21001231'
)
SELECT [DWDateKey]=[date],[DayDate]=datepart(dd,[date]),[DayOfWeekName]=datename(dw,[date]),[WeekNumber]=DATEPART( WEEK , [date]),[MonthNumber]=DATEPART( MONTH , [date]),[MonthName]=DATENAME( MONTH , [date]),[MonthShortName]=substring(LTRIM( DATENAME(MONTH,[date])),0, 4),[Year]=DATEPART(YY,[date]),[QuarterNumber]=DATENAME(quarter, [date]),[QuarterName]=DATENAME(quarter, [date]) into DimDate   FROM CTE_DatesTable

OPTION (MAXRECURSION 0);

Is there a way to check if a file is in use?

I'm interested to see if this triggers any WTF reflexes. I have a process which creates and subsequently launches a PDF document from a console app. However, I was dealing with a frailty where if the user were to run the process multiple times, generating the same file without first closing the previously generated file, the app would throw an exception and die. This was a rather frequent occurrence because file names are based on sales quote numbers.

Rather than failing in such an ungraceful manner, I decided to rely on auto-incremented file versioning:

private static string WriteFileToDisk(byte[] data, string fileName, int version = 0)
{
    try
    {
        var versionExtension = version > 0 ? $"_{version:000}" : string.Empty;
        var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{fileName}{versionExtension}.pdf");
        using (var writer = new FileStream(filePath, FileMode.Create))
        {
            writer.Write(data, 0, data.Length);
        }
        return filePath;
    }
    catch (IOException)
    {
        return WriteFileToDisk(data, fileName, ++version);
    }
}

Probably some more care can be given to the catch block to ensure I'm catching the correct IOException(s). I'll probably also clear out the app storage on startup since these files are intended to be temporary anyways.

I realize this goes beyond the scope of the OP's question of simply checking if the file is in use but this was indeed the problem I was looking to solve when I arrived here so perhaps it will be useful to someone else.

How to disable or enable viewpager swiping in android

Disable swipe progmatically by-

    final View touchView = findViewById(R.id.Pager); 
    touchView.setOnTouchListener(new View.OnTouchListener() 
    {         
        @Override
        public boolean onTouch(View v, MotionEvent event)
        { 
           return true; 
        }
     });

and use this to swipe manually

touchView.setCurrentItem(int index);

HashMaps and Null values?

You can keep note of below possibilities:

1. Values entered in a map can be null.

However with multiple null keys and values it will only take a null key value pair once.

Map<String, String> codes = new HashMap<String, String>();

codes.put(null, null);
codes.put(null,null);
codes.put("C1", "Acathan");

for(String key:codes.keySet()){
    System.out.println(key);
    System.out.println(codes.get(key));
}

output will be :

null //key  of the 1st entry
null //value of 1st entry
C1
Acathan

2. your code will execute null only once

options.put(null, null);  
Person person = sample.searchPerson(null);   

It depends on the implementation of your searchPerson method if you want multiple values to be null, you can implement accordingly

Map<String, String> codes = new HashMap<String, String>();

    codes.put(null, null);
    codes.put("X1",null);
    codes.put("C1", "Acathan");
    codes.put("S1",null);


    for(String key:codes.keySet()){
        System.out.println(key);
        System.out.println(codes.get(key));
    }

output:

null
null

X1
null
S1
null
C1
Acathan

Java: Calling a super method which calls an overridden method

this always refers to currently executing object.

To further illustrate the point here is a simple sketch:

+----------------+
|  Subclass      |
|----------------|
|  @method1()    |
|  @method2()    |
|                |
| +------------+ |
| | Superclass | |
| |------------| |
| | method1()  | |
| | method2()  | |
| +------------+ |
+----------------+

If you have an instance of the outer box, a Subclass object, wherever you happen to venture inside the box, even into the Superclass 'area', it is still the instance of the outer box.

What's more, in this program there is only one object that gets created out of the three classes, so this can only ever refer to one thing and it is:

enter image description here

as shown in the Netbeans 'Heap Walker'.

"Keep Me Logged In" - the best approach

I asked one angle of this question here, and the answers will lead you to all the token-based timing-out cookie links you need.

Basically, you do not store the userId in the cookie. You store a one-time token (huge string) which the user uses to pick-up their old login session. Then to make it really secure, you ask for a password for heavy operations (like changing the password itself).

fix java.net.SocketTimeoutException: Read timed out

I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).

e.g. (from the doc)

     System.out.println("<< Response: " + response.getStatusLine());
     System.out.println(EntityUtils.toString(response.getEntity()));

Download image with JavaScript

The problem is that jQuery doesn't trigger the native click event for <a> elements so that navigation doesn't happen (the normal behavior of an <a>), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).

To trigger it manually, try:

var a = $("<a>")
    .attr("href", "http://i.stack.imgur.com/L8rHf.png")
    .attr("download", "img.png")
    .appendTo("body");

a[0].click();

a.remove();

DEMO: http://jsfiddle.net/HTggQ/

Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332

if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
        jQuery.acceptData( elem ) ) {

Best practices to test protected methods with PHPUnit

I'm going to throw my hat into the ring here:

I've used the __call hack with mixed degrees of success. The alternative I came up with was to use the Visitor pattern:

1: generate a stdClass or custom class (to enforce type)

2: prime that with the required method and arguments

3: ensure that your SUT has an acceptVisitor method which will execute the method with the arguments specified in the visiting class

4: inject it into the class you wish to test

5: SUT injects the result of operation into the visitor

6: apply your test conditions to the Visitor's result attribute

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Since Django 2.0 the ForeignKey field requires two positional arguments:

  1. the model to map to
  2. the on_delete argument
categorie = models.ForeignKey('Categorie', on_delete=models.PROTECT)

Here are some methods can used in on_delete

  1. CASCADE

Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey

  1. PROTECT

Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

  1. DO_NOTHING

Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.

you can find more about on_delete by reading the documentation.

angular.service vs angular.factory

Here are the primary differences:

Services

Syntax: module.service( 'serviceName', function );

Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to module.service.

Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending ( ) to the injected function reference. Could also be run with injectedArg.call( this ) or similar.

Factories

Syntax: module.factory( 'factoryName', function );

Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.

Here is example using services and factory. Read more about AngularJS Service vs Factory.

You can also check the AngularJS documentation and similar question on stackoverflow confused about service vs factory.

Get list of JSON objects with Spring RestTemplate

Maybe this way...

ResponseEntity<Object[]> responseEntity = restTemplate.getForEntity(urlGETList, Object[].class);
Object[] objects = responseEntity.getBody();
MediaType contentType = responseEntity.getHeaders().getContentType();
HttpStatus statusCode = responseEntity.getStatusCode();

Controller code for the RequestMapping

@RequestMapping(value="/Object/getList/", method=RequestMethod.GET)
public @ResponseBody List<Object> findAllObjects() {

    List<Object> objects = new ArrayList<Object>();
    return objects;
}

ResponseEntity is an extension of HttpEntity that adds a HttpStatus status code. Used in RestTemplate as well @Controller methods. In RestTemplate this class is returned by getForEntity() and exchange().

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

Note that if the problem is being caused by appearing scrollbars, putting

body {
  overflow: hidden;
}

in your CSS might be an easy fix (if you don't need the page to scroll).

How to pass multiple parameters from ajax to mvc controller?

  var data = JSON.stringify
            ({
            'StrContactDetails': Details,
            'IsPrimary': true
            })

How to start Apache and MySQL automatically when Windows 8 comes up

  1. Window + R
  2. Type services.msc
  3. Search for your WAMP Apache and go to property and select Auto.
  4. Restart your computer.

As a service

You can set this one by:

Going first to your installation directory (in my case it’s c:\xampplite). It could be somewhere else depending on your installation. Have also my full version in c:\x2\xampp. Once your in the installation directory, find xampp-control.exe and click/double-click to launch it.

You should first stop all running instances of your apache2 and mysqld/mysql processes to do this.

Click the checkmark next to Apache and MySQL with the header name service. It will warn you that it’s installing as a service which of course is what we like it to do. Click Yes.

Also do step 5 with MySQL. We’re almost done.

Click Start ? Run

Type services.msc (it can also be done in the control panel under administrative tools which is a way lot of click than this one). Find the Apache 2 and MySQL services.

Double click each one and set the startup type to Automatic (you will be presented with three options: Automatic, Manual, and Disabled):

  • Automatic – will start it automatically at startup
  • Manual – users will have to start it up manually i.e. by issuing a command like net start apache2
  • Disabled – will disable it.

Be warned though that any change in the services just like the registry can cause your system to stall.

Click the start button to manually start it (just for the session though). At the next restart it’ll be automated.

Do the same with MySQL.

As a startup program

Find xampp_start.exe from your installation directory.

Press Ctrl + C to copy it or right-click the file and hit copy.

Go to C:\Documents and Settings\Administrator\Start Menu\Programs\Startup and right click on it and hit Paste Shortcut.

When you restart it’ll be starting also and you’ll see something like this:

You can stop it by issuing the xampp_stop.exe command in your installation directory.

Also worth mentioning is that if you right click again on the shortcut and hit properties, try to change the run option to minimized. This way the shortcut will be on your taskbar once started.

allowing only alphabets in text box using java script

just use onkeypress event like below:

<input type="text" name="onlyalphabet" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">

Unexpected token ILLEGAL in webkit

It won't be exactly refering to the given problem, but I wanna share my mistake here, maybe some1 will make simmilar one and will also land with his/her problem here:

Ive got Unexpected token ILLEGAL error because I named a function with a number as 1st char.

It was 3x3check(). Changing it to check3x3() solved my problem.

How to undo a SQL Server UPDATE query?

If you already have a full backup from your database, fortunately, you have an option in SQL Management Studio. In this case, you can use the following steps:

  1. Right click on database -> Tasks -> Restore -> Database.

  2. In General tab, click on Timeline -> select Specific date and time option.

  3. Move the timeline slider to before update command time -> click OK.

  4. In the destination database name, type a new name.

  5. In the Files tab, check in Reallocate all files to folder and then select a new path to save your recovered database.

  6. In the options tab, check in Overwrite ... and remove Take tail-log... check option.

  7. Finally, click on OK and wait until the recovery process is over.

I have used this method myself in an operational database and it was very useful.

symfony2 twig path with parameter url creation

In Twig:

{% for l in locations %}

<tr>
    <td>
        <input type="checkbox" class="filled-in" id="filled-in-box-{{ l.idLocation }}" />
        <label for="filled-in-box-{{ l.idLocation }}"></label>
    </td>
    <td>{{ l.loc }}</td>
    <td>{{ l.mun }}</td>
    <td>{{ l.pro }}</td>
    <td>{{ l.cou }}</td>
    {#<td>
        {% if l.active == 1  %}
            <span class="fa fa-check"></span>
        {% else %}
            <span class="fa fa-close"></span>
        {% endif %}
    </td>#}
    <td><a href="{{ url('admin_edit_location',{'id': l.idLocation}) }}" class="db-list-edit"><span class="fa fa-pencil-square-o"></span></a>
    </td>
</tr>{% endfor %}

The route admin_edit_location:

admin_edit_location:
  path: /edit_location/{id}
  defaults: { _controller: "AppBundle:Admin:editLocation" }
  methods: GET

And the controller

public function editLocationAction($id){
    // use $id 

    $em = $this->getDoctrine()->getManager();
    $location = $em->getRepository('BackendBundle:locations')->findOneBy(array(
    'id'    => $id
    ));
}

Permission denied at hdfs

I solved this problem temporary by disabling the dfs permission.By adding below property code to conf/hdfs-site.xml

<property>
  <name>dfs.permissions</name>
  <value>false</value>
</property>

Check date between two other dates spring data jpa

Maybe you could try

List<Article> findAllByPublicationDate(Date publicationDate);

The detail could be checked in this article:

https://www.baeldung.com/spring-data-jpa-query-by-date

How to overlay density plots in R?

That's how I do it in base (it's actually mentionned in the first answer comments but I'll show the full code here, including legend as I can not comment yet...)

First you need to get the info on the max values for the y axis from the density plots. So you need to actually compute the densities separately first

dta_A <- density(VarA, na.rm = TRUE)
dta_B <- density(VarB, na.rm = TRUE)

Then plot them according to the first answer and define min and max values for the y axis that you just got. (I set the min value to 0)

plot(dta_A, col = "blue", main = "2 densities on one plot"), 
     ylim = c(0, max(dta_A$y,dta_B$y)))  
lines(dta_B, col = "red")

Then add a legend to the top right corner

legend("topright", c("VarA","VarB"), lty = c(1,1), col = c("blue","red"))

How can I hide a TD tag using inline JavaScript or CSS?

If you have more than this in javascript consider some javascript library, e.g. jquery which takes away a little speed, but gives you more readable code.

Your question's code via jquery:

$("td").hide();

Of course there are other javascript libraries out there, as this comparison on wikipedia shows.

How to escape single quotes within single quoted strings

In the given example, simply used double quotes instead of single quotes as outer escape mechanism:

alias rxvt="urxvt -fg '#111111' -bg '#111111'"

This approach is suited for many cases where you just want to pass a fixed string to a command: Just check how the shell will interpret the double-quoted string through an echo, and escape characters with backslash if necessary.

In the example, you'd see that double quotes are sufficient to protect the string:

$ echo "urxvt -fg '#111111' -bg '#111111'"
urxvt -fg '#111111' -bg '#111111'

How to make a phone call programmatically?

This doesn't require a permission.

val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:+123456"))
startActivity(intent)

Or

val intent = Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", "+123456", null))
startActivity(intent)

But it shows one more dialog (asking whether you want to call phone just once or always). So it would be better to use ACTION_CALL with a permission (see Revoked permission android.permission.CALL_PHONE).

How to specify preference of library path?

This is an old question, but no one seems to have mentioned this.

You were getting lucky that the thing was linking at all.

You needed to change

g++ -g -Wall -o my_binary -L/my/dir -lfoo bar.cpp

to this:

g++ -g -Wall -o my_binary -L/my/dir bar.cpp -lfoo

Your linker keeps track of symbols it needs to resolve. If it reads the library first, it doesn't have any needed symbols, so it ignores the symbols in it. Specify the libraries after the things that need to link to them so that your linker has symbols to find in them.

Also, -lfoo makes it search specifically for a file named libfoo.a or libfoo.so as needed. Not libfoo.so.0. So either ln the name or rename the library as appopriate.

To quote the gcc man page:

-l library
   ...
   It makes a difference where in the command you 
   write this option; the linker searches and processes 
   libraries and object files in the order they are 
   specified.  Thus, foo.o -lz bar.o searches library z 
   after file foo.o but before bar.o.  If bar.o refers 
   to functions in z, those functions may not be loaded.

Adding the file directly to g++'s command line should have worked, unless of course, you put it prior to bar.cpp, causing the linker to ignore it for lacking any needed symbols, because no symbols were needed yet.

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

I got this error and found that I don't have my SSH port (non standard number) whitelisted in config server firewall.

Map vs Object in JavaScript

I don't think the following points have been mentioned in the answers so far, and I thought they'd be worth mentioning.


Maps can be bigger

In chrome I can get 16.7 million key/value pairs with Map vs. 11.1 million with a regular object. Almost exactly 50% more pairs with a Map. They both take up about 2GB of memory before they crash, and so I think may be to do with memory limiting by chrome (Edit: Yep, try filling 2 Maps and you only get to 8.3 million pairs each before it crashes). You can test it yourself with this code (run them separately and not at the same time, obviously):

var m = new Map();
var i = 0;
while(1) {
    m.set(((10**30)*Math.random()).toString(36), ((10**30)*Math.random()).toString(36));
    i++;
    if(i%1000 === 0) { console.log(i/1000,"thousand") }
}
// versus:
var m = {};
var i = 0;
while(1) {
    m[((10**30)*Math.random()).toString(36)] = ((10**30)*Math.random()).toString(36);
    i++;
    if(i%1000 === 0) { console.log(i/1000,"thousand") }
}

Objects have some properties/keys already

This one has tripped me up before. Regular objects have toString, constructor, valueOf, hasOwnProperty, isPrototypeOf and a bunch of other pre-existing properties. This may not be a big problem for most use cases, but it has caused problems for me before.

Maps can be slower:

Due to the .get function call overhead and lack of internal optimisation, Map can be considerably slower than a plain old JavaScript object for some tasks.

good postgresql client for windows?

do you mean something like pgAdmin for administration?

How to initialize an array in Kotlin with values?

Old question, but if you'd like to use a range:

var numbers: IntArray = IntRange(10, 50).step(10).toList().toIntArray()

Yields nearly the same result as:

var numbers = Array(5, { i -> i*10 + 10 })

result: 10, 20, 30, 40, 50

I think the first option is a little more readable. Both work.

How to add line break for UILabel?

enter image description here

Use option-return when typing in the little box in Interface Builder to insert a line feed (\n). In Interface Builder's Label attributes, set # Lines = 0.

Select the label and then change Lines property to 0 like in the above image, and then use \n in your string for line break.

Can't run Curl command inside my Docker Container

curl: command not found

is a big hint, you have to install it with :

apt-get update; apt-get install curl

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

relative path to CSS file

if the file containing that link tag is in the root dir of the project, then the correct path would be "css/styles.css"

How to change the timeout on a .NET WebClient object

In some cases it is necessary to add user agent to headers:

WebClient myWebClient = new WebClient();
myWebClient.DownloadFile(myStringWebResource, fileName);
myWebClient.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

This was the solution to my case.

Credit:

http://genjurosdojo.blogspot.com/2012/10/the-remote-server-returned-error-504.html

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

I had the same problem and I did it this way

//note that I added jquery separately above this

<!--ENJOY HINT PACKAGES --START -->
<link href="path/enjoyhint/jquery.enjoyhint.css" rel="stylesheet">
<script src="path/enjoyhint/jquery.enjoyhint.js"></script>
<script src="path/enjoyhint/kinetic.min.js"></script>
<script src="path/enjoyhint/enjoyhint.js"></script>  
<!--ENJOY HINT PACKAGES --END -->

and it works

Error including image in Latex

If you have Gimp, I saw that exporting the image in .eps format would do the job.

AngularJS- Login and Authentication in each route and controller

You should check user authentication in two main sites.

  • When users change state, checking it using '$routeChangeStart' callback
  • When a $http request is sent from angular, using an interceptor.

Make a directory and copy a file

Use the FileSystemObject object, namely, its CreateFolder and CopyFile methods. Basically, this is what your script will look like:

Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Create a new folder
oFSO.CreateFolder "C:\MyFolder"

' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"

You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:

Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO

Set oFSO = CreateObject("Scripting.FileSystemObject")

If Not oFSO.FolderExists(strFolder) Then
  oFSO.CreateFolder strFolder
End If

oFSO.CopyFile strFile, strFolder, Overwrite

How to check if object has been disposed in C#

If you're not sure whether the object has been disposed or not, you should call the Dispose method itself rather than methods such as Close. While the framework doesn't guarantee that the Dispose method must run without exceptions even if the object had previously been disposed, it's a common pattern and to my knowledge implemented on all disposable objects in the framework.

The typical pattern for Dispose, as per Microsoft:

public void Dispose() 
{
    Dispose(true);

    // Use SupressFinalize in case a subclass
    // of this type implements a finalizer.
    GC.SuppressFinalize(this);      
}

protected virtual void Dispose(bool disposing)
{
    // If you need thread safety, use a lock around these 
    // operations, as well as in your methods that use the resource.
    if (!_disposed)
    {
        if (disposing) {
            if (_resource != null)
                _resource.Dispose();
                Console.WriteLine("Object disposed.");
        }

        // Indicate that the instance has been disposed.
        _resource = null;
        _disposed = true;   
    }
}

Notice the check on _disposed. If you were to call a Dispose method implementing this pattern, you could call Dispose as many times as you wanted without hitting exceptions.

How to increment a pointer address and pointer's value?

First, the ++ operator takes precedence over the * operator, and the () operators take precedence over everything else.

Second, the ++number operator is the same as the number++ operator if you're not assigning them to anything. The difference is number++ returns number and then increments number, and ++number increments first and then returns it.

Third, by increasing the value of a pointer, you're incrementing it by the sizeof its contents, that is you're incrementing it as if you were iterating in an array.

So, to sum it all up:

ptr++;    // Pointer moves to the next int position (as if it was an array)
++ptr;    // Pointer moves to the next int position (as if it was an array)
++*ptr;   // The value of ptr is incremented
++(*ptr); // The value of ptr is incremented
++*(ptr); // The value of ptr is incremented
*ptr++;   // Pointer moves to the next int position (as if it was an array). But returns the old content
(*ptr)++; // The value of ptr is incremented
*(ptr)++; // Pointer moves to the next int position (as if it was an array). But returns the old content
*++ptr;   // Pointer moves to the next int position, and then get's accessed, with your code, segfault
*(++ptr); // Pointer moves to the next int position, and then get's accessed, with your code, segfault

As there are a lot of cases in here, I might have made some mistake, please correct me if I'm wrong.

EDIT:

So I was wrong, the precedence is a little more complicated than what I wrote, view it here: http://en.cppreference.com/w/cpp/language/operator_precedence

Internet Explorer cache location

Are you looking for a Windows API?

Just use SHGetFolderPath function with CSIDL_INTERNET_CACHE flag or SHGetKnownFolderPath with FOLDERID_InternetCache flag to get the exact location. This way you don't have to worry about the OS. The former function works in Windows XP. The latter one works in Windows Vista+.

Selecting distinct values from a JSON

I would use one Object and one Array, if you want to save some cycle:

var lookup = {};
var items = json.DATA;
var result = [];

for (var item, i = 0; item = items[i++];) {
  var name = item.name;

  if (!(name in lookup)) {
    lookup[name] = 1;
    result.push(name);
  }
}

In this way you're basically avoiding the indexOf / inArray call, and you will get an Array that can be iterate quicker than iterating object's properties – also because in the second case you need to check hasOwnProperty.

Of course if you're fine with just an Object you can avoid the check and the result.push at all, and in case get the array using Object.keys(lookup), but it won't be faster than that.

image.onload event and browser cache

There are two possible solutions for these kind of situations:

  1. Use the solution suggested on this post
  2. Add a unique suffix to the image src to force browser downloading it again, like this:

    var img = new Image();
    img.src = "img.jpg?_="+(new Date().getTime());
    img.onload = function () {
        alert("image is loaded");
    }
    

In this code every time adding current timestamp to the end of the image URL you make it unique and browser will download the image again

How do you detect where two line segments intersect?

Based on t3chb0t's answer:

int intersezione_linee(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int& p_x, int& p_y)
{
   //L1: estremi (x1,y1)(x2,y2) L2: estremi (x3,y3)(x3,y3)
   int d;
   d = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4);
   if(!d)
       return 0;
   p_x = ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4))/d;
   p_y = ((x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4))/d;
   return 1;
}

int in_bounding_box(int x1, int y1, int x2, int y2, int p_x, int p_y)
{
    return p_x>=x1 && p_x<=x2 && p_y>=y1 && p_y<=y2;

}

int intersezione_segmenti(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int& p_x, int& p_y)
{
    if (!intersezione_linee(x1,y1,x2,y2,x3,y3,x4,y4,p_x,p_y))
        return 0;

    return in_bounding_box(x1,y1,x2,y2,p_x,p_y) && in_bounding_box(x3,y3,x4,y4,p_x,p_y);
}

Assign result of dynamic sql to variable

You can use sp_executesql with output parameter.

declare @S nvarchar(max) = 'select @x = 1'

declare @xx int
set @xx = 0

exec sp_executesql @S, N'@x int out', @xx out

select @xx

Result:

(No column name)
1

Edit

In my sample @S is instead of your @template. As you can see I assign a value to @x so you need to modify @template so it internally assigns the comma separated string to the variable you define in your second argument to sp_executesql. In my sample N'@x int out'. You probably want a varchar(max) output parameter. Something like N'@Result varchar(max) out'

Here is another example building a comma separated string from master..spt_values

declare @template nvarchar(max)
set @template = 
'select @Result += cast(number as varchar(10))+'',''
from master..spt_values
where type = ''P''
'

declare @CommaString varchar(max)
set @CommaString = ''

exec sp_executesql @template, N'@Result varchar(max) out', @CommaString out

select @CommaString

How to automatically generate a stacktrace when my program crashes

Even though a correct answer has been provided that describes how to use the GNU libc backtrace() function1 and I provided my own answer that describes how to ensure a backtrace from a signal handler points to the actual location of the fault2, I don't see any mention of demangling C++ symbols output from the backtrace.

When obtaining backtraces from a C++ program, the output can be run through c++filt1 to demangle the symbols or by using abi::__cxa_demangle1 directly.

  • 1 Linux & OS X Note that c++filt and __cxa_demangle are GCC specific
  • 2 Linux

The following C++ Linux example uses the same signal handler as my other answer and demonstrates how c++filt can be used to demangle the symbols.

Code:

class foo
{
public:
    foo() { foo1(); }

private:
    void foo1() { foo2(); }
    void foo2() { foo3(); }
    void foo3() { foo4(); }
    void foo4() { crash(); }
    void crash() { char * p = NULL; *p = 0; }
};

int main(int argc, char ** argv)
{
    // Setup signal handler for SIGSEGV
    ...

    foo * f = new foo();
    return 0;
}

Output (./test):

signal 11 (Segmentation fault), address is (nil) from 0x8048e07
[bt]: (1) ./test(crash__3foo+0x13) [0x8048e07]
[bt]: (2) ./test(foo4__3foo+0x12) [0x8048dee]
[bt]: (3) ./test(foo3__3foo+0x12) [0x8048dd6]
[bt]: (4) ./test(foo2__3foo+0x12) [0x8048dbe]
[bt]: (5) ./test(foo1__3foo+0x12) [0x8048da6]
[bt]: (6) ./test(__3foo+0x12) [0x8048d8e]
[bt]: (7) ./test(main+0xe0) [0x8048d18]
[bt]: (8) ./test(__libc_start_main+0x95) [0x42017589]
[bt]: (9) ./test(__register_frame_info+0x3d) [0x8048981]

Demangled Output (./test 2>&1 | c++filt):

signal 11 (Segmentation fault), address is (nil) from 0x8048e07
[bt]: (1) ./test(foo::crash(void)+0x13) [0x8048e07]
[bt]: (2) ./test(foo::foo4(void)+0x12) [0x8048dee]
[bt]: (3) ./test(foo::foo3(void)+0x12) [0x8048dd6]
[bt]: (4) ./test(foo::foo2(void)+0x12) [0x8048dbe]
[bt]: (5) ./test(foo::foo1(void)+0x12) [0x8048da6]
[bt]: (6) ./test(foo::foo(void)+0x12) [0x8048d8e]
[bt]: (7) ./test(main+0xe0) [0x8048d18]
[bt]: (8) ./test(__libc_start_main+0x95) [0x42017589]
[bt]: (9) ./test(__register_frame_info+0x3d) [0x8048981]

The following builds on the signal handler from my original answer and can replace the signal handler in the above example to demonstrate how abi::__cxa_demangle can be used to demangle the symbols. This signal handler produces the same demangled output as the above example.

Code:

void crit_err_hdlr(int sig_num, siginfo_t * info, void * ucontext)
{
    sig_ucontext_t * uc = (sig_ucontext_t *)ucontext;

    void * caller_address = (void *) uc->uc_mcontext.eip; // x86 specific

    std::cerr << "signal " << sig_num 
              << " (" << strsignal(sig_num) << "), address is " 
              << info->si_addr << " from " << caller_address 
              << std::endl << std::endl;

    void * array[50];
    int size = backtrace(array, 50);

    array[1] = caller_address;

    char ** messages = backtrace_symbols(array, size);    

    // skip first stack frame (points here)
    for (int i = 1; i < size && messages != NULL; ++i)
    {
        char *mangled_name = 0, *offset_begin = 0, *offset_end = 0;

        // find parantheses and +address offset surrounding mangled name
        for (char *p = messages[i]; *p; ++p)
        {
            if (*p == '(') 
            {
                mangled_name = p; 
            }
            else if (*p == '+') 
            {
                offset_begin = p;
            }
            else if (*p == ')')
            {
                offset_end = p;
                break;
            }
        }

        // if the line could be processed, attempt to demangle the symbol
        if (mangled_name && offset_begin && offset_end && 
            mangled_name < offset_begin)
        {
            *mangled_name++ = '\0';
            *offset_begin++ = '\0';
            *offset_end++ = '\0';

            int status;
            char * real_name = abi::__cxa_demangle(mangled_name, 0, 0, &status);

            // if demangling is successful, output the demangled function name
            if (status == 0)
            {    
                std::cerr << "[bt]: (" << i << ") " << messages[i] << " : " 
                          << real_name << "+" << offset_begin << offset_end 
                          << std::endl;

            }
            // otherwise, output the mangled function name
            else
            {
                std::cerr << "[bt]: (" << i << ") " << messages[i] << " : " 
                          << mangled_name << "+" << offset_begin << offset_end 
                          << std::endl;
            }
            free(real_name);
        }
        // otherwise, print the whole line
        else
        {
            std::cerr << "[bt]: (" << i << ") " << messages[i] << std::endl;
        }
    }
    std::cerr << std::endl;

    free(messages);

    exit(EXIT_FAILURE);
}

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.

Here is a complete example from your data that shows a bar of for each required value at each date:

import pylab as pl
import datetime

data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""

values = []
dates = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()

You need to parse the date with strptime and set the x-axis to use dates (as described in this answer).

If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)

EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):

fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

How to show android checkbox at right side?

    <android.support.v7.widget.AppCompatCheckBox
  android:id="@+id/checkBox"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="10dp"
  android:layoutDirection="rtl"
  android:text="text" />`

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Acked Unseen sample

Hi guys! Just some observations from what I just found in my capture:

On many occasions, the packet capture reports “ACKed segment that wasn't captured” on the client side, which alerts of the condition that the client PC has sent a data packet, the server acknowledges receipt of that packet, but the packet capture made on the client does not include the packet sent by the client

Initially, I thought it indicates a failure of the PC to record into the capture a packet it sends because “e.g., machine which is running Wireshark is slow” (https://osqa-ask.wireshark.org/questions/25593/tcp-previous-segment-not-captured-is-that-a-connectivity-issue)
However, then I noticed every time I see this “ACKed segment that wasn't captured” alert I can see a record of an “invalid” packet sent by the client PC

  • In the capture example above, frame 67795 sends an ACK for 10384

  • Even though wireshark reports Bogus IP length (0), frame 67795 is reported to have length 13194

  • Frame 67800 sends an ACK for 23524
  • 10384+13194 = 23578
  • 23578 – 23524 = 54
  • 54 is in fact length of the Ethernet / IP / TCP headers (14 for Ethernt, 20 for IP, 20 for TCP)
  • So in fact, the frame 67796 does represent a large TCP packets (13194 bytes) which operating system tried to put on the wore
    • NIC driver will fragment it into smaller 1500 bytes pieces in order to transmit over the network
    • But Wireshark running on my PC fails to understand it is a valid packet and parse it. I believe Wireshark running on 2012 Windows server reads these captures correctly
  • So after all, these “Bogus IP length” and “ACKed segment that wasn't captured” alerts were in fact false positives in my case

Python function overloading

I think a Bullet class hierarchy with the associated polymorphism is the way to go. You can effectively overload the base class constructor by using a metaclass so that calling the base class results in the creation of the appropriate subclass object. Below is some sample code to illustrate the essence of what I mean.

Updated

The code has been modified to run under both Python 2 and 3 to keep it relevant. This was done in a way that avoids the use Python's explicit metaclass syntax, which varies between the two versions.

To accomplish that objective, a BulletMetaBase instance of the BulletMeta class is created by explicitly calling the metaclass when creating the Bullet baseclass (rather than using the __metaclass__= class attribute or via a metaclass keyword argument depending on the Python version).

class BulletMeta(type):
    def __new__(cls, classname, bases, classdict):
        """ Create Bullet class or a subclass of it. """
        classobj = type.__new__(cls, classname, bases, classdict)
        if classname != 'BulletMetaBase':
            if classname == 'Bullet':  # Base class definition?
                classobj.registry = {}  # Initialize subclass registry.
            else:
                try:
                    alias = classdict['alias']
                except KeyError:
                    raise TypeError("Bullet subclass %s has no 'alias'" %
                                    classname)
                if alias in Bullet.registry: # unique?
                    raise TypeError("Bullet subclass %s's alias attribute "
                                    "%r already in use" % (classname, alias))
                # Register subclass under the specified alias.
                classobj.registry[alias] = classobj

        return classobj

    def __call__(cls, alias, *args, **kwargs):
        """ Bullet subclasses instance factory.

            Subclasses should only be instantiated by calls to the base
            class with their subclass' alias as the first arg.
        """
        if cls != Bullet:
            raise TypeError("Bullet subclass %r objects should not to "
                            "be explicitly constructed." % cls.__name__)
        elif alias not in cls.registry: # Bullet subclass?
            raise NotImplementedError("Unknown Bullet subclass %r" %
                                      str(alias))
        # Create designated subclass object (call its __init__ method).
        subclass = cls.registry[alias]
        return type.__call__(subclass, *args, **kwargs)


class Bullet(BulletMeta('BulletMetaBase', (object,), {})):
    # Presumably you'd define some abstract methods that all here
    # that would be supported by all subclasses.
    # These definitions could just raise NotImplementedError() or
    # implement the functionality is some sub-optimal generic way.
    # For example:
    def fire(self, *args, **kwargs):
        raise NotImplementedError(self.__class__.__name__ + ".fire() method")

    # Abstract base class's __init__ should never be called.
    # If subclasses need to call super class's __init__() for some
    # reason then it would need to be implemented.
    def __init__(self, *args, **kwargs):
        raise NotImplementedError("Bullet is an abstract base class")


# Subclass definitions.
class Bullet1(Bullet):
    alias = 'B1'
    def __init__(self, sprite, start, direction, speed):
        print('creating %s object' % self.__class__.__name__)
    def fire(self, trajectory):
        print('Bullet1 object fired with %s trajectory' % trajectory)


class Bullet2(Bullet):
    alias = 'B2'
    def __init__(self, sprite, start, headto, spead, acceleration):
        print('creating %s object' % self.__class__.__name__)


class Bullet3(Bullet):
    alias = 'B3'
    def __init__(self, sprite, script): # script controlled bullets
        print('creating %s object' % self.__class__.__name__)


class Bullet4(Bullet):
    alias = 'B4'
    def __init__(self, sprite, curve, speed): # for bullets with curved paths
        print('creating %s object' % self.__class__.__name__)


class Sprite: pass
class Curve: pass

b1 = Bullet('B1', Sprite(), (10,20,30), 90, 600)
b2 = Bullet('B2', Sprite(), (-30,17,94), (1,-1,-1), 600, 10)
b3 = Bullet('B3', Sprite(), 'bullet42.script')
b4 = Bullet('B4', Sprite(), Curve(), 720)
b1.fire('uniform gravity')
b2.fire('uniform gravity')

Output:

creating Bullet1 object
creating Bullet2 object
creating Bullet3 object
creating Bullet4 object
Bullet1 object fired with uniform gravity trajectory
Traceback (most recent call last):
  File "python-function-overloading.py", line 93, in <module>
    b2.fire('uniform gravity') # NotImplementedError: Bullet2.fire() method
  File "python-function-overloading.py", line 49, in fire
    raise NotImplementedError(self.__class__.__name__ + ".fire() method")
NotImplementedError: Bullet2.fire() method

Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

Put your url here Facebook Login -> Settings -> Valid OAuth redirect URIs AND you'll also get that error if your APP ID is wrong

What does the colon (:) operator do?

The colon actually exists in conjunction with ?

int minVal = (a < b) ? a : b;

is equivalent to:

int minval;
if(a < b){ minval = a;} 
else{ minval = b; }

Also in the for each loop:

for(Node n : List l){ ... }

literally:

for(Node n = l.head; n.next != null; n = n.next)

Single-threaded apartment - cannot instantiate ActiveX control

The problem you're running into is that most background thread / worker APIs will create the thread in a Multithreaded Apartment state. The error message indicates that the control requires the thread be a Single Threaded Apartment.

You can work around this by creating a thread yourself and specifying the STA apartment state on the thread.

var t = new Thread(MyThreadStartMethod);
t.SetApartmentState(ApartmentState.STA);
t.Start();

Setting transparent images background in IrfanView

You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.

You just need to re-open the image with IrfanView after changing the view color to white.

To change the viewing color in Irfanview go to:

Options > Properties/Settings > Viewing > Main window color

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

ggplot combining two plots from different data.frames

The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.

Like this:

ggplot() + 
geom_line(data=Data1, aes(x=A, y=B), color='green') + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

instead of

ggplot(data=Data1, aes(x=A, y=B), color='green') + 
geom_line() + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

More info here

Get hostname of current request in node.js Express

You can use the os Module:

var os = require("os");
os.hostname();

See http://nodejs.org/docs/latest/api/os.html#os_os_hostname

Caveats:

  1. if you can work with the IP address -- Machines may have several Network Cards and unless you specify it node will listen on all of them, so you don't know on which NIC the request came in, before it comes in.

  2. Hostname is a DNS matter -- Don't forget that several DNS aliases can point to the same machine.

How to use pull to refresh in Swift?

func pullToRefresh(){

    let refresh = UIRefreshControl()
    refresh.addTarget(self, action: #selector(handleTopRefresh(_:)), for: .valueChanged )
    refresh.tintColor = UIColor.appBlack
    self.tblAddressBook.addSubview(refresh)

}
@objc func handleTopRefresh(_ sender:UIRefreshControl){
    self.callAddressBookListApi(isLoaderRequired: false)
    sender.endRefreshing()
}

How to create a database from shell command?

You mean while the mysql environment?

create database testdb;

Or directly from command line:

mysql -u root -e "create database testdb"; 

What's the best practice for putting multiple projects in a git repository?

While most people will tell you to just use multiple repositories, I feel it's worth mentioning there are other solutions.

Solution 1

A single repository can contain multiple independent branches, called orphan branches. Orphan branches are completely separate from each other; they do not share histories.

git checkout --orphan BRANCHNAME

This creates a new branch, unrelated to your current branch. Each project should be in its own orphaned branch.

Now for whatever reason, git needs a bit of cleanup after an orphan checkout.

rm .git/index
rm -r *

Make sure everything is committed before deleting

Once the orphan branch is clean, you can use it normally.

Solution 2

Avoid all the hassle of orphan branches. Create two independent repositories, and push them to the same remote. Just use different branch names for each repo.

# repo 1
git push origin master:master-1

# repo 2
git push origin master:master-2

Python way to clone a git repository

My solution is very simple and straight forward. It doesn't even need the manual entry of passphrase/password.

Here is my complete code:

import sys
import os

path  = "/path/to/store/your/cloned/project" 
clone = "git clone gitolite@<server_ip>:/your/project/name.git" 

os.system("sshpass -p your_password ssh user_name@your_localhost")
os.chdir(path) # Specifying the path where the cloned project needs to be copied
os.system(clone) # Cloning

Check if a string contains a substring in SQL Server 2005, using a stored procedure

CHARINDEX() searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found

if CHARINDEX('ME',@mainString) > 0
begin
    --do something
end

Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX call would look like:

CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')

(Add more recursive REPLACE() calls for any other punctuation that may occur)

jQuery - select the associated label element of a input field

As long and your input and label elements are associated by their id and for attributes, you should be able to do something like this:

$('.input').each(function() { 
   $this = $(this);
   $label = $('label[for="'+ $this.attr('id') +'"]');
   if ($label.length > 0 ) {
       //this input has a label associated with it, lets do something!
   }
});

If for is not set then the elements have no semantic relation to each other anyway, and there is no benefit to using the label tag in that instance, so hopefully you will always have that relationship defined.

Colorizing text in the console with C++

Assuming you're talking about a Windows console window, look up the console functions in the MSDN Library documentation.

Otherwise, or more generally, it depends on the console. Colors are not supported by the C++ library. But a library for console handling may/will support colors. E.g. google "ncurses colors".

For connected serial terminals and terminal emulators you can control things by outputting "escape sequences". These typically start with ASCII 27 (the escape character in ASCII). There is an ANSI standard and a lot of custom schemes.

CSS3 transition on click using pure CSS

If you want a css only solution you can use active

.crossRotate:active {
   transform: rotate(45deg);
   -webkit-transform: rotate(45deg);
   -ms-transform: rotate(45deg);
}

But the transformation will not persist when the activity moves. For that you need javascript (jquery click and css is the cleanest IMO).

$( ".crossRotate" ).click(function() {
    if (  $( this ).css( "transform" ) == 'none' ){
        $(this).css("transform","rotate(45deg)");
    } else {
        $(this).css("transform","" );
    }
});

Fiddle

Removing specific rows from a dataframe

Here's a solution to your problem using dplyr's filter function.

Although you can pass your data frame as the first argument to any dplyr function, I've used its %>% operator, which pipes your data frame to one or more dplyr functions (just filter in this case).

Once you are somewhat familiar with dplyr, the cheat sheet is very handy.

> print(df <- data.frame(sub=rep(1:3, each=4), day=1:4))
   sub day
1    1   1
2    1   2
3    1   3
4    1   4
5    2   1
6    2   2
7    2   3
8    2   4
9    3   1
10   3   2
11   3   3
12   3   4
> print(df <- df %>% filter(!((sub==1 & day==2) | (sub==3 & day==4))))
   sub day
1    1   1
2    1   3
3    1   4
4    2   1
5    2   2
6    2   3
7    2   4
8    3   1
9    3   2
10   3   3

How can we redirect a Java program console output to multiple files?

You could use a "variable" inside the output filename, for example:

/tmp/FetchBlock-${current_date}.txt

current_date:

Returns the current system time formatted as yyyyMMdd_HHmm. An optional argument can be used to provide alternative formatting. The argument must be valid pattern for java.util.SimpleDateFormat.

Or you can also use a system_property or an env_var to specify something dynamic (either one needs to be specified as arguments)

Open text file and program shortcut in a Windows batch file

Its very simple, 1)Just go on directory where the file us stored 2)then enter command i.e. type filename.file_extention e.g type MyFile.tx

Linq select objects in list where exists IN (A,B,C)

var statuses = new[] { "A", "B", "C" };

var filteredOrders = from order in orders.Order
                             where statuses.Contains(order.StatusCode)
                             select order;

Clear MySQL query cache without restarting server

I believe you can use...

RESET QUERY CACHE;

...if the user you're running as has reload rights. Alternatively, you can defragment the query cache via...

FLUSH QUERY CACHE;

See the Query Cache Status and Maintenance section of the MySQL manual for more information.

Create a branch in Git from another branch

If you want to make a branch from some another branch then follow bellow steps:

Assumptions:

  1. You are currently in master branch.
  2. You have no changes to commit. (If you have any changes to commit, stash it!).
  3. BranchExisting is the name of branch from which you need to make a new branch with name BranchMyNew.

Steps:

  1. Fetch the branch to your local machine.

    $ git fetch origin BranchExisting : BranchExisting
    

This command will create a new branch in your local with same branch name.

  1. Now, from master branch checkout to the newly fetched branch

    $ git checkout BranchExisting
    
  2. You are now in BranchExisting. Now create a new branch from this existing branch.

    $ git checkout -b BranchMyNew
    

Here you go!

rand() between 0 and 1

rand() / double(RAND_MAX) generates a floating-point random number between 0 (inclusive) and 1 (inclusive), but it's not a good way for the following reasons (because RAND_MAX is usually 32767):

  1. The number of different random numbers that can be generated is too small: 32768. If you need more different random numbers, you need a different way (a code example is given below)
  2. The generated numbers are too coarse-grained: you can get 1/32768, 2/32768, 3/32768, but never anything in between.
  3. Limited states of random number generator engine: after generating RAND_MAX random numbers, implementations usually start to repeat the same sequence of random numbers.

Due to the above limitations of rand(), a better choice for generation of random numbers between 0 (inclusive) and 1 (exclusive) would be the following snippet (similar to the example at http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution ):

#include <iostream>
#include <random>
#include <chrono>

int main()
{
    std::mt19937_64 rng;
    // initialize the random number generator with time-dependent seed
    uint64_t timeSeed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
    std::seed_seq ss{uint32_t(timeSeed & 0xffffffff), uint32_t(timeSeed>>32)};
    rng.seed(ss);
    // initialize a uniform distribution between 0 and 1
    std::uniform_real_distribution<double> unif(0, 1);
    // ready to generate random numbers
    const int nSimulations = 10;
    for (int i = 0; i < nSimulations; i++)
    {
        double currentRandomNumber = unif(rng);
        std::cout << currentRandomNumber << std::endl;
    }
    return 0;
}

This is easy to modify to generate random numbers between 1 (inclusive) and 2 (exclusive) by replacing unif(0, 1) with unif(1, 2).

How can I change the font-size of a select option?

Tell the option element to be 13pt

select option{
    font-size: 13pt;
}

and then the first option element to be 7pt

select option:first-child {
    font-size: 7pt;
}

Running demo: http://jsfiddle.net/VggvD/1/

How can I execute Python scripts using Anaconda's version of Python?

Set your python path to the Anaconda version instead

Windows has a built-in dialog for changing environment variables (following guide applies to XP classical view): Right-click the icon for your machine (usually located on your Desktop and called “My Computer”) and choose Properties there. Then, open the Advanced tab and click the Environment Variables button.

In short, your path is:

My Computer ? Properties ? Advanced ? Environment Variables In this dialog, you can add or modify User and System variables. To change System variables, you need non-restricted access to your machine (i.e. Administrator rights).

Find your PATH variable and add the location of your Anaconda directory.

Example of someone doing it here: How to add to the PYTHONPATH in Windows, so it finds my modules/packages? Make sure that you sub path out for the Anaconda file though.

How to set user environment variables in Windows Server 2008 R2 as a normal user?

Under "Start" enter "environment" in the search field. That will list the option to change the system variables directly in the start menu.

What does $ mean before a string?

the $ sign in the string is for definition of interpolation string that is a feature in C# to interpolate the string is a "true string" that might contain interpolated expressions

for further information this is the source of the answer and example: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

Get the current time in C

Easy way:

#include <time.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    time_t mytime = time(NULL);
    char * time_str = ctime(&mytime);
    time_str[strlen(time_str)-1] = '\0';
    printf("Current Time : %s\n", time_str);

    return 0;
}

Detect if range is empty

This single line works better imho:

Application.Evaluate("SUMPRODUCT(--(E10:E14<>""""))=0")

in this case, it evaluates if range E10:E14 is empty.

Is it valid to have a html form inside another html form?

In case someone find this post here is a great solution without the need of JS. Use two submit buttons with different name attributes check in your server language which submit button was pressed cause only one of them will be sent to the server.

<form method="post" action="ServerFileToExecute.php">
    <input type="submit" name="save" value="Click here to save" />
    <input type="submit" name="delete" value="Click here to delete" />
</form>

The server side could look something like this if you use php:

<?php
    if(isset($_POST['save']))
        echo "Stored!";
    else if(isset($_POST['delete']))
        echo "Deleted!";
    else
        echo "Action is missing!";
?>

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

Get device information (such as product, model) from adb command

The correct way to do it would be:

adb -s 123abc12 shell getprop

Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop to access its value directly, like this:

adb -s 123abc12 shell getprop ro.product.model

The details in adb devices -l consist of the following three properties: ro.product.name, ro.product.model and ro.product.device.

Note that ADB shell ends lines with \r\n, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7 you might get Nexus 7\r).

Manually install Gradle and use it in Android Studio

I used like this,

distributionUrl=file\:///E\:/Android/Gradle/gradle-5.4.1-all.zip

And its worked for me.

Does file_get_contents() have a timeout setting?

As @diyism mentioned, "default_socket_timeout, stream_set_timeout, and stream_context_create timeout are all the timeout of every line read/write, not the whole connection timeout." And the top answer by @stewe has failed me.

As an alternative to using file_get_contents, you can always use curl with a timeout.

So here's a working code that works for calling links.

$url='http://example.com/';
$ch=curl_init();
$timeout=5;

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

$result=curl_exec($ch);
curl_close($ch);
echo $result;

Split string into array of characters?

According to this code golfing solution by Gaffi, the following works:

a = Split(StrConv(s, 64), Chr(0))

Understanding the Rails Authenticity Token

What is CSRF?

The Authenticity Token is a countermeasure to Cross-Site Request Forgery (CSRF). What is CSRF, you ask?

It's a way that an attacker can potentially hijack sessions without even knowing session tokens.

Scenario:

  • Visit your bank's site, log in.
  • Then visit the attacker's site (e.g. sponsored ad from an untrusted organization).
  • Attacker's page includes form with same fields as the bank's "Transfer Funds" form.
  • Attacker knows your account info, and has pre-filled form fields to transfer money from your account to attacker's account.
  • Attacker's page includes Javascript that submits form to your bank.
  • When form gets submitted, browser includes your cookies for the bank site, including the session token.
  • Bank transfers money to attacker's account.
  • The form can be in an iframe that is invisible, so you never know the attack occurred.
  • This is called Cross-Site Request Forgery (CSRF).

CSRF solution:

  • Server can mark forms that came from the server itself
  • Every form must contain an additional authentication token as a hidden field.
  • Token must be unpredictable (attacker can't guess it).
  • Server provides valid token in forms in its pages.
  • Server checks token when form posted, rejects forms without proper token.
  • Example token: session identifier encrypted with server secret key.
  • Rails automatically generates such tokens: see the authenticity_token input field in every form.

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

I had the same problem with numpy arrays and the solution is to flatten them:

data = {
    'b': array1.flatten(),
    'a': array2.flatten(),
}

df = pd.DataFrame(data)

Floating point inaccuracy examples

Show them that the base-10 system suffers from exactly the same problem.

Try to represent 1/3 as a decimal representation in base 10. You won't be able to do it exactly.

So if you write "0.3333", you will have a reasonably exact representation for many use cases.

But if you move that back to a fraction, you will get "3333/10000", which is not the same as "1/3".

Other fractions, such as 1/2 can easily be represented by a finite decimal representation in base-10: "0.5"

Now base-2 and base-10 suffer from essentially the same problem: both have some numbers that they can't represent exactly.

While base-10 has no problem representing 1/10 as "0.1" in base-2 you'd need an infinite representation starting with "0.000110011..".

Your project path contains non-ASCII characters android studio

If you face with the problem at the first time installing Android Studio on your computer.

  1. mklink /D "c:\Android-Sdk" "C:\Users\ **YOUR-USERNAME** \AppData\Local\Android\sdk"

  2. Go to "C:\Users\ YOUR-USERNAME \AppData\Local\" path and create Android\sdk folders inside it.

  3. After that you can continue installation.

How to list AD group membership for AD users using input list?

First: As it currently stands, the $User variable does not have a .Users property. In your code, $User simply represents one line (the "current" line in the foreach loop) from the text file.

$getmembership = Get-ADUser $User -Properties MemberOf | Select -ExpandProperty memberof

Secondly, I do not believe you can query an entire forest with one command. You will have to break it down into smaller chunks:

  1. Query forest for list of domains
  2. Call Get-ADUser for each domain (you may have to specify alternate credentials via the -Credential parameter

Thirdly, to get a list of groups that a user is a member of:

$User = Get-ADUser -Identity trevor -Properties *;
$GroupMembership = ($user.memberof | % { (Get-ADGroup $_).Name; }) -join ';';

# Result:
Orchestrator Users Group;ConfigMgr Administrators;Service Manager Admins;Domain Admins;Schema Admins

Fourthly: To get the final, desired string format, simply add the $User.Name, a semicolon, and the $GroupMembership string together:

$User.SamAccountName + ';' + $GroupMembership;

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

This expression 12-4-2005 is a calculated int and the value is -1997. You should do like this instead '2005-04-12' with the ' before and after.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

To fix this you need add your machine name in the /etc/hosts file to point to localhost(127.0.0.1).

You can find your machine name by running the following command:

$ hostname
macbook-pro

From the output above you know your hostname is "macbook-pro". Edit "/etc/hosts" file and add that name at the end of line that lists 127.0.0.1

127.0.0.1 localhost macbook-pro

Save the file.

Now you IntelliJ should be able to start your server.

How to get Month Name from Calendar?

This worked for me

        import java.text.SimpleDateFormat;
        import java.util.Calendar;


        Calendar cal = Calendar.getInstance();
        String currentdate=new SimpleDateFormat("dd-MMM").format(cal.getTime());

Print the address or pointer for value in C

What you have is correct. Of course, you'll see that emp1 and item1 have the same pointer value.

How to select an option from drop down using Selenium WebDriver C#?

To Select an Option Via Text;

(new SelectElement(driver.FindElement(By.XPath(""))).SelectByText("");

To Select an Option via Value:

 (new SelectElement(driver.FindElement(By.XPath(""))).SelectByValue("");

Convert canvas to PDF

Please see https://github.com/joshua-gould/canvas2pdf. This library creates a PDF representation of your canvas element, unlike the other proposed solutions which embed an image in a PDF document.

//Create a new PDF canvas context.
var ctx = new canvas2pdf.Context(blobStream());

//draw your canvas like you would normally
ctx.fillStyle='yellow';
ctx.fillRect(100,100,100,100);
// more canvas drawing, etc...

//convert your PDF to a Blob and save to file
ctx.stream.on('finish', function () {
    var blob = ctx.stream.toBlob('application/pdf');
    saveAs(blob, 'example.pdf', true);
});
ctx.end();

How to secure RESTful web services?

There's another, very secure method. It's client certificates. Know how servers present an SSL Cert when you contact them on https? Well servers can request a cert from a client so they know the client is who they say they are. Clients generate certs and give them to you over a secure channel (like coming into your office with a USB key - preferably a non-trojaned USB key).

You load the public key of the cert client certificates (and their signer's certificate(s), if necessary) into your web server, and the web server won't accept connections from anyone except the people who have the corresponding private keys for the certs it knows about. It runs on the HTTPS layer, so you may even be able to completely skip application-level authentication like OAuth (depending on your requirements). You can abstract a layer away and create a local Certificate Authority and sign Cert Requests from clients, allowing you to skip the 'make them come into the office' and 'load certs onto the server' steps.

Pain the neck? Absolutely. Good for everything? Nope. Very secure? Yup.

It does rely on clients keeping their certificates safe however (they can't post their private keys online), and it's usually used when you sell a service to clients rather then letting anyone register and connect.

Anyway, it may not be the solution you're looking for (it probably isn't to be honest), but it's another option.

How does one remove a Docker image?

Update, as commented by VonC in How to remove old Docker containers.

With Docker 1.13 (Q4 2016), you now have:

docker system prune will delete ALL unused data (i.e., in order: containers stopped, volumes without containers and images with no containers).

See PR 26108 and commit 86de7c0, which are introducing a few new commands to help facilitate visualizing how much space the Docker daemon data is taking on disk and allowing for easily cleaning up "unneeded" excess.

docker system prune

WARNING! This will remove:
    - all stopped containers
    - all volumes not used by at least one container
    - all images without at least one container associated to them
Are you sure you want to continue? [y/N] y

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

Instead of overriding the library search path at runtime with LD_LIBRARY_PATH, you could instead bake it into the binary itself with rpath. If you link with GCC adding -Wl,-rpath,<libdir> should do the trick, if you link with ld it's just -rpath <libdir>.

Remove leading comma from a string

One-liner

str = str.replace(/^,/, '');

I'll be back.

Run AVD Emulator without Android Studio

Assuming you've got Android Studio installed, and SDK in your PATH, it's:

emulator -avd avd_name

To get a list of AVD names, run:

emulator -list-avds

Source: https://developer.android.com/studio/run/emulator-commandline.html

How to remove item from array by value?

The simplest solution is:

array - array for remove some element valueForRemove; valueForRemove - element for remove;

array.filter(arrayItem => !array.includes(valueForRemove));

More simple:

array.filter(arrayItem => arrayItem !== valueForRemove);

No pretty, but works:

array.filter(arrayItem => array.indexOf(arrayItem) != array.indexOf(valueForRemove))

No pretty, but works:

while(array.indexOf(valueForRemove) !== -1) {
  array.splice(array.indexOf(valueForRemove), 1)
}

P.S. The filter() method creates a new array with all elements that pass the test implemented by the provided function. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Java switch statement: Constant expression required, but it IS constant

This was answered ages ago and probably not relevant, but just in case. When I was confronted with this issue, I simply used an if statement instead of switch, it solved the error. It is of course a workaround and probably not the "right" solution, but in my case it was just enough.

Edit: 2021.01.21

This Answer is a bit misleading, And I would like to clarify it.

  1. Replacing a switch statement with an if should not be considered as a goto solution, there are very good reasons why both concepts of switch and if exist in software development, as well as performance matters to consider when choosing between the two.
  2. Although I provide a solution to the presented error, My answer sheds no light on "why" the problem occurs but instead offers a way around the problem.

In my specific case, using an if statement instead was just enough to solve the problem. Developers should take the time and decide if this is the right solution for the current problem you have at hand.

Thus this answer should be considered solely as a workaround in specific cases as stated in my first response, and by no means as the correct answer to this question

Property 'map' does not exist on type 'Observable<Response>'

just install rxjs-compat by typing in terminal:

npm install --save rxjs-compat

then import :

import 'rxjs/Rx';

Background Image for Select (dropdown) does not work in Chrome

select 
{
    -webkit-appearance: none;
}

If you need to you can also add an image that contains the arrow as part of the background.

jQuery AJAX Call to PHP Script with JSON Return

Make it dataType instead of datatype.

And add below code in php as your ajax request is expecting json and will not accept anything, but json.

header('Content-Type: application/json');

Correct Content type for JSON and JSONP

The response visible in firebug is text data. Check Content-Type of the response header to verify, if the response is json. It should be application/json for dataType:'json' and text/html for dataType:'html'.

Why should I use IHttpActionResult instead of HttpResponseMessage?

You might decide not to use IHttpActionResult because your existing code builds a HttpResponseMessage that doesn't fit one of the canned responses. You can however adapt HttpResponseMessage to IHttpActionResult using the canned response of ResponseMessage. It took me a while to figure this out, so I wanted to post it showing that you don't necesarily have to choose one or the other:

public IHttpActionResult SomeAction()
{
   IHttpActionResult response;
   //we want a 303 with the ability to set location
   HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
   responseMsg.Headers.Location = new Uri("http://customLocation.blah");
   response = ResponseMessage(responseMsg);
   return response;
}

Note, ResponseMessage is a method of the base class ApiController that your controller should inherit from.

PL/SQL print out ref cursor returned by a stored procedure

You can use a bind variable at the SQLPlus level to do this. Of course you have little control over the formatting of the output.

VAR x REFCURSOR;
EXEC GetGrantListByPI(args, :x);
PRINT x;

Making a button invisible by clicking another button in HTML

Use this code :

<input type="button" onclick="demoShow()" value="edit" />
<script type="text/javascript"> 
function demoShow()
{document.getElementById("p2").style.visibility="hidden";}
</script>
<input id="p2" type="submit" value="submit" name="submit" />

How to Set Opacity (Alpha) for View in Android

I know this already has a bunch of answers but I found that for buttons it is just easiest to create your own .xml selectors and set that to the background of said button. That way you can also change it state when pressed or enabled and so on. Here is a quick snippet of one that I use. If you want to add a transparency to any of the colors, add a leading hex value (#XXcccccc). (XX == "alpha of color")

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#70c656" />
            <stroke
                android:width="1dp"
                android:color="#53933f" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#70c656"
                android:endColor="#53933f"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#53933f" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

Setting focus on an HTML input box on page load

This is one of the common issues with IE and fix for this is simple. Add .focus() twice to the input.

Fix :-

function FocusOnInput() {
    var element = document.getElementById('txtContactMobileNo');
    element.focus();
    setTimeout(function () { element.focus(); }, 1);
}

And call FocusOnInput() on $(document).ready(function () {.....};

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Because otherwise scanf will think you are passing a pointer to a float which is a smaller size than a double, and it will return an incorrect value.

Table and Index size in SQL Server

On SQL 2012 getting this information on a table level has become deliciously simple:

SQL Management Studio -> Right click on Db -> Reports -> Standard Reports -> Disk usage by table !

Enjoy

What are the use cases for selecting CHAR over VARCHAR in SQL?

Char is a little bit faster, so if you have a column that you KNOW will be a certain length, use char. For example, storing (M)ale/(F)emale/(U)nknown for gender, or 2 characters for a US state.

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

align textbox and text/labels in html?

Using a table would be one (and easy) option.

Other options are all about setting fixed width on the and making it text-aligned to the right:

label {
   width: 200px;
   display: inline-block;
   text-align: right;
}

or, as was pointed out, make them all float instead of inline.

Javascript - object key->value

Use this syntax:

obj[name]

Note that obj.x is the same as obj["x"] for all valid JS identifiers, but the latter form accepts all string as keys (not just valid identifiers).

obj["Hey, this is ... neat?"] = 42

can we use xpath with BeautifulSoup?

As others have said, BeautifulSoup doesn't have xpath support. There are probably a number of ways to get something from an xpath, including using Selenium. However, here's a solution that works in either Python 2 or 3:

from lxml import html
import requests

page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(page.content)
#This will create a list of buyers:
buyers = tree.xpath('//div[@title="buyer-name"]/text()')
#This will create a list of prices
prices = tree.xpath('//span[@class="item-price"]/text()')

print('Buyers: ', buyers)
print('Prices: ', prices)

I used this as a reference.

How to add a new row to datagridview programmatically

yourDGV.Rows.Add(column1,column2...columnx); //add a row to a dataGridview
yourDGV.Rows[rowindex].Cells[Cell/Columnindex].value = yourvalue; //edit the value

you can also create a new row and then add it to the DataGridView like this:

DataGridViewRow row = new DataGridViewRow();
row.Cells[Cell/Columnindex].Value = yourvalue;
yourDGV.Rows.Add(row);

Get all parameters from JSP page

Even though this is an old question, I had to do something similar today but I prefer JSTL:

<c:forEach var="par" items="${paramValues}">
    <c:if test="${fn:startsWith(par.key, 'question')}"> 
${par.key} = ${par.value[0]}; //whatever
    </c:if>
</c:forEach>

Export and Import all MySQL databases at one time

All the answers I see on this question can have problems with the character sets in some databases due to the problem of redirecting the exit of mysqldump to a file within the shell operator >.

To solve this problem you should do the backup with a command like this

mysqldump -u root -p --opt --all-databases -r backup.sql

To do a good BD restore without any problem with character sets. Obviously you can change the default-character-set as you need.

mysql -uroot -p --default-character-set=utf8
mysql> SET names 'utf8';
mysql> SOURCE backup.sql;

Updating PartialView mvc 4

So, say you have your View with PartialView, which have to be updated by button click:

<div class="target">
    @{ Html.RenderAction("UpdatePoints");}
</div>

<input class="button" value="update" />

There are some ways to do it. For example you may use jQuery:

<script type="text/javascript">
    $(function(){    
        $('.button').on("click", function(){        
            $.post('@Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
                $('.target').load('/Home/UpdatePoints');        
            })        
        });
    });        
</script>

PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points

If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:

[HttpPost]
public ActionResult UpdatePoints()
{    
    ViewBag.points =  _Repository.Points;
    return PartialView("UpdatePoints");
}

How do I pass variables and data from PHP to JavaScript?

  1. Convert the data into JSON
  2. Call AJAX to recieve JSON file
  3. Convert JSON into Javascript object

Example:

STEP 1

<?php

   $servername = "localhost";
   $username = "";
   $password = "";
   $dbname = "";
   $conn = new mysqli($servername, $username, $password, $dbname);

   if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
   } 

   $sql = "SELECT id, name, image FROM phone";
   $result = $conn->query($sql);

   while($row = $result->fetch_assoc()){ 
      $v[] = $row;    
   }

  echo json_encode($v);

  $conn->close();
?>

STEP 2

function showUser(fnc) {
   var xhttp = new XMLHttpRequest();

   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
         // STEP 3    
         var p = JSON.parse(this.responseText);
      }
   }
}

How to store NULL values in datetime fields in MySQL?

This is a a sensible point.

A null date is not a zero date. They may look the same, but they ain't. In mysql, a null date value is null. A zero date value is an empty string ('') and '0000-00-00 00:00:00'

On a null date "... where mydate = ''" will fail.
On an empty/zero date "... where mydate is null" will fail.

But now let's get funky. In mysql dates, empty/zero date are strictly the same.

by example

select if(myDate is null, 'null', myDate) as mydate from myTable where  myDate = '';
select if(myDate is null, 'null', myDate) as mydate from myTable where  myDate = '0000-00-00 00:00:00'

will BOTH output: '0000-00-00 00:00:00'. if you update myDate with '' or '0000-00-00 00:00:00', both selects will still work the same.

In php, the mysql null dates type will be respected with the standard mysql connector, and be real nulls ($var === null, is_null($var)). Empty dates will always be represented as '0000-00-00 00:00:00'.

I strongly advise to use only null dates, OR only empty dates if you can. (some systems will use "virual" zero dates which are valid Gregorian dates, like 1970-01-01 (linux) or 0001-01-01 (oracle).

empty dates are easier in php/mysql. You don't have the "where field is null" to handle. However, you have to "manually" transform the '0000-00-00 00:00:00' date in '' to display empty fields. (to store or search you don't have special case to handle for zero dates, which is nice).

Null dates need better care. you have to be careful when you insert or update to NOT add quotes around null, else a zero date will be inserted instead of null, which causes your standard data havoc. In search forms, you will need to handle cases like "and mydate is not null", and so on.

Null dates are usually more work. but they much MUCH MUCH faster than zero dates for queries.

multiple packages in context:component-scan, spring config

<context:component-scan base-package="x.y.z"/>

will work since the rest of the packages are sub packages of "x.y.z". Thus, you dont need to mention each package individually.

Create array of all integers between two numbers, inclusive, in Javascript/jQuery

var list = [];
for (var i = lowEnd; i <= highEnd; i++) {
    list.push(i);
}

Checking if type == list in python

Your issue is that you have re-defined list as a variable previously in your code. This means that when you do type(tmpDict[key])==list if will return False because they aren't equal.

That being said, you should instead use isinstance(tmpDict[key], list) when testing the type of something, this won't avoid the problem of overwriting list but is a more Pythonic way of checking the type.

Is the LIKE operator case-sensitive with MSSQL Server?

Try running,

SELECT SERVERPROPERTY('COLLATION')

Then find out if your collation is case sensitive or not.

How to get week numbers from dates?

if you want to get the week number with the year use: "%Y-W%V":

e.g    yearAndweeks <- strftime(dates, format = "%Y-W%V")

so

> strftime(c("2014-03-16", "2014-03-17","2014-03-18", "2014-01-01"), format = "%Y-W%V")

becomes:

[1] "2014-W11" "2014-W12" "2014-W12" "2014-W01"

How do I tell if a variable has a numeric value in Perl?

A simple (and maybe simplistic) answer to the question is the content of $x numeric is the following:

if ($x  eq  $x+0) { .... }

It does a textual comparison of the original $x with the $x converted to a numeric value.

Why should C++ programmers minimize use of 'new'?

Because the stack is faster and leak-proof

In C++, it takes but a single instruction to allocate space -- on the stack -- for every local scope object in a given function, and it's impossible to leak any of that memory. That comment intended (or should have intended) to say something like "use the stack and not the heap".

Android studio Gradle icon error, Manifest Merger

I tried all the solution mentioned above

in Manifest.xml :

  • add this code in top of your xml file within manifest tag:

    xmlns:tools="http://schemas.android.com/tools"

  • Then added :

    tools:replace="android:icon,android:theme,android:label,android:name" to the application tag

but none of it worked. I needed to delete a xml file which was situated in

mipmap-anydpi-v26/ic_launcher_round.xml

I was testing the application in

Samsung Galaxy 8 with OS version 8.0.0

is it really a solution?

Minimum and maximum date

As you can see, 01/01/1970 returns 0, which means it is the lowest possible date.

new Date('1970-01-01Z00:00:00:000') //returns Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)
new Date('1970-01-01Z00:00:00:000').getTime() //returns 0
new Date('1970-01-01Z00:00:00:001').getTime() //returns 1

How to change FontSize By JavaScript?

Please never do this in real projects:

_x000D_
_x000D_
document.getElementById("span").innerHTML = "String".fontsize(25);
_x000D_
<span id="span"></span>
_x000D_
_x000D_
_x000D_

How to redirect 404 errors to a page in ExpressJS?

You can put a middleware at the last position that throws a NotFound error,
or even renders the 404 page directly:

app.use(function(req,res){
    res.status(404).render('404.jade');
});

How do I find out if the GPS of an Android device is enabled

This method will use the LocationManager service.

Source Link

//Check GPS Status true/false
public static boolean checkGPSStatus(Context context){
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
    boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return statusOfGPS;
};

How can I set multiple CSS styles in JavaScript?

Using plain Javascript, you can't set all the styles at once; you need to use single lines for each of them.

However, you don't have to repeat the document.getElementById(...).style. code over and over; create an object variable to reference it, and you'll make your code much more readable:

var obj=document.getElementById("myElement").style;
obj.top=top;
obj.left=left;

...etc. Much easier to read than your example (and frankly, just as easy to read as the jQuery alternative).

(if Javascript had been designed properly, you could also have used the with keyword, but that's best left alone, as it can cause some nasty namespace issues)

How to append the output to a file?

Yeah.

command >> file to redirect just stdout of command.

command >> file 2>&1 to redirect stdout and stderr to the file (works in bash, zsh)

And if you need to use sudo, remember that just

sudo command >> /file/requiring/sudo/privileges does not work, as privilege elevation applies to command but not shell redirection part. However, simply using tee solves the problem:

command | sudo tee -a /file/requiring/sudo/privileges

How to detect scroll direction

Existing Solution

There could be 3 solution from this posting and other stackoverflow article.

Solution 1

    var lastScrollTop = 0;
    $(window).on('scroll', function() {
        st = $(this).scrollTop();
        if(st < lastScrollTop) {
            console.log('up 1');
        }
        else {
            console.log('down 1');
        }
        lastScrollTop = st;
    });

Solution 2

    $('body').on('DOMMouseScroll', function(e){
        if(e.originalEvent.detail < 0) {
            console.log('up 2');
        }
        else {
            console.log('down 2');
        }
    });

Solution 3

    $('body').on('mousewheel', function(e){
        if(e.originalEvent.wheelDelta > 0) {
            console.log('up 3');
        }
        else {
            console.log('down 3');
        }
    });

Multi Browser Test

I couldn't tested it on Safari

chrome 42 (Win 7)

  • Solution 1
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll
  • Soltion 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll

Firefox 37 (Win 7)

  • Solution 1
    • Up : 20 events per 1 scroll
    • Down : 20 events per 1 scroll
  • Soltion 2
    • Up : Not working
    • Down : 1 event per 1 scroll
  • Solution 3
    • Up : Not working
    • Down : Not working

IE 11 (Win 8)

  • Solution 1
    • Up : 10 events per 1 scroll (side effect : down scroll occured at last)
    • Down : 10 events per 1 scroll
  • Soltion 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : Not working
    • Down : 1 event per 1 scroll

IE 10 (Win 7)

  • Solution 1
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll
  • Soltion 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll

IE 9 (Win 7)

  • Solution 1
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll
  • Soltion 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll

IE 8 (Win 7)

  • Solution 1
    • Up : 2 events per 1 scroll (side effect : down scroll occured at last)
    • Down : 2~4 events per 1 scroll
  • Soltion 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll

Combined Solution

I checked that side effect from IE 11 and IE 8 is come from if else statement. So, I replaced it with if else if statement as following.

From the multi browser test, I decided to use Solution 3 for common browsers and Solution 1 for firefox and IE 11.

I referred this answer to detect IE 11.

    // Detect IE version
    var iev=0;
    var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
    var trident = !!navigator.userAgent.match(/Trident\/7.0/);
    var rv=navigator.userAgent.indexOf("rv:11.0");

    if (ieold) iev=new Number(RegExp.$1);
    if (navigator.appVersion.indexOf("MSIE 10") != -1) iev=10;
    if (trident&&rv!=-1) iev=11;

    // Firefox or IE 11
    if(typeof InstallTrigger !== 'undefined' || iev == 11) {
        var lastScrollTop = 0;
        $(window).on('scroll', function() {
            st = $(this).scrollTop();
            if(st < lastScrollTop) {
                console.log('Up');
            }
            else if(st > lastScrollTop) {
                console.log('Down');
            }
            lastScrollTop = st;
        });
    }
    // Other browsers
    else {
        $('body').on('mousewheel', function(e){
            if(e.originalEvent.wheelDelta > 0) {
                console.log('Up');
            }
            else if(e.originalEvent.wheelDelta < 0) {
                console.log('Down');
            }
        });
    }

Java 8 Filter Array Using Lambda

Yes, you can do this by creating a DoubleStream from the array, filtering out the negatives, and converting the stream back to an array. Here is an example:

double[] d = {8, 7, -6, 5, -4};
d = Arrays.stream(d).filter(x -> x > 0).toArray();
//d => [8, 7, 5]

If you want to filter a reference array that is not an Object[] you will need to use the toArray method which takes an IntFunction to get an array of the original type as the result:

String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);

Using jquery to get all checked checkboxes with a certain class name

 $('input.myclass[type=checkbox]').each(function () {
   var sThisVal = (this.checked ? $(this).val() : ""); });

See jQuery class selectors.

Laravel use same form for create and edit

You can use form binding and 3 methods in your Controller. Here's what I do

class ActivitiesController extends BaseController {
    public function getAdd() {
        return $this->form();
    }
    public function getEdit($id) {
        return $this->form($id);
    }
    protected function form($id = null) {
        $activity = ! is_null($id) ? Activity::findOrFail($id) : new Activity;

        //
        // Your logic here
        //

        $form = View::make('path.to.form')
            ->with('activity', $activity);

        return $form->render(); 
    }
}

And in my views I have

{{ Form::model($activity, array('url' => "/admin/activities/form/{$activity->id}", 'method' => 'post')) }}
{{ Form::close() }}

time data does not match format

I had a case where solution was hard to figure out. This is not exactly relevant to particular question, but might help someone looking to solve a case with same error message when strptime is fed with timezone information. In my case, the reason for throwing

ValueError: time data '2016-02-28T08:27:16.000-07:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

was presence of last colon in the timezone part. While in some locales (Russian one, for example) code was able to execute well, in another (English one) it was failing. Removing the last colon helped remedy my situation.

How to pad zeroes to a string?

For the ones who came here to understand and not just a quick answer. I do these especially for time strings:

hour = 4
minute = 3
"{:0>2}:{:0>2}".format(hour,minute)
# prints 04:03

"{:0>3}:{:0>5}".format(hour,minute)
# prints '004:00003'

"{:0<3}:{:0<5}".format(hour,minute)
# prints '400:30000'

"{:$<3}:{:#<5}".format(hour,minute)
# prints '4$$:3####'

"0" symbols what to replace with the "2" padding characters, the default is an empty space

">" symbols allign all the 2 "0" character to the left of the string

":" symbols the format_spec

How to call a method with a separate thread in Java?

Sometime ago, I had written a simple utility class that uses JDK5 executor service and executes specific processes in the background. Since doWork() typically would have a void return value, you may want to use this utility class to execute it in the background.

See this article where I had documented this utility.

Windows batch script launch program and exit console

start "" ExeToExecute

method does not work for me in the case of Xilinx xsdk, because as pointed out by @jeb in the comments below it is actaully a bat file.

so what does not work de-facto is

start "" BatToExecute

I am trying to open xsdk like that and it opens a separate cmd that needs to be closed and xsdk can run on its own

Before launching xsdk I run (source) the Env / Paths (with settings64.bat) so that xsdk.bat command gets recognized (simply as xsdk, withoitu the .bat)

what works with .bat

call BatToExecute

How to initialize a static array?

Nope, no difference. It's just syntactic sugar. Arrays.asList(..) creates an additional list.

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

What is the difference between localStorage, sessionStorage, session and cookies?

The Web Storage API provides mechanisms by which browsers can securely store key/value pairs, in a much more intuitive fashion than using cookies. The Web Storage API extends the Window object with two new properties — Window.sessionStorage and Window.localStorage. — invoking one of these will create an instance of the Storage object, through which data items can be set, retrieved, and removed. A different Storage object is used for the sessionStorage and localStorage for each origin (domain).

Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads.

localStorage.colorSetting = '#a4509b';
localStorage['colorSetting'] = '#a4509b';
localStorage.setItem('colorSetting', '#a4509b');

The keys and the values are always strings. To store any type convert it to String and then store it. It's always recommended to use Storage interface methods.

var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('Converting String to Object: ', JSON.parse(retrievedObject));

The two mechanisms within Web Storage are as follows:

  • sessionStorage maintains a separate storage area for each given originSame-origin policy that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
  • localStorage does the same thing, but persists even when the browser is closed and reopened.

Storage « Local storage writes the data to the disk, while session storage writes the data to the memory only. Any data written to the session storage is purged when your app exits.

The maximum storage available is different per browser, but most browsers have implemented at least the w3c recommended maximum storage limit of 5MB.

+----------------+--------+---------+-----------+--------+
|                | Chrome | Firefox | Safari    |  IE    |
+----------------+--------+---------+-----------+--------+
| LocalStorage   | 10MB   | 10MB    | 5MB       | 10MB   |
+----------------+--------+---------+-----------+--------+
| SessionStorage | 10MB   | 10MB    | Unlimited | 10MB   |
+----------------+--------+---------+-----------+--------+

Always catch LocalStorage security and quota exceeded errors

StorageEvent « The storage event is fired on a document's Window object when a storage area changes. When a user agent is to send a storage notification for a Document, the user agent must queue a task to fire an event named storage at the Document object's Window object, using StorageEvent.

Note: For a real world example, see Web Storage Demo. check out the source code

Listen to the storage event on dom/Window to catch changes in the storage. fiddle.


Cookies (web cookie, browser cookie) Cookies are data, stored in small text files as name-value pairs, on your computer.

JavaScript access using Document.cookie

New cookies can also be created via JavaScript using the Document.cookie property, and if the HttpOnly flag is not set, existing cookies can be accessed from JavaScript as well.

document.cookie = "yummy_cookie=choco"; 
document.cookie = "tasty_cookie=strawberry"; 
console.log(document.cookie); 
// logs "yummy_cookie=choco; tasty_cookie=strawberry"

Secure and HttpOnly cookies HTTP State Management Mechanism

Cookies are often used in web application to identify a user and their authenticated session

When receiving an HTTP request, a server can send a Set-Cookie header with the response. The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header.

Set-Cookie: <cookie-name>=<cookie-value> 
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>

Session cookies will get removed when the client is shut down. They don't specify the Expires or Max-Age directives.

Set-Cookie: sessionid=38afes7a8; HttpOnly; Path=/

Permanent cookies expire at a specific date (Expires) or after a specific length of time (Max-Age).

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly

The Cookie HTTP request header contains stored HTTP cookies previously sent by the server with the Set-Cookie header. HTTP-only cookies aren't accessible via JavaScript through the Document.cookie property, the XMLHttpRequest and Request APIs to mitigate attacks against cross-site scripting (XSS).

Cookies are mainly used for three purposes:

  • Session management « Logins, shopping carts, game scores, or anything else the server should remember
  • Personalization « User preferences, themes, and other settings
  • Tracking (Recording and analyzing user behavior) « Cookies have a domain associated to them. If this domain is the same as the domain of the page you are on, the cookies is said to be a first-party cookie. If the domain is different, it is said to be a third-party cookie. While first-party cookies are sent only to the server setting them, a web page may contain images or other components stored on servers in other domains (like ad banners). Cookies that are sent through these third-party components are called third-party cookies and are mainly used for advertising and tracking across the web.

Cookies were invented to solve the problem "how to remember information about the user":

  • When a user visits a web page, his name can be stored in a cookie.
  • Next time the user visits the page, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.

GitHubGist Example


As summary,

  • localStorage persists over different tabs or windows, and even if we close the browser, accordingly with the domain security policy and user choices about quota limit.
  • sessionStorage object does not persist if we close the tab (top-level browsing context) as it does not exists if we surf via another tab or window.
  • Web Storage (session, local) allows us to save a large amount of key/value pairs and lots of text, something impossible to do via cookie.
  • Cookies that are used for sensitive actions should have a short lifetime only.
  • Cookies mainly used for advertising and tracking across the web. See for example the types of cookies used by Google.
  • Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web storage API (localStorage and sessionStorage) and IndexedDB.

TLS 1.2 not working in cURL

Replace following

curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_TLSv1_2');

With

curl_setopt ($ch, CURLOPT_SSLVERSION, 6);

Should work flawlessly.

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

Just for completion, here is a code example indicating the differences:

success \ error:

$http.get('/someURL')
.success(function(data, status, header, config) {
    // success handler
})
.error(function(data, status, header, config) {
    // error handler
});

then:

$http.get('/someURL')
.then(function(response) {
    // success handler
}, function(response) {
    // error handler
})
.then(function(response) {
    // success handler
}, function(response) {
    // error handler
})
.then(function(response) {
    // success handler
}, function(response) {
    // error handler
}).