Programs & Examples On #Perfmon

A tool used to launch Performance Monitor for Microsoft Windows.

What is private bytes, virtual bytes, working set?

The short answer to this question is that none of these values are a reliable indicator of how much memory an executable is actually using, and none of them are really appropriate for debugging a memory leak.

Private Bytes refer to the amount of memory that the process executable has asked for - not necessarily the amount it is actually using. They are "private" because they (usually) exclude memory-mapped files (i.e. shared DLLs). But - here's the catch - they don't necessarily exclude memory allocated by those files. There is no way to tell whether a change in private bytes was due to the executable itself, or due to a linked library. Private bytes are also not exclusively physical memory; they can be paged to disk or in the standby page list (i.e. no longer in use, but not paged yet either).

Working Set refers to the total physical memory (RAM) used by the process. However, unlike private bytes, this also includes memory-mapped files and various other resources, so it's an even less accurate measurement than the private bytes. This is the same value that gets reported in Task Manager's "Mem Usage" and has been the source of endless amounts of confusion in recent years. Memory in the Working Set is "physical" in the sense that it can be addressed without a page fault; however, the standby page list is also still physically in memory but not reported in the Working Set, and this is why you might see the "Mem Usage" suddenly drop when you minimize an application.

Virtual Bytes are the total virtual address space occupied by the entire process. This is like the working set, in the sense that it includes memory-mapped files (shared DLLs), but it also includes data in the standby list and data that has already been paged out and is sitting in a pagefile on disk somewhere. The total virtual bytes used by every process on a system under heavy load will add up to significantly more memory than the machine actually has.

So the relationships are:

  • Private Bytes are what your app has actually allocated, but include pagefile usage;
  • Working Set is the non-paged Private Bytes plus memory-mapped files;
  • Virtual Bytes are the Working Set plus paged Private Bytes and standby list.

There's another problem here; just as shared libraries can allocate memory inside your application module, leading to potential false positives reported in your app's Private Bytes, your application may also end up allocating memory inside the shared modules, leading to false negatives. That means it's actually possible for your application to have a memory leak that never manifests itself in the Private Bytes at all. Unlikely, but possible.

Private Bytes are a reasonable approximation of the amount of memory your executable is using and can be used to help narrow down a list of potential candidates for a memory leak; if you see the number growing and growing constantly and endlessly, you would want to check that process for a leak. This cannot, however, prove that there is or is not a leak.

One of the most effective tools for detecting/correcting memory leaks in Windows is actually Visual Studio (link goes to page on using VS for memory leaks, not the product page). Rational Purify is another possibility. Microsoft also has a more general best practices document on this subject. There are more tools listed in this previous question.

I hope this clears a few things up! Tracking down memory leaks is one of the most difficult things to do in debugging. Good luck.

Best way to check if column returns a null value (from database to .net application)

Just use DataRow.IsNull. It has overrides accepting a column index, a column name, or a DataColumn object as parameters.

Example using the column index:

if (table.rows[0].IsNull(0))
{
    //Whatever I want to do
}

And although the function is called IsNull it really compares with DbNull (which is exactly what you need).


What if I want to check for DbNull but I don't have a DataRow? Use Convert.IsDBNull.

Difference between string object and string literal

According to String class documentation they are equivalent.

Documentation for String(String original) also says that: Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

Look for other responses, because it seems that Java documentation is misleading :(

Download file from web in Python 3

from urllib import request

def get(url):
    with request.urlopen(url) as r:
        return r.read()


def download(url, file=None):
    if not file:
        file = url.split('/')[-1]
    with open(file, 'wb') as f:
        f.write(get(url))

What's the difference between OpenID and OAuth?

I'd like to address a particular aspect of this question, as captured in this comment:

OAuth: before granting access to some feature, authentication must be done, right ?. so OAuth = what OpenId does + grants access to some features ? – Hassan Makarov Jun 21 at 1:57

Yes... and no. The answer is subtle, so bear with me.

When the OAuth flow redirects you to a target service (the OAuth provider, that is), it is likely that you'll need to authenticate with that service before a token will be handed back to the client application/service. The resulting token then allows the client app to make requests on behalf of a given user.

Note the generality of that last sentence: specifically, I wrote "on behalf of a given user", not "on behalf of you". It's a common error to assume that "having a capability to interact with a resource owned by a given user" implies "you and the owner of the target resource(s) are one in the same".

Don't make this mistake.

While it's true that you authenticate with the OAuth provider (say, by user name and password, or maybe SSL client certs, or some other means), what the client gets in return should not necessarily be taken as proof of identity. An example would be a flow in which access to another user's resources was delegated to you (and by proxy, the OAuth client). Authorization does not imply authentication.

To handle authentication, you'll likely want to look into OpenID Connect, which is essentially another layer on top of the foundation set by OAuth 2.0. Here's a quote that captures (in my opinion) the most salient points regarding OpenID Connect (from https://oauth.net/articles/authentication/):

OpenID Connect is an open standard published in early 2014 that defines an interoperable way to use OAuth 2.0 to perform user authentication. In essence, it is a widely published recipe for chocolate fudge that has been tried and tested by a wide number and variety of experts. Instead of building a different protocol to each potential identity provider, an application can speak one protocol to as many providers as they want to work with. Since it's an open standard, OpenID Connect can be implemented by anyone without restriction or intellectual property concerns.

OpenID Connect is built directly on OAuth 2.0 and in most cases is deployed right along with (or on top of) an OAuth infrastructure. OpenID Connect also uses the JSON Object Signing And Encryption (JOSE) suite of specifications for carrying signed and encrypted information around in different places. In fact, an OAuth 2.0 deployment with JOSE capabilities is already a long way to defining a fully compliant OpenID Connect system, and the delta between the two is relatively small. But that delta makes a big difference, and OpenID Connect manages to avoid many of the pitfalls discussed above by adding several key components to the OAuth base: [...]

The document then goes on to describe (among other things) token IDs and a UserInfo endpoint. The former provides a set of claims (who you are, when the token was issued, etc, and possibly a signature to verify the authenticity of the token via a published public key without having to ask the upstream service), and the latter provides a means of e.g. asking for the user's first/last name, email, and similar bits of info, all in a standardized way (as opposed to the ad-hoc extensions to OAuth that people used before OpenID Connect standardized things).

How to select only 1 row from oracle sql?

select name, price
  from (
    select name, price, 
    row_number() over (order by price) r
      from items
  )
where r between 1 and 5; 

How do I run a VBScript in 32-bit mode on a 64-bit machine?

We can force vbscript always run with 32 bit mode by changing "system32" to "sysWOW64" in default value of key "Computer\HKLM\SOFTWARE]\Classes\VBSFile\Shell\Open\Command"

Forcing Internet Explorer 9 to use standards document mode

There is something very important about this thread that has been touched on but not fully explained. The HTML approach (adding a meta tag in the head) only works consistently on raw HTML or very basic server pages. My site is a very complex server-driven site with master pages, themeing and a lot of third party controls, etc. What I found was that some of these controls were programmatically adding their own tags to the final HTML which were being pushed to the browser at the beginning of the head tag. This effectively rendered the HTML meta tags useless.

Well, if you can't beat them, join them. The only solution that worked for me is to do exactly the same thing in the pre-render event of my master pages as such:

Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
    Dim MetaTag As HtmlMeta = New HtmlMeta()
    MetaTag.Attributes("http-equiv") = "Content-Type"
    MetaTag.Attributes("content") = "text/html; charset=utf-8;"
    Page.Header.Controls.AddAt(0, MetaTag)

    MetaTag = New HtmlMeta()
    MetaTag.Attributes("http-equiv") = "X-UA-Compatible"
    MetaTag.Attributes("content") = "IE=9,chrome=1"
    Page.Header.Controls.AddAt(0, MetaTag)
End Sub

This is VB.NET but the same approach would work for any server-side technology. As long as you make sure it's the last thing that gets done right before the page is rendered.

onclick event function in JavaScript

<script>
//$(document).ready(function () {
function showcontent() {
        document.getElementById("demo22").innerHTML = "Hello World";
}
//});// end of ready function
</script>

I had the same problem where onclick function calls would not work. I had included the function inside the usual "$(document).ready(function(){});" block used to wrap jquery scripts. Commenting this block out solved the problem.

Regexp Java for password validation

You should not use overly complex Regex (if you can avoid them) because they are

  • hard to read (at least for everyone but yourself)
  • hard to extend
  • hard to debug

Although there might be a small performance overhead in using many small regular expressions, the points above outweight it easily.

I would implement like this:

bool matchesPolicy(pwd) {
    if (pwd.length < 8) return false;
    if (not pwd =~ /[0-9]/) return false;
    if (not pwd =~ /[a-z]/) return false;
    if (not pwd =~ /[A-Z]/) return false;
    if (not pwd =~ /[%@$^]/) return false;
    if (pwd =~ /\s/) return false;
    return true;
}

Use bash to find first folder name that contains a string

You can use the -quit option of find:

find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit

How to get the size of a varchar[n] field in one SQL statement?

For t-SQL I use the following query for varchar columns (shows the collation and is_null properties):

SELECT
    s.name
    , o.name as table_name
    , c.name as column_name
    , t.name as type
    , c.max_length
    , c.collation_name
    , c.is_nullable
FROM
    sys.columns c
    INNER JOIN sys.objects o ON (o.object_id = c.object_id)
    INNER JOIN sys.schemas s ON (s.schema_id = o.schema_id)
    INNER JOIN sys.types t ON (t.user_type_id = c.user_type_id)
WHERE
    s.name = 'dbo'
    AND t.name IN ('varchar') -- , 'char', 'nvarchar', 'nchar')
ORDER BY
    o.name, c.name

How to do an array of hashmaps?

You can use something like this:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class testHashes {

public static void main(String args[]){
    Map<String,String> myMap1 = new HashMap<String, String>();

    List<Map<String , String>> myMap  = new ArrayList<Map<String,String>>();

    myMap1.put("URL", "Val0");
    myMap1.put("CRC", "Vla1");
    myMap1.put("SIZE", "Val2");
    myMap1.put("PROGRESS", "Val3");

    myMap.add(0,myMap1);
    myMap.add(1,myMap1);

    for (Map<String, String> map : myMap) {
        System.out.println(map.get("URL"));
        System.out.println(map.get("CRC"));
        System.out.println(map.get("SIZE"));
        System.out.println(map.get("PROGRESS"));
    }

    //System.out.println(myMap);

}


}

Plotting time in Python with Matplotlib

You can also plot the timestamp, value pairs using pyplot.plot (after parsing them from their string representation). (Tested with matplotlib versions 1.2.0 and 1.3.1.)

Example:

import datetime
import random
import matplotlib.pyplot as plt

# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

plt.show()

Resulting image:

Line Plot


Here's the same as a scatter plot:

import datetime
import random
import matplotlib.pyplot as plt

# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.scatter(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

plt.show()

Produces an image similar to this:

Scatter Plot

How can I combine flexbox and vertical scroll in a full-height app?

Flexbox spec editor here.

This is an encouraged use of flexbox, but there are a few things you should tweak for best behavior.

  • Don't use prefixes. Unprefixed flexbox is well-supported across most browsers. Always start with unprefixed, and only add prefixes if necessary to support it.

  • Since your header and footer aren't meant to flex, they should both have flex: none; set on them. Right now you have a similar behavior due to some overlapping effects, but you shouldn't rely on that unless you want to accidentally confuse yourself later. (Default is flex:0 1 auto, so they start at their auto height and can shrink but not grow, but they're also overflow:visible by default, which triggers their default min-height:auto to prevent them from shrinking at all. If you ever set an overflow on them, the behavior of min-height:auto changes (switching to zero rather than min-content) and they'll suddenly get squished by the extra-tall <article> element.)

  • You can simplify the <article> flex too - just set flex: 1; and you'll be good to go. Try to stick with the common values in https://drafts.csswg.org/css-flexbox/#flex-common unless you have a good reason to do something more complicated - they're easier to read and cover most of the behaviors you'll want to invoke.

How to pause / sleep thread or process in Android?

I use this:

Thread closeActivity = new Thread(new Runnable() {
  @Override
  public void run() {
    try {
      Thread.sleep(3000);
      // Do some stuff
    } catch (Exception e) {
      e.getLocalizedMessage();
    }
  }
});

How to add border radius on table row

All the answers are way too long. The easiest way to add border radius to a table element that accepts border as a property, is doing border radius with overflow: hidden.

border: xStyle xColor xSize;
border-collapse: collapse;
border-radius: 1em;
overflow: hidden;

What do the result codes in SVN mean?

There is also an 'E' status

E = File existed before update

This can happen if you have manually created a folder that would have been created by performing an update.

Selecting multiple items in ListView

Best way is to have a contextual action bar with listview on multiselect, You can make listview as multiselect using the following code

listview.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);

And now set multichoice listener for Listview ,You can see the complete implementation of multiselect listview at Android multi select listview

How to use onClick() or onSelect() on option tag in a JSP page?

<html>
<head>
<title>Cars</title>
</head>
<body >

<h1>Cars</h1>
    <p>Name </p>
        <select id="selectBox" onchange="myFunction(value);">
            <option value="volvo" >Volvo</option>
            <option value="saab"  >Saab</option>
            <option value="mercedes">Mercedes</option>
        </select>        
<p id="result"> Price : </p>
<script>
function myFunction($value)
{       
    if($value=="volvo")
    {document.getElementById("result").innerHTML = "30L";}
    else if($value=="saab")
    {document.getElementById("result").innerHTML = "40L";}
     else if($value=="mercedes")
    {document.getElementById("result").innerHTML = "50L";}
}
</script>
</body>
</html>```

How to get 0-padded binary representation of an integer in java?

I do not know "right" solution but I can suggest you a fast patch.

String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0");

I have just tried it and saw that it works fine.

How do I detect if software keyboard is visible on Android Device or not?

Very Easy

1. Put id on your root view

rootView is just a view pointing to my root view in this case a relative layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/addresses_confirm_root_view"
                android:background="@color/WHITE_CLR">

2. Initialize your root view in your Activity:

RelativeLayout rootView = (RelativeLayout) findViewById(R.id.addresses_confirm_root_view);

3. Detect if keyboard is opened or closed by using getViewTreeObserver()

    rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightDiff = rootView.getRootView().getHeight() - rootView.getHeight();
                
                if (heightDiff > 100) { // Value should be less than keyboard's height 
                    Log.e("MyActivity", "keyboard opened");
                } else { 
                    Log.e("MyActivity", "keyboard closed");
                }
            }
        });

Something better than .NET Reflector?

I am not sure what you really want here. If you want to see the .NET framework source code, you may try Netmassdownloader. It's free.

If you want to see any assembly's code (not just .NET), you can use ReSharper. Although it's not free.

Convert A String (like testing123) To Binary In Java

You can also do this with the ol' good method :

String inputLine = "test123";
String translatedString = null;
char[] stringArray = inputLine.toCharArray();
for(int i=0;i<stringArray.length;i++){
      translatedString += Integer.toBinaryString((int) stringArray[i]);
}

Convert Year/Month/Day to Day of Year in Python

I want to present performance of different approaches, on Python 3.4, Linux x64. Excerpt from line profiler:

      Line #      Hits         Time  Per Hit   % Time  Line Contents
      ==============================================================
         (...)
         823      1508        11334      7.5     41.6          yday = int(period_end.strftime('%j'))
         824      1508         2492      1.7      9.1          yday = period_end.toordinal() - date(period_end.year, 1, 1).toordinal() + 1
         825      1508         1852      1.2      6.8          yday = (period_end - date(period_end.year, 1, 1)).days + 1
         826      1508         5078      3.4     18.6          yday = period_end.timetuple().tm_yday
         (...)

So most efficient is

yday = (period_end - date(period_end.year, 1, 1)).days

How to create a Rectangle object in Java using g.fillRect method

Note:drawRect and fillRect are different.

Draws the outline of the specified rectangle:

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

Fills the specified rectangle. The rectangle is filled using the graphics context's current color:

public abstract void fillRect(int x,
        int y,
        int width,
        int height)

@JsonProperty annotation on field as well as getter/setter

In addition to existing good answers, note that Jackson 1.9 improved handling by adding "property unification", meaning that ALL annotations from difference parts of a logical property are combined, using (hopefully) intuitive precedence.

In Jackson 1.8 and prior, only field and getter annotations were used when determining what and how to serialize (writing JSON); and only and setter annotations for deserialization (reading JSON). This sometimes required addition of "extra" annotations, like annotating both getter and setter.

With Jackson 1.9 and above these extra annotations are NOT needed. It is still possible to add those; and if different names are used, one can create "split" properties (serializing using one name, deserializing using other): this is occasionally useful for sort of renaming.

SQLAlchemy insert or update example

assuming certain column names...

INSERT one

newToner = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

dbsession.add(newToner)   
dbsession.commit()

INSERT multiple

newToner1 = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

newToner2 = Toner(toner_id = 2,
                    toner_color = 'red',
                    toner_hex = '#F01731')

dbsession.add_all([newToner1, newToner2])   
dbsession.commit()

UPDATE

q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'

dbsession.commit()

or using a fancy one-liner using MERGE

record = dbsession.merge(Toner( **kwargs))

How to automatically redirect HTTP to HTTPS on Apache servers?

This worked for me:

RewriteCond %{HTTPS} =off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L,R=301]

JQuery - $ is not defined

I had the same problem and it was because my reference to the jQuery.js was not in the tag. Once I switched that, everything started working.

Anthony

validate a dropdownlist in asp.net mvc

Example from MVC 4 for dropdownlist validation on Submit using Dataannotation and ViewBag (less line of code)

Models:

namespace Project.Models
{
    public class EmployeeReferral : Person
    {

        public int EmployeeReferralId { get; set; }


        //Company District
        //List                
        [Required(ErrorMessage = "Required.")]
        [Display(Name = "Employee District:")]
        public int? DistrictId { get; set; }

    public virtual District District { get; set; }       
}


namespace Project.Models
{
    public class District
    {
        public int? DistrictId { get; set; }

        [Display(Name = "Employee District:")]
        public string DistrictName { get; set; }
    }
}

EmployeeReferral Controller:

namespace Project.Controllers
{
    public class EmployeeReferralController : Controller
    {
        private ProjDbContext db = new ProjDbContext();

        //
        // GET: /EmployeeReferral/

        public ActionResult Index()
        {
            return View();
        }

 public ActionResult Create()
        {
            ViewBag.Districts = db.Districts;            
            return View();
        }

View:

<td>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.DistrictId, "District")
                    </div>
                </td>
                <td>
                    <div class="editor-field">
                        @*@Html.DropDownList("DistrictId", "----Select ---")*@
                        @Html.DropDownListFor(model => model.DistrictId, new SelectList(ViewBag.Districts, "DistrictId", "DistrictName"), "--- Select ---")
                        @Html.ValidationMessageFor(model => model.DistrictId)                                                
                    </div>
                </td>

Why can't we use ViewBag for populating dropdownlists that can be validated with Annotations. It is less lines of code.

Is it possible to specify proxy credentials in your web.config?

Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision

Finding height in Binary Search Tree

For anyone else that reads this!!!!

HEIGHT is defined as the number of nodes in the longest path from the root node to a leaf node. Therefore: a tree with only a root node has a height of 1 and not 0.

The LEVEL of a given node is the distance from the root plus 1. Therefore: The root is on level 1, its child nodes are on level 2 and so on.

(Information courtesy of Data Structures: Abstraction and Design Using Java, 2nd Edition, by Elliot B. Koffman & Paul A. T. Wolfgang) - Book used in Data Structures Course I am currently taking at Columbus State University.

How to clear all data in a listBox?

this should work:

private void cleanlistbox(object sender, EventArgs e)
{
    listBox1.Items.Clear( );
}

TypeError: 'dict_keys' object does not support indexing

You're passing the result of somedict.keys() to the function. In Python 3, dict.keys doesn't return a list, but a set-like object that represents a view of the dictionary's keys and (being set-like) doesn't support indexing.

To fix the problem, use list(somedict.keys()) to collect the keys, and work with that.

Maximum length for MySQL type text

How many characters can a type text field store?

According to Documentation You can use maximum of 21,844 characters if the charset is UTF8

If a lot, would I be able to specify length in the db text type field as I would with varchar?

You dont need to specify the length. If you need more character use data types MEDIUMTEXT or LONGTEXT. With VARCHAR, specifieng length is not for Storage requirement, it is only for how the data is retrieved from data base.

100% width table overflowing div container

Well, given your constraints, I think setting overflow: scroll; on the .page div is probably your only option. 280 px is pretty narrow, and given your font size, word wrapping alone isn't going to do it. Some words are just long and can't be wrapped. You can either reduce your font size drastically or go with overflow: scroll.

Getting value from appsettings.json in .net core

Its simple: In appsettings.json

  "MyValues": {
    "Value1": "Xyz"
  }

In .cs file:

static IConfiguration conf = (new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build());
        public static string myValue1= conf["MyValues:Value1"].ToString();

ModuleNotFoundError: What does it mean __main__ is not a package?

The problem still not resolved after remove the '.', then it start points the error to my folder. As i added this folder first time then i restarted the PyCharm and it automatically resolved the issue

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

if cordova app copy a valid png file to

resources\android\icon.png

and then run

ionic resources --icon

Loop timer in JavaScript

I believe you are looking for setInterval()

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

Finally, solved the problem above. I was receiving errors

  • Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service

Since I have not added WKWebView object on the view as a subview and tried to call -loadHTMLString:baseURL: on the top of it. And only after it was successfully loaded I was adding it to view's subviews - which was totally wrong. The correct solution for my problem is:

1. Add WKWebView object to view's subviews array

2. Call -loadHTMLString:baseURL: for recently added WKWebView

MS-DOS Batch file pause with enter key

You can do it with the pause command, example:

dir
pause
echo Now about to end...
pause

Convert Xml to Table SQL Server

This is the answer, hope it helps someone :)

First there are two variations on how the xml can be written:

1

<row>
    <IdInvernadero>8</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>8</IdCaracteristica1>
    <IdCaracteristica2>8</IdCaracteristica2>
    <Cantidad>25</Cantidad>
    <Folio>4568457</Folio>
</row>
<row>
    <IdInvernadero>3</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>1</IdCaracteristica1>
    <IdCaracteristica2>2</IdCaracteristica2>
    <Cantidad>72</Cantidad>
    <Folio>4568457</Folio>
</row>

Answer:

SELECT  
       Tbl.Col.value('IdInvernadero[1]', 'smallint'),  
       Tbl.Col.value('IdProducto[1]', 'smallint'),  
       Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
       Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
       Tbl.Col.value('Cantidad[1]', 'int'),
       Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM   @xml.nodes('//row') Tbl(Col)  

2.

<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />                         
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />

Answer:

SELECT  
       Tbl.Col.value('@IdInvernadero', 'smallint'),  
       Tbl.Col.value('@IdProducto', 'smallint'),  
       Tbl.Col.value('@IdCaracteristica1', 'smallint'),
       Tbl.Col.value('@IdCaracteristica2', 'smallint'),
       Tbl.Col.value('@Cantidad', 'int'),
       Tbl.Col.value('@Folio', 'varchar(7)')

FROM   @xml.nodes('//row') Tbl(Col)

Taken from:

  1. http://kennyshu.blogspot.com/2007/12/convert-xml-file-to-table-in-sql-2005.html

  2. http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx

Import and insert sql.gz file into database with putty

Login into your server using a shell program like putty.

Type in the following command on the command line

zcat DB_File_Name.sql.gz | mysql -u username -p Target_DB_Name

where

DB_File_Name.sql.gz = full path of the sql.gz file to be imported

username = your mysql username

Target_DB_Name = database name where you want to import the database

When you hit enter in the command line, it will prompt for password. Enter your MySQL password.

You are done!

Forgot Oracle username and password, how to retrieve?

The usernames are shown in the dba_users's username column, there is a script you can run called:

alter user username identified by password

You can get more information here - https://community.oracle.com/thread/632617?tstart=0

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

I think you have a couple of options here.

you could store the last Exception in the Session and retrieve it from your custom error page; or you could just redirect to your custom error page within the Application_error event. If you choose the latter, you want to make sure you use the Server.Transfer method.

What is an .inc and why use it?

If you are concerned about the file's content being served rather than its output. You can use a double extension like: file.inc.php. It then serves the same purpose of helpfulness and maintainability.

I normally have 2 php files for each page on my site:

  1. One named welcome.php in the root folder, containing all of the HTML markup.
  2. And another named welcome.inc.php in the inc folder, containing all PHP functions specific to the welcome.php page.

EDIT: Another benefit of using the double extention .inc.php would be that any IDE can still recognise the file as PHP code.

TypeError: no implicit conversion of Symbol into Integer

Your item variable holds Array instance (in [hash_key, hash_value] format), so it doesn't expect Symbol in [] method.

This is how you could do it using Hash#each:

def format(hash)
  output = Hash.new
  hash.each do |key, value|
    output[key] = cleanup(value)
  end
  output
end

or, without this:

def format(hash)
  output = hash.dup
  output[:company_name] = cleanup(output[:company_name])
  output[:street] = cleanup(output[:street])
  output
end

How to set recurring schedule for xlsm file using Windows Task Scheduler

I found a much easier way and I hope it works for you. (using Windows 10 and Excel 2016)

Create a new module and enter the following code: Sub auto_open() 'Macro to be run (doesn't have to be in this module, just in this workbook End Sub

Set up a task through the Task Scheduler and set the "program to be run as" Excel (found mine at C:\Program Files (x86)\Microsoft Office\root\Office16). Then set the "Add arguments (optional): as the file path to the macro-enabled workbook. Remember that both the path to Excel and the path to the workbook should be in double quotes.

*See example from Rich, edited by Community, for an image of the windows scheduler screen.

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

Not really a technical solution, but SQL Server 2017 flat file import is totally revamped, and imported my large-ish file with 5 clicks, handled encoding / field length issues without any input from me

enter image description here

How to execute python file in linux

1.save your file name as hey.py with the below given hello world script

#! /usr/bin/python
print('Hello, world!')

2.open the terminal in that directory

$ python hey.py

or if you are using python3 then

$ python3 hey.py

Epoch vs Iteration when training neural networks

You have a training data which you shuffle and pick mini-batches from it. When you adjust your weights and biases using one mini-batch, you have completed one iteration. Once you run out of your mini-batches, you have completed an epoch. Then you shuffle your training data again, pick your mini-batches again, and iterate through all of them again. That would be your second epoch.

How can you dynamically create variables via a while loop?

playing with globals() makes it possible:

import random

alphabet = tuple('abcdefghijklmnopqrstuvwxyz')


print '\n'.join(repr(u) for u in globals() if not u.startswith('__'))

for i in xrange(8):
    globals()[''.join(random.sample(alphabet,random.randint(3,26)))] = random.choice(alphabet)

print

print '\n'.join(repr((u,globals()[u])) for u in globals() if not u.startswith('__'))

one result:

'alphabet'
'random'

('hadmgoixzkcptsbwjfyrelvnqu', 'h')
('nzklv', 'o')
('alphabet', ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'))
('random', <module 'random' from 'G:\Python27\lib\random.pyc'>)
('ckpnwqguzyslmjveotxfbadh', 'f')
('i', 7)
('xwbujzkicyd', 'j')
('isjckyngxvaofdbeqwutl', 'n')
('wmt', 'g')
('aesyhvmw', 'q')
('azfjndwhkqgmtyeb', 'o')

I used random because you don't explain which names of "variables" to give, and which values to create. Because i don't think it's possible to create a name without making it binded to an object.

Is there a /dev/null on Windows?

Jon Skeet is correct. Here is the Nul Device Driver page in the Windows Embedded documentation (I have no idea why it's not somewhere else...).

Here is another:

Use of contains in Java ArrayList<String>

Your question is not very clear.

  • What's your code exactly doing? Give more code.
  • What's the error you're getting?

You say you get a null-pointer. You cannot get a null pointer as a value returned by contains().

However you can get a NullPointerException if your list has not been initialized. By reading your question now, I'd say that what you show here is correct, but maybe you just didn't instantiate the list.

For this to work (to add a feed URL if it isn't already in the list):

if (!this.rssFeedURLs.contains(rssFeedURL)) {
    this.rssFeedURLs.add(rssFeedUrl);
}

then this declaration would do:

private ArrayList<String> rssFeedURLs = new ArrayList<String>();

or initialize your list later on, but before trying to access its methods:

rssFeedUrls = new ArrayList<String>();

Finally... Do you really need a List? Maybe a Set would be better if you don't want duplicates. Use a LinkedHashSet if preserving the ordering matters.

ImportError: numpy.core.multiarray failed to import

Just fixed this issue. import c2 or import numpy was not working. Uninstalled the most current version of numpy. Tried to install numpy==1.15.2 just like specified above, did not work. Tried numpy==1.19.3 IT worked. I guess not all versions work perfectly with all versions of python and dependencies. So keep uninstalling and install one that works.

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

Mike, I had the same problem with SSIS in SQL Server 2005... Apparently, the DataFlowDestination object will always attempt to validate the data coming in, into Unicode. Go to that object, Advanced Editor, Component Properties pane, change the "ValidateExternalMetaData" property to False. Now, go to the Input and Output Properties pane, Destination Input, External Columns - set each column Data type and Length to match the database table it's going to. Now, when you close that editor, those column changes will be saved and not validated over, and it will work.

How to concatenate strings with padding in sqlite

Just one more line for @tofutim answer ... if you want custom field name for concatenated row ...

SELECT 
  (
    col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
  ) AS my_column 
FROM
  mytable;

Tested on SQLite 3.8.8.3, Thanks!

How to check if the request is an AJAX request with PHP

This function is using in yii framework for ajax call check.

public function isAjax() {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}

Rebuild Docker container on file changes

After some research and testing, I found that I had some misunderstandings about the lifetime of Docker containers. Simply restarting a container doesn't make Docker use a new image, when the image was rebuilt in the meantime. Instead, Docker is fetching the image only before creating the container. So the state after running a container is persistent.

Why removing is required

Therefore, rebuilding and restarting isn't enough. I thought containers works like a service: Stopping the service, do your changes, restart it and they would apply. That was my biggest mistake.

Because containers are permanent, you have to remove them using docker rm <ContainerName> first. After a container is removed, you can't simply start it by docker start. This has to be done using docker run, which itself uses the latest image for creating a new container-instance.

Containers should be as independent as possible

With this knowledge, it's comprehensible why storing data in containers is qualified as bad practice and Docker recommends data volumes/mounting host directorys instead: Since a container has to be destroyed to update applications, the stored data inside would be lost too. This cause extra work to shutdown services, backup data and so on.

So it's a smart solution to exclude those data completely from the container: We don't have to worry about our data, when its stored safely on the host and the container only holds the application itself.

Why -rf may not really help you

The docker run command, has a Clean up switch called -rf. It will stop the behavior of keeping docker containers permanently. Using -rf, Docker will destroy the container after it has been exited. But this switch has two problems:

  1. Docker also remove the volumes without a name associated with the container, which may kill your data
  2. Using this option, its not possible to run containers in the background using -d switch

While the -rf switch is a good option to save work during development for quick tests, it's less suitable in production. Especially because of the missing option to run a container in the background, which would mostly be required.

How to remove a container

We can bypass those limitations by simply removing the container:

docker rm --force <ContainerName>

The --force (or -f) switch which use SIGKILL on running containers. Instead, you could also stop the container before:

docker stop <ContainerName>
docker rm <ContainerName>

Both are equal. docker stop is also using SIGTERM. But using --force switch will shorten your script, especially when using CI servers: docker stop throws an error if the container is not running. This would cause Jenkins and many other CI servers to consider the build wrongly as failed. To fix this, you have to check first if the container is running as I did in the question (see containerRunning variable).

Full script for rebuilding a Docker container

According to this new knowledge, I fixed my script in the following way:

#!/bin/bash
imageName=xx:my-image
containerName=my-container

docker build -t $imageName -f Dockerfile  .

echo Delete old container...
docker rm -f $containerName

echo Run new container...
docker run -d -p 5000:5000 --name $containerName $imageName

This works perfectly :)

Calendar Recurring/Repeating Events - Best Storage Method

While the currently accepted answer was a huge help to me, I wanted to share some useful modifications that simplify the queries and also increase performance.


"Simple" Repeat Events

To handle events which recur at regular intervals, such as:

Repeat every other day 

or

Repeat every week on Tuesday 

You should create two tables, one called events like this:

ID    NAME
1     Sample Event
2     Another Event

And a table called events_meta like this:

ID    event_id      repeat_start       repeat_interval
1     1             1369008000         604800            -- Repeats every Monday after May 20th 2013
1     1             1369008000         604800            -- Also repeats every Friday after May 20th 2013

With repeat_start being a unix timestamp date with no time (1369008000 corresponds to May 20th 2013) , and repeat_interval an amount in seconds between intervals (604800 is 7 days).

By looping over each day in the calendar you can get repeat events using this simple query:

SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
WHERE  (( 1299736800 - repeat_start) % repeat_interval = 0 )

Just substitute in the unix-timestamp (1299736800) for each date in your calendar.

Note the use of the modulo (% sign). This symbol is like regular division, but returns the ''remainder'' instead of the quotient, and as such is 0 whenever the current date is an exact multiple of the repeat_interval from the repeat_start.

Performance Comparison

This is significantly faster than the previously suggested "meta_keys"-based answer, which was as follows:

SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
RIGHT JOIN `events_meta` EM2 ON EM2.`meta_key` = CONCAT( 'repeat_interval_', EM1.`id` )
WHERE EM1.meta_key = 'repeat_start'
    AND (
        ( CASE ( 1299132000 - EM1.`meta_value` )
            WHEN 0
              THEN 1
            ELSE ( 1299132000 - EM1.`meta_value` )
          END
        ) / EM2.`meta_value`
    ) = 1

If you run EXPLAIN this query, you'll note that it required the use of a join buffer:

+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref              | rows | Extra                          |
+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+
|  1 | SIMPLE      | EM1   | ALL    | NULL          | NULL    | NULL    | NULL             |    2 | Using where                    |
|  1 | SIMPLE      | EV    | eq_ref | PRIMARY       | PRIMARY | 4       | bcs.EM1.event_id |    1 |                                |
|  1 | SIMPLE      | EM2   | ALL    | NULL          | NULL    | NULL    | NULL             |    2 | Using where; Using join buffer |
+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+

The solution with 1 join above requires no such buffer.


"Complex" Patterns

You can add support for more complex types to support these types of repeat rules:

Event A repeats every month on the 3rd of the month starting on March 3, 2011

or

Event A repeats second Friday of the month starting on March 11, 2011

Your events table can look exactly the same:

ID    NAME
1     Sample Event
2     Another Event

Then to add support for these complex rules add columns to events_meta like so:

ID    event_id      repeat_start       repeat_interval    repeat_year    repeat_month    repeat_day    repeat_week    repeat_weekday
1     1             1369008000         604800             NULL           NULL            NULL          NULL           NULL             -- Repeats every Monday after May 20, 2013
1     1             1368144000         604800             NULL           NULL            NULL          NULL           NULL             -- Repeats every Friday after May 10, 2013
2     2             1369008000         NULL               2013           *               *             2              5                -- Repeats on Friday of the 2nd week in every month    

Note that you simply need to either specify a repeat_interval or a set of repeat_year, repeat_month, repeat_day, repeat_week, and repeat_weekday data.

This makes selection of both types simultaneously very simple. Just loop through each day and fill in the correct values, (1370563200 for June 7th 2013, and then the year, month, day, week number and weekday as follows):

SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
WHERE  (( 1370563200 - repeat_start) % repeat_interval = 0 )
  OR ( 
    (repeat_year = 2013 OR repeat_year = '*' )
    AND
    (repeat_month = 6 OR repeat_month = '*' )
    AND
    (repeat_day = 7 OR repeat_day = '*' )
    AND
    (repeat_week = 2 OR repeat_week = '*' )
    AND
    (repeat_weekday = 5 OR repeat_weekday = '*' )
    AND repeat_start <= 1370563200
  )

This returns all events that repeat on the Friday of the 2nd week, as well as any events that repeat every Friday, so it returns both event ID 1 and 2:

ID    NAME
1     Sample Event
2     Another Event

*Sidenote in the above SQL I used PHP Date's default weekday indexes, so "5" for Friday


Hope this helps others as much as the original answer helped me!

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

On bulk, you can always delete the row before the insert. A deletion of a row that doesn't exist doesn't cause an error, so its safely skipped.

What's the yield keyword in JavaScript?

A simple example:

const strArr = ["red", "green", "blue", "black"];

const strGen = function*() {
    for(let str of strArr) {
        yield str;
    }
};

let gen = strGen();

for (let i = 0; i < 5; i++) {
    console.log(gen.next())
}

//prints: {value: "red", done: false} -> 5 times with different colors, if you try it again as below:

console.log(gen.next());

//prints: {value: undefined, done: true}

Java: Local variable mi defined in an enclosing scope must be final or effectively final

As I can see the array is of String only.For each loop can be used to get individual element of the array and put them in local inner class for use.

Below is the code snippet for it :

     //WorkAround 
    for (String color : colors ){

String pos = Character.toUpperCase(color.charAt(0)) + color.substring(1);
JMenuItem Jmi =new JMenuItem(pos);
Jmi.setIcon(new IconA(color));

Jmi.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JMenuItem item = (JMenuItem) e.getSource();
            IconA icon = (IconA) item.getIcon();
            // HERE YOU USE THE String color variable and no errors!!!
            Color kolorIkony = getColour(color); 
            textArea.setForeground(kolorIkony);
        }
    });

    mnForeground.add(Jmi);
}

}

How to enable TLS 1.2 in Java 7

I had similar issue when connecting to RDS Oracle even when client and server were both set to TLSv1.2 the certs was right and java was 1.8.0_141 So Finally I had to apply patch at Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files

After applying the patch the issue went away and connection went fine.

How to configure encoding in Maven?

OK, I have found the problem.

I use some reporting plugins. In the documentation of the failsafe-maven-plugin I found, that the <encoding> configuration - of course - uses ${project.reporting.outputEncoding} by default.

So I added the property as a child element of the project element and everything is fine now:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

See also http://maven.apache.org/general.html#encoding-warning

Aligning textviews on the left and right edges in Android layout

<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Hello world" />

<View
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Gud bye" />

Remove leading comma from a string

remove leading or trailing characters:

function trimLeadingTrailing(inputStr, toRemove) {
    // use a regex to match toRemove at the start (^)
    // and at the end ($) of inputStr
    const re = new Regex(`/^${toRemove}|{toRemove}$/`);
    return inputStr.replace(re, '');
}

How do I set a cookie on HttpClient's HttpRequestMessage

The accepted answer is the correct way to do this in most cases. However, there are some situations where you want to set the cookie header manually. Normally if you set a "Cookie" header it is ignored, but that's because HttpClientHandler defaults to using its CookieContainer property for cookies. If you disable that then by setting UseCookies to false you can set cookie headers manually and they will appear in the request, e.g.

var baseAddress = new Uri("http://example.com");
using (var handler = new HttpClientHandler { UseCookies = false })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var message = new HttpRequestMessage(HttpMethod.Get, "/test");
    message.Headers.Add("Cookie", "cookie1=value1; cookie2=value2");
    var result = await client.SendAsync(message);
    result.EnsureSuccessStatusCode();
}

How to submit a form with JavaScript by clicking a link?

If you use jQuery and would need an inline solution, this would work very well;

<a href="#" onclick="$(this).closest('form').submit();">submit form</a>

Also, you might want to replace

<a href="#">text</a>

with

<a href="javascript:void(0);">text</a>

so the user does not scroll to the top of your page when clicking the link.

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

A 'for' loop to iterate over an enum in Java

values() method may simply work:

for (Direction  d : Direction.values()) {
   //whatever you want to do with each of these enum values  
}

Typescript - multidimensional array initialization

If you want to do it typed:

class Something {

  areas: Area[][];

  constructor() {
    this.areas = new Array<Array<Area>>();
    for (let y = 0; y <= 100; y++) {
      let row:Area[]  = new Array<Area>();      
      for (let x = 0; x <=100; x++){
        row.push(new Area(x, y));
      }
      this.areas.push(row);
    }
  }
}

How do I disable a jquery-ui draggable?

Change draggable attribute from

<span draggable="true">Label</span>

to

<span draggable="false">Label</span>

How to create dispatch queue in Swift 3

You can create dispatch queue using this code in swift 3.0

DispatchQueue.main.async
 {
   /*Write your code here*/
 }

   /* or */

let delayTime = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)                   
DispatchQueue.main.asyncAfter(deadline: delayTime)
{
  /*Write your code here*/
}

Docker error: invalid reference format: repository name must be lowercase

In my case I was trying to run postgres through docker. Initially I was running as :

docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=test_password POSTGRES_USER=test_user POSTGRES_DB=test_db --rm -v ~/docker/volumes/postgres:/var/lib/postgresql/data --name pg-docker postgres

I was missing -e after each environment variable. Changing the above command to the one below worked

docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=test_password -e POSTGRES_USER=test_user -e POSTGRES_DB=test_db --rm -v ~/docker/volumes/postgres:/var/lib/postgresql/data --name pg-docker postgres

Euclidean distance of two vectors

try using this:

sqrt(sum((x1-x2)^2))

get enum name from enum value

This is my take on it:

public enum LoginState { 
    LOGGED_IN(1), LOGGED_OUT(0), IN_TRANSACTION(-1);

    private int code;

    LoginState(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public static LoginState getLoginStateFromCode(int code){
        for(LoginState e : LoginState.values()){
            if(code == e.code) return e;
        }
        return LoginState.LOGGED_OUT; //or null
    }
};

And I have used it with System Preferences in Android like so:

LoginState getLoginState(int i) {
    return LoginState.getLoginStateFromCode(
                prefs().getInt(SPK_IS_LOGIN, LoginState.LOGGED_OUT.getCode())
            );
}

public static void setLoginState(LoginState newLoginState) {
    editor().putInt(SPK_IS_LOGIN, newLoginState.getCode());
    editor().commit();
}

where pref and editor are SharedPreferences and a SharedPreferences.Editor

Comparison between Corona, Phonegap, Titanium

Rhomobile Rhodes (http://rhomobile.com/products/rhodes) is very similar in approach to PhoneGap, but is the only framework with:

  1. a Model View Controller pattern (as most web frameworks provide)
  2. an Object Relational Manager
  3. support for all popular smartphones (including Windows Phone 7)
  4. a hosted development service (not just hosted build): http://rhohub.com
  5. a full debugger and SDK-less emulator in the RhoStudio IDE
  6. support for synchronized offline data

should use size_t or ssize_t

ssize_t is used for functions whose return value could either be a valid size, or a negative value to indicate an error. It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX] (SSIZE_MAX is system-dependent).

So you should use size_t whenever you mean to return a size in bytes, and ssize_t whenever you would return either a size in bytes or a (negative) error value.

See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html

Ruby objects and JSON serialization (without Rails)

If you're using 1.9.2 or above, you can convert hashes and arrays to nested JSON objects just using to_json.

{a: [1,2,3], b: 4}.to_json

In Rails, you can call to_json on Active Record objects. You can pass :include and :only parameters to control the output:

@user.to_json only: [:name, :email]

You can also call to_json on AR relations, like so:

User.order("id DESC").limit(10).to_json

You don't need to import anything and it all works exactly as you'd hope.

Maven Install on Mac OS X

A simple approach to install Maven.

  1. Open Terminal

Finder -> Go -> Utilities -> Terminal

  1. Install Homebrew using the below command

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

  1. After that install maven

brew install maven

How to force 'cp' to overwrite directory instead of creating another one inside?

Very similar to @Jonathan Wheeler:

If you do not want to remember, but not rewrite bar:

rm -r bar/
cp -r foo/ !$

!$ displays the last argument of your previous command.

Removing all line breaks and adding them after certain text

You need to that in two steps, at least.

First, click on the ¶ symbol in the toolbar: you can see if you have CRLF line endings or just LF.

Click on the Replace button, and put \r\n or \n, depending on the kind of line ending. In the Search Mode section of the dialog, check Extended radio button (interpret \n and such). Then replace all occurrences with nothing (empty string).

You end with a big line...

Next, in the same Replace dialog, put your delimiter (</Row>) for example and in the Replace With field, put the same with a line ending (</Row>\r\n). Replace All, and you are done.

Create an array of strings

Another option:

names = repmat({'Sample Text'}, 10, 1)

Using both Python 2.x and Python 3.x in IPython Notebook

Use sudo pip3 install jupyter for installing jupyter for python3 and sudo pip install jupyter for installing jupyter notebook for python2. Then, you can call ipython kernel install command to enable both types of notebook to choose from in jupyter notebook.

Font awesome is not showing icon

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.js" integrity="sha256-2JRzNxMJiS0aHOJjG+liqsEOuBb6++9cY4dSOyiijX4=" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

How do I automatically scroll to the bottom of a multiline text box?

It seems the interface has changed in .NET 4.0. There is the following method that achieves all of the above. As Tommy Engebretsen suggested, putting it in a TextChanged event handler makes it automatic.

textBox1.ScrollToEnd();

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

The error is down to an "inappropriate use" of the double colon operator:

return $cnf::getConfig($key);

as by using the :: you're attempting to call a static method of the class itself. In your example you want to call a non-static method on an instantiated object.

I think what you want is:

return $cnf->getConfig($key);

Write variable to file, including name

The default string representation for a dictionary seems to be just right:

>>> a={3: 'foo', 17: 'bar' }
>>> a
{17: 'bar', 3: 'foo'}
>>> print a
{17: 'bar', 3: 'foo'}
>>> print "a=", a
a= {17: 'bar', 3: 'foo'}

Not sure if you can get at the "variable name", since variables in Python are just labels for values. See this question.

printf not printing on console

You could try writing to stderr, rather than stdout.

fprintf(stderr, "Hello, please enter your age\n");

You should also have a look at this relevant thread.

HTML Mobile -forcing the soft keyboard to hide

Scott S's answer worked perfectly.

I was coding a web-based phone dialpad for mobile, and every time the user would press a number on the keypad (composed of td span elements in a table), the softkeyboard would pop up. I also wanted the user to not be able to tap into the input box of the number being dialed. This actually solved both problems in 1 shot. The following was used:

<input type="text" id="phone-number" onfocus="blur();" />

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

Is it possible to make abstract classes in Python?

I find the accepted answer, and all the others strange, since they pass self to an abstract class. An abstract class is not instantiated so can't have a self.

So try this, it works.

from abc import ABCMeta, abstractmethod


class Abstract(metaclass=ABCMeta):
    @staticmethod
    @abstractmethod
    def foo():
        """An abstract method. No need to write pass"""


class Derived(Abstract):
    def foo(self):
        print('Hooray!')


FOO = Derived()
FOO.foo()

HTTPS setup in Amazon EC2

An old question but worth mentioning another option in the answers. In case the DNS system of your domain has been defined in Amazon Route 53, you can use Amazon CloudFront service in front of your EC2 and attach a free Amazon SSL certificate to it. This way you will benefit from both having a CDN for a faster content delivery and also securing you domain with HTTPS protocol.

What is TypeScript and why would I use it in place of JavaScript?

TypeScript does something similar to what less or sass does for CSS. They are super sets of it, which means that every JS code you write is valid TypeScript code. Plus you can use the other goodies that it adds to the language, and the transpiled code will be valid js. You can even set the JS version that you want your resulting code on.

Currently TypeScript is a super set of ES2015, so might be a good choice to start learning the new js features and transpile to the needed standard for your project.

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

In a shameless attempt to steal some votes, SecurityProtocol is an Enum with the [Flags] attribute. So you can do this:

[Net.ServicePointManager]::SecurityProtocol = 
  [Net.SecurityProtocolType]::Tls12 -bor `
  [Net.SecurityProtocolType]::Tls11 -bor `
  [Net.SecurityProtocolType]::Tls

Or since this is PowerShell, you can let it parse a string for you:

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"

Then you don't technically need to know the TLS version.

I copied and pasted this from a script I created after reading this answer because I didn't want to cycle through all the available protocols to find one that worked. Of course, you could do that if you wanted to.

Final note - I have the original (minus SO edits) statement in my PowerShell profile so it's in every session I start now. It's not totally foolproof since there are still some sites that just fail but I surely see the message in question much less frequently.

How do I pass a command line argument while starting up GDB in Linux?

Try

gdb --args InsertionSortWithErrors arg1toinsort arg2toinsort

Get name of current script in Python

import sys
print(sys.argv[0])

This will print foo.py for python foo.py, dir/foo.py for python dir/foo.py, etc. It's the first argument to python. (Note that after py2exe it would be foo.exe.)

Bootstrap modal opening on page load

I found the problem. This code was placed in a separate file that was added with a php include() function. And this include was happening before the Bootstrap files were loaded. So the Bootstrap JS file was not loaded yet, causing this modal to not do anything.

With the above code sample is nothing wrong and works as intended when placed in the body part of a html page.

<script type="text/javascript">
$('#memberModal').modal('show');
</script>

Unix command to find lines common in two files

On limited version of Linux (like a QNAP (nas) I was working on):

  • comm did not exist
  • grep -f file1 file2 can cause some problems as said by @ChristopherSchultz and using grep -F -f file1 file2 was really slow (more than 5 minutes - not finished it - over 2-3 seconds with the method below on files over 20MB)

So here is what I did :

sort file1 > file1.sorted
sort file2 > file2.sorted

diff file1.sorted file2.sorted | grep "<" | sed 's/^< *//' > files.diff
diff file1.sorted files.diff | grep "<" | sed 's/^< *//' > files.same.sorted

If files.same.sorted shall have been in same order than the original ones, than add this line for same order than file1 :

awk 'FNR==NR {a[$0]=$0; next}; $0 in a {print a[$0]}' files.same.sorted file1 > files.same

or, for same order than file2 :

awk 'FNR==NR {a[$0]=$0; next}; $0 in a {print a[$0]}' files.same.sorted file2 > files.same

Docker compose, running containers in net:host

Just print

network_mode: "host"

How to get the day of week and the month of the year?

var GetWeekDays = function (format) {
    var weekDays = {};

    var curDate = new Date();
    for (var i = 0; i < 7; ++i) {
        weekDays[curDate.getDay()] = curDate.toLocaleDateString('ru-RU', {
            weekday: format ? format : 'short'
        });

        curDate.setDate(curDate.getDate() + 1);
    }

    return weekDays;
};

me.GetMonthNames = function (format) {
    var monthNames = {};

    var curDate = new Date();
    for (var i = 0; i < 12; ++i) {
        monthNames[curDate.getMonth()] = curDate.toLocaleDateString('ru-RU', {
            month: format ? format : 'long'
        });

        curDate.setMonth(curDate.getMonth() + 1);
    }

    return monthNames;
};

PHP header(Location: ...): Force URL change in address bar

why all of this location url?

http://localhost:8080/meet2eat/index.php

you can just use

index.php

if the php files are in the same folder and this is better because if you want to host the files or change the port you will have no problem reaching this URL.

List of all users that can connect via SSH

Any user whose login shell setting in /etc/passwd is an interactive shell can login. I don't think there's a totally reliable way to tell if a program is an interactive shell; checking whether it's in /etc/shells is probably as good as you can get.

Other users can also login, but the program they run should not allow them to get much access to the system. And users that aren't allowed to login at all should have /etc/false as their shell -- this will just log them out immediately.

how to measure running time of algorithms in python

The module timeit is useful for this and is included in the standard Python distribution.

Example:

import timeit
timeit.Timer('for i in xrange(10): oct(i)').timeit()

What is the volatile keyword useful for?

In my opinion, two important scenarios other than stopping thread in which volatile keyword is used are:

  1. Double-checked locking mechanism. Used often in Singleton design pattern. In this the singleton object needs to be declared volatile.
  2. Spurious Wakeups. Thread may sometimes wake up from wait call even if no notify call has been issued. This behavior is called spurious wakeup. This can be countered by using a conditional variable (boolean flag). Put the wait() call in a while loop as long as the flag is true. So if thread wakes up from wait call due to any reasons other than Notify/NotifyAll then it encounters flag is still true and hence calls wait again. Prior to calling notify set this flag to true. In this case the boolean flag is declared as volatile.

How to set text size in a button in html

Try this

<input type="submit" 
       value="HOME" 
       onclick="goHome()" 
       style="font-size : 20px; width: 100%; height: 100px;" /> 

Save classifier to disk in scikit-learn

Classifiers are just objects that can be pickled and dumped like any other. To continue your example:

import cPickle
# save the classifier
with open('my_dumped_classifier.pkl', 'wb') as fid:
    cPickle.dump(gnb, fid)    

# load it again
with open('my_dumped_classifier.pkl', 'rb') as fid:
    gnb_loaded = cPickle.load(fid)

Edit: if you are using a sklearn Pipeline in which you have custom transformers that cannot be serialized by pickle (nor by joblib), then using Neuraxle's custom ML Pipeline saving is a solution where you can define your own custom step savers on a per-step basis. The savers are called for each step if defined upon saving, and otherwise joblib is used as default for steps without a saver.

SVN checkout the contents of a folder, not the folder itself

Just add the directory on the command line:

svn checkout svn://192.168.1.1/projectname/ target-directory/

Getting an attribute value in xml element

Below is the code to do it in vtd-xml. It basically queries the XML with the XPath of "/xml/item/@name."

import com.ximpleware.*;

public class getAttrs{

   public static void main(String[] s) throws VTDException{
         VTDGen vg = new VTDGen();
         if (!vg.parseFile("input.xml",false)) // turn off namespace
              return;
         VTDNav vn = vg.getNav();
         AutoPilot ap =  new AutoPilot(vn);
         ap.selectXPath("/xml/item/@name");
         int i=0;
         while( (i=ap.evalXPath())!=-1){
              System.out.println(" item name is ===>"+vn.toString(i+1)); 
         }
   }
}

How do I style a <select> dropdown with only CSS?

As of Internet Explorer 10, you can use the ::-ms-expand pseudo element selector to style, and hide, the drop down arrow element.

select::-ms-expand {
    display:none;
    /* or visibility: hidden; to keep it's space/hitbox */
}

The remaining styling should be similar to other browsers.

Here is a basic fork of Danield's jsfiddle that applies support for IE10

check if a string matches an IP address pattern in python?

you should precompile the regexp, if you use it repeatedly

re_ip = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
# note the terminating $ to really match only the IPs

then use

if re_ip.match(st):
    print '!IP'

but.. is e.g. '111.222.333.444' really the IP?

i'd look at netaddr or ipaddr libraries whether they can be used to match IPs

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

css - position div to bottom of containing div

Assign position:relative to .outside, and then position:absolute; bottom:0; to your .inside.

Like so:

.outside {
    position:relative;
}
.inside {
    position: absolute;
    bottom: 0;
}

command/usr/bin/codesign failed with exit code 1- code sign error

Just reset your development and distribution certificate and clean your project. After that , Reboot also worked for me. Interestingly it seems to be an issue with allowing Xcode access to the certificates. When i tried the archive again, i received 2 popups asking me if i wanted to allow Xcode to access my keychain. After this it worked fine.

jquery UI dialog: how to initialize without a title bar?

If you have multiple dialog, you can use this:

$("#the_dialog").dialog({
        open: function(event, ui) { 
            //hide titlebar.
            $(this).parent().children('.ui-dialog-titlebar').hide();
        }
    });

How to force Selenium WebDriver to click on element which is not currently visible?

I had the same problem with selenium 2 in internet explorer 9, but my fix is really strange. I was not able to click into inputs inside my form -> selenium repeats, their are not visible.

It occured when my form had curved shadows -> http://www.paulund.co.uk/creating-different-css3-box-shadows-effects: in the concrete "Effect no. 2"

I have no idea, why&how this pseudo element solution's stopped selenium tests, but it works for me.

Maven fails to find local artifact

As the options here didn't work for me, I'm sharing how I solved it:

My project has a parent project (with its own pom.xml) that has many children modules, one of which (A) has a dependency to another child (B). When I tried mvn package in A, it didn't work because B could not be resolved.

Executing mvn install in the parent directory did the job. After that, I could do mvn package inside of A and only then it could find B.

How to insert an item at the beginning of an array in PHP?

Or you can use temporary array and then delete the real one if you want to change it while in cycle:

$array = array(0 => 'a', 1 => 'b', 2 => 'c');
$temp_array = $array[1];

unset($array[1]);
array_unshift($array , $temp_array);

the output will be:

array(0 => 'b', 1 => 'a', 2 => 'c')

and when are doing it while in cycle, you should clean $temp_array after appending item to array.

How to parse a string in JavaScript?

Use the Javascript string split() function.

var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc

How to add header row to a pandas DataFrame

Alternatively you could read you csv with header=None and then add it with df.columns:

Cov = pd.read_csv("path/to/file.txt", sep='\t', header=None)
Cov.columns = ["Sequence", "Start", "End", "Coverage"]

Outputting data from unit test in Python

Admitting that I haven't tried it, the testfixtures' logging feature looks quite useful...

ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings

In my case it was python path issue.

#1 First set your PYTHONPATH

#2 then set DJANGO_SETTINGS_MODULE

then run django-admin shell command (django-admin dbshell)
(venv) shakeel@workstation:~/project_path$ export PYTHONPATH=/home/shakeel/project_path
(venv) shakeel@workstation:~/project_path$ export DJANGO_SETTINGS_MODULE=my_project.settings
(venv) shakeel@workstation:~/project_path$ django-admin dbshell
SQLite version 3.22.0 2018-01-22 18:45:57
Enter ".help" for usage hints.
sqlite>

otherwise python manage.py shell works like charm.

What does '&' do in a C++ declaration?

Your function declares a constant reference to a string:

int foo(const string &myname) {
  cout << "called foo for: " << myname << endl;
  return 0;
}

A reference has some special properties, which make it a safer alternative to pointers in many ways:

  • it can never be NULL
  • it must always be initialised
  • it cannot be changed to refer to a different variable once set
  • it can be used in exactly the same way as the variable to which it refers (which means you do not need to deference it like a pointer)

How does the function signature differ from the equivalent C:

int foo(const char *myname)

There are several differences, since the first refers directly to an object, while const char* must be dereferenced to point to the data.

Is there a difference between using string *myname vs string &myname?

The main difference when dealing with parameters is that you do not need to dereference &myname. A simpler example is:

int add_ptr(int *x, int* y)
{
    return *x + *y;
}
int add_ref(int &x, int &y)
{
    return x + y;
}

which do exactly the same thing. The only difference in this case is that you do not need to dereference x and y as they refer directly to the variables passed in.

const string &GetMethodName() { ... }

What is the & doing here? Is there some website that explains how & is used differently in C vs C++?

This returns a constant reference to a string. So the caller gets to access the returned variable directly, but only in a read-only sense. This is sometimes used to return string data members without allocating extra memory.

There are some subtleties with references - have a look at the C++ FAQ on References for some more details.

Where can I find decent visio templates/diagrams for software architecture?

There should be templates already included in Visio 2007 for software architecture but you might want to check out Visio 2007 templates.

PIL image to array (numpy array to array) - Python

I think what you are looking for is:

list(im.getdata())

or, if the image is too big to load entirely into memory, so something like that:

for pixel in iter(im.getdata()):
    print pixel

from PIL documentation:

getdata

im.getdata() => sequence

Returns the contents of an image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.

Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations, including iteration and basic sequence access. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).

Get 2 Digit Number For The Month

SELECT REPLACE(CONVERT(varchar, MONTH(GetDate()) * 0.01), '0.', '')

Run a JAR file from the command line and specify classpath

When you specify -jar then the -cp parameter will be ignored.

From the documentation:

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)

You have two options:

  1. include all jar files from the lib directory into the manifest (you can use relative paths there)
  2. Specify everything (including your jar) on the commandline using -cp:
    java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

Converting JSONarray to ArrayList

Java 8 style

   JSONArray data = jsonObject.getJSONArray("some-node");

   List<JSONObject> list = StreamSupport.stream(data.spliterator(), false)
                .map(e -> (JSONObject)e)
                .collect(Collectors.toList());

How to make an HTTP request + basic auth in Swift

my solution works as follows:

import UIKit


class LoginViewController: UIViewController, NSURLConnectionDataDelegate {

  @IBOutlet var usernameTextField: UITextField
  @IBOutlet var passwordTextField: UITextField

  @IBAction func login(sender: AnyObject) {
    var url = NSURL(string: "YOUR_URL")
    var request = NSURLRequest(URL: url)
    var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)

  }

  func connection(connection:NSURLConnection!, willSendRequestForAuthenticationChallenge challenge:NSURLAuthenticationChallenge!) {

    if challenge.previousFailureCount > 1 {

    } else {
        let creds = NSURLCredential(user: usernameTextField.text, password: passwordTextField.text, persistence: NSURLCredentialPersistence.None)
        challenge.sender.useCredential(creds, forAuthenticationChallenge: challenge)

    }

}

  func connection(connection:NSURLConnection!, didReceiveResponse response: NSURLResponse) {
    let status = (response as NSHTTPURLResponse).statusCode
    println("status code is \(status)")
    // 200? Yeah authentication was successful
  }


  override func viewDidLoad() {
    super.viewDidLoad()

  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

  }  
}

You can use this class as the implementation of a ViewController. Connect your fields to the IBOutlet annotated vars and your Button to the IBAction annotated function.

Explanation: In function login you create your request with NSURL, NSURLRequest and NSURLConnection. Essential here is the delegate which references to this class (self). For receiving the delegates calls you need to

  • Add the protocol NSURLConnectionDataDelegate to the class
  • Implement the protocols' function "connection:willSendRequestForAuthenticationChallenge" This is used for adding the credentials to the request
  • Implement the protocols' function "connection:didReceiveResponse" This will check the http response status code

Why does Node.js' fs.readFile() return a buffer instead of string?

Async:

fs.readFile('test.txt', 'utf8', callback);

Sync:

var content = fs.readFileSync('test.txt', 'utf8');

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

Numpy arrays do not have an append method. Use the Numpy append function instead:

import numpy as np

array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely

For example, if array_1 and array_2 have the following values:

array_1 = np.array([1, 2])
array_2 = np.array([3, 4])

If you call np.append without specifying an axis value, like so:

array_3 = np.append(array_1, array_2)

array_3 will have the following value:

array([1, 2, 3, 4])

Else, if you call np.append with an axis value of 0, like so:

array_3 = np.append(array_1, array_2, axis=0)

array_3 will have the following value:

 array([[1, 2],
        [3, 4]]) 

More information on the append function here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html

How can I pass a username/password in the header to a SOAP WCF Service

I got a better method from here: WCF: Creating Custom Headers, How To Add and Consume Those Headers

Client Identifies Itself
The goal here is to have the client provide some sort of information which the server can use to determine who is sending the message. The following C# code will add a header named ClientId:

var cl = new ActiveDirectoryClient();

var eab = new EndpointAddressBuilder(cl.Endpoint.Address);

eab.Headers.Add( AddressHeader.CreateAddressHeader("ClientId",       // Header Name
                                                   string.Empty,     // Namespace
                                                    "OmegaClient")); // Header Value
cl.Endpoint.Address = eab.ToEndpointAddress();

// Now do an operation provided by the service.
cl.ProcessInfo("ABC");

What that code is doing is adding an endpoint header named ClientId with a value of OmegaClient to be inserted into the soap header without a namespace.

Custom Header in Client’s Config File
There is an alternate way of doing a custom header. That can be achieved in the Xml config file of the client where all messages sent by specifying the custom header as part of the endpoint as so:

<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IActiveDirectory" />
            </basicHttpBinding>
        </bindings>
        <client>
          <endpoint address="http://localhost:41863/ActiveDirectoryService.svc"
              binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IActiveDirectory"
              contract="ADService.IActiveDirectory" name="BasicHttpBinding_IActiveDirectory">
            <headers>
              <ClientId>Console_Client</ClientId>
            </headers>
          </endpoint>
        </client>
    </system.serviceModel>
</configuration>

Cast to generic type in C#

As mentioned, you cannot cast it directly. One possible solution is to have those generic types inherit from a non-generic interface, in which case you can still invoke methods on it without reflection. Using reflection, you can pass the mapped object to any method expecting it, then the cast will be performed for you. So if you have a method called Accept expecting a MessageProcessor as a parameter, then you can find it and invoke it dynamically.

Bootstrap Modal sitting behind backdrop

i encountred this problem, and after investigating my css, the main container (direct child of the body) had:

position: relative
z-index: 1

the backdrop worked well after i removed those two properties. You may also encounter this problem if the main wraper have a position: fixed

java.math.BigInteger cannot be cast to java.lang.Long

I'm lacking context, but this is working just fine:

List<BigInteger> nums = new ArrayList<BigInteger>();
Long max = Collections.max(nums).longValue(); // from BigInteger to Long...

Java: how do I get a class literal from a generic type?

To expound on cletus' answer, at runtime all record of the generic types is removed. Generics are processed only in the compiler and are used to provide additional type safety. They are really just shorthand that allows the compiler to insert typecasts at the appropriate places. For example, previously you'd have to do the following:

List x = new ArrayList();
x.add(new SomeClass());
Iterator i = x.iterator();
SomeClass z = (SomeClass) i.next();

becomes

List<SomeClass> x = new ArrayList<SomeClass>();
x.add(new SomeClass());
Iterator<SomeClass> i = x.iterator();
SomeClass z = i.next();

This allows the compiler to check your code at compile-time, but at runtime it still looks like the first example.

Docker - a way to give access to a host USB or serial device?

Adding to the answers above, for those who want a quick way to use an external USB device (HDD, flash drive) working inside docker, and not using priviledged mode:

Find the devpath to your device on the host:

sudo fdisk -l

You can recognize your drive by it's capacity quite easily from the list. Copy this path (for the following example it is /dev/sda2).

Disque /dev/sda2 : 554,5 Go, 57151488 octets, 111624 secteurs
Unités : secteur de 1 × 512 = 512 octets
Taille de secteur (logique / physique) : 512 octets / 512 octets
taille d'E/S (minimale / optimale) : 512 octets / 512 octets

Mount this devpath (preferable to /media):

sudo mount <drive path> /media/<mount folder name>

You can then use this either as a param to docker run like:

docker run -it -v /media/<mount folder name>:/media/<mount folder name>

or in docker compose under volumes:

services:
  whatevermyserviceis:
    volumes:
      - /media/<mount folder name>:/media/<mount folder name>

And now when you run and enter your container, you should be able to access the drive inside the container at /media/<mount folder name>

DISCLAIMER:

  1. This will probably not work for serial devices such as webcams etc. I have only tested this for USB storage drives.
  2. If you need to reconnect and disconnect devices regularly, this method would be annoying, and also would not work unless you reset the mount path and restart the container.
  3. I used docker 17.06 + as prescribed in the docs

Skip first line(field) in loop using CSV file?

There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:

with open(filename, 'r') as f:
    next(f)
    for line in f:

and:

with open(filename,'r') as f:
    lines = f.readlines()[1:]

How to "z-index" to make a menu always on top of the content

you could put the style in container div menu with:

<div style="position:relative; z-index:10">
   ...
   <!--html menu-->
   ...
</div>

before enter image description here

after

enter image description here

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

I fixed it by deleting my app.config with

<assemblyIdentity name="System.Runtime" ....> 

entries.

app.config was automatically added (but not needed) during refactoring

What is a StackOverflowError?

Like you say, you need to show some code. :-)

A stack overflow error usually happens when your function calls nest too deeply. See the Stack Overflow Code Golf thread for some examples of how this happens (though in the case of that question, the answers intentionally cause stack overflow).

How to write a CSS hack for IE 11?

Here is a two steps solution here is a hack to IE10 and 11

    @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
}

because IE10 and IE11 Supports -ms-high-cotrast you can take the advantage of this to target this two browsers

and if you want to exclude the IE10 from this you must create a IE10 specific code as follow it's using the user agent trick you must add this Javascript

var doc = document.documentElement;
doc.setAttribute('data-useragent', navigator.userAgent);

and this HTML tag

<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">

and now you can write your CSS code like this

html[data-useragent*='MSIE 10.0'] h1 {
  color: blue;
}

for more information please refer to this websites,wil tutorail, Chris Tutorial


And if you want to target IE11 and later,here is what I've found:

_:-ms-fullscreen, :root .selector {}

Here is a great resource for getting more information: browserhacks.com

Stop handler.postDelayed()

You can use:

 Handler handler = new Handler()
 handler.postDelayed(new Runnable())

Or you can use:

 handler.removeCallbacksAndMessages(null);

Docs

public final void removeCallbacksAndMessages (Object token)

Added in API level 1 Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

Or you could also do like the following:

Handler handler =  new Handler()
Runnable myRunnable = new Runnable() {
public void run() {
    // do something
}
};
handler.postDelayed(myRunnable,zeit_dauer2);

Then:

handler.removeCallbacks(myRunnable);

Docs

public final void removeCallbacks (Runnable r)

Added in API level 1 Remove any pending posts of Runnable r that are in the message queue.

public final void removeCallbacks (Runnable r, Object token)

Edit:

Change this:

@Override
public void onClick(View v) {
    Handler handler =  new Handler();
    Runnable myRunnable = new Runnable() {

To:

@Override
public void onClick(View v) {
    handler = new Handler();
    myRunnable = new Runnable() { /* ... */}

Because you have the below. Declared before onCreate but you re-declared and then initialized it in onClick leading to a NPE.

Handler handler; // declared before onCreate
Runnable myRunnable;

Printing to the console in Google Apps Script?

In a google script project you can create html files (example: index.html) or gs files (example:code.gs). The .gs files are executed on the server and you can use Logger.log as @Peter Herrman describes. However if the function is created in a .html file it is being executed on the user's browser and you can use console.log. The Chrome browser console can be viewed by Ctrl Shift J on Windows/Linux or Cmd Opt J on Mac

If you want to use Logger.log on an html file you can use a scriptlet to call the Logger.log function from the html file. To do so you would insert <? Logger.log(something) ?> replacing something with whatever you want to log. Standard scriptlets, which use the syntax <? ... ?>, execute code without explicitly outputting content to the page.

print highest value in dict with key

The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max key (as opposed to the dict key) you can easily extract the highest value and its associated key.

 mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)

How do I find the caller of a method using stacktrace or reflection?

I've done this before. You can just create a new exception and grab the stack trace on it without throwing it, then examine the stack trace. As the other answer says though, it's extremely costly--don't do it in a tight loop.

I've done it before for a logging utility on an app where performance didn't matter much (Performance rarely matters much at all, actually--as long as you display the result to an action such as a button click quickly).

It was before you could get the stack trace, exceptions just had .printStackTrace() so I had to redirect System.out to a stream of my own creation, then (new Exception()).printStackTrace(); Redirect System.out back and parse the stream. Fun stuff.

How to give Jenkins more heap space when it´s started as a service under Windows?

If you used Aptitude (apt-get) to install Jenkins on Ubuntu 12.04, uncomment the JAVA_ARGS line in the top few lines of /etc/default/jenkins:

# arguments to pass to java
#JAVA_ARGS="-Xmx256m"   # <--default value
JAVA_ARGS="-Xmx2048m"
#JAVA_ARGS="-Djava.net.preferIPv4Stack=true" # make jenkins listen on IPv4 address

What's the proper way to install pip, virtualenv, and distribute for Python?

I've had various problems (see below) installing upgraded SSL modules, even inside a virtualenv, on top of older OS-provided Python versions, so I now use pyenv.

pyenv makes it very easy to install new Python versions and supports virtualenvs. Getting started is much easier than the recipes for virtualenv listed in other answers:

  • On Mac, type brew install pyenv and on Linux, use pyenv-installer
  • this gets you built-in virtualenv support as well as Python version switching (if required)
  • works well with Python 2 or 3, can have many versions installed at once

This works very well to insulate the "new Python" version and virtualenv from system Python. Because you can easily use a more recent Python (post 2.7.9), the SSL modules are already upgraded, and of course like any modern virtualenv setup you are insulated from the system Python modules.

A couple of nice tutorials:

The pyenv-virtualenv plugin is now built in - type pyenv commands | grep virtualenv to check. I wouldn't use the pyenv-virtualenvwrapper plugin to start with - see how you get on with pyenv-virtualenv which is more integrated into pyenv, as this covers most of what virtualenvwrapper does.

pyenv is modelled on rbenv (a good tool for Ruby version switching) and its only dependency is bash.

  • pyenv is unrelated to the very similarly named pyvenv - that is a virtualenv equivalent that's part of recent Python 3 versions, and doesn't handle Python version switching

Caveats

Two warnings about pyenv:

  1. It only works from a bash or similar shell - or more specifically, the pyenv-virtualenv plugin doesn't like dash, which is /bin/sh on Ubuntu or Debian.
  2. It must be run from an interactive login shell (e.g. bash --login using a terminal), which is not always easy to achieve with automation tools such as Ansible.

Hence pyenv is best for interactive use, and less good for scripting servers.

Older distributions - SSL module problems

One reason to use pyenv was that there were often problems with upgrading Python SSL modules when using older system-provided Python versions. This may be less of a problem now that current Linux distributions support Python 3.x.

Insert new item in array on any position in PHP

If you want to keep the keys of the initial array and also add an array that has keys, then use the function below:

function insertArrayAtPosition( $array, $insert, $position ) {
    /*
    $array : The initial array i want to modify
    $insert : the new array i want to add, eg array('key' => 'value') or array('value')
    $position : the position where the new array will be inserted into. Please mind that arrays start at 0
    */
    return array_slice($array, 0, $position, TRUE) + $insert + array_slice($array, $position, NULL, TRUE);
}

Call example:

$array = insertArrayAtPosition($array, array('key' => 'Value'), 3);

Where is SQL Server Management Studio 2012?

Select SQL Management Studio from the dropdown in Download SQL Server 2012 Express.

Git commit with no commit message

You don't need git to accomplish this. Creative use of a bash function will do the trick just fine. If you don't care about messages, just set a default one and forget it.

function gitcom() {
  git commit -m "my default commit message"
}

If you were feeling really adventurous you could add, commit and push with one command

function gitzap() {
  git add . && git commit -m "whatevs" && git push $1 $2
}

Which you would then run as

gitzap origin master

You could even get deeper and use parse_git_branch to save yourself some keystrokes there, or set a common default of "origin" and "master".

How to get HTTP response code for a URL in Java?

You could try the following:

class ResponseCodeCheck 
{

    public static void main (String args[]) throws Exception
    {

        URL url = new URL("http://google.com");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        int code = connection.getResponseCode();
        System.out.println("Response code of the object is "+code);
        if (code==200)
        {
            System.out.println("OK");
        }
    }
}

Manually highlight selected text in Notepad++

"Select your text, right click, then choose Style Token and then using 1st style (2nd style, etc …). At the moment is not possible to save the style tokens but there is an idea pending on Idea torrent you may vote for if your are interested in that."

It should be default, but it might be hidden.

"It might be that something happened to your contextMenu.xml so that you only get the basic standard. Have a look in NPPs config folder (%appdata%\Notepad++\) if the contextMenu.xml is there. If no: that would be the answer; if yes: it might be defect. Anyway you can grab the original standart contextMenu.xml from here and place it into the config folder (or replace the existing xml). Start NPP and you should have quite a long context menu. Tip: have a look at the contextmenu.xml itself - because you're allowed to change it to your own needs."

See this for more information

Change one value based on another value in pandas

You can use map, it can map vales from a dictonairy or even a custom function.

Suppose this is your df:

    ID First_Name Last_Name
0  103          a         b
1  104          c         d

Create the dicts:

fnames = {103: "Matt", 104: "Mr"}
lnames = {103: "Jones", 104: "X"}

And map:

df['First_Name'] = df['ID'].map(fnames)
df['Last_Name'] = df['ID'].map(lnames)

The result will be:

    ID First_Name Last_Name
0  103       Matt     Jones
1  104         Mr         X

Or use a custom function:

names = {103: ("Matt", "Jones"), 104: ("Mr", "X")}
df['First_Name'] = df['ID'].map(lambda x: names[x][0])

pull out p-values and r-squared from a linear regression

x = cumsum(c(0, runif(100, -1, +1)))
y = cumsum(c(0, runif(100, -1, +1)))
fit = lm(y ~ x)
> names(summary(fit))
[1] "call"          "terms"        
 [3] "residuals"     "coefficients" 
 [5] "aliased"       "sigma"        
 [7] "df"            "r.squared"    
 [9] "adj.r.squared" "fstatistic"   
[11] "cov.unscaled" 
    summary(fit)$r.squared

How to change colour of blue highlight on select box dropdown

i just found this site that give a cool themes for the select box http://gregfranko.com/jquery.selectBoxIt.js/

and you can try this themes if your problem with the overall look blue - yellow - grey

Uses of content-disposition in an HTTP response header

This header is defined in RFC 2183, so that would be the best place to start reading.

Permitted values are those registered with the Internet Assigned Numbers Authority (IANA); their registry of values should be seen as the definitive source.

Path to Powershell.exe (v 2.0)

I believe it's in C:\Windows\System32\WindowsPowershell\v1.0\. In order to confuse the innocent, MS kept it in a directory labeled "v1.0". Running this on Windows 7 and checking the version number via $Host.Version (Determine installed PowerShell version) shows it's 2.0.

Another option is type $PSVersionTable at the command prompt. If you are running v2.0, the output will be:

Name                           Value
----                           -----
CLRVersion                     2.0.50727.4927
BuildVersion                   6.1.7600.16385
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

If you're running version 1.0, the variable doesn't exist and there will be no output.

Localization PowerShell version 1.0, 2.0, 3.0, 4.0:

  • 64 bits version: C:\Windows\System32\WindowsPowerShell\v1.0\
  • 32 bits version: C:\Windows\SysWOW64\WindowsPowerShell\v1.0\

Freeing up a TCP/IP port?

To check all ports:

netstat -lnp

To close an open port:

fuser -k port_no/tcp

Example:

fuser -k 8080/tcp

In both cases you can use the sudo command if needed.

Reading a UTF8 CSV file with Python

If you want to read a CSV File with encoding utf-8, a minimalistic approach that I recommend you is to use something like this:

with open(file_name, encoding="utf8") as csv_file:

With that statement, you can use later a CSV reader to work with.

Apply .gitignore on an existing repository already tracking large number of files

Here is one way to “untrack” any files that are would otherwise be ignored under the current set of exclude patterns:

(GIT_INDEX_FILE=some-non-existent-file \
git ls-files --exclude-standard --others --directory --ignored -z) |
xargs -0 git rm --cached -r --ignore-unmatch --

This leaves the files in your working directory but removes them from the index.

The trick used here is to provide a non-existent index file to git ls-files so that it thinks there are no tracked files. The shell code above asks for all the files that would be ignored if the index were empty and then removes them from the actual index with git rm.

After the files have been “untracked”, use git status to verify that nothing important was removed (if so adjust your exclude patterns and use git reset -- path to restore the removed index entry). Then make a new commit that leaves out the “crud”.

The “crud” will still be in any old commits. You can use git filter-branch to produce clean versions of the old commits if you really need a clean history (n.b. using git filter-branch will “rewrite history”, so it should not be undertaken lightly if you have any collaborators that have pulled any of your historical commits after the “crud” was first introduced).

Offset a background image from the right using CSS

use center right as the position then add a transparent border to offset it?

How to pass credentials to httpwebrequest for accessing SharePoint Library

You could also use:

request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 

How can I map True/False to 1/0 in a Pandas DataFrame?

True is 1 in Python, and likewise False is 0*:

>>> True == 1
True
>>> False == 0
True

You should be able to perform any operations you want on them by just treating them as though they were numbers, as they are numbers:

>>> issubclass(bool, int)
True
>>> True * 5
5

So to answer your question, no work necessary - you already have what you are looking for.

* Note I use is as an English word, not the Python keyword is - True will not be the same object as any random 1.

How to dismiss keyboard iOS programmatically when pressing return

Simply use this in Objective-C to dismiss keyboard:

[[UIApplication sharedApplication].keyWindow endEditing:YES];

Find if current time falls in a time range

Try using the TimeRange object in C# to complete your goal.

TimeRange timeRange = new TimeRange();
timeRange = TimeRange.Parse("13:00-14:00");

bool IsNowInTheRange = timeRange.IsIn(DateTime.Now.TimeOfDay);
Console.Write(IsNowInTheRange);

Here is where I got that example of using TimeRange

Launch Minecraft from command line - username and password as prefix

Those are all ways to start the standard minecraft launcher with those credentials in the text boxes.

There used to be a way to login to minecraft without the launcher using the command line, but it has since been patched.

If you want to make a custom launcher using the command line then good luck, the only way to login to the minecraft jar(IE: the way the launcher does it) is to send a post request to https://login.minecraft.net/ with the username,password,launcher version, and a RSA key. It then parses the pseudo Json, and uses the session token from that to authenticate the jar from the command line with a load of arguments.

If you are trying to make a minecraft launcher and you have no knowledge of java,http requests or json then you have no chance.

Swift

What is PHPSESSID?

It's the identifier for your current session in PHP. If you delete it, you won't be able to access/make use of session variables. I'd suggest you keep it.

Strings in C, how to get subString

Generalized:

char* subString (const char* input, int offset, int len, char* dest)
{
  int input_len = strlen (input);

  if (offset + len > input_len)
  {
     return NULL;
  }

  strncpy (dest, input + offset, len);
  return dest;
}

char dest[80];
const char* source = "hello world";

if (subString (source, 0, 5, dest))
{
  printf ("%s\n", dest);
}

Show MySQL host via SQL Command

show variables where Variable_name='hostname'; 

That could help you !!

How do I perform the SQL Join equivalent in MongoDB?

Before 3.2.6, Mongodb does not support join query as like mysql. below solution which works for you.

 db.getCollection('comments').aggregate([
        {$match : {pid : 444}},
        {$lookup: {from: "users",localField: "uid",foreignField: "uid",as: "userData"}},
   ])

How to disable back swipe gesture in UINavigationController on iOS 7

It worked for me for most of the viewcontrollers.

self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false

It wasn't not working for some viewcontrollers like UIPageViewController. On UIPageViewController's pagecontentviewcontroller below code worked for me.

override func viewDidLoad() {
   self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
   self.navigationController?.interactivePopGestureRecognizer?.delegate = self
}
override func viewWillDisappear(_ animated: Bool) {
   self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
   self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
}

On UIGestureRecognizerDelegate,

func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
   if gestureRecognizer == self.navigationController?.interactivePopGestureRecognizer {
      return false
}
      return true
}

Combine hover and click functions (jQuery)?

var hoverAndClick = function() {
    // Your actions here
} ;

$("#target").hover( hoverAndClick ).click( hoverAndClick ) ;

Invalid length parameter passed to the LEFT or SUBSTRING function

This is because the CHARINDEX-1 is returning a -ive value if the look-up for " " (space) is 0. The simplest solution would be to avoid '-ve' by adding

ABS(CHARINDEX(' ', PostCode ) -1))

which will return only +ive values for your length even if CHARINDEX(' ', PostCode ) -1) is a -ve value. Correct me if I'm wrong!

Save plot to image file instead of displaying it using Matplotlib

If, like me, you use Spyder IDE, you have to disable the interactive mode with :

plt.ioff()

(this command is automatically launched with the scientific startup)

If you want to enable it again, use :

plt.ion()

Xcode 6.1 - How to uninstall command line tools?

If you installed the command line tools separately, delete them using:

sudo rm -rf /Library/Developer/CommandLineTools

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

Ask the person maintaining the server at http://172.16.1.157:8002/ to add your hostname to Access-Control-Allow-Origin hosts, the server should return a header similar to the following with the response-

Access-Control-Allow-Origin: yourhostname:port

Python: printing a file to stdout

Sure. Assuming you have a string with the file's name called fname, the following does the trick.

with open(fname, 'r') as fin:
    print(fin.read())

Is it possible to convert char[] to char* in C?

If you have char[] c then you can do char* d = &c[0] and access element c[1] by doing *(d+1), etc.

Check if a String contains numbers Java

You can try this

String text = "ddd123.0114cc";
    String numOnly = text.replaceAll("\\p{Alpha}","");
    try {
        double numVal = Double.valueOf(numOnly);
        System.out.println(text +" contains numbers");
    } catch (NumberFormatException e){
        System.out.println(text+" not contains numbers");
    }     

Cannot start MongoDB as a service

For mongoDB 3.0, You will have to set the following in the config file.

logpath=E:\mongoDBdata\log\mongoDB.log
dbpath=E:\mongoDBdata\db

the logpath should end with a file and not a folder.

Apply pandas function to column to create multiple new columns?

This is the correct and easiest way to accomplish this for 95% of use cases:

>>> df = pd.DataFrame(zip(*[range(10)]), columns=['num'])
>>> df
    num
0    0
1    1
2    2
3    3
4    4
5    5

>>> def example(x):
...     x['p1'] = x['num']**2
...     x['p2'] = x['num']**3
...     x['p3'] = x['num']**4
...     return x

>>> df = df.apply(example, axis=1)
>>> df
    num  p1  p2  p3
0    0   0   0    0
1    1   1   1    1
2    2   4   8   16
3    3   9  27   81
4    4  16  64  256

How can I change the version of npm using nvm?

What about npm i -g npm? Did you try to run this as well?

Regex Until But Not Including

A lookahead regex syntax can help you to achieve your goal. Thus a regex for your example is

.*?quick.*?(?=z)

And it's important to notice the .*? lazy matching before the (?=z) lookahead: the expression matches a substring until a first occurrence of the z letter.

Here is C# code sample:

const string text = "The quick red fox jumped over the lazy brown dogz";

string lazy = new Regex(".*?quick.*?(?=z)").Match(text).Value;
Console.WriteLine(lazy); // The quick red fox jumped over the la

string greedy = new Regex(".*?quick.*(?=z)").Match(text).Value;
Console.WriteLine(greedy); // The quick red fox jumped over the lazy brown dog

How to enable curl in xampp?

In XAMPP installation directory, open %XAMPP_HOME%/php/php.ini file. Uncomment the following line: extension=php_curl.dll

PS: If that doesn't work then check whether %XAMPP_HOME%/php/ext/php_curl.dll file exist or not.

SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

I suggest you to do:

chmod 400 ~/.ssh/id_rsa

It works fine for me.

Activate a virtualenv with a Python script

If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the Python interpreter that lives inside virtualenv's /bin/ directory:

import subprocess

# Path to a Python interpreter that runs any Python script
# under the virtualenv /path/to/virtualenv/
python_bin = "/path/to/virtualenv/bin/python"

# Path to the script that must run under the virtualenv
script_file = "must/run/under/virtualenv/script.py"

subprocess.Popen([python_bin, script_file])

However, if you want to activate the virtualenv under the current Python interpreter instead of a subprocess, you can use the activate_this.py script:

# Doing execfile() on this file will alter the current interpreter's
# environment so you can import libraries in the virtualenv
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"

execfile(activate_this_file, dict(__file__=activate_this_file))

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

java Arrays.sort 2d array

much simpler code:

import java.util.Arrays; int[][] array = new int[][];

Arrays.sort(array, ( a, b) -> a[1] - b[1]);

How can I change the Java Runtime Version on Windows (7)?

Since Java 1.6, a java.exe is installed into %windir%\system32 that supports a "-version" command line option. You can use this to select a specific version to run, e.g.:

java -version:1.7 -jar [path to jar file]

will run a jar application in java 1.7, if it is installed.

See Oracle's documentation here: http://docs.oracle.com/javase/6/docs/technotes/tools/windows/java.html

How to get a function name as a string?

As an extension of @Demyn's answer, I created some utility functions which print the current function's name and current function's arguments:

import inspect
import logging
import traceback

def get_function_name():
    return traceback.extract_stack(None, 2)[0][2]

def get_function_parameters_and_values():
    frame = inspect.currentframe().f_back
    args, _, _, values = inspect.getargvalues(frame)
    return ([(i, values[i]) for i in args])

def my_func(a, b, c=None):
    logging.info('Running ' + get_function_name() + '(' + str(get_function_parameters_and_values()) +')')
    pass

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
    '%(asctime)s [%(levelname)s] -> %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)

my_func(1, 3) # 2016-03-25 17:16:06,927 [INFO] -> Running my_func([('a', 1), ('b', 3), ('c', None)])

How do I get a list of installed CPAN modules?

Try "perldoc -l":

$ perldoc -l Log::Dispatch /usr/local/share/perl/5.26.1/Log/Dispatch.pm

How to add action listener that listens to multiple buttons

First, exend JFrame properly with a super() and a constructor then add actionlisteners to the frame and add the buttons.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;


public class Calc extends JFrame implements ActionListener {
    JButton button1 = new JButton("1");
    JButton button2 = new JButton("2");

    public Calc()
    {
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setSize(100, 100);
         button1.addActionListener(this);
         button2.addActionListener(this);
         calcFrame.add(button1);
         calcFrame.add(button2);
    }
    public void actionPerformed(ActionEvent e)
    {
        Object source = e.getSource();
        if(source == button1)
        {
            \\button1 code here
        } else if(source == button2)
        {
            \\button2 code here
        }
    } 
    public static void main(String[] args)
    {

        JFrame calcFrame = new JFrame();
        calcFrame.setVisible(true);
    }
}