Programs & Examples On #Mission critical

Mission-Critical is a term that refers to something that is indispensable.

Globally catch exceptions in a WPF application?

Like "VB's On Error Resume Next?" That sounds kind of scary. First recommendation is don't do it. Second recommendation is don't do it and don't think about it. You need to isolate your faults better. As to how to approach this problem, it depends on how you're code is structured. If you are using a pattern like MVC or the like then this shouldn't be too difficult and would definitely not require a global exception swallower. Secondly, look for a good logging library like log4net or use tracing. We'd need to know more details like what kinds of exceptions you're talking about and what parts of your application may result in exceptions being thrown.

How to measure time elapsed on Javascript?

var seconds = 0;
setInterval(function () {
  seconds++;
}, 1000);

There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.

Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.

You could also solve this by saving and comparing times.

EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.

HttpClient not supporting PostAsJsonAsync method C#

The missing reference is the System.Net.Http.Formatting.dll. But the better solution is to add the NuGet package Microsoft.AspNet.WebApi.Client to ensure the version of the formatting dll worked with the .NET framework version of System.Net.Http in my project.

How to get a random number in Ruby

Well, I figured it out. Apparently there is a builtin (?) function called rand:

rand(n + 1)

If someone answers with a more detailed answer, I'll mark that as the correct answer.

Is 'bool' a basic datatype in C++?

Yes, bool is a built-in type.

WIN32 is C code, not C++, and C does not have a bool, so they provide their own typedef BOOL.

Show all tables inside a MySQL database using PHP?

SHOW TABLE_NAME is not valid. Try SHOW TABLES

TD

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.

How to get the current branch name in Git?

git branch | grep -e "^*" | cut -d' ' -f 2

will show only the branch name

CryptographicException 'Keyset does not exist', but only through WCF

I just reinstalled my certificate in local machine and then it is working fine

NSRange from Swift Range?

Swift 4

I think, there are two ways.

1. NSRange(range, in: )

2. NSRange(location:, length: )

Sample code:

let attributedString = NSMutableAttributedString(string: "Sample Text 12345", attributes: [.font : UIFont.systemFont(ofSize: 15.0)])

// NSRange(range, in: )
if let range = attributedString.string.range(of: "Sample")  {
    attributedString.addAttribute(.foregroundColor, value: UIColor.orange, range: NSRange(range, in: attributedString.string))
}

// NSRange(location: , length: )
if let range = attributedString.string.range(of: "12345") {
    attributedString.addAttribute(.foregroundColor, value: UIColor.green, range: NSRange(location: range.lowerBound.encodedOffset, length: range.upperBound.encodedOffset - range.lowerBound.encodedOffset))
}

Screen Shot: enter image description here

How to check if a string starts with a specified string?

There is also the strncmp() function and strncasecmp() function which is perfect for this situation:

if (strncmp($string_n, "http", 4) === 0)

In general:

if (strncmp($string_n, $prefix, strlen($prefix)) === 0)

The advantage over the substr() approach is that strncmp() just does what needs to be done, without creating a temporary string.

Instagram: Share photo from webpage

Updated June 2020

It is no longer possible... allegedly. If you have a Facebook or Instagram dedicated contact (because you work in either a big agency or with a big client) it may potentially be possible depending on your use case, but it's highly discouraged.


Before December 2019:

It is now "possible":

https://developers.facebook.com/docs/instagram-api/content-publishing

The Content Publishing API is a subset of Instagram Graph API endpoints that allow you to publish media objects. Publishing media objects with this API is a two step process — you first create a media object container, then publish the container on your Business Account.

Its worth noting that "The Content Publishing API is in closed beta with Facebook Marketing Partners and Instagram Partners only. We are not accepting new applicants at this time." from https://stackoverflow.com/a/49677468/445887

Visual Studio Code open tab in new window

When I want to split the screens I usually do one of the following:

  1. open new window with: Ctrl+Shift+N
    and after that I drag the current file I want to the new window.
  2. on the File explorer - I hit Ctrl+Enter on the file I want - and then this file and the other file open together in the same screen but in split mode, so you can see the two files together. If the screen is wide enough this is not a bad solution at all that you can get used to.

SOAP vs REST (differences)

What is REST

REST stands for representational state transfer, it's actually an architectural style for creating Web API which treats everything(data or functionality) as recourse. It expects; exposing resources through URI and responding in multiple formats and representational transfer of state of the resources in stateless manner. Here I am talking about two things:

  1. Stateless manner: Provided by HTTP.
  2. Representational transfer of state: For example if we are adding an employee. . into our system, it's in POST state of HTTP, after this it would be in GET state of HTTP, PUT and DELETE likewise.

REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP.SOAP uses services interfaces to expose the business logic. REST uses URI to expose business logic.

REST is not REST without HATEOAS. This means that a client only knows the entry point URI and the resources are supposed to return links the client should follow. Those fancy documentation generators that give URI patterns for everything you can do in a REST API miss the point completely. They are not only documenting something that's supposed to be following the standard, but when you do that, you're coupling the client to one particular moment in the evolution of the API, and any changes on the API have to be documented and applied, or it will break.

HATEOAS, an abbreviation for Hypermedia As The Engine Of Application State, is a constraint of the REST application architecture that distinguishes it from most other network application architectures. The principle is that a client interacts with a network application entirely through hypermedia provided dynamically by application servers. A REST client needs no prior knowledge about how to interact with any particular application or server beyond a generic understanding of hypermedia. By contrast, in some service-oriented architectures (SOA), clients and servers interact through a fixed interface shared through documentation or an interface description language (IDL).

Reference 1 Reference 2

how to draw directed graphs using networkx in python?

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_node("A")
G.add_node("B")
G.add_node("C")
G.add_node("D")
G.add_node("E")
G.add_node("F")
G.add_node("G")
G.add_edge("A","B")
G.add_edge("B","C")
G.add_edge("C","E")
G.add_edge("C","F")
G.add_edge("D","E")
G.add_edge("F","G")

print(G.nodes())
print(G.edges())

pos = nx.spring_layout(G)

nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edge_color='r', arrows = True)

plt.show()

Remove file extension from a file name string

    /// <summary>
    /// Get the extension from the given filename
    /// </summary>
    /// <param name="fileName">the given filename ie:abc.123.txt</param>
    /// <returns>the extension ie:txt</returns>
    public static string GetFileExtension(this string fileName)
    {
        string ext = string.Empty;
        int fileExtPos = fileName.LastIndexOf(".", StringComparison.Ordinal);
        if (fileExtPos >= 0)
            ext = fileName.Substring(fileExtPos, fileName.Length - fileExtPos);

        return ext;
    }

Convert string (without any separator) to list

Make a list(your_string).

>>> s = "mep"
>>> list(s)
['m', 'e', 'p']

How to specify a port number in SQL Server connection string?

The correct SQL connection string for SQL with specify port is use comma between ip address and port number like following pattern: xxx.xxx.xxx.xxx,yyyy

What is a mixin, and why are they useful?

I'd advise against mix-ins in new Python code, if you can find any other way around it (such as composition-instead-of-inheritance, or just monkey-patching methods into your own classes) that isn't much more effort.

In old-style classes you could use mix-ins as a way of grabbing a few methods from another class. But in the new-style world everything, even the mix-in, inherits from object. That means that any use of multiple inheritance naturally introduces MRO issues.

There are ways to make multiple-inheritance MRO work in Python, most notably the super() function, but it means you have to do your whole class hierarchy using super(), and it's considerably more difficult to understand the flow of control.

Java Process with Input/Output Stream

You have writer.close(); in your code. So bash receives EOF on its stdin and exits. Then you get Broken pipe when trying to read from the stdoutof the defunct bash.

How to insert a picture into Excel at a specified cell position with VBA

Looking at posted answers I think this code would be also an alternative for someone. Nobody above used .Shapes.AddPicture in their code, only .Pictures.Insert()

Dim myPic As Object
Dim picpath As String

picpath = "C:\Users\photo.jpg" 'example photo path

Set myPic = ws.Shapes.AddPicture(picpath, False, True, 20, 20, -1, -1)

With myPic
    .Width = 25
    .Height = 25
    .Top = xlApp.Cells(i, 20).Top 'according to variables from correct answer
    .Left = xlApp.Cells(i, 20).Left
    .LockAspectRatio = msoFalse
End With

I'm working in Excel 2013. Also realized that You need to fill all the parameters in .AddPicture, because of error "Argument not optional". Looking at this You may ask why I set Height and Width as -1, but that doesn't matter cause of those parameters are set underneath between With brackets.

Hope it may be also useful for someone :)

How can I check if PostgreSQL is installed or not via Linux script?

We can simply write:

psql --version

output show like:

psql (PostgreSQL) 11.5 (Ubuntu 11.5-1.pgdg18.04+1)

What is PEP8's E128: continuation line under-indented for visual indent?

This goes also for statements like this (auto-formatted by PyCharm):

    return combine_sample_generators(sample_generators['train']), \
           combine_sample_generators(sample_generators['dev']), \
           combine_sample_generators(sample_generators['test'])

Which will give the same style-warning. In order to get rid of it I had to rewrite it to:

    return \
        combine_sample_generators(sample_generators['train']), \
        combine_sample_generators(sample_generators['dev']), \
        combine_sample_generators(sample_generators['test'])

Are iframes considered 'bad practice'?

There are definitely uses for iframes folks. How else would you put the weather networks widget on your page? The only other way is to grab their XML and parse it, but then of course you need conditions to throw up the pertenant weather graphics... not really worth it, but way cleaner if you have the time.

Split comma separated column data into additional columns

If the number of fields in the CSV is constant then you could do something like this:

select a[1], a[2], a[3], a[4]
from (
    select regexp_split_to_array('a,b,c,d', ',')
) as dt(a)

For example:

=> select a[1], a[2], a[3], a[4] from (select regexp_split_to_array('a,b,c,d', ',')) as dt(a);
 a | a | a | a 
---+---+---+---
 a | b | c | d
(1 row)

If the number of fields in the CSV is not constant then you could get the maximum number of fields with something like this:

select max(array_length(regexp_split_to_array(csv, ','), 1))
from your_table

and then build the appropriate a[1], a[2], ..., a[M] column list for your query. So if the above gave you a max of 6, you'd use this:

select a[1], a[2], a[3], a[4], a[5], a[6]
from (
    select regexp_split_to_array(csv, ',')
    from your_table
) as dt(a)

You could combine those two queries into a function if you wanted.

For example, give this data (that's a NULL in the last row):

=> select * from csvs;
     csv     
-------------
 1,2,3
 1,2,3,4
 1,2,3,4,5,6

(4 rows)

=> select max(array_length(regexp_split_to_array(csv, ','), 1)) from csvs;
 max 
-----
   6
(1 row)

=> select a[1], a[2], a[3], a[4], a[5], a[6] from (select regexp_split_to_array(csv, ',') from csvs) as dt(a);
 a | a | a | a | a | a 
---+---+---+---+---+---
 1 | 2 | 3 |   |   | 
 1 | 2 | 3 | 4 |   | 
 1 | 2 | 3 | 4 | 5 | 6
   |   |   |   |   | 
(4 rows)

Since your delimiter is a simple fixed string, you could also use string_to_array instead of regexp_split_to_array:

select ...
from (
    select string_to_array(csv, ',')
    from csvs
) as dt(a);

Thanks to Michael for the reminder about this function.

You really should redesign your database schema to avoid the CSV column if at all possible. You should be using an array column or a separate table instead.

MVC DateTime binding with incorrect date format

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var str = controllerContext.HttpContext.Request.QueryString[bindingContext.ModelName];
    if (string.IsNullOrEmpty(str)) return null;
    var date = DateTime.ParseExact(str, "dd.MM.yyyy", null);
    return date;
}

When to use single quotes, double quotes, and backticks in MySQL

In MySQL, these symbols are used to delimit a query ` ," ,' and () .

  1. " or ' are used for enclosing string-like values "26-01-2014 00:00:00" or '26-01-2014 00:00:00' . These symbols are only for strings, not aggregate functions like now, sum, or max.

  2. ` is used for enclosing table or column names, e.g. select `column_name` from `table_name` where id='2'

  3. ( and ) simply enclose parts of a query e.g. select `column_name` from `table_name` where (id='2' and gender='male') or name='rakesh' .

Convert string to JSON Object

Your string is not valid. Double quots cannot be inside double quotes. You should escape them:

"{\"TeamList\" : [{\"teamid\" : \"1\",\"teamname\" : \"Barcelona\"}]}"

or use single quotes and double quotes

'{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}'

Unknown version of Tomcat was specified in Eclipse

I know this is and oldie but i had this issue recently with the latest versions of Tomcat and Eclipse on Windows 10.

It was a permissions issue. All i had to do was navigate to the Tomcat install directory and open the folder. I was prompted to access the folder as an Administrator.

After this the versions were recognised by Eclipse and I could add the new runtime.

Can I change the scroll speed using css or jQuery?

The scroll speed CAN be changed, adjusted, reversed, all of the above - via javascript (or a js library such as jQuery).

WHY would you want to do this? Parallax is just one of the reasons. I have no idea why anyone would argue against doing so -- the same negative arguments can be made against hiding DIVs, sliding elements up/down, etc. Websites are always a combination of technical functionality and UX design -- a good designer can use almost any technical capability to improve UX. That is what makes him/her good.

Toni Almeida of Portugal created a brilliant demo, reproduced below:

jsFiddle Demo

HTML:

<div id="myDiv">
    Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. <span class="boldit">Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. </span>
</div>

javascript/jQuery:

  function wheel(event) {
      var delta = 0;
      if (event.wheelDelta) {(delta = event.wheelDelta / 120);}
      else if (event.detail) {(delta = -event.detail / 3);}

      handle(delta);
      if (event.preventDefault) {(event.preventDefault());}
      event.returnValue = false;
  }

  function handle(delta) {
      var time = 1000;
      var distance = 300;

      $('html, body').stop().animate({
          scrollTop: $(window).scrollTop() - (distance * delta)
      }, time );
  }

  if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);}
    window.onmousewheel = document.onmousewheel = wheel;

Source:

How to change default scrollspeed,scrollamount,scrollinertia of a webpage

Start ssh-agent on login

Users of the fish shell can use this script to do the same thing.

# content has to be in .config/fish/config.fish
# if it does not exist, create the file
setenv SSH_ENV $HOME/.ssh/environment

function start_agent                                                                                                                                                                    
    echo "Initializing new SSH agent ..."
    ssh-agent -c | sed 's/^echo/#echo/' > $SSH_ENV
    echo "succeeded"
    chmod 600 $SSH_ENV 
    . $SSH_ENV > /dev/null
    ssh-add
end

function test_identities                                                                                                                                                                
    ssh-add -l | grep "The agent has no identities" > /dev/null
    if [ $status -eq 0 ]
        ssh-add
        if [ $status -eq 2 ]
            start_agent
        end
    end
end

if [ -n "$SSH_AGENT_PID" ] 
    ps -ef | grep $SSH_AGENT_PID | grep ssh-agent > /dev/null
    if [ $status -eq 0 ]
        test_identities
    end  
else
    if [ -f $SSH_ENV ]
        . $SSH_ENV > /dev/null
    end  
    ps -ef | grep $SSH_AGENT_PID | grep -v grep | grep ssh-agent > /dev/null
    if [ $status -eq 0 ]
        test_identities
    else 
        start_agent
    end  
end

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

Ajax UpdatePanel makes it, and I think it's the easiest way, ignoring the Ajax postback overhead.

How to import NumPy in the Python shell

On Debian/Ubuntu:

aptitude install python-numpy

On Windows, download the installer:

http://sourceforge.net/projects/numpy/files/NumPy/

On other systems, download the tar.gz and run the following:

$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install

runOnUiThread in fragment

You can also post runnable using the view from any other thread. But be sure that the view is not null:

 tView.post(new Runnable() {
                    @Override
                    public void run() {
                        tView.setText("Success");
                    }
                });

According to the Documentation:

"boolean post (Runnable action) Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread."

Reading a cell value in Excel vba and write in another Cell

I have this function for this case ..

Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean

c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
  Select Case Mid(c, x, 1)
    Case ":":    bNum = True
    Case " ": Exit For
    Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
  End Select
Next
GetValue = val(nRet)
End Function

To fill cell BC .. (assumed that you check cell A1)

Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")

java.text.ParseException: Unparseable date

        String date="Sat Jun 01 12:53:10 IST 2013";
        SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
        Date currentdate=sdf.parse(date);
        SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");
        System.out.println(sdf2.format(currentdate));

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

How do you handle a form change in jQuery?

_x000D_
_x000D_
$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {_x000D_
  $("#result").html($(this).val());_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h2>Form "your_form_name"</h2>_x000D_
<form name="your_form_name">_x000D_
  <input type="text" name="one_a" id="one_a" value="AAAAAAAA" />_x000D_
  <input type="text" name="one_b" id="one_b" value="BBBBBBBB" />_x000D_
  <input type="text" name="one_c" id="one_c" value="CCCCCCCC" />_x000D_
  <select name="one_d">_x000D_
    <option value="111111">111111</option>_x000D_
    <option value="222222">222222</option>_x000D_
    <option value="333333">333333</option>_x000D_
  </select>_x000D_
</form>_x000D_
<hr/>_x000D_
<h2>Form "your_other_form_name"</h2>_x000D_
<form name="your_other_form_name">_x000D_
  <input type="text" name="two_a" id="two_a" value="DDDDDDDD" />_x000D_
  <input type="text" name="two_b" id="two_b" value="EEEEEEEE" />_x000D_
  <input type="text" name="two_c" id="two_c" value="FFFFFFFF" />_x000D_
  <input type="text" name="two_d" id="two_d" value="GGGGGGGG" />_x000D_
  <input type="text" name="two_e" id="two_f" value="HHHHHHHH" />_x000D_
  <input type="text" name="two_f" id="two_e" value="IIIIIIII" />_x000D_
  <select name="two_g">_x000D_
    <option value="444444">444444</option>_x000D_
    <option value="555555">555555</option>_x000D_
    <option value="666666">666666</option>_x000D_
  </select>_x000D_
</form>_x000D_
<h2>Result</h2>_x000D_
<div id="result">_x000D_
  <h2>Click on a field..</h2>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In addition to above @JoeD's answer.

If you want to target fields in a particular form (assuming there are more than one forms) than just fields, you can use the following code:

$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
    // A form element was clicked
});

How to simulate a real mouse click using java?

You could create a simple AutoIt Script that does the job for you, compile it as an executable and perform a system call there.

in au3 Script:

; how to use: MouseClick ( "button" [, x, y [, clicks = 1 [, speed = 10]]] )
MouseClick ( "left" , $CmdLine[1], $CmdLine[1] )

Now find aut2exe in your au3 Folder or find 'Compile Script to .exe' in your Start Menu and create an executable.

in your Java class call:

Runtime.getRuntime().exec(
    new String[]{
        "yourscript.exe", 
        String.valueOf(mypoint.x),
        String.valueOf(mypoint.y)}
);

AutoIt will behave as if it was a human and won't be detected as a machine.

Find AutoIt here: https://www.autoitscript.com/

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

sudo apt-get -y install python-software-properties && \
sudo apt-get -y install software-properties-common && \
sudo apt-get -y install gcc make build-essential libssl-dev libffi-dev python-dev

You need the libssl-dev and libffi-dev if especially you are trying to install python's cryptography libraries or python libs that depend on it(eg ansible)

How to find which git branch I am on when my disk is mounted on other server

Our git repo disk is mounted on AIX box to do BUILD.

It sounds like you mounted the drive on which the git repository is stored on another server, and you are asking how to modify that. If that is the case, this is a bad idea.

The build server should have its own copy of the git repository, and it will be locally managed by git on the build server. The build server's repository will be connected to the "main" git repository with a "remote", and you can issue the command git pull to update the local repository on the build server.

If you don't want to go to the trouble of setting up SSH or a gitolite server or something similar, you can use a file path as the "remote" location. So you could continue to mount the Linux server's file system on the build server, but instead of running the build out of that mounted path, clone the repository into another folder and run it from there.

Global keyboard capture in C# application

As requested by dube I'm posting my modified version of Siarhei Kuchuk's answer.
If you want to check my changes search for // EDT. I've commented most of it.

The Setup

class GlobalKeyboardHookEventArgs : HandledEventArgs
{
    public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
    public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }

    public GlobalKeyboardHookEventArgs(
        GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
        GlobalKeyboardHook.KeyboardState keyboardState)
    {
        KeyboardData = keyboardData;
        KeyboardState = keyboardState;
    }
}

//Based on https://gist.github.com/Stasonix
class GlobalKeyboardHook : IDisposable
{
    public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;

    // EDT: Added an optional parameter (registeredKeys) that accepts keys to restict
    // the logging mechanism.
    /// <summary>
    /// 
    /// </summary>
    /// <param name="registeredKeys">Keys that should trigger logging. Pass null for full logging.</param>
    public GlobalKeyboardHook(Keys[] registeredKeys = null)
    {
        RegisteredKeys = registeredKeys;
        _windowsHookHandle = IntPtr.Zero;
        _user32LibraryHandle = IntPtr.Zero;
        _hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

        _user32LibraryHandle = LoadLibrary("User32");
        if (_user32LibraryHandle == IntPtr.Zero)
        {
            int errorCode = Marshal.GetLastWin32Error();
            throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
        }



        _windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
        if (_windowsHookHandle == IntPtr.Zero)
        {
            int errorCode = Marshal.GetLastWin32Error();
            throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
        }
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // because we can unhook only in the same thread, not in garbage collector thread
            if (_windowsHookHandle != IntPtr.Zero)
            {
                if (!UnhookWindowsHookEx(_windowsHookHandle))
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
                }
                _windowsHookHandle = IntPtr.Zero;

                // ReSharper disable once DelegateSubtraction
                _hookProc -= LowLevelKeyboardProc;
            }
        }

        if (_user32LibraryHandle != IntPtr.Zero)
        {
            if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }
            _user32LibraryHandle = IntPtr.Zero;
        }
    }

    ~GlobalKeyboardHook()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private IntPtr _windowsHookHandle;
    private IntPtr _user32LibraryHandle;
    private HookProc _hookProc;

    delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll")]
    private static extern IntPtr LoadLibrary(string lpFileName);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    private static extern bool FreeLibrary(IntPtr hModule);

    /// <summary>
    /// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
    /// You would install a hook procedure to monitor the system for certain types of events. These events are
    /// associated either with a specific thread or with all threads in the same desktop as the calling thread.
    /// </summary>
    /// <param name="idHook">hook type</param>
    /// <param name="lpfn">hook procedure</param>
    /// <param name="hMod">handle to application instance</param>
    /// <param name="dwThreadId">thread identifier</param>
    /// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
    [DllImport("USER32", SetLastError = true)]
    static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);

    /// <summary>
    /// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
    /// </summary>
    /// <param name="hhk">handle to hook procedure</param>
    /// <returns>If the function succeeds, the return value is true.</returns>
    [DllImport("USER32", SetLastError = true)]
    public static extern bool UnhookWindowsHookEx(IntPtr hHook);

    /// <summary>
    /// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
    /// A hook procedure can call this function either before or after processing the hook information.
    /// </summary>
    /// <param name="hHook">handle to current hook</param>
    /// <param name="code">hook code passed to hook procedure</param>
    /// <param name="wParam">value passed to hook procedure</param>
    /// <param name="lParam">value passed to hook procedure</param>
    /// <returns>If the function succeeds, the return value is true.</returns>
    [DllImport("USER32", SetLastError = true)]
    static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);

    [StructLayout(LayoutKind.Sequential)]
    public struct LowLevelKeyboardInputEvent
    {
        /// <summary>
        /// A virtual-key code. The code must be a value in the range 1 to 254.
        /// </summary>
        public int VirtualCode;

        // EDT: added a conversion from VirtualCode to Keys.
        /// <summary>
        /// The VirtualCode converted to typeof(Keys) for higher usability.
        /// </summary>
        public Keys Key { get { return (Keys)VirtualCode; } }

        /// <summary>
        /// A hardware scan code for the key. 
        /// </summary>
        public int HardwareScanCode;

        /// <summary>
        /// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
        /// </summary>
        public int Flags;

        /// <summary>
        /// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
        /// </summary>
        public int TimeStamp;

        /// <summary>
        /// Additional information associated with the message. 
        /// </summary>
        public IntPtr AdditionalInformation;
    }

    public const int WH_KEYBOARD_LL = 13;
    //const int HC_ACTION = 0;

    public enum KeyboardState
    {
        KeyDown = 0x0100,
        KeyUp = 0x0101,
        SysKeyDown = 0x0104,
        SysKeyUp = 0x0105
    }

    // EDT: Replaced VkSnapshot(int) with RegisteredKeys(Keys[])
    public static Keys[] RegisteredKeys;
    const int KfAltdown = 0x2000;
    public const int LlkhfAltdown = (KfAltdown >> 8);

    public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
    {
        bool fEatKeyStroke = false;

        var wparamTyped = wParam.ToInt32();
        if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
        {
            object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
            LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;

            var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);

            // EDT: Removed the comparison-logic from the usage-area so the user does not need to mess around with it.
            // Either the incoming key has to be part of RegisteredKeys (see constructor on top) or RegisterdKeys
            // has to be null for the event to get fired.
            var key = (Keys)p.VirtualCode;
            if (RegisteredKeys == null || RegisteredKeys.Contains(key))
            {
                EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
                handler?.Invoke(this, eventArguments);

                fEatKeyStroke = eventArguments.Handled;
            }
        }

        return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
    }
}

The Usage differences can be seen here

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private GlobalKeyboardHook _globalKeyboardHook;

    private void buttonHook_Click(object sender, EventArgs e)
    {
        // Hooks only into specified Keys (here "A" and "B").
        _globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });

        // Hooks into all keys.
        _globalKeyboardHook = new GlobalKeyboardHook();
        _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
    }

    private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
    {
        // EDT: No need to filter for VkSnapshot anymore. This now gets handled
        // through the constructor of GlobalKeyboardHook(...).
        if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown)
        {
            // Now you can access both, the key and virtual code
            Keys loggedKey = e.KeyboardData.Key;
            int loggedVkCode = e.KeyboardData.VirtualCode;
        }
    }
}

Thanks to Siarhei Kuchuk for his post. Even tho I've simplified the usage this initial code was very useful for me.

File uploading with Express 4.0: req.files undefined

1) Make sure that your file is really sent from the client side. For example you can check it in Chrome Console: screenshot

2) Here is the basic example of NodeJS backend:

const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();

app.use(fileUpload()); // Don't forget this line!

app.post('/upload', function(req, res) {
   console.log(req.files);
   res.send('UPLOADED!!!');
});

How to set scope property with ng-init?

HTML:

<body ng-app="App">
    <div ng-controller="testController" >
        <input type="hidden" id="testInput" ng-model="testInput" ng-init="testInput=123" />
    </div>
    {{ testInput }}
</body>

JS:

angular.module('App', []);

testController = function ($scope) {
    console.log('test');
    $scope.$watch('testInput', testShow, true);
    function testShow() {
      console.log($scope.testInput);
    }
}

Fiddle

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Count the number of occurrences of a string in a VARCHAR field?

This is the mysql function using the space technique (tested with mysql 5.0 + 5.5): CREATE FUNCTION count_str( haystack TEXT, needle VARCHAR(32)) RETURNS INTEGER DETERMINISTIC RETURN LENGTH(haystack) - LENGTH( REPLACE ( haystack, needle, space(char_length(needle)-1)) );

duplicate 'row.names' are not allowed error

This related question points out a part of the ?read.table documentation that explains your problem:

If there is a header and the first row contains one fewer field than the number of columns, the first column in the input is used for the row names. Otherwise if row.names is missing, the rows are numbered.

Your header row likely has 1 fewer column than the rest of the file and so read.table assumes that the first column is the row.names (which must all be unique), not a column (which can contain duplicated values). You can fix this by using one of the following two Solutions:

  1. adding a delimiter (ie \t or ,) to the front or end of your header row in the source file, or,
  2. removing any trailing delimiters in your data

The choice will depend on the structure of your data.

Example:
Here the header row is interpreted as having one fewer column than the data because the delimiters don't match:

v1,v2,v3   # 3 items!!
a1,a2,a3,  # 4 items
b1,b2,b3,  # 4 items

This is how it is interpreted by default:

   v1,v2,v3   # 3 items!!
a1,a2,a3,  # 4 items
b1,b2,b3,  # 4 items

The first column (with no header) values are interpreted as row.names: a1 and b1. If this column contains duplicates, which is entirely possible, then you get the duplicate 'row.names' are not allowed error.

If you set row.names = FALSE, the shift doesn't happen, but you still have a mismatching number of items in the header and in the data because the delimiters don't match.

Solution 1 Add trailing delimiter to header:

v1,v2,v3,  # 4 items!!
a1,a2,a3,  # 4 items
b1,b2,b3,  # 4 items

Solution 2 Remove excess trailing delimiter from non-header rows:

v1,v2,v3   # 3 items
a1,a2,a3   # 3 items!!
b1,b2,b3   # 3 items!!

Python update a key in dict if it doesn't exist

You do not need to call d.keys(), so

if key not in d:
    d[key] = value

is enough. There is no clearer, more readable method.

You could update again with dict.get(), which would return an existing value if the key is already present:

d[key] = d.get(key, value)

but I strongly recommend against this; this is code golfing, hindering maintenance and readability.

Disable sorting for a particular column in jQuery DataTables

If you already have to hide Some columns, like I hide last name column. I just had to concatenate fname , lname , So i made query but hide that column from front end. The modifications in Disable sorting in such situation are :

    "aoColumnDefs": [
        { 'bSortable': false, 'aTargets': [ 3 ] },
        {
            "targets": [ 4 ],
            "visible": false,
            "searchable": true
        }
    ],

Notice that I had Hiding functionality here

    "columnDefs": [
            {
                "targets": [ 4 ],
                "visible": false,
                "searchable": true
            }
        ],

Then I merged it into "aoColumnDefs"

Moment js date time comparison

I believe you are looking for the query functions, isBefore, isSame, and isAfter.

But it's a bit difficult to tell exactly what you're attempting. Perhaps you are just looking to get the difference between the input time and the current time? If so, consider the difference function, diff. For example:

moment().diff(date_time, 'minutes')

A few other things:

  • There's an error in the first line:

      var date_time = 2013-03-24 + 'T' + 10:15:20:12 + 'Z'
    

    That's not going to work. I think you meant:

      var date_time = '2013-03-24' + 'T' + '10:15:20:12' + 'Z';
    

    Of course, you might as well:

      var date_time = '2013-03-24T10:15:20:12Z';
    
  • You're using: .tz('UTC') incorrectly. .tz belongs to moment-timezone. You don't need to use that unless you're working with other time zones, like America/Los_Angeles.

    If you want to parse a value as UTC, then use:

      moment.utc(theStringToParse)
    

    Or, if you want to parse a local value and convert it to UTC, then use:

      moment(theStringToParse).utc()
    

    Or perhaps you don't need it at all. Just because the input value is in UTC, doesn't mean you have to work in UTC throughout your function.

  • You seem to be getting the "now" instance by moment(new Date()). You can instead just use moment().

Updated

Based on your edit, I think you can just do this:

var date_time = req.body.date + 'T' + req.body.time + 'Z';
var isafter = moment(date_time).isAfter('2014-03-24T01:14:00Z');

Or, if you would like to ensure that your fields are validated to be in the correct format:

var m = moment.utc(req.body.date + ' ' + req.body.time, "YYYY-MM-DD  HH:mm:ss");
var isvalid = m.isValid();
var isafter = m.isAfter('2014-03-24T01:14:00Z');

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

Goto Advanced tab----> data type of column---> Here change data type from DT_STR to DT_TEXT and column width 255. Now you can check it will work perfectly.

Automatically resize images with browser size using CSS

The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!

<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />

Change the window width and the image scales obligingly.

How to get a list of MySQL views?

Here's a way to find all the views in every database on your instance:

SELECT TABLE_SCHEMA, TABLE_NAME 
FROM information_schema.tables 
WHERE TABLE_TYPE LIKE 'VIEW';

How do I clear my local working directory in Git?

Use:

git clean -df

It's not well advertised, but git clean is really handy. Git Ready has a nice introduction to git clean.

YouTube iframe API: how do I control an iframe player that's already in the HTML?

You can do this with far less code:

function callPlayer(func, args) {
    var i = 0,
        iframes = document.getElementsByTagName('iframe'),
        src = '';
    for (i = 0; i < iframes.length; i += 1) {
        src = iframes[i].getAttribute('src');
        if (src && src.indexOf('youtube.com/embed') !== -1) {
            iframes[i].contentWindow.postMessage(JSON.stringify({
                'event': 'command',
                'func': func,
                'args': args || []
            }), '*');
        }
    }
}

Working example: http://jsfiddle.net/kmturley/g6P5H/296/

Sublime Text 2: How to delete blank/empty lines

Select the text

Press:

  • Ctrl + H on PC, or
  • Command + Alt + F on Mac or
  • Click Find->Replace.

Make sure you have selected 'regular expression' by pressing:

  • Alt + R on PC or
  • Command + Alt + R on Mac or
  • Click .* in the Find box.

Find what: ^\n or ^(\r|\n\r?)

Replace With: (nothing, leave in blank).

How to make a div 100% height of the browser window

Here is something that is not exactly like what you had in previous answers, but it could be helpful to some:

body {
  display: flex;
  flex-direction: column;
  height: 100vh;
  margin: 0px;
}

#one {
  background-color: red;
}

#two {
  margin-top: 0px;
  background-color: black;
  color: white;
  overflow-y: scroll;
}

https://jsfiddle.net/newdark/qyxkk558/10/

Changing background color of text box input not working when empty

You could have the CSS first style the textbox, then have js change it:

<input type="text" style="background-color: yellow;" id="subEmail" />

js:

function changeColor() {
  document.getElementById("subEmail").style.backgroundColor = "Insert color here"
}

"No backupset selected to be restored" SQL Server 2012

I have run into the same issue. Run SSMS as administrator then right click and do database restore. Should work.

Converting XDocument to XmlDocument and vice versa

If you need to convert the instance of System.Xml.Linq.XDocument into the instance of the System.Xml.XmlDocument this extension method will help you to do not lose the XML declaration in the resulting XmlDocument instance:

using System.Xml; 
using System.Xml.Linq;

namespace www.dimaka.com
{ 
    internal static class LinqHelper 
    { 
        public static XmlDocument ToXmlDocument(this XDocument xDocument) 
        { 
            var xmlDocument = new XmlDocument(); 
            using (var reader = xDocument.CreateReader()) 
            { 
                xmlDocument.Load(reader); 
            }

            var xDeclaration = xDocument.Declaration; 
            if (xDeclaration != null) 
            { 
                var xmlDeclaration = xmlDocument.CreateXmlDeclaration( 
                    xDeclaration.Version, 
                    xDeclaration.Encoding, 
                    xDeclaration.Standalone);

                xmlDocument.InsertBefore(xmlDeclaration, xmlDocument.FirstChild); 
            }

            return xmlDocument; 
        } 
    } 
}

Hope that helps!

Open link in new tab or window

You should add the target="_blank" and rel="noopener noreferrer" in the anchor tag.

For example:

<a target="_blank" rel="noopener noreferrer" href="http://your_url_here.html">Link</a>

Adding rel="noopener noreferrer" is not mandatory, but it's a recommended security measure. More information can be found in the links below.

Source:

System.Security.SecurityException when writing to Event Log

I had a console application where I also had done a "Publish" to create an Install disk.
I was getting the same error at the OP: Error Message

The solution was right click setup.exe and click Run as Administrator

This enabled the install process the necessary privilege's.

How can I check if a string only contains letters in Python?

Looks like people are saying to use str.isalpha.

This is the one line function to check if all characters are letters.

def only_letters(string):
    return all(letter.isalpha() for letter in string)

all accepts an iterable of booleans, and returns True iff all of the booleans are True.

More generally, all returns True if the objects in your iterable would be considered True. These would be considered False

  • 0
  • None
  • Empty data structures (ie: len(list) == 0)
  • False. (duh)

How to get records randomly from the oracle database?

SELECT * FROM table SAMPLE(10) WHERE ROWNUM <= 20;

This is more efficient as it doesn't need to sort the Table.

Get height and width of a layout programmatically

As CapDroid say, you are trying to get the size before the view drawn, another possible solution could be to do a Post with a runnable on the View:

mView.post(new Runnable() {
        @Override
        public void run() {
            int width = mView.getWidth();
            int height = mView.getHeight();
        }
}

Install mysql-python (Windows)

I have a slightly different setup, but think my solution will help you out.

I have a Windows 8 Machine, Python 2.7 installed and running my stuff through eclipse.

Some Background:

When I did an easy install it tries to install MySQL-python 1.2.5 which failed with an error: Unable to find vcvarsall.bat. I did an easy_install of pip and tried the pip install which also failed with a similar error. They both reference vcvarsall.bat which is something to do with visual studio, since I don't have visual studio on my machine, it left me looking for a different solution, which I share below.

The Solution:

  1. Reinstall python 2.7.8 from 2.7.8 from https://www.python.org/download this will add any missing registry settings, which is required by the next install.
  2. Install 1.2.4 from http://pypi.python.org/pypi/MySQL-python/1.2.4

After I did both of those installs I was able to query my MySQL db through eclipse.

Passing an integer by reference in Python

Most cases where you would need to pass by reference are where you need to return more than one value back to the caller. A "best practice" is to use multiple return values, which is much easier to do in Python than in languages like Java.

Here's a simple example:

def RectToPolar(x, y):
    r = (x ** 2 + y ** 2) ** 0.5
    theta = math.atan2(y, x)
    return r, theta # return 2 things at once

r, theta = RectToPolar(3, 4) # assign 2 things at once

How to set the focus for a particular field in a Bootstrap modal, once it appears

I am using this in my layout to capture all modals and focus on the first input

  $('.modal').on('shown', function() {
     $(this).find('input').focus();
  });

Linux cmd to search for a class file among jars irrespective of jar path

Where are you jar files? Is there a pattern to find where they are?

1. Are they all in one directory?

For example, foo/a/a.jar and foo/b/b.jar are all under the folder foo/, in this case, you could use find with grep:

find foo/ -name "*.jar" | xargs grep Hello.class

Sure, at least you can search them under the root directory /, but it will be slow.

As @loganaayahee said, you could also use the command locate. locate search the files with an index, so it will be faster. But the command should be:

locate "*.jar" | xargs grep Hello.class

Since you want to search the content of the jar files.

2. Are the paths stored in an environment variable?

Typically, Java will store the paths to find jar files in an environment variable like CLASS_PATH, I don't know if this is what you want. But if your variable is just like this:CLASS_PATH=/lib:/usr/lib:/bin, which use a : to separate the paths, then you could use this commend to search the class:

for P in `echo $CLASS_PATH | sed 's/:/ /g'`; do grep Hello.calss $P/*.jar; done

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

Travis-ci and Jenkins, while both are tools for continuous integration are very different.

Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.

Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.

You can have a similar feature with Jenkins if you use one of the following plugins:

  • Travis YML Plugin - warning: does not seem to be popular, probably not feature complete in comparison to the real Travis.
  • Jervis - a modification of Jenkins to make it read create jobs from a .jervis.yml file found at the root of project code. If .jervis.yml does not exist, it will fall back to using .travis.yml file instead.

There are other hosted services you might also consider for continuous integration (non exhaustive list):


How to choose ?

You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)

Depending on where your code repository is hosted I would make the following choices:

  • in-house ? Jenkins or gitlab-ci
  • Github.com ? Travis-CI

To setup Travis-CI on a github project, all you have to do is:

  • add a .travis.yml file at the root of your project
  • create an account at travis-ci.com and activate your project

The features you get are:

  • Travis will run your tests for every push made on your repo
  • Travis will run your tests on every pull request contributors will make

Android toolbar center title and custom font

Update from @MrEngineer13's answer: to align title center in any cases, including Hamburger icon, option menus, you can add a FrameLayout in toolbar like this:

   <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_top"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/action_bar_bkgnd"
    app:theme="@style/ToolBarTheme" >

         <FrameLayout android:layout_width="match_parent"
                    android:layout_height="match_parent">

              <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:text="Toolbar Title"
               android:layout_gravity="center"
               style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
               android:id="@+id/toolbar_title" />

        </FrameLayout>

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

multiple plot in one figure in Python

Since I don't have a high enough reputation to comment I'll answer liang question on Feb 20 at 10:01 as an answer to the original question.

In order for the for the line labels to show you need to add plt.legend to your code. to build on the previous example above that also includes title, ylabel and xlabel:

import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.title('title')
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.legend()
plt.show()

Clear MySQL query cache without restarting server

I believe you can use...

RESET QUERY CACHE;

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

FLUSH QUERY CACHE;

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

Display XML content in HTML page

2017 Update I guess. textarea worked fine for me using Spring, Bootstrap and a bunch of other things. Got the SOAP payload stored in a DB, read by Spring and push via Spring-MVC. xmp didn't work at all.

Find a file by name in Visual Studio Code

It is CMD + P (or CTRL + P) by default. However the keyboard bindings may differ according to your preferences.

To know your bindings go to the "Keyboard Shortcuts" settings and search for "Go to File"

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

On Windows I kept facing different errors messages when trying to use pg_upgrade.

Saved a lot of time for me to just:

  1. Backup DB
  2. Uninstall all copies of PostgreSQL
  3. Install 9.5
  4. Restore DB

Convert varchar to float IF ISNUMERIC

..extending Mikaels' answers

SELECT
  CASE WHEN ISNUMERIC(QTY + 'e0') = 1 THEN CAST(QTY AS float) ELSE null END AS MyFloat
  CASE WHEN ISNUMERIC(QTY + 'e0') = 0 THEN QTY ELSE null END AS MyVarchar
FROM
  ...
  • Two data types requires two columns
  • Adding e0 fixes some ISNUMERIC issues (such as + - . and empty string being accepted)

Create a button programmatically and set a background image

To set background we can no longer use forState, so we have to use for to set the UIControlState:

let zoomInImage = UIImage(named: "Icon - plus") as UIImage?
let zoomInButton = UIButton(frame: CGRect(x: 10), y: 10, width: 45, height: 45))
zoomInButton.setBackgroundImage(zoomInImage, for: UIControlState.normal)
zoomInButton.addTarget(self, action: #selector(self.mapZoomInAction), for: .touchUpInside)
self.view.addSubview(zoomInButton)

What is a singleton in C#?

Thread Safe Singleton without using locks and no lazy instantiation.

This implementation has a static constructor, so it executes only once per Application Domain.

public sealed class Singleton
{

    static Singleton(){}

    private Singleton(){}

    public static Singleton Instance { get; } = new Singleton();

}

How to print all information from an HTTP request to the screen, in PHP

Putting together answers from Peter Bailey and Cmyker you get something like:

<?php
foreach ($_SERVER as $key => $value) {
    if (strpos($key, 'HTTP_') === 0) {
        $chunks = explode('_', $key);
        $header = '';
        for ($i = 1; $y = sizeof($chunks) - 1, $i < $y; $i++) {
            $header .= ucfirst(strtolower($chunks[$i])).'-';
        }
        $header .= ucfirst(strtolower($chunks[$i])).': '.$value;
        echo $header."\n";
    }
}
$body = file_get_contents('php://input');
if ($body != '') {
  print("\n$body\n\n");
}
?>

which works with the php -S built-in webserver, which is quite a handy feature of PHP.

How to run code after some delay in Flutter?

Figured it out

class AnimatedFlutterLogo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
}

class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
  Timer _timer;
  FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;

  _AnimatedFlutterLogoState() {
    _timer = new Timer(const Duration(milliseconds: 400), () {
      setState(() {
        _logoStyle = FlutterLogoStyle.horizontal;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return new FlutterLogo(
      size: 200.0,
      textColor: Palette.white,
      style: _logoStyle,
    );
  }
}

How to set the locale inside a Debian/Ubuntu Docker container?

Just add

ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8

into your Dockerfile. (You may need to make sure the locales package is installed.) Nothing else is needed for the basic operation. Meanwhile, outside of Ubuntu, locale-gen doesn’t accept any arguments, that’s why none of the ‘fixes’ using it work e.g. on Debian. Ubuntu have patched locale-gen to accept a list of locales to generate but the patch at the moment has not been accepted in Debian of anywhere else.

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

In the following httpd.conf file, configure the ServerName properly.

/etc/httpd/conf/httpd.conf

Like below:

ServerName 127.0.0.1:80

or

ServerName sitename

This resolved similar issue I was facing.

sh: react-scripts: command not found after running npm start

if anyone is willing to use npm only, then run this npm i react-native-scripts --save, then npm start or whatever the command you use

How can I make SMTP authenticated in C#

How do you send the message?

The classes in the System.Net.Mail namespace (which is probably what you should use) has full support for authentication, either specified in Web.config, or using the SmtpClient.Credentials property.

How to write to an existing excel file without overwriting data (using pandas)?

Starting in pandas 0.24 you can simplify this with the mode keyword argument of ExcelWriter:

import pandas as pd

with pd.ExcelWriter('the_file.xlsx', engine='openpyxl', mode='a') as writer: 
     data_filtered.to_excel(writer) 

Change Git repository directory location.

This did not work for me. I moved a repo from (e.g.) c:\project1\ to c:\repo\project1\ and Git for windows does not show any changes.

git status shows an error because one of the submodules "is not a git repository" and shows the old path. e.g. (names changed to protect IP)

fatal: Not a git repository: C:/project1/.git/modules/subproject/subproject2 fatal: 'git status --porcelain' failed in submodule subproject

I had to manually edit the .git files in the submodules to point to the correct relative path to the submodule's repo (in the main repo's .git/modules directory)

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\ is an escape character in Python. \t gets interpreted as a tab. If you need \ character in a string, you have to use \\.

Your code should be:
test_file=open('c:\\Python27\\test.txt','r')

How to redirect to another page using PHP

Although not secure, (no offense or anything), just stick the header function after you set the session variable

 while($row = mysql_fetch_assoc($result))
    {
            $_SESSION["user"] = $username;
    }
header('Location: /profile.php');

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

C# Parsing JSON array of objects

Use NewtonSoft JSON.Net library.

dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);

Hope this helps.

How to post JSON to PHP with curl

Normally the parameter -d is interpreted as form-encoded. You need the -H parameter:

curl -v -H "Content-Type: application/json" -X POST -d '{"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json

Thymeleaf: Concatenation - Could not parse as expression

Note that with | char, you can get a warning with your IDE, for exemple I get warning with the last version of IntelliJ, So the best solution it's to use this syntax:

th:text="${'static_content - ' + you_variable}"

Cannot resolve symbol 'AppCompatActivity'

If all else has failed, make sure you have added the import statement. I had removed it as it was showing error and forgot to add it back and was trying everything else to fix:

import android.support.v7.app.AppCompatActivity;

compare differences between two tables in mysql

INTERSECT needs to be emulated in MySQL:

SELECT  'robot' AS `set`, r.*
FROM    robot r
WHERE   ROW(r.col1, r.col2, …) NOT IN
        (
        SELECT  col1, col2, ...
        FROM    tbd_robot
        )
UNION ALL
SELECT  'tbd_robot' AS `set`, t.*
FROM    tbd_robot t
WHERE   ROW(t.col1, t.col2, …) NOT IN
        (
        SELECT  col1, col2, ...
        FROM    robot
        )

What operator is <> in VBA

Not Equal To


Before C came along and popularized !=, languages tended to use <> for not equal to.

At least, the various dialects of Basic did, and they predate C.

An even older and more unusual case is Fortran, which uses .NE., as in X .NE. Y.

How do I force make/GCC to show me the commands?

Since GNU Make version 4.0, the --trace argument is a nice way to tell what and why a makefile do, outputing lines like:

makefile:8: target 'foo.o' does not exist

or

makefile:12: update target 'foo' due to: bar

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

You'll have to pass your arguments as reference types.

#First create the variables (note you have to set them to something)
$global:var1 = $null
$global:var2 = $null
$global:var3 = $null

#The type of the reference argument should be of type [REF]
function foo ($a, $b, [REF]$c)
{
    # add $a and $b and set the requested global variable to equal to it
    # Note how you modify the value.
    $c.Value = $a + $b
}

#You can then call it like this:
foo 1 2 [REF]$global:var3

Setting an environment variable before a command in Bash is not working for the second command in a pipe

A simple approach is to make use of ;

For example:

ENV=prod; ansible-playbook -i inventories/$ENV --extra-vars "env=$ENV"  deauthorize_users.yml --check

What is the best way to do a substring in a batch file?

As an additional info to Joey's answer, which isn't described in the help of set /? nor for /?.

%~0 expands to the name of the own batch, exactly as it was typed.
So if you start your batch it will be expanded as

%~0   - mYbAtCh
%~n0  - mybatch
%~nx0 - mybatch.bat

But there is one exception, expanding in a subroutine could fail

echo main- %~0
call :myFunction
exit /b

:myFunction
echo func - %~0
echo func - %~n0
exit /b

This results to

main - myBatch
Func - :myFunction
func - mybatch

In a function %~0 expands always to the name of the function, not of the batch file.
But if you use at least one modifier it will show the filename again!

How to check if a variable is a dictionary in Python?

How would you check if a variable is a dictionary in Python?

This is an excellent question, but it is unfortunate that the most upvoted answer leads with a poor recommendation, type(obj) is dict.

(Note that you should also not use dict as a variable name - it's the name of the builtin object.)

If you are writing code that will be imported and used by others, do not presume that they will use the dict builtin directly - making that presumption makes your code more inflexible and in this case, create easily hidden bugs that would not error the program out.

I strongly suggest, for the purposes of correctness, maintainability, and flexibility for future users, never having less flexible, unidiomatic expressions in your code when there are more flexible, idiomatic expressions.

is is a test for object identity. It does not support inheritance, it does not support any abstraction, and it does not support the interface.

So I will provide several options that do.

Supporting inheritance:

This is the first recommendation I would make, because it allows for users to supply their own subclass of dict, or a OrderedDict, defaultdict, or Counter from the collections module:

if isinstance(any_object, dict):

But there are even more flexible options.

Supporting abstractions:

from collections.abc import Mapping

if isinstance(any_object, Mapping):

This allows the user of your code to use their own custom implementation of an abstract Mapping, which also includes any subclass of dict, and still get the correct behavior.

Use the interface

You commonly hear the OOP advice, "program to an interface".

This strategy takes advantage of Python's polymorphism or duck-typing.

So just attempt to access the interface, catching the specific expected errors (AttributeError in case there is no .items and TypeError in case items is not callable) with a reasonable fallback - and now any class that implements that interface will give you its items (note .iteritems() is gone in Python 3):

try:
    items = any_object.items()
except (AttributeError, TypeError):
    non_items_behavior(any_object)
else: # no exception raised
    for item in items: ...

Perhaps you might think using duck-typing like this goes too far in allowing for too many false positives, and it may be, depending on your objectives for this code.

Conclusion

Don't use is to check types for standard control flow. Use isinstance, consider abstractions like Mapping or MutableMapping, and consider avoiding type-checking altogether, using the interface directly.

How do I rewrite URLs in a proxy response in NGINX

You can use the following nginx configuration example:

upstream adminhost {
  server adminhostname:8080;
}

server {
  listen 80;

  location ~ ^/admin/(.*)$ {
    proxy_pass http://adminhost/$1$is_args$args;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $server_name;
  }
}

Cannot send a content-body with this verb-type

Because you didn't specify the Header.

I've added an extended example:

var request = (HttpWebRequest)WebRequest.Create(strServer + strURL.Split('&')[1].ToString());

Header(ref request, p_Method);

And the method Header:

private void Header(ref HttpWebRequest p_request, string p_Method)
{
    p_request.ContentType = "application/x-www-form-urlencoded";
    p_request.Method = p_Method;
    p_request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows CE)";
    p_request.Host = strServer.Split('/')[2].ToString();
    p_request.Accept = "*/*";
    if (String.IsNullOrEmpty(strURLReferer))
    {
        p_request.Referer = strServer;
    }
    else
    {
        p_request.Referer = strURLReferer;
    }
    p_request.Headers.Add("Accept-Language", "en-us\r\n");
    p_request.Headers.Add("UA-CPU", "x86 \r\n");
    p_request.Headers.Add("Cache-Control", "no-cache\r\n");
    p_request.KeepAlive = true;
}

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No, it is not possible to use the curl_setopt call with CURLOPT_HTTPHEADER. The second call will overwrite the headers of the first call.

Instead the function needs to be called once with all headers:

$headers = array(
    'Content-type: application/xml',
    'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

React.js: How to append a component on click?

As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.

In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field

class HealthConditions extends React.Component {
  constructor(props) {
    super(props);


    this.state = {
      inputLinkClicked: false
    }
  }

  handleAddSecondInput() {
    this.setState({
      inputLinkClicked: true
    })
  }


  render() {
    return(
      <main id="wrapper" className="" data-reset-cookie-tab>
        <div id="content" role="main">
          <div className="inner-block">

            <H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>

            <InputField label="Name of condition"
              InputType="text"
              InputId="id-condition"
              InputName="condition"
            />

            {
              this.state.inputLinkClicked?

              <InputField label=""
                InputType="text"
                InputId="id-condition2"
                InputName="condition2"
              />

              :

              <div></div>
            }

            <button
              type="button"
              className="make-button-link"
              data-add-button=""
              href="#"
              onClick={this.handleAddSecondInput}
            >
              Add a condition
            </button>

            <FormButton buttonLabel="Next"
              handleSubmit={this.handleSubmit}
              linkto={
                this.state.illnessOrDisability === 'true' ?
                "/404"
                :
                "/add-your-details"
              }
            />

            <BackLink backLink="/add-your-details" />

          </div>
         </div>
      </main>
    );
  }
}

Char array to hex string C++

You could use std::hex

Eg.

std::cout << std::hex << packet;

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

The fact that you're getting an error from the Names Pipes Provider tells us that you're not using the TCP/IP protocol when you're trying to establish the connection. Try adding the "tcp" prefix and specifying the port number:

tcp:name.cloudapp.net,1433

Toad for Oracle..How to execute multiple statements?

I prefer the Execute via SQL*Plus option. It's in the little down-arrow menu under the "Execute as script" toolbar button.

Make columns of equal width in <table>

Found this on HTML table: keep the same width for columns

If you set the style table-layout: fixed; on your table, you can override the browser's automatic column resizing. The browser will then set column widths based on the width of cells in the first row of the table. Change your to and remove the inside of it, and then set fixed widths for the cells in .

How to read the post request parameters using JavaScript

You can read the post request parameter with jQuery-PostCapture(@ssut/jQuery-PostCapture).

PostCapture plugin is consisted of some tricks.

When you are click the submit button, the onsubmit event will be dispatched.

At the time, PostCapture will be serialize form data and save to html5 localStorage(if available) or cookie storage.

ExecuteReader: Connection property has not been initialized

As mentioned you should assign the connection and you should preferably also use sql parameters instead, so your command assignment would read:

    // 3. Pass the connection to a command object
    SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn); // ", conn)" added
    cmd.Parameters.Add("project", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;
    cmd.Parameters.Add("iteration", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;

    //
    // 4. Use the connection
    //

By using parameters you avoid SQL injection and other problematic typos (project names like "myproject's" is an example).

How to trim a list in Python

l = [4,76,2,8,6,4,3,7,2,1]
l = l[:5]

How to parse a JSON string to an array using Jackson

I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.

 Main Class:-

String jsonStr = "[{\r\n" + "       \"name\": \"John\",\r\n" + "        \"city\": \"Berlin\",\r\n"
                + "         \"cars\": [\r\n" + "            \"FIAT\",\r\n" + "          \"Toyata\"\r\n"
                + "     ],\r\n" + "     \"job\": \"Teacher\"\r\n" + "   },\r\n" + " {\r\n"
                + "     \"name\": \"Mark\",\r\n" + "        \"city\": \"Oslo\",\r\n" + "        \"cars\": [\r\n"
                + "         \"VW\",\r\n" + "            \"Toyata\"\r\n" + "     ],\r\n"
                + "     \"job\": \"Doctor\"\r\n" + "    }\r\n" + "]";

        ObjectMapper mapper = new ObjectMapper();

        MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);

        for (MyPojo itr : jsonObj) {

            System.out.println("Val of getName is: " + itr.getName());
            System.out.println("Val of getCity is: " + itr.getCity());
            System.out.println("Val of getJob is: " + itr.getJob());
            System.out.println("Val of getCars is: " + itr.getCars() + "\n");

        }

POJO:

public class MyPojo {

private List<String> cars = new ArrayList<String>();

private String name;

private String job;

private String city;

public List<String> getCars() {
    return cars;
}

public void setCars(List<String> cars) {
    this.cars = cars;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getJob() {
    return job;
}

public void setJob(String job) {
    this.job = job;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
} }

  RESULT:-
         Val of getName is: John
         Val of getCity is: Berlin
         Val of getJob is: Teacher
         Val of getCars is: [FIAT, Toyata]

          Val of getName is: Mark
          Val of getCity is: Oslo
          Val of getJob is: Doctor
          Val of getCars is: [VW, Toyata]

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

HTML:

<div  ng-repeat="scannedDevice in ScanResult">
        <!--GridStarts-->
          <div >
              <img ng-src={{'./assets/img/PlaceHolder/Test.png'}} 
                   <!--Pass Param-->
                   ng-click="connectDevice(scannedDevice.id)"
                   altSrc="{{'./assets/img/PlaceHolder/user_place_holder.png'}}" 
                   onerror="this.src = $(this).attr('altSrc')">
           </div>    
 </div>

Java Script:

   //Global Variables
    var  ANGULAR_APP = angular.module('TestApp',[]);

    ANGULAR_APP .controller('TestCtrl',['$scope', function($scope) {

      //Variables
      $scope.ScanResult = [];

      //Pass Parameter
      $scope.connectDevice = function(deviceID) {
            alert("Connecting : "+deviceID );
        };
     }]);

How to do SELECT MAX in Django?

See this. Your code would be something like the following:

from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}

You can also use this on existing querysets:

from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}

If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:

arg = args.order_by('-rating')[0]

Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0] part will raise an IndexError). If you want to avoid that behavior and instead simply return None in that case, use .first():

arg = args.order_by('-rating').first() # may return None

jquery drop down menu closing by clicking outside

You would need to attach your click event to some element. If there are lots of other elements on the page you would not want to attach a click event to all of them.

One potential way would be to create a transparent div below your dropdown menu but above all other elements on the page. You would show it when the drop down was shown. Have the element have a click hander that hides the drop down and the transparent div.

_x000D_
_x000D_
$('#clickCatcher').click(function () { _x000D_
  $('#dropContainer').hide();_x000D_
  $(this).hide();_x000D_
});
_x000D_
#dropContainer { z-index: 101; ... }_x000D_
#clickCatcher { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="dropDown"></div>_x000D_
<div id="clickCatcher"></div>
_x000D_
_x000D_
_x000D_

How to get ERD diagram for an existing database?

You can use dbeaver to do this. It allows you to export the ER diagram as png/svg etc.

DBeaver - https://dbeaver.io/

Double click on a schema (eg, Schemas->public->Tables) and open the "ER Diagram" tab (next to "Properties" tab)

Copy Notepad++ text with formatting?

Taken from here:

You can use Notepad++ to accomplish this in three ways. Just so you know, Notepad++ is a more advanced version of Notepad, which supports syntax highlighting of different code files "out of the box" - PHP included!

Download & install it, fire it up, and load up your PHP file. You should automatically see it beautifully coloured (if not, because the file extension is something other than .php, go to Language -> PHP or Language -> P -> PHP).

If you need to change any of the colours, you can easily do so - just go to Settings -> Styler Configurator. From that menu, you can change the various highlighting and font options, to suit your needs - although the default usually suffices for most.

Then, go to Plugins -> NppExport. From there, you have three options you can consider:

Export to RTF Export to HTML Copy all formats to clipboard Start with the last one - "Copy all formats to clipboard" - which will copy the entire file with the highlighted syntax to the clipboard. Once you click it, then open Microsoft Word, and just hit paste! You should see the beautifully syntax-highlighted code. If something goes wrong, then you can try one of the other options (export to RTF/HTML), although I've never had a problem with the clipboard method.

Instagram API: How to get all user media?

You can user pagination of Instagram PHP API: https://github.com/cosenary/Instagram-PHP-API/wiki/Using-Pagination

Something like that:

    $Instagram = new MetzWeb\Instagram\Instagram(array(
        "apiKey"      => IG_APP_KEY,
        "apiSecret"   => IG_APP_SECRET,
        "apiCallback" => IG_APP_CALLBACK
    ));
    $Instagram->setSignedHeader(true);

    $pictures = $Instagram->getUserMedia(123);
    do {

        foreach ($pictures->data as $picture_data):

            echo '<img src="'.$picture_data->images->low_resolution->url.'">';

        endforeach;

    } while ($pictures = $instagram->pagination($pictures));

Checking if an object is null in C#

  public static bool isnull(object T)
  {
      return T == null ? true : false;
  }

use:

isnull(object.check.it)

Conditional use:

isnull(object.check.it) ? DoWhenItsTrue : DoWhenItsFalse;

Update (another way) updated 08/31/2017 and 01/25/2021. Thanks for the comment.

public static bool IsNull(object T)
{
    return (bool)T ? true : false;
}

Demostration Demostration on Visual Studio console application

And for the records, you have my code on Github, go check it out: https://github.com/j0rt3g4/ValidateNull PS: This one is especially for you Chayim Friedman, don't use beta software assuming that is all true. Wait for final versions or use your own environment to test, before assuming true beta software without any sort of documentation or demonstration from your end.

What is the meaning of "Failed building wheel for X" in pip install?

In my case, update the pip versión after create the venv, this update pip from 9.0.1 to 20.3.1

python3 -m venv env/python
source env/python/bin/activate
pip3 install pip --upgrade

But, the message was...

Using legacy 'setup.py install' for django-avatar, since package 'wheel' is not installed.

Then, I install wheel package after update pip

python3 -m venv env/python
source env/python/bin/activate
pip3 install --upgrade pip
pip3 install wheel

And the message was...

Building wheel for django-avatar (setup.py): started
default:   Building wheel for django-avatar (setup.py): finished with status 'done'

How to update UI from another thread running in another class

First you need to use Dispatcher.Invoke to change the UI from another thread and to do that from another class, you can use events.
Then you can register to that event(s) in the main class and Dispatch the changes to the UI and in the calculation class you throw the event when you want to notify the UI:

class MainWindow : Window
{
    private void startCalc()
    {
        //your code
        CalcClass calc = new CalcClass();
        calc.ProgressUpdate += (s, e) => {
            Dispatcher.Invoke((Action)delegate() { /* update UI */ });
        };
        Thread calcthread = new Thread(new ParameterizedThreadStart(calc.testMethod));
        calcthread.Start(input);
    }
}

class CalcClass
{
    public event EventHandler ProgressUpdate;

    public void testMethod(object input)
    {
        //part 1
        if(ProgressUpdate != null)
            ProgressUpdate(this, new YourEventArgs(status));
        //part 2
    }
}

UPDATE:
As it seems this is still an often visited question and answer I want to update this answer with how I would do it now (with .NET 4.5) - this is a little longer as I will show some different possibilities:

class MainWindow : Window
{
    Task calcTask = null;

    void buttonStartCalc_Clicked(object sender, EventArgs e) { StartCalc(); } // #1
    async void buttonDoCalc_Clicked(object sender, EventArgs e) // #2
    {
        await CalcAsync(); // #2
    }

    void StartCalc()
    {
        var calc = PrepareCalc();
        calcTask = Task.Run(() => calc.TestMethod(input)); // #3
    }
    Task CalcAsync()
    {
        var calc = PrepareCalc();
        return Task.Run(() => calc.TestMethod(input)); // #4
    }
    CalcClass PrepareCalc()
    {
        //your code
        var calc = new CalcClass();
        calc.ProgressUpdate += (s, e) => Dispatcher.Invoke((Action)delegate()
            {
                // update UI
            });
        return calc;
    }
}

class CalcClass
{
    public event EventHandler<EventArgs<YourStatus>> ProgressUpdate; // #5

    public TestMethod(InputValues input)
    {
        //part 1
        ProgressUpdate.Raise(this, status); // #6 - status is of type YourStatus
        //part 2
    }
}

static class EventExtensions
{
    public static void Raise<T>(this EventHandler<EventArgs<T>> theEvent,
                                object sender, T args)
    {
        if (theEvent != null)
            theEvent(sender, new EventArgs<T>(args));
    }
}

@1) How to start the "synchronous" calculations and run them in the background

@2) How to start it "asynchronous" and "await it": Here the calculation is executed and completed before the method returns, but because of the async/await the UI is not blocked (BTW: such event handlers are the only valid usages of async void as the event handler must return void - use async Task in all other cases)

@3) Instead of a new Thread we now use a Task. To later be able to check its (successfull) completion we save it in the global calcTask member. In the background this also starts a new thread and runs the action there, but it is much easier to handle and has some other benefits.

@4) Here we also start the action, but this time we return the task, so the "async event handler" can "await it". We could also create async Task CalcAsync() and then await Task.Run(() => calc.TestMethod(input)).ConfigureAwait(false); (FYI: the ConfigureAwait(false) is to avoid deadlocks, you should read up on this if you use async/await as it would be to much to explain here) which would result in the same workflow, but as the Task.Run is the only "awaitable operation" and is the last one we can simply return the task and save one context switch, which saves some execution time.

@5) Here I now use a "strongly typed generic event" so we can pass and receive our "status object" easily

@6) Here I use the extension defined below, which (aside from ease of use) solve the possible race condition in the old example. There it could have happened that the event got null after the if-check, but before the call if the event handler was removed in another thread at just that moment. This can't happen here, as the extensions gets a "copy" of the event delegate and in the same situation the handler is still registered inside the Raise method.

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

Prefixing with 'r' works very well, but it needs to be in the correct syntax. For example:

passwordFile = open(r'''C:\Users\Bob\SecretPasswordFile.txt''')

No need for \\ here - maintains readability and works well.

Change input value onclick button - pure javascript or jQuery

My Attempt ( JsFiddle)

Javascript

$(document).ready(function () {
    $('#buttons input[type=button]').on('click', function () {
        var qty = $(this).data('quantity');
        var price = $('#totalPrice').text(); 
        $('#count').val(price * qty);
    });
});

Html

  Product price:$500
<br>Total price: $<span id='totalPrice'>500</span>
<br>
<div id='buttons'>
    <input id='qty2' type="button" data-quantity='2' value="2&#x00A;Qty">
    <input id='qty2' type="button" class="mnozstvi_sleva" data-quantity='4' value="4&#x00A;Qty">
</div>
<br>Total
<input type="text" id="count" value="1">

How to declare a global variable in php?

If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:

$variable = 5;

function name()
{
    global $variable;

    $value = $variable + 5;

    return $value;  

}

Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.

config.php

global $variable;

$variable = 5;

other.php

function name()
{
    require_once __DIR__ . '/config.php';
}

You can use $GLOBALS as well. It's a superglobal so it has access everywhere.

$GLOBALS['variable'] = 5;

function name()
{
    echo $GLOBALS['variable'];
}

Depending on your choice you can choose either.

how to align all my li on one line?

I think the NOBR tag might be overkill, and as you said, unreliable.

There are 2 options available depending on how you are displaying the text.

If you are displaying text in a table cell you would do Long Text Here. If you are using a div or a span, you can use the style="white-space: nowrap;"

How to get file creation & modification date/times in Python?

os.stat does include the creation time. There's just no definition of st_anything for the element of os.stat() that contains the time.

So try this:

os.stat('feedparser.py')[8]

Compare that with your create date on the file in ls -lah

They should be the same.

Copying HTML code in Google Chrome's inspect element

  1. Select the <html> tag in Elements.
  2. Do CTRL-C.
  3. Check if there is only lefting <!DOCTYPE html> before the <html>.

When should I really use noexcept?

I think it is too early to give a "best practices" answer for this as there hasn't been enough time to use it in practice. If this was asked about throw specifiers right after they came out then the answers would be very different to now.

Having to think about whether or not I need to append noexcept after every function declaration would greatly reduce programmer productivity (and frankly, would be a pain).

Well, then use it when it's obvious that the function will never throw.

When can I realistically expect to observe a performance improvement after using noexcept? [...] Personally, I care about noexcept because of the increased freedom provided to the compiler to safely apply certain kinds of optimizations.

It seems like the biggest optimization gains are from user optimizations, not compiler ones due to the possibility of checking noexcept and overloading on it. Most compilers follow a no-penalty-if-you-don't-throw exception handling method, so I doubt it would change much (or anything) on the machine code level of your code, although perhaps reduce the binary size by removing the handling code.

Using noexcept in the big four (constructors, assignment, not destructors as they're already noexcept) will likely cause the best improvements as noexcept checks are 'common' in template code such as in std containers. For instance, std::vector won't use your class's move unless it's marked noexcept (or the compiler can deduce it otherwise).

How do I set up access control in SVN?

Apache Subversion supports path-based authorization that helps you configure granular permissions for user and group accounts on paths in your repositories (files or directories). Path-based authorization supports three access levels - No Access, Read Only and Read / Write.

Path-based authorization permissions are stored in per-repository or per-server authorization files with a special syntax. Here is an example from SVNBook:

[calc:/branches/calc/bug-142]
harry = rw
sally = r

When you require a complex permission structure with many paths and accounts you can benefit from a GUI-based permission management tools provided by VisualSVN Server:

  • Server administrators can manage user and group permissions via the VisualSVN Server Manager console or PowerShell,
  • Non-admin users can manage permissions via RepoCfg.

Repository permissions in VisualSVN Server Manager enter image description here

Repository permissions in PowerShell enter image description here

Non-admin users can manage permissions via the RepoCfg tool enter image description here

equivalent of vbCrLf in c#

You are looking for System.Environment.NewLine.

On Windows, this is equivalent to \r\n though it could be different under another .NET implementation, such as Mono on Linux, for example.

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Really the format can be quite simple - sometimes there's no need to predefine a temp table - it will be created from results of the select.

Select FieldA...FieldN 
into #MyTempTable 
from MyTable

So unless you want different types or are very strict on definition, keep things simple. Note also that any temporary table created inside a stored procedure is automatically dropped when the stored procedure finishes executing. If stored procedure A creates a temp table and calls stored procedure B, then B will be able to use the temporary table that A created.

However, it's generally considered good coding practice to explicitly drop every temporary table you create anyway.

Fit image to table cell [Pure HTML]

if you want to do it with pure HTML solution ,you can delete the border in the table if you want...or you can add align="center" attribute to your img tag like this:

<img align="center" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />

see the fiddle : http://jsfiddle.net/Lk2Rh/27/

but still it better to handling this with CSS, i suggest you that.

  • I hope this help.

How can I find the last element in a List<>?

I would have to agree a foreach would be a lot easier something like

foreach(AllIntegerIDs allIntegerIDs in integerList)
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n", allIntegerIDs.m_MessageID,
allIntegerIDs.m_MessageType,
allIntegerIDs.m_ClassID,
allIntegerIDs.m_CategoryID,
allIntegerIDs.m_MessageText);
}

Also I would suggest you add properties to access your information instead of public fields, depending on your .net version you can add it like public int MessageType {get; set;} and get rid of the m_ from your public fields, properties etc as it shouldnt be there.

Android: Scale a Drawable or background image?

What Dweebo proposed works. But in my humble opinion it is unnecessary. A background drawable scales well by itself. The view should have fixed width and height, like in the following example:

 < RelativeLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/black">

    <LinearLayout
        android:layout_width="500dip"
        android:layout_height="450dip"
        android:layout_centerInParent="true"
        android:background="@drawable/my_drawable"
        android:orientation="vertical"
        android:padding="30dip"
        >
        ...
     </LinearLayout>
 < / RelativeLayout>

Xcode "Build and Archive" from command line

Going one step further, uploading to iTunesConnect via commandline with Xcode 7! (Assuming you are starting with an .ipa that has been signed with the correct release profile and signing identity.)

Enter altool, the CLI interface for the Application Loader (docs, page 38). Hidden deep within Xcode.app's structure, is a handy function to let us upload directly to ItunesConnect.

/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/Versions/A/Support/altool

Simply run $ altool --upload-app -f file -u username [-p password] to upload your newly minted .ipa straight to Apple. The password is optional, and will prompt you for it if you leave it off the command.

If there are any issues with the app during the verification step, the console will print them out.

You will likely have to export the path to altool if you don't want to save its location.

export PATH=$PATH:/Applications/Xcode.app/Contents/Applications/Application\ Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/Versions/A/Support/

Thats it! Simply login to iTunesConnect.com and select your new build for testing with testflight.

Final Note: If you get an error saying Exception while launching iTunesTransporter: Transporter not found at path: /usr/local/itms/bin/iTMSTransporter. You should reinstall the application, you can follow the suggestion on this SO answer, to run a symlink to the correct location:

ln -s /Applications/Xcode.app/Contents/Applications/Application\ Loader.app/Contents/itms /usr/local/itms

Can I access a form in the controller?

Definitely you can't access form in scope bec. it is not created. The DOM from html template is loaded little bit slowly like controller constructor. the solution is to watch until DOM loaded and all the scope defined!

in controller:

$timeout(function(){
    console.log('customerForm:', $scope.customerForm);
    // everything else what you need
});

AngularJS - Binding radio buttons to models with boolean values

The way your radios are set up in the fiddle - sharing the same model - will cause only the last group to show a checked radio if you decide to quote all of the truthy values. A more solid approach will involve giving the individual groups their own model, and set the value as a unique attribute of the radios, such as the id:

$scope.radioMod = 1;
$scope.radioMod2 = 2;

Here is a representation of the new html:

<label data-ng-repeat="choice2 in question2.choices">
            <input type="radio" name="response2" data-ng-model="radioMod2" value="{{choice2.id}}"/>
                {{choice2.text}}
        </label>

And a fiddle.

Invariant Violation: _registerComponent(...): Target container is not a DOM element

If you use webpack for rendering your react and use HtmlWebpackPlugin in your react,this plugin builds its blank index.html by itself and injects js file in it,so it does not contain div element,as HtmlWebpackPlugin docs you can build your own index.html and give its address to this plugin, in my webpack.config.js

plugins: [            
    new HtmlWebpackPlugin({
        title: 'dev',
        template: 'dist/index.html'
    })
],

and this is my index.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="shortcut icon" href="">
    <meta name="viewport" content="width=device-width">
    <title>Epos report</title>
</head>
<body>
   <div id="app"></div>
   <script src="./bundle.js"></script>
</body>
</html>

How does Junit @Rule work?

Rules are used to add additional functionality which applies to all tests within a test class, but in a more generic way.

For instance, ExternalResource executes code before and after a test method, without having to use @Before and @After. Using an ExternalResource rather than @Before and @After gives opportunities for better code reuse; the same rule can be used from two different test classes.

The design was based upon: Interceptors in JUnit

For more information see JUnit wiki : Rules.

Php $_POST method to get textarea value

Remove some of your textarea class like

<textarea name="Address" rows="3" class="input-text full-width" placeholder="Your Address" ></textarea>

To

<textarea name="Address" rows="3" class="full-width" placeholder="Your Address" ></textarea>

It's dependent on your template (Purchased Template). The developer has included some JavaScript to get the value from correct object on UI, but class like input-text just finds only $('input[type=text]'), that's why.

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

try this

http://jsfiddle.net/VggvD/2/

CSS add your code

.select_join option{
    font-size:13px;
}

how to implement a pop up dialog box in iOS

Since the release of iOS 8, UIAlertView is now deprecated; UIAlertController is the replacement.

Here is a sample of how it looks in Swift:

let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let alertAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.default)
{
    (UIAlertAction) -> Void in
}
alert.addAction(alertAction)
present(alert, animated: true)
{
    () -> Void in
}

As you can see, the API allows us to implement callbacks for both the action and when we are presenting the alert, which is quite handy!

Updated for Swift 4.2

let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK!", style: .default)
        {
            (UIAlertAction) -> Void in
        }
        alert.addAction(alertAction)
        present(alert, animated: true)
        {
            () -> Void in
        }

Jquery to open Bootstrap v3 modal of remote url

From Bootstrap's docs about the remote option;

This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.

If a remote URL is provided, content will be loaded one time via jQuery's load method and injected into the .modal-content div. If you're using the data-api, you may alternatively use the href attribute to specify the remote source. An example of this is shown below:

<a data-toggle="modal" href="remote.html" data-target="#modal">Click me</a>

That's the .modal-content div, not .modal-body. If you want to put content inside .modal-body then you need to do that with custom javascript.

So I would call jQuery.load programmatically, meaning you can keep the functionality of the dismiss and/or other buttons as required.

To do this you could use a data tag with the URL from the button that opens the modal, and use the show.bs.modal event to load content into the .modal-body div.

HTML Link/Button

<a href="#" data-toggle="modal" data-load-url="remote.html" data-target="#myModal">Click me</a>

jQuery

$('#myModal').on('show.bs.modal', function (e) {
    var loadurl = $(e.relatedTarget).data('load-url');
    $(this).find('.modal-body').load(loadurl);
});

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I had similar error: "Expecting value: line 1 column 1 (char 0)"

It helped for me to add "myfile.seek(0)", move the pointer to the 0 character

with open(storage_path, 'r') as myfile:
if len(myfile.readlines()) != 0:
    myfile.seek(0)
    Bank_0 = json.load(myfile)

Angular 2: How to access an HTTP response body?

Here is an example to access response body using angular2 built in Response

import { Injectable } from '@angular/core';
import {Http,Response} from '@angular/http';

@Injectable()
export class SampleService {
  constructor(private http:Http) { }

  getData(){

    this.http.get(url)
   .map((res:Response) => (
       res.json() //Convert response to JSON
       //OR
       res.text() //Convert response to a string
   ))
   .subscribe(data => {console.log(data)})

  }
}

Timer Interval 1000 != 1 second?

Any other places you use TimerEventProcessor or Counter?

Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.

So instead of _Counter, you should use:

 // when starting the timer:
 DateTime _started = DateTime.UtcNow;

 // in TimerEventProcessor:
 seconds = (DateTime.UtcNow-started).TotalSeconds;
 Label.Text = seconds.ToString();

Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.

How can I get query string values in JavaScript?

If you do not wish to use a JavaScript library you can use the JavaScript string functions to parse window.location. Keep this code in an external .js file and you can use it over and over again in different projects.

// Example - window.location = "index.htm?name=bob";

var value = getParameterValue("name");

alert("name = " + value);

function getParameterValue(param)
{
    var url = window.location;
    var parts = url.split('?');
    var params = parts[1].split('&');
    var val = "";

    for ( var i=0; i<params.length; i++)
    {
        var paramNameVal = params[i].split('=');

        if ( paramNameVal[0] == param )
        {
            val = paramNameVal[1];
        }
    }
    return val;
}

How do I pass along variables with XMLHTTPRequest

Yes that's the correct method to do it with a GET request.

However, please remember that multiple query string parameters should be separated with &

eg. ?variable1=value1&variable2=value2

How can I discard remote changes and mark a file as "resolved"?

Make sure of the conflict origin: if it is the result of a git merge, see Brian Campbell's answer.

But if is the result of a git rebase, in order to discard remote (their) changes and use local changes, you would have to do a:

git checkout --theirs -- .

See "Why is the meaning of “ours” and “theirs” reversed"" to see how ours and theirs are swapped during a rebase (because the upstream branch is checked out).

T-SQL How to select only Second row from a table?

I have a much easier way than the above ones.

DECLARE @FirstId int, @SecondId int

    SELECT TOP 1 @FirstId = TableId from MyDataTable ORDER BY TableId 
    SELECT TOP 1 @SecondId = TableId from MyDataTable WHERE TableId <> @FirstId  ORDER BY TableId 

SELECT @SecondId 

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

This could a permission issue. The user needs at least ALTER permission to truncate a table. Another option is to call DELETE FROM instead of TRUNCATE TABLE, but this operation is slower because it writes to the Log file, whereas TRUNCATE does not write to the log file.

The minimum permission required is ALTER on table_name. TRUNCATE TABLE permissions default to the table owner, members of the sysadmin fixed server role, and the db_owner and db_ddladmin fixed database roles, and are not transferable. However, you can incorporate the TRUNCATE TABLE statement within a module, such as a stored procedure, and grant appropriate permissions to the module using the EXECUTE AS clause.

HTTP Range header

For folks who are stumbling across Victor Stoddard's answer above in 2019, and become hopeful and doe eyed, note that:

a) Support for X-Content-Duration was removed in Firefox 41: https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/41#HTTP

b) I think it was only supported in Firefox for .ogg audio and .ogv video, not for any other types.

c) I can't see that it was ever supported at all in Chrome, but that may just be a lack of research on my part. But its presence or absence seems to have no effect one way or another for webm or ogv videos as of today in Chrome 71.

d) I can't find anywhere where 'Content-Duration' replaced 'X-Content-Duration' for anything, I don't think 'X-Content-Duration' lived long enough for there to be a successor header name.

I think this means that, as of today if you want to serve webm or ogv containers that contain streams that don't know their duration (e.g. the output of an ffpeg pipe) to Chrome or FF, and you want them to be scrubbable in an HTML 5 video element, you are probably out of luck. Firefox 64.0 makes a half hearted attempt to make these scrubbable whether or not you serve via range requests, but it gets confused and throws up a spinning wheel until the stream is completely downloaded if you seek a few times more than it thinks is appropriate. Chrome doesn't even try, it just nopes out and won't let you scrub at all until the entire stream is finished playing.

python: Appending a dictionary to a list - I see a pointer like behavior

Also with dict

a = []
b = {1:'one'}

a.append(dict(b))
print a
b[1]='iuqsdgf'
print a

result

[{1: 'one'}]
[{1: 'one'}]

How do I get total physical memory size using PowerShell without WMI?

For those coming here from a later day and age and one a working solution:

(Get-WmiObject -class "cim_physicalmemory" | Measure-Object -Property Capacity -Sum).Sum

this will give the total sum of bytes.

$bytes = (Get-WmiObject -class "cim_physicalmemory" | Measure-Object -Property Capacity -Sum).Sum

$kb = $bytes / 1024
$mb = $bytes / 1024 / 1024
$gb = $bytes / 1024 / 1024 / 1024

I tested this up to windows server 2008 (winver 6.0) even there this command seems to work

How to get all checked checkboxes

In IE9+, Chrome or Firefox you can do:

var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');

Gradle: Execution failed for task ':processDebugManifest'

I wish the Lukas Olsen solution works for other scenarios, But in my case is quite different.

I faced the same while add ActionBarShelock to project, by comparing to the older library I found that application tag is missing in manifest. By adding one line I fixed my issue.

</application>

Highlighting Text Color using Html.fromHtml() in Android?

font is deprecated use span instead Html.fromHtml("<span style=color:red>"+content+"</span>")

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

SendRedirect() will search the content between the servers. it is slow because it has to intimate the browser by sending the URL of the content. then browser will create a new request for the content within the same server or in another one.

RquestDispatcher is for searching the content within the server i think. its the server side process and it is faster compare to the SendRedirect() method. but the thing is that it will not intimate the browser in which server it is searching the required date or content, neither it will not ask the browser to change the URL in URL tab. so it causes little inconvenience to the user.

How can I use regex to get all the characters after a specific character, e.g. comma (",")

You can try with the following:

new_string = your_string.split(',').pop().trim();

This is how it works:

  • split(',') creates an array made of the different parts of your_string

(e.g. if the string is "'SELECT___100E___7',24", the array would be ["'SELECT___100E___7'", "24"]).

  • pop() gets the last element of the array

(in the example, it would be "24").

This would already be enough, but in case there might be some spaces (not in the case of the OP, but more in general), we could have:

  • trim() that would remove the spaces around the string (in case it would be " 24 ", it would become simply "24")

It's a simple solution and surely easier than a regexp.

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

How to check type of variable in Java?

public class Demo1 {

Object printType(Object o)
{
    return o;
}
 public static void main(String[] args) {

    Demo1 d=new Demo1();
    Object o1=d.printType('C');
    System.out.println(o1.getClass().getSimpleName());

}

}

How to open a link in new tab (chrome) using Selenium WebDriver?

I had used the below code to open a new tab in the browser using C# selenium..

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

js.ExecuteScript("window.open();");

Multiline editing in Visual Studio Code

I am using the latest version of VS code i.e., 1.46.1 (May 2020) in Windows 10. Just press Alt+mouse left click on the lines you want to select. This will let you select multiple lines at once and let you edit them. Also Press Esc to exit from it. This is really helpful if you're coming from sublime text.

How to set enum to null

You can either use the "?" operator for a nullable type.

public Color? myColor = null;

Or use the standard practice for enums that cannot be null by having the FIRST value in the enum (aka 0) be the default value. For example in a case of color None.

public Color myColor = Color.None;

How to hide a button programmatically?

For "Xamarin Android":

FindViewById<Button>(Resource.Id.Button1).Visibility = ViewStates.Gone;

Check If array is null or not in php

you can use

empty($result) 

to check if the main array is empty or not.

But since you have a SimpleXMLElement object, you need to query the object if it is empty or not. See http://www.php.net/manual/en/simplexmlelement.count.php

ex:

if (empty($result) || !isset($result['Tags'])) {
    return false;
}
if ( !($result['Tags'] instanceof SimpleXMLElement)) {
    return false;
}
return ($result['Tags']->count());

Run Android studio emulator on AMD processor

Windows 10 home version with latest android studio (Nov/2019):

  1. Enable virtualization from BIOS. If you have a laptop, google how to access the BIOS.

  2. Enable via Windows Features: "Windows Hypervisor Platform". Restart. No need for Hyper-V and Win10 Pro.

Done. Open Android Studio, the annoying warning is gone, emulator starts just fine.

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

Delete generated R package from your referenced library. Sometimes Clean and Rebuild doesn't remove old R generated files.

How to change the status bar color in Android?

Just add these lines in your styles.xml file

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- This is used for statusbar color. -->
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <!-- This is used for statusbar content color. If statusbarColor is light, use "true" otherwise use "false"-->
    <item name="android:windowLightStatusBar">false</item>
</style>

Running code after Spring Boot starts

With spring configuration :

@Configuration
public class ProjectConfiguration {
    private static final Logger log = 
   LoggerFactory.getLogger(ProjectConfiguration.class);

   @EventListener(ApplicationReadyEvent.class)
   public void doSomethingAfterStartup() {
    log.info("hello world, I have just started up");
  }
}

Permutations between two lists of unequal length

Answering the question "given two lists, find all possible permutations of pairs of one item from each list" and using basic Python functionality (i.e., without itertools) and, hence, making it easy to replicate for other programming languages:

def rec(a, b, ll, size):
    ret = []
    for i,e in enumerate(a):
        for j,f in enumerate(b):
            l = [e+f]
            new_l = rec(a[i+1:], b[:j]+b[j+1:], ll, size)
            if not new_l:
                ret.append(l)
            for k in new_l:
                l_k = l + k
                ret.append(l_k)
                if len(l_k) == size:
                    ll.append(l_k)
    return ret

a = ['a','b','c']
b = ['1','2']
ll = []
rec(a,b,ll, min(len(a),len(b)))
print(ll)

Returns

[['a1', 'b2'], ['a1', 'c2'], ['a2', 'b1'], ['a2', 'c1'], ['b1', 'c2'], ['b2', 'c1']]

AutoComplete TextBox in WPF

I know this is a very old question but I want to add an answer I have come up with.

First you need a handler for your normal TextChanged event handler for the TextBox:

private bool InProg;
internal void TBTextChanged(object sender, TextChangedEventArgs e)
            {
            var change = e.Changes.FirstOrDefault();
            if ( !InProg )
                {
                InProg = true;
                var culture = new CultureInfo(CultureInfo.CurrentCulture.Name);
                var source = ( (TextBox)sender );
                    if ( ( ( change.AddedLength - change.RemovedLength ) > 0 || source.Text.Length > 0 ) && !DelKeyPressed )
                        {
                         if ( Files.Where(x => x.IndexOf(source.Text, StringComparison.CurrentCultureIgnoreCase) == 0 ).Count() > 0 )
                            {
                            var _appendtxt = Files.FirstOrDefault(ap => ( culture.CompareInfo.IndexOf(ap, source.Text, CompareOptions.IgnoreCase) == 0 ));
                            _appendtxt = _appendtxt.Remove(0, change.Offset + 1);
                            source.Text += _appendtxt;
                            source.SelectionStart = change.Offset + 1;
                            source.SelectionLength = source.Text.Length;
                            }
                        }
                InProg = false;
                }
            }

Then make a simple PreviewKeyDown handler:

    private static bool DelKeyPressed;
    internal static void DelPressed(object sender, KeyEventArgs e)
    { if ( e.Key == Key.Back ) { DelKeyPressed = true; } else { DelKeyPressed = false; } }

In this example "Files" is a list of directory names created on application startup.

Then just attach the handlers:

public class YourClass
  {
  public YourClass()
    {
    YourTextbox.PreviewKeyDown += DelPressed;
    YourTextbox.TextChanged += TBTextChanged;
    }
  }

With this whatever you choose to put in the List will be used for the autocomplete box. This may not be a great option if you expect to have an enormous list for the autocomplete but in my app it only ever sees 20-50 items so it cycles through very quick.

How to convert all elements in an array to integer in JavaScript?

_x000D_
_x000D_
var arr = ["1", "2", "3"];_x000D_
arr = arr.map(Number);_x000D_
console.log(arr); // [1, 2, 3]
_x000D_
_x000D_
_x000D_

What is the difference between signed and unsigned variables?

This may not be the exact definition but I'll give you an example: If you were to create a random number taking it from the system time, here using the unsigned variable is beneficial as there is large scope for random numbers as signed numbers give both positive and negative numbers. As the system time can't be negative we use unsigned variable(Only positive numbers) and we have more wide range of random numbers.

rails 3 validation on uniqueness on multiple attributes

In Rails 2, I would have written:

validates_uniqueness_of :zipcode, :scope => :recorded_at

In Rails 3:

validates :zipcode, :uniqueness => {:scope => :recorded_at}

For multiple attributes:

validates :zipcode, :uniqueness => {:scope => [:recorded_at, :something_else]}

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

cut or awk command to print first field of first row

You could use the head instead of cat:

head -n1 /etc/*release | awk '{print $1}'

calling java methods in javascript code

Java is a server side language, whereas javascript is a client side language. Both cannot communicate. If you have setup some server side script using Java you could use AJAX on the client in order to send an asynchronous request to it and thus invoke any possible Java functions. For example if you use jQuery as js framework you may take a look at the $.ajax() method. Or if you wanted to do it using plain javascript, here's a tutorial.

How to select label for="XYZ" in CSS?

The selector would be label[for=email], so in CSS:

label[for=email]
{
    /* ...definitions here... */
}

...or in JavaScript using the DOM:

var element = document.querySelector("label[for=email]");

...or in JavaScript using jQuery:

var element = $("label[for=email]");

It's an attribute selector. Note that some browsers (versions of IE < 8, for instance) may not support attribute selectors, but more recent ones do. To support older browsers like IE6 and IE7, you'd have to use a class (well, or some other structural way), sadly.

(I'm assuming that the template {t _your_email} will fill in a field with id="email". If not, use a class instead.)

Note that if the value of the attribute you're selecting doesn't fit the rules for a CSS identifier (for instance, if it has spaces or brackets in it, or starts with a digit, etc.), you need quotes around the value:

label[for="field[]"]
{
    /* ...definitions here... */
}

They can be single or double quotes.

Normalize numpy array columns in python

If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.

Starting with your example array:

import numpy as np

x = np.array([[1000,  10,   0.5],
              [ 765,   5,  0.35],
              [ 800,   7,  0.09]])

x_normed = x / x.max(axis=0)

print(x_normed)
# [[ 1.     1.     1.   ]
#  [ 0.765  0.5    0.7  ]
#  [ 0.8    0.7    0.18 ]]

x.max(0) takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,) containing the maximum value in each column. You can then divide x by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.


If x contains negative values you would need to subtract the minimum first:

x_normed = (x - x.min(0)) / x.ptp(0)

Here, x.ptp(0) returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.

@ variables in Ruby on Rails

title is a local variable. They only exists within its scope (current block)

@title is an instance variable - and is available to all methods within the class.

You can read more here: http://strugglingwithruby.blogspot.dk/2010/03/variables.html

In Ruby on Rails - declaring your variables in your controller as instance variables (@title) makes them available to your view.

Can you find all classes in a package using reflection?

If you are merely looking to load a group of related classes, then Spring can help you.

Spring can instantiate a list or map of all classes that implement a given interface in one line of code. The list or map will contain instances of all the classes that implement that interface.

That being said, as an alternative to loading the list of classes out of the file system, instead just implement the same interface in all the classes you want to load, regardless of package and use Spring to provide you instances of all of them. That way, you can load (and instantiate) all the classes you desire regardless of what package they are in.

On the other hand, if having them all in a package is what you want, then simply have all the classes in that package implement a given interface.

Wait for shell command to complete

what you proposed with a change at the parenthesis at the Run command worked fine with VBA for me

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Integer
wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn

What is the difference between a symbolic link and a hard link?

Simply , Hard link : is just add new name to a file, that's mean , a file can have many name in the same time, all name are equal to each other, no one preferred, Hard link is not mean to copy the all contents of file and make new file is not that, it just create an alternative name to be known..

Symbolic link (symlink) : is a file pointer to another file, if the symbolic link points to an existing file which is later deleted, the symbolic link continues to point to the same file name even though the name no longer names any file.

Detect if value is number in MySQL

Still missing this simple version:

SELECT * FROM myTable WHERE `col1` + 0 = `col1`

(addition should be faster as multiplication)

Or slowest version for further playing:

SELECT *, 
CASE WHEN `col1` + 0 = `col1` THEN 1 ELSE 0 END AS `IS_NUMERIC` 
FROM `myTable`
HAVING `IS_NUMERIC` = 1

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

At the very core, the file extension you use makes no difference as to how perl interprets those files.

However, putting modules in .pm files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD and you put it in a directory Example/Plot/FourD.pm in a path in your @INC, then use and require will do the right thing when given the package name as in use Example::Plot::FourD.

The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1;, in case you add more statements.

If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

All use does is to figure out the filename from the package name provided, require it in a BEGIN block and invoke import on the package. There is nothing preventing you from not using use but taking those steps manually.

For example, below I put the Example::Plot::FourD package in a file called t.pl, loaded it in a script in file s.pl.

C:\Temp> cat t.pl
package Example::Plot::FourD;

use strict; use warnings;

sub new { bless {} => shift }

sub something { print "something\n" }

"Example::Plot::FourD"

C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;

BEGIN {
    require 't.pl';
}

my $p = Example::Plot::FourD->new;
$p->something;


C:\Temp> s
something

This example shows that module files do not have to end in 1, any true value will do.

slf4j: how to log formatted message, object array, exception

In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using

<encoder>
    <pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern> 
</encoder>

the %ex in pattern is what makes the difference

VBA collection: list of keys

You can create a small class to hold the key and value, and then store objects of that class in the collection.

Class KeyValue:

Public key As String
Public value As String
Public Sub Init(k As String, v As String)
    key = k
    value = v
End Sub

Then to use it:

Public Sub Test()
    Dim col As Collection, kv As KeyValue
    Set col = New Collection
    Store col, "first key", "first string"
    Store col, "second key", "second string"
    Store col, "third key", "third string"
    For Each kv In col
        Debug.Print kv.key, kv.value
    Next kv
End Sub

Private Sub Store(col As Collection, k As String, v As String)
    If (Contains(col, k)) Then
        Set kv = col(k)
        kv.value = v
    Else
        Set kv = New KeyValue
        kv.Init k, v
        col.Add kv, k
    End If
End Sub

Private Function Contains(col As Collection, key As String) As Boolean
    On Error GoTo NotFound
    Dim itm As Object
    Set itm = col(key)
    Contains = True
MyExit:
    Exit Function
NotFound:
    Contains = False
    Resume MyExit
End Function

This is of course similar to the Dictionary suggestion, except without any external dependencies. The class can be made more complex as needed if you want to store more information.

Android Studio - Emulator - eglSurfaceAttrib not implemented

I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)

In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

It is possible and here is how I do the same thing with a table of inputs.

wrap the table in a form like so

Then just use this

I have a form with multi-nested directives that all contain input(s), select(s), etc... These elements are all enclosed in ng-repeats, and dynamic string values.

This is how to use the directive:

<form name="myFormName">
  <nested directives of many levels>
    <your table here>
    <perhaps a td here>
    ex: <input ng-repeat=(index, variable) in variables" type="text"
               my-name="{{ variable.name + '/' + 'myFormName' }}"
               ng-model="variable.name" required />
    ex: <select ng-model="variable.name" ng-options="label in label in {{ variable.options }}"
                my-name="{{ variable.name + index + '/' + 'myFormName' }}"
        </select>
</form>

Note: you can add and index to the string concatenation if you need to serialize perhaps a table of inputs; which is what I did.

app.directive('myName', function(){

  var myNameError = "myName directive error: "

  return {
    restrict:'A', // Declares an Attributes Directive.
    require: 'ngModel', // ngModelController.

    link: function( scope, elem, attrs, ngModel ){
      if( !ngModel ){ return } // no ngModel exists for this element

      // check myName input for proper formatting ex. something/something
      checkInputFormat(attrs);

      var inputName = attrs.myName.match('^\\w+').pop(); // match upto '/'
      assignInputNameToInputModel(inputName, ngModel);

      var formName = attrs.myName.match('\\w+$').pop(); // match after '/'
      findForm(formName, ngModel, scope);
    } // end link
  } // end return

  function checkInputFormat(attrs){
    if( !/\w\/\w/.test(attrs.rsName )){
      throw myNameError + "Formatting should be \"inputName/formName\" but is " + attrs.rsName
    }
  }

  function assignInputNameToInputModel(inputName, ngModel){
    ngModel.$name = inputName
  }

  function addInputNameToForm(formName, ngModel, scope){
    scope[formName][ngModel.$name] = ngModel; return
  }

  function findForm(formName, ngModel, scope){
    if( !scope ){ // ran out of scope before finding scope[formName]
      throw myNameError + "<Form> element named " + formName + " could not be found."
    }

    if( formName in scope){ // found scope[formName]
      addInputNameToForm(formName, ngModel, scope)
      return
    }
    findForm(formName, ngModel, scope.$parent) // recursively search through $parent scopes
  }
});

This should handle many situations where you just don't know where the form will be. Or perhaps you have nested forms, but for some reason you want to attach this input name to two forms up? Well, just pass in the form name you want to attach the input name to.

What I wanted, was a way to assign dynamic values to inputs that I will never know, and then just call $scope.myFormName.$valid.

You can add anything else you wish: more tables more form inputs, nested forms, whatever you want. Just pass the form name you want to validate the inputs against. Then on form submit ask if the $scope.yourFormName.$valid

How to fix "Incorrect string value" errors?

There's good answers in here. I'm just adding mine since I ran into the same error but it turned out to be a completely different problem. (Maybe on the surface the same, but a different root cause.)

For me the error happened for the following field:

@Column(nullable = false, columnDefinition = "VARCHAR(255)")
private URI consulUri;

This ends up being stored in the database as a binary serialization of the URI class. This didn't raise any flags with unit testing (using H2) or CI/integration testing (using MariaDB4j), it blew up in our production-like setup. (Though, once the problem was understood, it was easy enough to see the wrong value in the MariaDB4j instance; it just didn't blow up the test.) The solution was to build a custom type mapper:

package redacted;

import javax.persistence.AttributeConverter;
import java.net.URI;
import java.net.URISyntaxException;

import static java.lang.String.format;

public class UriConverter implements AttributeConverter<URI, String> {
    @Override
    public String convertToDatabaseColumn(URI attribute) {
        return attribute.toString();
    }

    @Override
    public URI convertToEntityAttribute(String field) {
        try {
            return new URI(field);
        }
        catch (URISyntaxException e) {
            throw new RuntimeException(format("could not convert database field to URI: %s", field));
        }
    }
}

Used as follows:

@Column(nullable = false, columnDefinition = "VARCHAR(255)")
@Convert(converter = UriConverter.class)
private URI consulUri;

As far as Hibernate is involved, it seems it has a bunch of provided type mappers, including for java.net.URL, but not for java.net.URI (which is what we needed here).

.NET 4.0 has a new GAC, why?

I also wanted to know why 2 GAC and found the following explanation by Mark Miller in the comments section of .NET 4.0 has 2 Global Assembly Cache (GAC):

Mark Miller said... June 28, 2010 12:13 PM

Thanks for the post. "Interference issues" was intentionally vague. At the time of writing, the issues were still being investigated, but it was clear there were several broken scenarios.

For instance, some applications use Assemby.LoadWithPartialName to load the highest version of an assembly. If the highest version was compiled with v4, then a v2 (3.0 or 3.5) app could not load it, and the app would crash, even if there were a version that would have worked. Originally, we partitioned the GAC under it's original location, but that caused some problems with windows upgrade scenarios. Both of these involved code that had already shipped, so we moved our (version-partitioned GAC to another place.

This shouldn't have any impact to most applications, and doesn't add any maintenance burden. Both locations should only be accessed or modified using the native GAC APIs, which deal with the partitioning as expected. The places where this does surface are through APIs that expose the paths of the GAC such as GetCachePath, or examining the path of mscorlib loaded into managed code.

It's worth noting that we modified GAC locations when we released v2 as well when we introduced architecture as part of the assembly identity. Those added GAC_MSIL, GAC_32, and GAC_64, although all still under %windir%\assembly. Unfortunately, that wasn't an option for this release.

Hope it helps future readers.

How to Query an NTP Server using C#?

Since the old accepted answer got deleted (It was a link to a Google code search results that no longer exist), I figured I could answer this question for future reference :

public static DateTime GetNetworkTime()
{
    //default Windows time server
    const string ntpServer = "time.windows.com";

    // NTP message size - 16 bytes of the digest (RFC 2030)
    var ntpData = new byte[48];

    //Setting the Leap Indicator, Version Number and Mode values
    ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)

    var addresses = Dns.GetHostEntry(ntpServer).AddressList;

    //The UDP port number assigned to NTP is 123
    var ipEndPoint = new IPEndPoint(addresses[0], 123);
    //NTP uses UDP

    using(var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
    {
        socket.Connect(ipEndPoint);

        //Stops code hang if NTP is blocked
        socket.ReceiveTimeout = 3000;     

        socket.Send(ntpData);
        socket.Receive(ntpData);
        socket.Close();
    }

    //Offset to get to the "Transmit Timestamp" field (time at which the reply 
    //departed the server for the client, in 64-bit timestamp format."
    const byte serverReplyTime = 40;

    //Get the seconds part
    ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);

    //Get the seconds fraction
    ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);

    //Convert From big-endian to little-endian
    intPart = SwapEndianness(intPart);
    fractPart = SwapEndianness(fractPart);

    var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

    //**UTC** time
    var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);

    return networkDateTime.ToLocalTime();
}

// stackoverflow.com/a/3294698/162671
static uint SwapEndianness(ulong x)
{
    return (uint) (((x & 0x000000ff) << 24) +
                   ((x & 0x0000ff00) << 8) +
                   ((x & 0x00ff0000) >> 8) +
                   ((x & 0xff000000) >> 24));
}

Note: You will have to add the following namespaces

using System.Net;
using System.Net.Sockets;

Multiple Cursors in Sublime Text 2 Windows

It's usually just easier to skip the mouse altogether--or it would be if Sublime didn't mess up multiselect when word wrapping. Here's the official documentation on using the keyboard and mouse for multiple selection. Since it's a bit spread out, I'll summarize it:

Where shortcuts are different in Sublime Text 3, I've made a note. For v3, I always test using the latest dev build; if you're using the beta build, your experience may be different.

If you lose your selection when switching tabs or windows (particularly on Linux), try using Ctrl + U to restore it.

Mouse

Windows/Linux

Building blocks:

  • Positive/negative:
    • Add to selection: Ctrl
    • Subtract from selection: Alt In early builds of v3, this didn't work for linear selection.
  • Selection type:
    • Linear selection: Left Click
    • Block selection: Middle Click or Shift + Right Click On Linux, middle click pastes instead by default.

Combine as you see fit. For example:

  • Add to selection: Ctrl + Left Click (and optionally drag)
  • Subtract from selection: Alt + Left Click This didn't work in early builds of v3.
  • Add block selection: Ctrl + Shift + Right Click (and drag)
  • Subtract block selection: Alt + Shift + Right Click (and drag)

Mac OS X

Building blocks:

  • Positive/negative:
    • Add to selection: ?
    • Subtract from selection: ?? (only works with block selection in v3; presumably bug)
  • Selection type:
    • Linear selection: Left Click
    • Block selection: Middle Click or ? + Left Click

Combine as you see fit. For example:

  • Add to selection: ? + Left Click (and optionally drag)
  • Subtract from selection: ?? + Left Click (and drag--this combination doesn't work in Sublime Text 3, but supposedly it works in 2)
  • Add block selection: ?? + Left Click (and drag)
  • Subtract block selection: ??? + Left Click (and drag)

Keyboard

Windows

  • Return to single selection mode: Esc
  • Extend selection upward/downward at all carets: Ctrl + Alt + Up/Down
  • Extend selection leftward/rightward at all carets: Shift + Left/Right
  • Move all carets up/down/left/right, and clear selection: Up/Down/Left/Right
  • Undo the last selection motion: Ctrl + U
  • Add next occurrence of selected text to selection: Ctrl + D
  • Add all occurrences of the selected text to the selection: Alt + F3
  • Rotate between occurrences of selected text (single selection): Ctrl + F3 (reverse: Ctrl + Shift + F3)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: Ctrl + Shift + L

Linux

  • Return to single selection mode: Esc
  • Extend selection upward/downward at all carets: Alt + Up/Down Note that you may be able to hold Ctrl as well to get the same shortcuts as Windows, but Linux tends to use Ctrl + Alt combinations for global shortcuts.
  • Extend selection leftward/rightward at all carets: Shift + Left/Right
  • Move all carets up/down/left/right, and clear selection: Up/Down/Left/Right
  • Undo the last selection motion: Ctrl + U
  • Add next occurrence of selected text to selection: Ctrl + D
  • Add all occurrences of the selected text to the selection: Alt + F3
  • Rotate between occurrences of selected text (single selection): Ctrl + F3 (reverse: Ctrl + Shift + F3)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: Ctrl + Shift + L

Mac OS X

  • Return to single selection mode: ? (that's the Mac symbol for Escape)
  • Extend selection upward/downward at all carets: ^??, ^?? (See note)
  • Extend selection leftward/rightward at all carets: ??/??
  • Move all carets up/down/left/right and clear selection: ?, ?, ?, ?
  • Undo the last selection motion: ?U
  • Add next occurrence of selected text to selection: ?D
  • Add all occurrences of the selected text to the selection: ^?G
  • Rotate between occurrences of selected text (single selection): ??G (reverse: ???G)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: ??L

Notes for Mac users

On Yosemite and El Capitan, ^?? and ^?? are system keyboard shortcuts by default. If you want them to work in Sublime Text, you will need to change them:

  1. Open System Preferences.
  2. Select the Shortcuts tab.
  3. Select Mission Control in the left listbox.
  4. Change the keyboard shortcuts for Mission Control and Application windows (or disable them). I use ^?? and ^??. They defaults are ^? and ^?; adding ^ to those shortcuts triggers the same actions, but slows the animations.

In case you're not familiar with Mac's keyboard symbols:

  • ? is the escape key
  • ^ is the control key
  • ? is the option key
  • ? is the shift key
  • ? is the command key
  • ? et al are the arrow keys, as depicted

How do you create a toggle button?

You could use an anchor element (<a></a>), and use a:active and a:link to change the background image to toggle on or off. Just a thought.

Edit: The above method doesn't work too well for toggle. But you don't need to use jquery. Write a simple onClick javascript function for the element, which changes the background image appropriately to make it look like the button is pressed, and set some flag. Then on next click, image and flag is is reverted. Like so

var flag = 0;
function toggle(){
if(flag==0){
    document.getElementById("toggleDiv").style.backgroundImage="path/to/img/img1.gif";
    flag=1;
}
else if(flag==1){
    document.getElementById("toggleDiv").style.backgroundImage="path/to/img/img2.gif";
    flag=0;
}
}

And the html like so <div id="toggleDiv" onclick="toggle()">Some thing</div>

How To have Dynamic SQL in MySQL Stored Procedure

I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

Here is an example:

mysql> PREPARE stmt FROM 
    -> 'select count(*) 
    -> from information_schema.schemata 
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt 
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;

The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

Here is a good link about this:

Don't forget to deallocate the stmt using the last line!

Good Luck!