Programs & Examples On #Validate request

ValidateRequest="false" doesn't work in Asp.Net 4

This works without changing the validation mode.

You have to use a System.Web.Helpers.Validation.Unvalidated helper from System.Web.WebPages.dll. It is going to return a UnvalidatedRequestValues object which allows to access the form and QueryString without validation.

For example,

var queryValue = Server.UrlDecode(Request.Unvalidated("MyQueryKey"));

Works for me for MVC3 and .NET 4.

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

I have faced this problem during development of a E-Commerce site using NopCommerce, I got this solution by 3 different ways as like the previous answers. But according to the NopCommerce structure I didn't found those three at a time. I have just seen that there they are using just [AllowHtml] and it's working fine except any problem. As previously asked question

Personally I don't prefer [ValidateInput(false)] because i's skipping total model entity checking, which is insecure. But if anyone just write have a look here

[AllowHtml] 
public string BlogText {get;set;}

then it just skip only single property, and just allow only particular property and check hardly all other entities. Therefore it seems preferable towards mine.

How to show progress bar while loading, using ajax

This link describes how you can add a progress event listener to the xhr object using jquery.

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();

        // Upload progress
        xhr.upload.addEventListener("progress", function(evt){
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                //Do something with upload progress
                console.log(percentComplete);
            }
       }, false);
       
       // Download progress
       xhr.addEventListener("progress", function(evt){
           if (evt.lengthComputable) {
               var percentComplete = evt.loaded / evt.total;
               // Do something with download progress
               console.log(percentComplete);
           }
       }, false);
       
       return xhr;
    },
    type: 'POST',
    url: "/",
    data: {},
    success: function(data){
        // Do something success-ish
    }
});

Correct way to select from two tables in SQL Server with no common field to join on

A suggestion - when using cross join please take care of the duplicate scenarios. For example in your case:

  • Table 1 may have >1 columns as part of primary keys(say table1_id, id2, id3, table2_id)
  • Table 2 may have >1 columns as part of primary keys(say table2_id, id3, id4)

since there are common keys between these two tables (i.e. foreign keys in one/other) - we will end up with duplicate results. hence using the following form is good:

WITH data_mined_table (col1, col2, col3, etc....) AS
SELECT DISTINCT col1, col2, col3, blabla
FROM table_1 (NOLOCK), table_2(NOLOCK))
SELECT * from data_mined WHERE data_mined_table.col1 = :my_param_value

MySQL SELECT AS combine two columns into one

If both columns can contain NULL, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

This way you won't have to check for NULL-ness of each column separately.

Alternatively, if both columns are actually defined as NOT NULL, CONCAT() will be quite enough:

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

As for COALESCE, it's a bit different beast: given the list of arguments, it returns the first that's not NULL.

How do I rename a column in a SQLite database table?

As mentioned before, there is a tool SQLite Database Browser, which does this. Lyckily, this tool keeps a log of all operations performed by the user or the application. Doing this once and looking at the application log, you will see the code involved. Copy the query and paste as required. Worked for me. Hope this helps

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

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

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

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

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

Example:

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

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

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

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

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

In Python 3 it's quite easy: read the file and rewrite it with utf-8 encoding:

s = open(bom_file, mode='r', encoding='utf-8-sig').read()
open(bom_file, mode='w', encoding='utf-8').write(s)

Error on renaming database in SQL Server 2008 R2

You could try setting the database to single user mode.

https://stackoverflow.com/a/11624/2408095

use master
ALTER DATABASE BOSEVIKRAM SET SINGLE_USER WITH ROLLBACK IMMEDIATE    
ALTER DATABASE BOSEVIKRAM MODIFY NAME = [BOSEVIKRAM_Deleted]
ALTER DATABASE BOSEVIKRAM_Deleted SET MULTI_USER

Release generating .pdb files, why?

Debug symbols (.pdb) and XML doc (.xml) files make up a large percentage of the total size and should not be part of the regular deployment package. But it should be possible to access them in case they are needed.

One possible approach: at the end of the TFS build process, move them to a separate artifact.

Eclipse shows errors but I can't find them

Right Click on Project -> Build Path -> Configure Build Path. Check if Maven Dependencies is there in list, if not then update maven project by Right Click on Project -> Maven -> Update Project

Create table (structure) from existing table

If you want to create a table with the only structure to be copied from the original table then you can use the following command to do that.

create table <tablename> as select * from <sourcetablename> where 1>2;

By this false condition you can leave the records and copy the structure.

Determine the type of an object?

Determine the type of a Python object

Determine the type of an object with type

>>> obj = object()
>>> type(obj)
<class 'object'>

Although it works, avoid double underscore attributes like __class__ - they're not semantically public, and, while perhaps not in this case, the builtin functions usually have better behavior.

>>> obj.__class__ # avoid this!
<class 'object'>

type checking

Is there a simple way to determine if a variable is a list, dictionary, or something else? I am getting an object back that may be either type and I need to be able to tell the difference.

Well that's a different question, don't use type - use isinstance:

def foo(obj):
    """given a string with items separated by spaces, 
    or a list or tuple, 
    do something sensible
    """
    if isinstance(obj, str):
        obj = str.split()
    return _foo_handles_only_lists_or_tuples(obj)

This covers the case where your user might be doing something clever or sensible by subclassing str - according to the principle of Liskov Substitution, you want to be able to use subclass instances without breaking your code - and isinstance supports this.

Use Abstractions

Even better, you might look for a specific Abstract Base Class from collections or numbers:

from collections import Iterable
from numbers import Number

def bar(obj):
    """does something sensible with an iterable of numbers, 
    or just one number
    """
    if isinstance(obj, Number): # make it a 1-tuple
        obj = (obj,)
    if not isinstance(obj, Iterable):
        raise TypeError('obj must be either a number or iterable of numbers')
    return _bar_sensible_with_iterable(obj)

Or Just Don't explicitly Type-check

Or, perhaps best of all, use duck-typing, and don't explicitly type-check your code. Duck-typing supports Liskov Substitution with more elegance and less verbosity.

def baz(obj):
    """given an obj, a dict (or anything with an .items method) 
    do something sensible with each key-value pair
    """
    for key, value in obj.items():
        _baz_something_sensible(key, value)

Conclusion

  • Use type to actually get an instance's class.
  • Use isinstance to explicitly check for actual subclasses or registered abstractions.
  • And just avoid type-checking where it makes sense.

adb command for getting ip address assigned by operator

Try:

adb shell ip addr show rmnet0  | grep 'inet ' | cut -d' ' -f6|cut -d/ -f1

It will return your IPV4 assigned by the operator

172.22.1.215

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

It looks like a bug http://code.google.com/p/android/issues/detail?id=939.

Finally I have to write something like this:

 <stroke android:width="3dp"
         android:color="#555555"
         />

 <padding android:left="1dp"
          android:top="1dp"
          android:right="1dp"
          android:bottom="1dp"
          /> 

 <corners android:radius="1dp"
  android:bottomRightRadius="2dp" android:bottomLeftRadius="0dp" 
  android:topLeftRadius="2dp" android:topRightRadius="0dp"/> 

I have to specify android:bottomRightRadius="2dp" for left-bottom rounded corner (another bug here).

How do I compare two hashes?

Rails is deprecating the diff method.

For a quick one-liner:

hash1.to_s == hash2.to_s

How to create a table from select query result in SQL Server 2008

Select [Column Name] into [New Table] from [Source Table]

HTML for the Pause symbol in audio and video control

There is no character encoded for use as a pause symbol, though various characters or combinations of characters may look more or less like a pause symbol, depending on font.

In a discussion in the public Unicode mailing list in 2005, a suggestion was made to use two copies of the U+275A HEAVY VERTICAL BAR character: ??. But the adequacy of the result depends on font; for example, the glyph might have been designed so that the bars are too much apart. – The list discussion explains why a pause symbol had not been encoded, and this has not changed.

Thus, the best option is to use an image. If you need to use the symbol in text, it is best to create it in a suitably large size (say 60 by 60 pixels) and scale it down to text size with CSS (e.g., setting height: 0.8em on the img element).

Why is jquery's .ajax() method not sending my session cookie?

Using

xhrFields: { withCredentials:true }

as part of my jQuery ajax call was only part of the solution. I also needed to have the headers returned in the OPTIONS response from my resource:

Access-Control-Allow-Origin : http://www.wombling.com
Access-Control-Allow-Credentials : true

It was important that only one allowed "origin" was in the response header of the OPTIONS call and not "*". I achieved this by reading the origin from the request and populating it back into the response - probably circumventing the original reason for the restriction, but in my use case the security is not paramount.

I thought it worth explicitly mentioning the requirement for only one origin, as the W3C standard does allow for a space separated list -but Chrome doesn't! http://www.w3.org/TR/cors/#access-control-allow-origin-response-header NB the "in practice" bit.

Single line sftp from terminal

Update Sep 2017 - tl;dr

Download a single file from a remote ftp server to your machine:

sftp {user}@{host}:{remoteFileName} {localFileName}

Upload a single file from your machine to a remote ftp server:

sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'

Original answer:

Ok, so I feel a little dumb. But I figured it out. I almost had it at the top with:

sftp user@host remoteFile localFile

The only documentation shown in the terminal is this:

sftp [user@]host[:file ...]
sftp [user@]host[:dir[/]]

However, I came across this site which shows the following under the synopsis:

sftp [-vC1 ] [-b batchfile ] [-o ssh_option ] [-s subsystem | sftp_server ] [-B buffer_size ] [-F ssh_config ] [-P sftp_server path ] [-R num_requests ] [-S program ] host 
sftp [[user@]host[:file [file]]] 
sftp [[user@]host[:dir[/]]]

So the simple answer is you just do : after your user and host then the remote file and local filename. Incredibly simple!

Single line, sftp copy remote file:

sftp username@hostname:remoteFileName localFileName
sftp kyle@kylesserver:/tmp/myLogFile.log /tmp/fileNameToUseLocally.log

Update Feb 2016

In case anyone is looking for the command to do the reverse of this and push a file from your local computer to a remote server in one single line sftp command, user @Thariama below posted the solution to accomplish that. Hat tip to them for the extra code.

sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'

selenium - chromedriver executable needs to be in PATH

Try this :

pip install webdriver-manager
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())

How can I plot data with confidence intervals?

Here is a solution using functions plot(), polygon() and lines().

 set.seed(1234)
 df <- data.frame(x =1:10,
                 F =runif(10,1,2),
                 L =runif(10,0,1),
                 U =runif(10,2,3))


 plot(df$x, df$F, ylim = c(0,4), type = "l")
 #make polygon where coordinates start with lower limit and 
 # then upper limit in reverse order
 polygon(c(df$x,rev(df$x)),c(df$L,rev(df$U)),col = "grey75", border = FALSE)
 lines(df$x, df$F, lwd = 2)
 #add red lines on borders of polygon
 lines(df$x, df$U, col="red",lty=2)
 lines(df$x, df$L, col="red",lty=2)

enter image description here

Now use example data provided by OP in another question:

   Lower <- c(0.418116841, 0.391011834, 0.393297710,
        0.366144073,0.569956636,0.224775521,0.599166016,0.512269587,
        0.531378573, 0.311448219, 0.392045751,0.153614913, 0.366684097,
        0.161100849,0.700274810,0.629714150, 0.661641288, 0.533404093,
        0.412427559, 0.432905333, 0.525306427,0.224292061,
        0.28893064,0.099543648, 0.342995605,0.086973739,0.289030388,
        0.081230826,0.164505624, -0.031290586,0.148383474,0.070517523,0.009686605,
        -0.052703529,0.475924192,0.253382210, 0.354011010,0.130295355,0.102253218,
        0.446598823,0.548330752,0.393985810,0.481691632,0.111811248,0.339626541,
        0.267831909,0.133460254,0.347996621,0.412472322,0.133671128,0.178969601,0.484070587,
        0.335833224,0.037258467, 0.141312363,0.361392799,0.129791998,
        0.283759439,0.333893418,0.569533076,0.385258093,0.356201955,0.481816148,
        0.531282473,0.273126565,0.267815691,0.138127486,0.008865700,0.018118398,0.080143484,
        0.117861634,0.073697418,0.230002398,0.105855042,0.262367348,0.217799352,0.289108011,
        0.161271889,0.219663224,0.306117717,0.538088622,0.320711912,0.264395149,0.396061543,
        0.397350946,0.151726970,0.048650180,0.131914718,0.076629840,0.425849394,
        0.068692279,0.155144797,0.137939059,0.301912657,-0.071415593,-0.030141781,0.119450922,
        0.312927614,0.231345972)

 Upper.limit <- c(0.6446223,0.6177311, 0.6034427, 0.5726503,
      0.7644718, 0.4585430, 0.8205418, 0.7154043,0.7370033,
      0.5285199, 0.5973728, 0.3764209, 0.5818298,
      0.3960867,0.8972357, 0.8370151, 0.8359921, 0.7449118,
      0.6152879, 0.6200704, 0.7041068, 0.4541011, 0.5222653,
      0.3472364, 0.5956551, 0.3068065, 0.5112895, 0.3081448,
      0.3745473, 0.1931089, 0.3890704, 0.3031025, 0.2472591,
      0.1976092, 0.6906118, 0.4736644, 0.5770463, 0.3528607,
      0.3307651, 0.6681629, 0.7476231, 0.5959025, 0.7128883,
      0.3451623, 0.5609742, 0.4739216, 0.3694883, 0.5609220,
      0.6343219, 0.3647751, 0.4247147, 0.6996334, 0.5562876,
      0.2586490, 0.3750040, 0.5922248, 0.3626322, 0.5243285,
      0.5548211, 0.7409648, 0.5820070, 0.5530232, 0.6863703,
      0.7206998, 0.4952387, 0.4993264, 0.3527727, 0.2203694,
      0.2583149, 0.3035342, 0.3462009, 0.3003602, 0.4506054,
      0.3359478, 0.4834151, 0.4391330, 0.5273411, 0.3947622,
      0.4133769, 0.5288060, 0.7492071, 0.5381701, 0.4825456,
      0.6121942, 0.6192227, 0.3784870, 0.2574025, 0.3704140,
      0.2945623, 0.6532694, 0.2697202, 0.3652230, 0.3696383,
      0.5268808, 0.1545602, 0.2221450, 0.3553377, 0.5204076,
      0.3550094)

  Fitted.values<- c(0.53136955, 0.50437146, 0.49837019,
  0.46939721, 0.66721423, 0.34165926, 0.70985388, 0.61383696,
  0.63419092, 0.41998407, 0.49470927, 0.26501789, 0.47425695,
  0.27859380, 0.79875525, 0.73336461, 0.74881668, 0.63915795,
  0.51385774, 0.52648789, 0.61470661, 0.33919656, 0.40559797,
  0.22339000, 0.46932536, 0.19689011, 0.40015996, 0.19468781,
  0.26952645, 0.08090917, 0.26872696, 0.18680999, 0.12847285,
  0.07245286, 0.58326799, 0.36352329, 0.46552867, 0.24157804,
  0.21650915, 0.55738088, 0.64797691, 0.49494416, 0.59728999,
  0.22848680, 0.45030036, 0.37087676, 0.25147426, 0.45445930,
  0.52339711, 0.24922310, 0.30184215, 0.59185198, 0.44606040,
  0.14795374, 0.25815819, 0.47680880, 0.24621212, 0.40404398,
  0.44435727, 0.65524894, 0.48363255, 0.45461258, 0.58409323,
  0.62599114, 0.38418264, 0.38357103, 0.24545011, 0.11461756,
  0.13821664, 0.19183886, 0.23203127, 0.18702881, 0.34030391,
  0.22090140, 0.37289121, 0.32846615, 0.40822456, 0.27801706,
  0.31652008, 0.41746184, 0.64364785, 0.42944100, 0.37347037,
  0.50412786, 0.50828681, 0.26510696, 0.15302635, 0.25116438,
  0.18559609, 0.53955941, 0.16920626, 0.26018389, 0.25378867,
  0.41439675, 0.04157232, 0.09600163, 0.23739430, 0.41666762,
  0.29317767)

Assemble into a data frame (no x provided, so using indices)

 df2 <- data.frame(x=seq(length(Fitted.values)),
                    fit=Fitted.values,lwr=Lower,upr=Upper.limit)
 plot(fit~x,data=df2,ylim=range(c(df2$lwr,df2$upr)))
 #make polygon where coordinates start with lower limit and then upper limit in reverse order
 with(df2,polygon(c(x,rev(x)),c(lwr,rev(upr)),col = "grey75", border = FALSE))
 matlines(df2[,1],df2[,-1],
          lwd=c(2,1,1),
          lty=1,
          col=c("black","red","red"))

enter image description here

find all the name using mysql query which start with the letter 'a'

Try this:

select * from artists where name like "A%" or name like "B%" or name like "C%"

React JS onClick event handler

Why not:

onItemClick: function (event) {

    event.currentTarget.style.backgroundColor = '#ccc';

},

render: function() {
    return (
        <div>
            <ul>
                <li onClick={this.onItemClick}>Component 1</li>
            </ul>
        </div>
    );
}

And if you want to be more React-ive about it, you might want to set the selected item as state of its containing React component, then reference that state to determine the item's color within render:

onItemClick: function (event) {

    this.setState({ selectedItem: event.currentTarget.dataset.id });
    //where 'id' =  whatever suffix you give the data-* li attribute
},

render: function() {
    return (
        <div>
            <ul>
                <li onClick={this.onItemClick} data-id="1" className={this.state.selectedItem == 1 ? "on" : "off"}>Component 1</li>
                <li onClick={this.onItemClick} data-id="2" className={this.state.selectedItem == 2 ? "on" : "off"}>Component 2</li>
                <li onClick={this.onItemClick} data-id="3" className={this.state.selectedItem == 3 ? "on" : "off"}>Component 3</li>
            </ul>
        </div>
    );
},

You'd want to put those <li>s into a loop, and you need to make the li.on and li.off styles set your background-color.

start/play embedded (iframe) youtube-video on click of an image

You can do this simply like this

$('#image_id').click(function() {
  $("#some_id iframe").attr('src', $("#some_id iframe", parent).attr('src') + '?autoplay=1'); 
});

where image_id is your image id you are clicking and some_id is id of div in which iframe is also you can use iframe id directly.

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

I found "Choose a Collection" section of Microsoft Docs on Collection and Data Structure page really useful

C# Collections and Data Structures : Choose a collection

enter image description here

And also the following matrix to compare some other features

enter image description here

jQuery - setting the selected value of a select control via its text description

take a look at the jquery selectedbox plugin

selectOptions(value[, clear]): 

Select options by value, using a string as the parameter $("#myselect2").selectOptions("Value 1");, or a regular expression $("#myselect2").selectOptions(/^val/i);.

You can also clear already selected options: $("#myselect2").selectOptions("Value 2", true);

Difference between null and empty string

Null means nothing. Its just a literal. Null is the value of reference variable. But empty string is blank.It gives the length=0. Empty string is a blank value,means the string does not have any thing.

Cannot call getSupportFragmentManager() from activity

This worked for me. Running android API 19 and above.

FragmentManager fragMan = getFragmentManager();

Textarea Auto height

I see that this is answered already, but I believe I have a simple jQuery solution ( jQuery is not even really needed; I just enjoy using it ):

I suggest counting the line breaks in the textarea text and setting the rows attribute of the textarea accordingly.

var text = jQuery('#your_textarea').val(),
    // look for any "\n" occurences
    matches = text.match(/\n/g),
    breaks = matches ? matches.length : 2;

jQuery('#your_textarea').attr('rows',breaks + 2);

How to read the last row with SQL Server

If you don't have any ordered column, you can use the physical id of each lines:

SELECT top 1 sys.fn_PhysLocFormatter(%%physloc%%) AS [File:Page:Slot], 
              T.*
FROM MyTable As T
order by sys.fn_PhysLocFormatter(%%physloc%%) DESC

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

The problem is the std namespace you are missing. cout is in the std namespace.
Add using namespace std; after the #include

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

We have had the same issue in eclipse or intellij. After trying many alternative solutions, I found simple solution - add this config to your application.properties: spring.main.web-application-type=none

"Prevent saving changes that require the table to be re-created" negative effects

Yes, there are negative effects from this:

If you script out a change blocked by this flag you get something like the script below (all i am turning the ID column in Contact into an autonumbered IDENTITY column, but the table has dependencies). Note potential errors that can occur while the following is running:

  1. Even microsoft warns that this may cause data loss (that comment is auto-generated)!
  2. for a period of time, foreign keys are not enforced.
  3. if you manually run this in ssms and the ' EXEC('INSERT INTO ' fails, and you let the following statements run (which they do by default, as they are split by 'go') then you will insert 0 rows, then drop the old table.
  4. if this is a big table, the runtime of the insert can be large, and the transaction is holding a schema modification lock, so blocks many things.

--

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/

BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
    DROP CONSTRAINT fk_Contact_AddressType
GO
ALTER TABLE ref.ContactpointType SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
    DROP CONSTRAINT fk_contact_profile
GO
ALTER TABLE raw.Profile SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE raw.Tmp_Contact
    (
    ContactID int NOT NULL IDENTITY (1, 1),
    ProfileID int NOT NULL,
    AddressType char(2) NOT NULL,
    ContactText varchar(250) NULL
    )  ON [PRIMARY]
GO
ALTER TABLE raw.Tmp_Contact SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT raw.Tmp_Contact ON
GO
IF EXISTS(SELECT * FROM raw.Contact)
     EXEC('INSERT INTO raw.Tmp_Contact (ContactID, ProfileID, AddressType, ContactText)
        SELECT ContactID, ProfileID, AddressType, ContactText FROM raw.Contact WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT raw.Tmp_Contact OFF
GO
ALTER TABLE raw.PostalAddress
    DROP CONSTRAINT fk_AddressProfile
GO
ALTER TABLE raw.MarketingFlag
    DROP CONSTRAINT fk_marketingflag_contact
GO
ALTER TABLE raw.Phones
    DROP CONSTRAINT fk_phones_contact
GO
DROP TABLE raw.Contact
GO
EXECUTE sp_rename N'raw.Tmp_Contact', N'Contact', 'OBJECT' 
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
    Idx_Contact_1 PRIMARY KEY CLUSTERED 
    (
    ProfileID,
    ContactID
    ) 

GO
ALTER TABLE raw.Contact ADD CONSTRAINT
    Idx_Contact UNIQUE NONCLUSTERED 
    (
    ProfileID,
    ContactID
    ) 

GO
CREATE NONCLUSTERED INDEX idx_Contact_0 ON raw.Contact
    (
    AddressType
    ) 
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
    fk_contact_profile FOREIGN KEY
    (
    ProfileID
    ) REFERENCES raw.Profile
    (
    ProfileID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE raw.Contact ADD CONSTRAINT
    fk_Contact_AddressType FOREIGN KEY
    (
    AddressType
    ) REFERENCES ref.ContactpointType
    (
    ContactPointTypeCode
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Phones ADD CONSTRAINT
    fk_phones_contact FOREIGN KEY
    (
    ProfileID,
    PhoneID
    ) REFERENCES raw.Contact
    (
    ProfileID,
    ContactID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE raw.Phones SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.MarketingFlag ADD CONSTRAINT
    fk_marketingflag_contact FOREIGN KEY
    (
    ProfileID,
    ContactID
    ) REFERENCES raw.Contact
    (
    ProfileID,
    ContactID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE raw.MarketingFlag SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.PostalAddress ADD CONSTRAINT
    fk_AddressProfile FOREIGN KEY
    (
    ProfileID,
    AddressID
    ) REFERENCES raw.Contact
    (
    ProfileID,
    ContactID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE raw.PostalAddress SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

referenced before assignment error in python

My Scenario

def example():
    cl = [0, 1]
    def inner():
        #cl = [1, 2] # access this way will throw `reference before assignment`
        cl[0] = 1 
        cl[1] = 2   # these won't

    inner()

Combination of async function + await + setTimeout

This is a quicker fix in one-liner.

Hope this will help.

// WAIT FOR 200 MILISECONDS TO GET DATA //
await setTimeout(()=>{}, 200);

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

How can I compile my Perl script so it can be executed on systems without perl installed?

And let's not forget ActiveState's PDK. It will allow you to compile UI, command line, Windows services and installers.

I highly recommend it, it has served me very well over the years, but it is around 300$ for a licence.

ENOENT, no such file or directory

__dirname 

Gives you the current node application's rooth directory.

In your case, you'd use

__dirname + '/Desktop/MyApp/newversion/partials/navigation.jade';

See this answer:

App base path from a module in NodeJS

Getting Excel to refresh data on sheet from within VBA

The following lines will do the trick:

ActiveSheet.EnableCalculation = False  
ActiveSheet.EnableCalculation = True  

Edit: The .Calculate() method will not work for all functions. I tested it on a sheet with add-in array functions. The production sheet I'm using is complex enough that I don't want to test the .CalculateFull() method, but it may work.

Add new element to an existing object

Use this:

myFunction.bookName = 'mybook';
myFunction.bookdesc = 'new';

Or, if you are using jQuery:

$(myFunction).extend({
    bookName:'mybook',
    bookdesc: 'new'
});

The push method is wrong because it belongs to the Array.prototype object.

To create a named object, try this:

var myObj = function(){
    this.property = 'foo';
    this.bar = function(){
    }
}
myObj.prototype.objProp = true;
var newObj = new myObj();

Import pandas dataframe column as string not int

Just want to reiterate this will work in pandas >= 0.9.1:

In [2]: read_csv('sample.csv', dtype={'ID': object})
Out[2]: 
                           ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

I'm creating an issue about detecting integer overflows also.

EDIT: See resolution here: https://github.com/pydata/pandas/issues/2247

Update as it helps others:

To have all columns as str, one can do this (from the comment):

pd.read_csv('sample.csv', dtype = str)

To have most or selective columns as str, one can do this:

# lst of column names which needs to be string
lst_str_cols = ['prefix', 'serial']
# use dictionary comprehension to make dict of dtypes
dict_dtypes = {x : 'str'  for x in lst_str_cols}
# use dict on dtypes
pd.read_csv('sample.csv', dtype=dict_dtypes)

Importing CSV with line breaks in Excel 2007

In my case opening CSV in notepad++ and adding SEP="," as the first line allows me open CSV with line breaks and utf-8 in Excel without issues

Create an application setup in visual studio 2013

Visual Studio 2013 now supports setup projects. Microsoft have shipped a Visual Studio extension to produce setup projects.

Visual Studio Installer Projects Extension

Running Facebook application on localhost

Forward is a great tool for helping with development of facebook apps locally, it supports SSL so the cert thing isn't a problem.

https://forwardhq.com/in-use/facebook

DISCLAIMER: I'm one of the devs

Proper way to use **kwargs in Python

@AbhinavGupta and @Steef suggested using update(), which I found very helpful for processing large argument lists:

args.update(kwargs)

What if we want to check that the user hasn't passed any spurious/unsupported arguments? @VinaySajip pointed out that pop() can be used to iteratively process the list of arguments. Then, any leftover arguments are spurious. Nice.

Here's another possible way to do this, which keeps the simple syntax of using update():

# kwargs = dictionary of user-supplied arguments
# args = dictionary containing default arguments

# Check that user hasn't given spurious arguments
unknown_args = user_args.keys() - default_args.keys()
if unknown_args:
    raise TypeError('Unknown arguments: {}'.format(unknown_args))

# Update args to contain user-supplied arguments
args.update(kwargs)

unknown_args is a set containing the names of arguments that don't occur in the defaults.

Why Maven uses JDK 1.6 but my java -version is 1.7

add the following to your ~/.mavenrc:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/{jdk-version}/Contents/Home

Second Solution:

echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.bash_profile

How do I remove duplicate items from an array in Perl?

Using concept of unique hash keys :

my @array  = ("a","b","c","b","a","d","c","a","d");
my %hash   = map { $_ => 1 } @array;
my @unique = keys %hash;
print "@unique","\n";

Output: a c b d

addEventListener vs onclick

In this answer I will describe the three methods of defining DOM event handlers.

element.addEventListener()

Code example:

_x000D_
_x000D_
const element = document.querySelector('a');_x000D_
element.addEventListener('click', event => event.preventDefault(), true);
_x000D_
<a href="//google.com">Try clicking this link.</a>
_x000D_
_x000D_
_x000D_

element.addEventListener() has multiple advantages:

  • Allows you to register unlimited events handlers and remove them with element.removeEventListener().
  • Has useCapture parameter, which indicates whether you'd like to handle event in its capturing or bubbling phase. See: Unable to understand useCapture attribute in addEventListener.
  • Cares about semantics. Basically, it makes registering event handlers more explicit. For a beginner, a function call makes it obvious that something happens, whereas assigning event to some property of DOM element is at least not intuitive.
  • Allows you to separate document structure (HTML) and logic (JavaScript). In tiny web applications it may not seem to matter, but it does matter with any bigger project. It's way much easier to maintain a project which separates structure and logic than a project which doesn't.
  • Eliminates confusion with correct event names. Due to using inline event listeners or assigning event listeners to .onevent properties of DOM elements, lots of inexperienced JavaScript programmers thinks that the event name is for example onclick or onload. on is not a part of event name. Correct event names are click and load, and that's how event names are passed to .addEventListener().
  • Works in almost all browser. If you still have to support IE <= 8, you can use a polyfill from MDN.

element.onevent = function() {} (e.g. onclick, onload)

Code example:

_x000D_
_x000D_
const element = document.querySelector('a');_x000D_
element.onclick = event => event.preventDefault();
_x000D_
<a href="//google.com">Try clicking this link.</a>
_x000D_
_x000D_
_x000D_

This was a way to register event handlers in DOM 0. It's now discouraged, because it:

  • Allows you to register only one event handler. Also removing the assigned handler is not intuitive, because to remove event handler assigned using this method, you have to revert onevent property back to its initial state (i.e. null).
  • Doesn't respond to errors appropriately. For example, if you by mistake assign a string to window.onload, for example: window.onload = "test";, it won't throw any errors. Your code wouldn't work and it would be really hard to find out why. .addEventListener() however, would throw error (at least in Firefox): TypeError: Argument 2 of EventTarget.addEventListener is not an object.
  • Doesn't provide a way to choose if you want to handle event in its capturing or bubbling phase.

Inline event handlers (onevent HTML attribute)

Code example:

_x000D_
_x000D_
<a href="//google.com" onclick="event.preventDefault();">Try clicking this link.</a>
_x000D_
_x000D_
_x000D_

Similarly to element.onevent, it's now discouraged. Besides the issues that element.onevent has, it:

  • Is a potential security issue, because it makes XSS much more harmful. Nowadays websites should send proper Content-Security-Policy HTTP header to block inline scripts and allow external scripts only from trusted domains. See How does Content Security Policy work?
  • Doesn't separate document structure and logic.
  • If you generate your page with a server-side script, and for example you generate a hundred links, each with the same inline event handler, your code would be much longer than if the event handler was defined only once. That means the client would have to download more content, and in result your website would be slower.

See also

Best way to extract a subvector from a vector?

You didn't mention what type std::vector<...> myVec is, but if it's a simple type or struct/class that doesn't include pointers, and you want the best efficiency, then you can do a direct memory copy (which I think will be faster than the other answers provided). Here is a general example for std::vector<type> myVec where type in this case is int:

typedef int type; //choose your custom type/struct/class
int iFirst = 100000; //first index to copy
int iLast = 101000; //last index + 1
int iLen = iLast - iFirst;
std::vector<type> newVec;
newVec.resize(iLen); //pre-allocate the space needed to write the data directly
memcpy(&newVec[0], &myVec[iFirst], iLen*sizeof(type)); //write directly to destination buffer from source buffer

Reading a binary file with python

Read the binary file content like this:

with open(fileName, mode='rb') as file: # b is important -> binary
    fileContent = file.read()

then "unpack" binary data using struct.unpack:

The start bytes: struct.unpack("iiiii", fileContent[:20])

The body: ignore the heading bytes and the trailing byte (= 24); The remaining part forms the body, to know the number of bytes in the body do an integer division by 4; The obtained quotient is multiplied by the string 'i' to create the correct format for the unpack method:

struct.unpack("i" * ((len(fileContent) -24) // 4), fileContent[20:-4])

The end byte: struct.unpack("i", fileContent[-4:])

Laravel 5.1 - Checking a Database Connection

You can use this, in a controller method or in an inline function of a route:

   try {
        DB::connection()->getPdo();
        if(DB::connection()->getDatabaseName()){
            echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
        }else{
            die("Could not find the database. Please check your configuration.");
        }
    } catch (\Exception $e) {
        die("Could not open connection to database server.  Please check your configuration.");
    }

execute shell command from android

Process p;
StringBuffer output = new StringBuffer();
try {
    p = Runtime.getRuntime().exec(params[0]);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
    String line = "";
    while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
        p.waitFor();
    }
} 
catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}
String response = output.toString();
return response;

Command-line tool for finding out who is locking a file

Handle should do the trick.

Ever wondered which program has a particular file or directory open? Now you can find out. Handle is a utility that displays information about open handles for any process in the system. You can use it to see the programs that have a file open, or to see the object types and names of all the handles of a program.

PHP: Split string

explode('.', $string)

If you know your string has a fixed number of components you could use something like

list($a, $b) = explode('.', 'object.attribute');
echo $a;
echo $b;

Prints:

object
attribute

Enabling WiFi on Android Emulator

Apparently it does not and I didn't quite expect it would. HOWEVER Ivan brings up a good possibility that has escaped Android people.

What is the purpose of an emulator? to EMULATE, right? I don't see why for testing purposes -provided the tester understands the limitations- the emulator might not add a Wifi emulator.

It could for example emulate WiFi access by using the underlying internet connection of the host. Obviously testing WPA/WEP differencess would not make sense but at least it could toggle access via WiFi.

Or some sort of emulator plugin where there would be a base WiFi emulator that would emulate WiFi access via the underlying connection but then via configuration it could emulate WPA/WEP by providing a list of fake WiFi networks and their corresponding fake passwords that would be matched against a configurable list of credentials.

After all the idea is to do initial testing on the emulator and then move on to the actual device.

Date Conversion from String to sql Date in Java giving different output?

While using the date formats, you may want to keep in mind to always use MM for months and mm for minutes. That should resolve your problem.

How can I detect the encoding/codepage of a text file

You can't detect the codepage, you need to be told it. You can analyse the bytes and guess it, but that can give some bizarre (sometimes amusing) results. I can't find it now, but I'm sure Notepad can be tricked into displaying English text in Chinese.

Anyway, this is what you need to read: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).

Specifically Joel says:

The Single Most Important Fact About Encodings

If you completely forget everything I just explained, please remember one extremely important fact. It does not make sense to have a string without knowing what encoding it uses. You can no longer stick your head in the sand and pretend that "plain" text is ASCII. There Ain't No Such Thing As Plain Text.

If you have a string, in memory, in a file, or in an email message, you have to know what encoding it is in or you cannot interpret it or display it to users correctly.

Where is the php.ini file on a Linux/CentOS PC?

php -i |grep 'Configuration File'

How to check whether a file is empty or not?

Both getsize() and stat() will throw an exception if the file does not exist. This function will return True/False without throwing (simpler but less robust):

import os
def is_non_zero_file(fpath):  
    return os.path.isfile(fpath) and os.path.getsize(fpath) > 0

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

You're probably setting a value for a key in the alertView, which is not allowed. The key is in this case LoginScreen. I don't see any call to setValue(), so I assume it's somewhere else in the code.

What are SP (stack) and LR in ARM?

SP is the stack register a shortcut for typing r13. LR is the link register a shortcut for r14. And PC is the program counter a shortcut for typing r15.

When you perform a call, called a branch link instruction, bl, the return address is placed in r14, the link register. the program counter pc is changed to the address you are branching to.

There are a few stack pointers in the traditional ARM cores (the cortex-m series being an exception) when you hit an interrupt for example you are using a different stack than when running in the foreground, you dont have to change your code just use sp or r13 as normal the hardware has done the switch for you and uses the correct one when it decodes the instructions.

The traditional ARM instruction set (not thumb) gives you the freedom to use the stack in a grows up from lower addresses to higher addresses or grows down from high address to low addresses. the compilers and most folks set the stack pointer high and have it grow down from high addresses to lower addresses. For example maybe you have ram from 0x20000000 to 0x20008000 you set your linker script to build your program to run/use 0x20000000 and set your stack pointer to 0x20008000 in your startup code, at least the system/user stack pointer, you have to divide up the memory for other stacks if you need/use them.

Stack is just memory. Processors normally have special memory read/write instructions that are PC based and some that are stack based. The stack ones at a minimum are usually named push and pop but dont have to be (as with the traditional arm instructions).

If you go to http://github.com/lsasim I created a teaching processor and have an assembly language tutorial. Somewhere in there I go through a discussion about stacks. It is NOT an arm processor but the story is the same it should translate directly to what you are trying to understand on the arm or most other processors.

Say for example you have 20 variables you need in your program but only 16 registers minus at least three of them (sp, lr, pc) that are special purpose. You are going to have to keep some of your variables in ram. Lets say that r5 holds a variable that you use often enough that you dont want to keep it in ram, but there is one section of code where you really need another register to do something and r5 is not being used, you can save r5 on the stack with minimal effort while you reuse r5 for something else, then later, easily, restore it.

Traditional (well not all the way back to the beginning) arm syntax:

...
stmdb r13!,{r5}
...temporarily use r5 for something else...
ldmia r13!,{r5}
...

stm is store multiple you can save more than one register at a time, up to all of them in one instruction.

db means decrement before, this is a downward moving stack from high addresses to lower addresses.

You can use r13 or sp here to indicate the stack pointer. This particular instruction is not limited to stack operations, can be used for other things.

The ! means update the r13 register with the new address after it completes, here again stm can be used for non-stack operations so you might not want to change the base address register, leave the ! off in that case.

Then in the brackets { } list the registers you want to save, comma separated.

ldmia is the reverse, ldm means load multiple. ia means increment after and the rest is the same as stm

So if your stack pointer were at 0x20008000 when you hit the stmdb instruction seeing as there is one 32 bit register in the list it will decrement before it uses it the value in r13 so 0x20007FFC then it writes r5 to 0x20007FFC in memory and saves the value 0x20007FFC in r13. Later, assuming you have no bugs when you get to the ldmia instruction r13 has 0x20007FFC in it there is a single register in the list r5. So it reads memory at 0x20007FFC puts that value in r5, ia means increment after so 0x20007FFC increments one register size to 0x20008000 and the ! means write that number to r13 to complete the instruction.

Why would you use the stack instead of just a fixed memory location? Well the beauty of the above is that r13 can be anywhere it could be 0x20007654 when you run that code or 0x20002000 or whatever and the code still functions, even better if you use that code in a loop or with recursion it works and for each level of recursion you go you save a new copy of r5, you might have 30 saved copies depending on where you are in that loop. and as it unrolls it puts all the copies back as desired. with a single fixed memory location that doesnt work. This translates directly to C code as an example:

void myfun ( void )
{
   int somedata;
}

In a C program like that the variable somedata lives on the stack, if you called myfun recursively you would have multiple copies of the value for somedata depending on how deep in the recursion. Also since that variable is only used within the function and is not needed elsewhere then you perhaps dont want to burn an amount of system memory for that variable for the life of the program you only want those bytes when in that function and free that memory when not in that function. that is what a stack is used for.

A global variable would not be found on the stack.

Going back...

Say you wanted to implement and call that function you would have some code/function you are in when you call the myfun function. The myfun function wants to use r5 and r6 when it is operating on something but it doesnt want to trash whatever someone called it was using r5 and r6 for so for the duration of myfun() you would want to save those registers on the stack. Likewise if you look into the branch link instruction (bl) and the link register lr (r14) there is only one link register, if you call a function from a function you will need to save the link register on each call otherwise you cant return.

...
bl myfun
    <--- the return from my fun returns here
...


myfun:
stmdb sp!,{r5,r6,lr}
sub sp,#4 <--- make room for the somedata variable
...
some code here that uses r5 and r6
bl more_fun <-- this modifies lr, if we didnt save lr we wouldnt be able to return from myfun
   <---- more_fun() returns here
...
add sp,#4 <-- take back the stack memory we allocated for the somedata variable
ldmia sp!,{r5,r6,lr}
mov pc,lr <---- return to whomever called myfun.

So hopefully you can see both the stack usage and link register. Other processors do the same kinds of things in a different way. for example some will put the return value on the stack and when you execute the return function it knows where to return to by pulling a value off of the stack. Compilers C/C++, etc will normally have a "calling convention" or application interface (ABI and EABI are names for the ones ARM has defined). if every function follows the calling convention, puts parameters it is passing to functions being called in the right registers or on the stack per the convention. And each function follows the rules as to what registers it does not have to preserve the contents of and what registers it has to preserve the contents of then you can have functions call functions call functions and do recursion and all kinds of things, so long as the stack does not go so deep that it runs into the memory used for globals and the heap and such, you can call functions and return from them all day long. The above implementation of myfun is very similar to what you would see a compiler produce.

ARM has many cores now and a few instruction sets the cortex-m series works a little differently as far as not having a bunch of modes and different stack pointers. And when executing thumb instructions in thumb mode you use the push and pop instructions which do not give you the freedom to use any register like stm it only uses r13 (sp) and you cannot save all the registers only a specific subset of them. the popular arm assemblers allow you to use

push {r5,r6}
...
pop {r5,r6}

in arm code as well as thumb code. For the arm code it encodes the proper stmdb and ldmia. (in thumb mode you also dont have the choice as to when and where you use db, decrement before, and ia, increment after).

No you absolutly do not have to use the same registers and you dont have to pair up the same number of registers.

push {r5,r6,r7}
...
pop {r2,r3}
...
pop {r1}

assuming there is no other stack pointer modifications in between those instructions if you remember the sp is going to be decremented 12 bytes for the push lets say from 0x1000 to 0x0FF4, r5 will be written to 0xFF4, r6 to 0xFF8 and r7 to 0xFFC the stack pointer will change to 0x0FF4. the first pop will take the value at 0x0FF4 and put that in r2 then the value at 0x0FF8 and put that in r3 the stack pointer gets the value 0x0FFC. later the last pop, the sp is 0x0FFC that is read and the value placed in r1, the stack pointer then gets the value 0x1000, where it started.

The ARM ARM, ARM Architectural Reference Manual (infocenter.arm.com, reference manuals, find the one for ARMv5 and download it, this is the traditional ARM ARM with ARM and thumb instructions) contains pseudo code for the ldm and stm ARM istructions for the complete picture as to how these are used. Likewise well the whole book is about the arm and how to program it. Up front the programmers model chapter walks you through all of the registers in all of the modes, etc.

If you are programming an ARM processor you should start by determining (the chip vendor should tell you, ARM does not make chips it makes cores that chip vendors put in their chips) exactly which core you have. Then go to the arm website and find the ARM ARM for that family and find the TRM (technical reference manual) for the specific core including revision if the vendor has supplied that (r2p0 means revision 2.0 (two point zero, 2p0)), even if there is a newer rev, use the manual that goes with the one the vendor used in their design. Not every core supports every instruction or mode the TRM tells you the modes and instructions supported the ARM ARM throws a blanket over the features for the whole family of processors that that core lives in. Note that the ARM7TDMI is an ARMv4 NOT an ARMv7 likewise the ARM9 is not an ARMv9. ARMvNUMBER is the family name ARM7, ARM11 without a v is the core name. The newer cores have names like Cortex and mpcore instead of the ARMNUMBER thing, which reduces confusion. Of course they had to add the confusion back by making an ARMv7-m (cortex-MNUMBER) and the ARMv7-a (Cortex-ANUMBER) which are very different families, one is for heavy loads, desktops, laptops, etc the other is for microcontrollers, clocks and blinking lights on a coffee maker and things like that. google beagleboard (Cortex-A) and the stm32 value line discovery board (Cortex-M) to get a feel for the differences. Or even the open-rd.org board which uses multiple cores at more than a gigahertz or the newer tegra 2 from nvidia, same deal super scaler, muti core, multi gigahertz. A cortex-m barely brakes the 100MHz barrier and has memory measured in kbytes although it probably runs of a battery for months if you wanted it to where a cortex-a not so much.

sorry for the very long post, hope it is useful.

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

Use __getattr__, very simple, works in Python 3.4.3

class myDict(dict):
    def __getattr__(self,val):
        return self[val]


blockBody=myDict()
blockBody['item1']=10000
blockBody['item2']="StackOverflow"
print(blockBody.item1)
print(blockBody.item2)

Output:

10000
StackOverflow

How to do an update + join in PostgreSQL?

The answer of Mark Byers is the optimal in this situation. Though in more complex situations you can take the select query that returns rowids and calculated values and attach it to the update query like this:

with t as (
  -- Any generic query which returns rowid and corresponding calculated values
  select t1.id as rowid, f(t2, t2) as calculatedvalue
  from table1 as t1
  join table2 as t2 on t2.referenceid = t1.id
)
update table1
set value = t.calculatedvalue
from t
where id = t.rowid

This approach lets you develop and test your select query and in two steps convert it to the update query.

So in your case the result query will be:

with t as (
    select v.id as rowid, s.price_per_vehicle as calculatedvalue
    from vehicles_vehicle v 
    join shipments_shipment s on v.shipment_id = s.id 
)
update vehicles_vehicle
set price = t.calculatedvalue
from t
where id = t.rowid

Note that column aliases are mandatory otherwise PostgreSQL will complain about the ambiguity of the column names.

How do you extract a column from a multi-dimensional array?

You can use this as well:

values = np.array([[1,2,3],[4,5,6]])
values[...,0] # first column
#[1,4]

Note: This is not working for built-in array and not aligned (e.g. np.array([[1,2,3],[4,5,6,7]]) )

Keyboard shortcuts are not active in Visual Studio with Resharper installed

Note for NVidia users: GeForce Experience silently overrides some hotkeys (for example Alt+F7) and ReSharper stops to handle them. So you need to disable or remap nvidia hotkeys first.

Laravel - check if Ajax request

Sometimes Request::ajax() doesn't work, then use \Request::ajax()

How to set width of a div in percent in JavaScript?

Yes, it is:

<div id="myid">Some Content........</div>

document.getElementById('#myid').style.width = '50%';

Login to Microsoft SQL Server Error: 18456

Another worked solution for me. serever->security->logins->new logins->General->create your user name as login name,Click sql server authentication add passwords

uncheck the password verification three checkboxes . This will work.

Remeber to change the server properties ->Security from Server authentication to SQL Server and Windows Authentication mode

php delete a single file in directory

// This code was tested by me (Helio Barbosa)

    // this directory (../backup) is for try only.
    // it is necessary create it and put files into him.

    $hDir = '../backup';
    if ($handle = opendir( $hDir )) {
        echo "Manipulador de diretório: $handle\n";
        echo "Arquivos:\n";

        /* Esta é a forma correta de varrer o diretório */
        /* Here is the correct form to do find files into the directory */
        while (false !== ($file = readdir($handle))) {
            // echo($file . "</br>");
            $filepath = $hDir . "/" . $file ;
            // echo( $filepath . "</br>" );
            if(is_file($filepath))
            {
                echo("Deleting:" . $file . "</br>");
                unlink($filepath);
            }           
        }

        closedir($handle);
    }

How do I shrink my SQL Server Database?

Delete data, make sure recovery model is simple, then skrink (either shrink database or shrink files works). If the data file is still too big, AND you use heaps to store data -- that is, no clustered index on large tables -- then you might have this problem regarding deleting data from heaps: http://support.microsoft.com/kb/913399

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

It is not the asker's problem in this instance but the first troubleshooting step for a generic "AttributeError: __exit__" should be making sure the brackets are there, e.g.

with SomeContextManager() as foo:
    #works because a new object is referenced...

not

with SomeContextManager as foo:
    #AttributeError because the class is referenced

Catches me out from time to time and I end up here -__-

How to find tag with particular text with Beautiful Soup?

You can pass a regular expression to the text parameter of findAll, like so:

import BeautifulSoup
import re

columns = soup.findAll('td', text = re.compile('your regex here'), attrs = {'class' : 'pos'})

how to use DEXtoJar

  1. Download latest dex2jar from here -> dex2jar
  2. Run this command on linux -> sh d2j-dex2jar.sh classes.dex
  3. Download java decompiler from here - > JD-GUI
  4. Drag and drop the classes-dex2jar.jar file to JD-GUI

Changing EditText bottom line color with appcompat v7

I worked out a working solution to this problem after 2 days of struggle, below solution is perfect for them who want to change few edit text only, change/toggle color through java code, and want to overcome the problems of different behavior on OS versions due to use setColorFilter() method.

    import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatDrawableManager;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import com.newco.cooltv.R;

public class RqubeErrorEditText extends AppCompatEditText {

  private int errorUnderlineColor;
  private boolean isErrorStateEnabled;
  private boolean mHasReconstructedEditTextBackground;

  public RqubeErrorEditText(Context context) {
    super(context);
    initColors();
  }

  public RqubeErrorEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    initColors();
  }

  public RqubeErrorEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initColors();
  }

  private void initColors() {
    errorUnderlineColor = R.color.et_error_color_rule;

  }

  public void setErrorColor() {
    ensureBackgroundDrawableStateWorkaround();
    getBackground().setColorFilter(AppCompatDrawableManager.getPorterDuffColorFilter(
        ContextCompat.getColor(getContext(), errorUnderlineColor), PorterDuff.Mode.SRC_IN));
  }

  private void ensureBackgroundDrawableStateWorkaround() {
    final Drawable bg = getBackground();
    if (bg == null) {
      return;
    }
    if (!mHasReconstructedEditTextBackground) {
      // This is gross. There is an issue in the platform which affects container Drawables
      // where the first drawable retrieved from resources will propogate any changes
      // (like color filter) to all instances from the cache. We'll try to workaround it...
      final Drawable newBg = bg.getConstantState().newDrawable();
      //if (bg instanceof DrawableContainer) {
      //  // If we have a Drawable container, we can try and set it's constant state via
      //  // reflection from the new Drawable
      //  mHasReconstructedEditTextBackground =
      //      DrawableUtils.setContainerConstantState(
      //          (DrawableContainer) bg, newBg.getConstantState());
      //}
      if (!mHasReconstructedEditTextBackground) {
        // If we reach here then we just need to set a brand new instance of the Drawable
        // as the background. This has the unfortunate side-effect of wiping out any
        // user set padding, but I'd hope that use of custom padding on an EditText
        // is limited.
        setBackgroundDrawable(newBg);
        mHasReconstructedEditTextBackground = true;
      }
    }
  }

  public boolean isErrorStateEnabled() {
    return isErrorStateEnabled;
  }

  public void setErrorState(boolean isErrorStateEnabled) {
    this.isErrorStateEnabled = isErrorStateEnabled;
    if (isErrorStateEnabled) {
      setErrorColor();
      invalidate();
    } else {
      getBackground().mutate().clearColorFilter();
      invalidate();
    }
  }
}

Uses in xml

<com.rqube.ui.widget.RqubeErrorEditText
            android:id="@+id/f_signup_et_referral_code"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toEndOf="@+id/referral_iv"
            android:layout_toRightOf="@+id/referral_iv"
            android:ems="10"
            android:hint="@string/lbl_referral_code"
            android:imeOptions="actionNext"
            android:inputType="textEmailAddress"
            android:textSize="@dimen/text_size_sp_16"
            android:theme="@style/EditTextStyle"/>

Add lines in style

<style name="EditTextStyle" parent="android:Widget.EditText">
    <item name="android:textColor">@color/txt_color_change</item>
    <item name="android:textColorHint">@color/et_default_color_text</item>
    <item name="colorControlNormal">@color/et_default_color_rule</item>
    <item name="colorControlActivated">@color/et_engagged_color_rule</item>
  </style>

java code to toggle color

myRqubeEditText.setErrorState(true);
myRqubeEditText.setErrorState(false);

Query to check index on a table

On Oracle:

  • Determine all indexes on table:

    SELECT index_name 
     FROM user_indexes
     WHERE table_name = :table
    
  • Determine columns indexes and columns on index:

    SELECT index_name
         , column_position
         , column_name
      FROM user_ind_columns
     WHERE table_name = :table
     ORDER BY index_name, column_order
    

References:

How do getters and setters work?

Tutorial is not really required for this. Read up on encapsulation

private String myField; //"private" means access to this is restricted

public String getMyField()
{
     //include validation, logic, logging or whatever you like here
    return this.myField;
}
public void setMyField(String value)
{
     //include more logic
     this.myField = value;
}

JQuery, select first row of table

Actually, if you try to use function "children" it will not be succesfull because it's possible to the table has a first child like 'th'. So you have to use function 'find' instead.

Wrong way:

var $row = $(this).closest('table').children('tr:first');

Correct way:

 var $row = $(this).closest('table').find('tr:first');

How do JavaScript closures work?

Imagine there is a very large park in your town where you see a magician called Mr. Coder starting baseball games in different corners of the park using his magic wand, called JavaScript.

Naturally each baseball game has the exact same rules and each game has its own score board.

Naturally, the scores of one baseball game are completely separate from the other games.

A closure is the special way Mr.Coder keeps the scoring of all his magical baseball games separate.

How can I preview a merge in git?

If you're like me, you're looking for equivalent to svn update -n. The following appears to do the trick. Note that make sure to do a git fetch first so that your local repo has the appropriate updates to compare against.

$ git fetch origin
$ git diff --name-status origin/master
D       TableAudit/Step0_DeleteOldFiles.sh
D       TableAudit/Step1_PopulateRawTableList.sh
A       manbuild/staff_companies.sql
M       update-all-slave-dbs.sh

or if you want a diff from your head to the remote:

$ git fetch origin
$ git diff origin/master

IMO this solution is much easier and less error prone (and therefore much less risky) than the top solution which proposes "merge then abort".

Adding a user on .htpasswd

Exact same thing, just omit the -c option. Apache's docs on it here.

htpasswd /etc/apache2/.htpasswd newuser

Also, htpasswd typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).

MongoError: connect ECONNREFUSED 127.0.0.1:27017

For Ubuntu users run sudo systemctl restart mongod

Modify a Column's Type in sqlite3

It is possible by recreating table.Its work for me please follow following step:

  1. create temporary table using as select * from your table
  2. drop your table, create your table using modify column type
  3. now insert records from temp table to your newly created table
  4. drop temporary table

do all above steps in worker thread to reduce load on uithread

Change variable name in for loop using R

Another option is using eval and parse, as in

d = 5
for (i in 1:10){
     eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}

ExecJS and could not find a JavaScript runtime

Ubuntu Users

I'm on Ubuntu 11.04 and had similar issues. Installing Node.js fixed it.

As of Ubuntu 13.04 x64 you only need to run:

sudo apt-get install nodejs

This will solve the problem.


CentOS/RedHat Users

sudo yum install nodejs

Android image caching

What actually worked for me was setting ResponseCache on my Main class:

try {
   File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
   long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
   HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) { } 

and

connection.setUseCaches(true);

when downloading bitmap.

http://practicaldroid.blogspot.com/2013/01/utilizing-http-response-cache.html

How to connect to MySQL Database?

Install Oracle's MySql.Data NuGet package.

using MySql.Data;
using MySql.Data.MySqlClient;

namespace Data
{
    public class DBConnection
    {
        private DBConnection()
        {
        }

        public string Server { get; set; }
        public string DatabaseName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

        private MySqlConnection Connection { get; set;}

        private static DBConnection _instance = null;
        public static DBConnection Instance()
        {
            if (_instance == null)
                _instance = new DBConnection();
           return _instance;
        }
    
        public bool IsConnect()
        {
            if (Connection == null)
            {
                if (String.IsNullOrEmpty(databaseName))
                    return false;
                string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);
                Connection = new MySqlConnection(connstring);
                Connection.Open();
            }
    
            return true;
        }
    
        public void Close()
        {
            Connection.Close();
        }        
    }
}

Example:

var dbCon = DBConnection.Instance();
dbCon.Server = "YourServer";
dbCon.DatabaseName = "YourDatabase";
dbCon.UserName = "YourUsername";
dbCon.Password = "YourPassword";
if (dbCon.IsConnect())
{
    //suppose col0 and col1 are defined as VARCHAR in the DB
    string query = "SELECT col0,col1 FROM YourTable";
    var cmd = new MySqlCommand(query, dbCon.Connection);
    var reader = cmd.ExecuteReader();
    while(reader.Read())
    {
        string someStringFromColumnZero = reader.GetString(0);
        string someStringFromColumnOne = reader.GetString(1);
        Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
    }
    dbCon.Close();
}

onSaveInstanceState () and onRestoreInstanceState ()

It is not necessary that onRestoreInstanceState will always be called after onSaveInstanceState.

Note that : onRestoreInstanceState will always be called, when activity is rotated (when orientation is not handled) or open your activity and then open other apps so that your activity instance is cleared from memory by OS.

select and echo a single field from mysql db using PHP

Try this:

echo mysql_result($result, 0);

This is enough because you are only fetching one field of one row.

CSS3 100vh not constant in mobile browser

A nice read about the problem and its possible solutions can be found in this blog post: Addressing the iOS Address Bar in 100vh Layouts

The solution I ended up in my React application is utilising the react-div-100vh library described in the post above.

How to only get file name with Linux 'find'?

I've found a solution (on makandracards page), that gives just the newest file name:

ls -1tr * | tail -1

(thanks goes to Arne Hartherz)

I used it for cp:

cp $(ls -1tr * | tail -1) /tmp/

How to convert image to byte array

Here's what I'm currently using. Some of the other techniques I've tried have been non-optimal because they changed the bit depth of the pixels (24-bit vs. 32-bit) or ignored the image's resolution (dpi).

  // ImageConverter object used to convert byte arrays containing JPEG or PNG file images into 
  //  Bitmap objects. This is static and only gets instantiated once.
  private static readonly ImageConverter _imageConverter = new ImageConverter();

Image to byte array:

  /// <summary>
  /// Method to "convert" an Image object into a byte array, formatted in PNG file format, which 
  /// provides lossless compression. This can be used together with the GetImageFromByteArray() 
  /// method to provide a kind of serialization / deserialization. 
  /// </summary>
  /// <param name="theImage">Image object, must be convertable to PNG format</param>
  /// <returns>byte array image of a PNG file containing the image</returns>
  public static byte[] CopyImageToByteArray(Image theImage)
  {
     using (MemoryStream memoryStream = new MemoryStream())
     {
        theImage.Save(memoryStream, ImageFormat.Png);
        return memoryStream.ToArray();
     }
  }

Byte array to Image:

  /// <summary>
  /// Method that uses the ImageConverter object in .Net Framework to convert a byte array, 
  /// presumably containing a JPEG or PNG file image, into a Bitmap object, which can also be 
  /// used as an Image object.
  /// </summary>
  /// <param name="byteArray">byte array containing JPEG or PNG file image or similar</param>
  /// <returns>Bitmap object if it works, else exception is thrown</returns>
  public static Bitmap GetImageFromByteArray(byte[] byteArray)
  {
     Bitmap bm = (Bitmap)_imageConverter.ConvertFrom(byteArray);

     if (bm != null && (bm.HorizontalResolution != (int)bm.HorizontalResolution ||
                        bm.VerticalResolution != (int)bm.VerticalResolution))
     {
        // Correct a strange glitch that has been observed in the test program when converting 
        //  from a PNG file image created by CopyImageToByteArray() - the dpi value "drifts" 
        //  slightly away from the nominal integer value
        bm.SetResolution((int)(bm.HorizontalResolution + 0.5f), 
                         (int)(bm.VerticalResolution + 0.5f));
     }

     return bm;
  }

Edit: To get the Image from a jpg or png file you should read the file into a byte array using File.ReadAllBytes():

 Bitmap newBitmap = GetImageFromByteArray(File.ReadAllBytes(fileName));

This avoids problems related to Bitmap wanting its source stream to be kept open, and some suggested workarounds to that problem that result in the source file being kept locked.

Curl not recognized as an internal or external command, operable program or batch file

Here you can find the direct download link for Curl.exe

I was looking for the download process of Curl and every where they said copy curl.exe file in System32 but they haven't provided the direct link but after digging little more I Got it. so here it is enjoy, find curl.exe easily in bin folder just

unzip it and then go to bin folder there you get exe file

link to download curl generic

Principal Component Analysis (PCA) in Python

I posted my answer even though another answer has already been accepted; the accepted answer relies on a deprecated function; additionally, this deprecated function is based on Singular Value Decomposition (SVD), which (although perfectly valid) is the much more memory- and processor-intensive of the two general techniques for calculating PCA. This is particularly relevant here because of the size of the data array in the OP. Using covariance-based PCA, the array used in the computation flow is just 144 x 144, rather than 26424 x 144 (the dimensions of the original data array).

Here's a simple working implementation of PCA using the linalg module from SciPy. Because this implementation first calculates the covariance matrix, and then performs all subsequent calculations on this array, it uses far less memory than SVD-based PCA.

(the linalg module in NumPy can also be used with no change in the code below aside from the import statement, which would be from numpy import linalg as LA.)

The two key steps in this PCA implementation are:

  • calculating the covariance matrix; and

  • taking the eivenvectors & eigenvalues of this cov matrix

In the function below, the parameter dims_rescaled_data refers to the desired number of dimensions in the rescaled data matrix; this parameter has a default value of just two dimensions, but the code below isn't limited to two but it could be any value less than the column number of the original data array.


def PCA(data, dims_rescaled_data=2):
    """
    returns: data transformed in 2 dims/columns + regenerated original data
    pass in: data as 2D NumPy array
    """
    import numpy as NP
    from scipy import linalg as LA
    m, n = data.shape
    # mean center the data
    data -= data.mean(axis=0)
    # calculate the covariance matrix
    R = NP.cov(data, rowvar=False)
    # calculate eigenvectors & eigenvalues of the covariance matrix
    # use 'eigh' rather than 'eig' since R is symmetric, 
    # the performance gain is substantial
    evals, evecs = LA.eigh(R)
    # sort eigenvalue in decreasing order
    idx = NP.argsort(evals)[::-1]
    evecs = evecs[:,idx]
    # sort eigenvectors according to same index
    evals = evals[idx]
    # select the first n eigenvectors (n is desired dimension
    # of rescaled data array, or dims_rescaled_data)
    evecs = evecs[:, :dims_rescaled_data]
    # carry out the transformation on the data using eigenvectors
    # and return the re-scaled data, eigenvalues, and eigenvectors
    return NP.dot(evecs.T, data.T).T, evals, evecs

def test_PCA(data, dims_rescaled_data=2):
    '''
    test by attempting to recover original data array from
    the eigenvectors of its covariance matrix & comparing that
    'recovered' array with the original data
    '''
    _ , _ , eigenvectors = PCA(data, dim_rescaled_data=2)
    data_recovered = NP.dot(eigenvectors, m).T
    data_recovered += data_recovered.mean(axis=0)
    assert NP.allclose(data, data_recovered)


def plot_pca(data):
    from matplotlib import pyplot as MPL
    clr1 =  '#2026B2'
    fig = MPL.figure()
    ax1 = fig.add_subplot(111)
    data_resc, data_orig = PCA(data)
    ax1.plot(data_resc[:, 0], data_resc[:, 1], '.', mfc=clr1, mec=clr1)
    MPL.show()

>>> # iris, probably the most widely used reference data set in ML
>>> df = "~/iris.csv"
>>> data = NP.loadtxt(df, delimiter=',')
>>> # remove class labels
>>> data = data[:,:-1]
>>> plot_pca(data)

The plot below is a visual representation of this PCA function on the iris data. As you can see, a 2D transformation cleanly separates class I from class II and class III (but not class II from class III, which in fact requires another dimension).

enter image description here

Closing Twitter Bootstrap Modal From Angular Controller

Have you looked at angular-ui bootstrap? There's a Dialog (ui.bootstrap.dialog) directive that works quite well. You can close the dialog during the call back the angular way (per the example):

$scope.close = function(result){
  dialog.close(result);
};

Update:

The directive has since been renamed Modal.

What are the options for storing hierarchical data in a relational database?

If your database supports arrays, you can also implement a lineage column or materialized path as an array of parent ids.

Specifically with Postgres you can then use the set operators to query the hierarchy, and get excellent performance with GIN indices. This makes finding parents, children, and depth pretty trivial in a single query. Updates are pretty manageable as well.

I have a full write up of using arrays for materialized paths if you're curious.

Format certain floating dataframe columns into percentage in pandas

As suggested by @linqu you should not change your data for presentation. Since pandas 0.17.1, (conditional) formatting was made easier. Quoting the documentation:

You can apply conditional formatting, the visual styling of a DataFrame depending on the data within, by using the DataFrame.style property. This is a property that returns a pandas.Styler object, which has useful methods for formatting and displaying DataFrames.

For your example, that would be (the usual table will show up in Jupyter):

df.style.format({
    'var1': '{:,.2f}'.format,
    'var2': '{:,.2f}'.format,
    'var3': '{:,.2%}'.format,
})

How to select ALL children (in any level) from a parent in jQuery?

I think you could do:

$('#google_translate_element').find('*').each(function(){
    $(this).unbind('click');
});

but it would cause a lot of overhead

Cross-browser window resize event - JavaScript / jQuery

Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):

// did not work in IE10
$(function() {
    $(window).resize(CmsContent.adjustSize);
});

while this worked in both browsers:

// did work in IE10
$(function() {
    $(window).bind('resize', function() {
        CmsContent.adjustSize();
    };
});

Edit:
)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.

How do multiple clients connect simultaneously to one port, say 80, on a server?

Multiple clients can connect to the same port (say 80) on the server because on the server side, after creating a socket and binding (setting local IP and port) listen is called on the socket which tells the OS to accept incoming connections.

When a client tries to connect to server on port 80, the accept call is invoked on the server socket. This creates a new socket for the client trying to connect and similarly new sockets will be created for subsequent clients using same port 80.

Words in italics are system calls.

Ref

http://www.scs.stanford.edu/07wi-cs244b/refs/net2.pdf

How do I scroll to an element using JavaScript?

Due to behavior "smooth" doesn't work in Safari, Safari ios, Explorer. I usually write a simple function utilizing requestAnimationFrame

(function(){
    var start;
    var startPos = 0;

    //Navigation scroll page to element
    function scrollTo(timestamp, targetTop){
      if(!start) start = timestamp
      var runtime = timestamp - start
      var progress = Math.min(runtime / 700, 1)

      window.scroll(0, startPos + (targetTop * progress) )

      if(progress >= 1){
        return;
      }else {
        requestAnimationFrame(function(timestamp){
            scrollTo(timestamp, targetTop)
        })
      }
   };

  navElement.addEventListener('click', function(e){

    var target = e.target  //or this 
    var targetTop = _(target).getBoundingClientRect().top
    startPos = window.scrollY

    requestAnimationFrame(function(timestamp){
        scrollTo(timestamp, targetTop)
    })
  }

})();

Add an image in a WPF button

Use:

<Button Height="100" Width="100">
  <StackPanel>
    <Image Source="img.jpg" />
    <TextBlock Text="Blabla" />
  </StackPanel>
</Button>

It should work. But remember that you must have an image added to the resource on your project!

how to convert a string to an array in php

$array = explode(' ', $string);

How do I install a Python package with a .whl file?

Download the package (.whl).

Put the file inside the script folder of python directory

C:\Python36\Scripts

Use the command prompt to install the package.

C:\Python36\Scripts>pip install package_name.whl

How to enable DataGridView sorting when user clicks on the column header?

put this line in your windows form (on load or better in a public method like "binddata" ):

//
// bind the data and make the grid sortable 
//
this.datagridview1.MakeSortable( myenumerablecollection ); 

Put this code in a file called DataGridViewExtensions.cs (or similar)

// MakeSortable extension. 
// this will make any enumerable collection sortable on a datagrid view.  

//
// BEGIN MAKESORTABLE - Mark A. Lloyd
//
// Enables sort on all cols of a DatagridView 

//



    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    public static class DataGridViewExtensions
    {
    public static void MakeSortable<T>(
        this DataGridView dataGridView, 
        IEnumerable<T> dataSource,
        SortOrder defaultSort = SortOrder.Ascending, 
        SortOrder initialSort = SortOrder.None)
    {
        var sortProviderDictionary = new Dictionary<int, Func<SortOrder, IEnumerable<T>>>();
        var previousSortOrderDictionary = new Dictionary<int, SortOrder>();
        var itemType = typeof(T);
        dataGridView.DataSource = dataSource;
        foreach (DataGridViewColumn c in dataGridView.Columns)
        {
            object Provider(T info) => itemType.GetProperty(c.Name)?.GetValue(info);
            sortProviderDictionary[c.Index] = so => so != defaultSort ? 
                dataSource.OrderByDescending<T, object>(Provider) : 
                dataSource.OrderBy<T,object>(Provider);
            previousSortOrderDictionary[c.Index] = initialSort;
        }

        async Task DoSort(int index)
        {

            switch (previousSortOrderDictionary[index])
            {
                case SortOrder.Ascending:
                    previousSortOrderDictionary[index] = SortOrder.Descending;
                    break;
                case SortOrder.None:
                case SortOrder.Descending:
                    previousSortOrderDictionary[index] = SortOrder.Ascending;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            IEnumerable<T> sorted = null;
            dataGridView.Cursor = Cursors.WaitCursor;
            dataGridView.Enabled = false;
            await Task.Run(() => sorted = sortProviderDictionary[index](previousSortOrderDictionary[index]).ToList());
            dataGridView.DataSource = sorted;
            dataGridView.Enabled = true;
            dataGridView.Cursor = Cursors.Default;

        }

        dataGridView.ColumnHeaderMouseClick+= (object sender, DataGridViewCellMouseEventArgs e) => DoSort(index: e.ColumnIndex);
    }
}

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

You can catch that exception and return whatever you want from there.

open(target, 'a').close()
scores = {};
try:
    with open(target, "rb") as file:
        unpickler = pickle.Unpickler(file);
        scores = unpickler.load();
        if not isinstance(scores, dict):
            scores = {};
except EOFError:
    return {}

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

If you want to obtain fingerprint-sha1 key from signing keystore.jks file Run the following command from terminal:

keytool -list -v -keystore <.../path/keystore.jks>

Example

keytool -list -v -keystore /Users/Home/Projects/Keystore/myApp_keystore.jks
Enter keystore password: 

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name:myApp_alias
Owner: CN=xxx, OU=xxx Dev, O=ZZZ, L=Dhaka, ST=Dhaka, C=BD
..........


Certificate fingerprints:
MD5:  12:10:11:12:11:11:11:11:11:11:33:11:11:11:11:11
SHA1: 11:44:11:11:55:11:17:11:11:66:11:11:88:11:11:77:11:11:01:11
.....................

Permission denied on CopyFile in VBS

I have read your problem, And i had the same problem. But af ter i changed some, my problem "Permission Denied" is solved.

Private Sub Addi_Click()
'On Error Resume Next
'call ds
browsers ("false")
Call makeAdir
ffgg = "C:\Users\Backups\user\" & User & "1\data\"
Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.Getfolder("c:\users\Backups\user\" & User & "1\data")
    f.Attributes = 0
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Call fso.Copyfile(filetarget, ffgg, True)

Look at ffgg = "C:\Users\Backups\user\" & User & "1\data\", Before I changed it was ffgg = "C:\Users\Backups\user\" & User & "1\data" When i add backslash after "\data\", my problem is solved. Try to add back slash. Maybe solved your problem. Good luck.

adb doesn't show nexus 5 device

Here is simple solution for Windows 7 and Nexus 5 on Android 5.

  1. Download the Nexus 5 Drivers from http://androidhost.org/jelry
  2. Extract the zip contents and place all files in a single folder on your desktop.
  3. Connect your device to your computer.
  4. Launch the Device Manager on your PC.
  5. Now you should see the Nexus 5 listed in the hardware list.
  6. Right-click the ‘Nexus 5' line and then click on Update Driver Software.
  7. Next, click the ‘browse my computer’ option.
  8. In the new window click on ‘Browse…’ button.
  9. Go to folder unzipped at step 2. Select the folder where you extract the USB Drivers. Click Next. – make sure to tick the subfolder box too.
  10. Now, the Windows installer will search for Nexus 5 drivers, click Install when asked for permission.
  11. Wait for the process to complete and then check the Device Manager list to confirm that the installation was successful.

Original: http://www.android.gs/download-and-install-google-nexus-5-usb-drivers-adb-fastboot/

Note: do not forget to enable USB debugging on your device :)

How are VST Plugins made?

I realize this is a very old post, but I have had success using the JUCE library, which builds projects for the major IDE's like Xcode, VS, and Codeblocks and automatically builds VST/3, AU/v3, RTAS, and AAX.

https://www.juce.com/

Creating a "Hello World" WebSocket example

Issue

Since you are using WebSocket, spender is correct. After recieving the initial data from the WebSocket, you need to send the handshake message from the C# server before any further information can flow.

HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: websocket
Connection: Upgrade
WebSocket-Origin: example
WebSocket-Location: something.here
WebSocket-Protocol: 13

Something along those lines.

You can do some more research into how WebSocket works on w3 or google.

Links and Resources

Here is a protocol specifcation: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76#section-1.3

List of working examples:

How to vertically center content with variable height within a div?

This is my awesome solution for a div with a dynamic (percentaged) height.

CSS

.vertical_placer{
  background:red;
  position:absolute; 
  height:43%; 
  width:100%;
  display: table;
}

.inner_placer{  
  display: table-cell;
  vertical-align: middle;
  text-align:center;
}

.inner_placer svg{
  position:relative;
  color:#fff;
  background:blue;
  width:30%;
  min-height:20px;
  max-height:60px;
  height:20%;
}

HTML

<div class="footer">
    <div class="vertical_placer">
        <div class="inner_placer">
            <svg> some Text here</svg>
        </div>
    </div>
</div>  

Try this by yourself.

A better way to check if a path exists or not in PowerShell

Add the following aliases. I think these should be made available in PowerShell by default:

function not-exist { -not (Test-Path $args) }
Set-Alias !exist not-exist -Option "Constant, AllScope"
Set-Alias exist Test-Path -Option "Constant, AllScope"

With that, the conditional statements will change to:

if (exist $path) { ... }

and

if (not-exist $path) { ... }
if (!exist $path) { ... }

Cannot assign requested address using ServerSocket.socketBind

As the error states, it can't bind - which typically means it's in use by another process. From a command line run:

netstat -a -n -o

Interrogate the output for port 9999 in use in the left hand column.

For more information: http://www.zdnetasia.com/see-what-process-is-using-a-tcp-port-62047950.htm

Running shell command and capturing the output

Your Mileage May Vary, I attempted @senderle's spin on Vartec's solution in Windows on Python 2.6.5, but I was getting errors, and no other solutions worked. My error was: WindowsError: [Error 6] The handle is invalid.

I found that I had to assign PIPE to every handle to get it to return the output I expected - the following worked for me.

import subprocess

def run_command(cmd):
    """given shell command, returns communication tuple of stdout and stderr"""
    return subprocess.Popen(cmd, 
                            stdout=subprocess.PIPE, 
                            stderr=subprocess.PIPE, 
                            stdin=subprocess.PIPE).communicate()

and call like this, ([0] gets the first element of the tuple, stdout):

run_command('tracert 11.1.0.1')[0]

After learning more, I believe I need these pipe arguments because I'm working on a custom system that uses different handles, so I had to directly control all the std's.

To stop console popups (with Windows), do this:

def run_command(cmd):
    """given shell command, returns communication tuple of stdout and stderr"""
    # instantiate a startupinfo obj:
    startupinfo = subprocess.STARTUPINFO()
    # set the use show window flag, might make conditional on being in Windows:
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    # pass as the startupinfo keyword argument:
    return subprocess.Popen(cmd,
                            stdout=subprocess.PIPE, 
                            stderr=subprocess.PIPE, 
                            stdin=subprocess.PIPE, 
                            startupinfo=startupinfo).communicate()

run_command('tracert 11.1.0.1')

Replacing Spaces with Underscores

Strtr replaces single characters instead of strings, so it's a good solution for this example. Supposedly strtr is faster than str_replace (but for this use case they're both immeasurably fast).

echo strtr('Alex Newton',' ','_');
//outputs: Alex_Newton

D3 Appending Text to a SVG Rectangle

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

http://bl.ocks.org/mbostock/7341714

Multi-line labels are also a little tricky, you might want to check out this wrap function.

How much should a function trust another function

If it is in the same class it is fine to trust the method.

It is very common to do this. It is good practice to check null values in constructor's and method's arguments to make sure that nobody is passing null values into them (if it is not allowed). Then if you implement your methods in a way that they never set the "start" graph to null, don't check for nulls there.

It is also good practice to implement unit tests for your methods and make sure that they are correctly implemented, so you can trust them.

Merge two array of objects based on a key

You can do it like this -

_x000D_
_x000D_
let arr1 = [_x000D_
    { id: "abdc4051", date: "2017-01-24" },_x000D_
    { id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
_x000D_
let arr2 = [_x000D_
    { id: "abdc4051", name: "ab" },_x000D_
    { id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i]));_x000D_
_x000D_
console.log(arr3);
_x000D_
_x000D_
_x000D_


Use below code if arr1 and arr2 are in a different order:

_x000D_
_x000D_
let arr1 = [_x000D_
  { id: "abdc4051", date: "2017-01-24" }, _x000D_
  { id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
_x000D_
let arr2 = [_x000D_
  { id: "abdc4051", name: "ab" },_x000D_
  { id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
let merged = [];_x000D_
_x000D_
for(let i=0; i<arr1.length; i++) {_x000D_
  merged.push({_x000D_
   ...arr1[i], _x000D_
   ...(arr2.find((itmInner) => itmInner.id === arr1[i].id))}_x000D_
  );_x000D_
}_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

Use this if arr1 and arr2 are in a same order

_x000D_
_x000D_
let arr1 = [_x000D_
  { id: "abdc4051", date: "2017-01-24" }, _x000D_
  { id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
_x000D_
let arr2 = [_x000D_
  { id: "abdc4051", name: "ab" },_x000D_
  { id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
let merged = [];_x000D_
_x000D_
for(let i=0; i<arr1.length; i++) {_x000D_
  merged.push({_x000D_
   ...arr1[i], _x000D_
   ...arr2[i]_x000D_
  });_x000D_
}_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

How do I use IValidatableObject?

Just to add a couple of points:

Because the Validate() method signature returns IEnumerable<>, that yield return can be used to lazily generate the results - this is beneficial if some of the validation checks are IO or CPU intensive.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (this.Enable)
    {
        // ...
        if (this.Prop1 > this.Prop2)
        {
            yield return new ValidationResult("Prop1 must be larger than Prop2");
        }

Also, if you are using MVC ModelState, you can convert the validation result failures to ModelState entries as follows (this might be useful if you are doing the validation in a custom model binder):

var resultsGroupedByMembers = validationResults
    .SelectMany(vr => vr.MemberNames
                        .Select(mn => new { MemberName = mn ?? "", 
                                            Error = vr.ErrorMessage }))
    .GroupBy(x => x.MemberName);

foreach (var member in resultsGroupedByMembers)
{
    ModelState.AddModelError(
        member.Key,
        string.Join(". ", member.Select(m => m.Error)));
}

How to open a file for both reading and writing?

Summarize the I/O behaviors

|          Mode          |  r   |  r+  |  w   |  w+  |  a   |  a+  |
| :--------------------: | :--: | :--: | :--: | :--: | :--: | :--: |
|          Read          |  +   |  +   |      |  +   |      |  +   |
|         Write          |      |  +   |  +   |  +   |  +   |  +   |
|         Create         |      |      |  +   |  +   |  +   |  +   |
|         Cover          |      |      |  +   |  +   |      |      |
| Point in the beginning |  +   |  +   |  +   |  +   |      |      |
|    Point in the end    |      |      |      |      |  +   |  +   |

and the decision branch

enter image description here

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You may need to config the CORS at Spring Boot side. Please add below class in your Project.

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebConfig implements Filter,WebMvcConfigurer {



    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
      HttpServletResponse response = (HttpServletResponse) res;
      HttpServletRequest request = (HttpServletRequest) req;
      System.out.println("WebConfig; "+request.getRequestURI());
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Credentials", "true");
      response.setHeader("Access-Control-Expose-Headers", "Authorization");
      response.addHeader("Access-Control-Expose-Headers", "responseType");
      response.addHeader("Access-Control-Expose-Headers", "observe");
      System.out.println("Request Method: "+request.getMethod());
      if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
          try {
              chain.doFilter(req, res);
          } catch(Exception e) {
              e.printStackTrace();
          }
      } else {
          System.out.println("Pre-flight");
          response.setHeader("Access-Control-Allow-Origin", "*");
          response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
          response.setHeader("Access-Control-Max-Age", "3600");
          response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type," +
          "USERID"+"ROLE"+
                  "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
          response.setStatus(HttpServletResponse.SC_OK);
      }

    }

}

UPDATE:

To append Token to each request you can create one Interceptor as below.

import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = window.localStorage.getItem('tokenKey'); // you probably want to store it in localStorage or something


    if (!token) {
      return next.handle(req);
    }

    const req1 = req.clone({
      headers: req.headers.set('Authorization', `${token}`),
    });

    return next.handle(req1);
  }

}

Example

How do I properly escape quotes inside HTML attributes?

Per HTML syntax, and even HTML5, the following are all valid options:

<option value="&quot;asd">test</option>
<option value="&#34;asd">test</option>
<option value='"asd'>test</option>
<option value='&quot;asd'>test</option>
<option value='&#34;asd'>test</option>
<option value=&quot;asd>test</option>
<option value=&#34;asd>test</option>

Note that if you are using XML syntax the quotes (single or double) are required.

Here's a jsfiddle showing all of the above working.

Download file from an ASP.NET Web API method using AngularJS

You could implement a showfile function which takes in parameters of the data returned from the WEBApi, and a filename for the file you are trying to download. What I did was create a separate browser service identifies the user's browser and then handles the rendering of the file based on the browser. For instance if the target browser is chrome on an ipad, you have to use javascripts FileReader object.

FileService.showFile = function (data, fileName) {
    var blob = new Blob([data], { type: 'application/pdf' });

    if (BrowserService.isIE()) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    }
    else if (BrowserService.isChromeIos()) {
        loadFileBlobFileReader(window, blob, fileName);
    }
    else if (BrowserService.isIOS() || BrowserService.isAndroid()) {
        var url = URL.createObjectURL(blob);
        window.location.href = url;
        window.document.title = fileName;
    } else {
        var url = URL.createObjectURL(blob);
        loadReportBrowser(url, window,fileName);
    }
}


function loadFileBrowser(url, window, fileName) {
    var iframe = window.document.createElement('iframe');
    iframe.src = url
    iframe.width = '100%';
    iframe.height = '100%';
    iframe.style.border = 'none';
    window.document.title = fileName;
    window.document.body.appendChild(iframe)
    window.document.body.style.margin = 0;
}

function loadFileBlobFileReader(window, blob,fileName) {
    var reader = new FileReader();
    reader.onload = function (e) {
        var bdata = btoa(reader.result);
        var datauri = 'data:application/pdf;base64,' + bdata;
        window.location.href = datauri;
        window.document.title = fileName;
    }
    reader.readAsBinaryString(blob);
}

Using Docker-Compose, how to execute multiple commands

I was having same problem where I wanted to run my react app on port 3000 and storybook on port 6006 both in the same containers.

I tried to start both as entrypoint commands from Dockerfile as well as using docker-compose command option.

After spending time on this, decided to separate these services into separate containers and it worked like charm

Createuser: could not connect to database postgres: FATAL: role "tom" does not exist

If you don't want to change the authentication method (ident) and mess with pg_hba.conf use this:

First login as the default user

 sudo su - posgres

then access psql and create a user with the same name as the one you are login in

postgres=# CREATE USER userOS WITH PASSWORD 'garbage' CREATEDB;

you can verify your user with the corresponding roles with

postgres=#  \du

Afer this you can create your database and verify it with

psql -d dbName
\l
\q

Eclipse does not highlight matching variables

For others running into this without any of the above solutions working AND you have modified the default theme, you might want to check the highlight color for occurrences.

Preferences > General > Editors > Text Editors > Annotations

Then select Occurrences in the Annotation Types, and change the Color Box to something other than your background color in your editor. You can also change the Highlight to a outline box by Checking "Text as" and selecting "Box" from the drop-down box (which is easier to see various syntax colors then with the highlights)

How to make php display \t \n as tab and new line instead of characters

You can use HTML,

foreach(...)
echo $data1 . '&nbsp' . $data2 . '&nbsp' . $data3 . '<br/>';

Make the current commit the only (initial) commit in a Git repository?

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D master

  5. Rename the current branch to master

    git branch -m master

  6. Finally, force update your repository

    git push -f origin master

PS: this will not keep your old commit history around

Combining (concatenating) date and time into a datetime

Concat date of one column with a time of another column in MySQL.

SELECT CONVERT(concat(CONVERT('dateColumn',DATE),' ',CONVERT('timeColumn', TIME)), DATETIME) AS 'formattedDate' FROM dbs.tableName;

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

From the javadocs:

When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

However, the javadocs are not very clear on whether the Statement and ResultSet are closed when you close the underlying Connection. They simply state that closing a Connection:

Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.

In my opinion, always explicitly close ResultSets, Statements and Connections when you are finished with them as the implementation of close could vary between database drivers.

You can save yourself a lot of boiler-plate code by using methods such as closeQuietly in DBUtils from Apache.

wampserver doesn't go green - stays orange

you can run appache:

E:\wamp\bin\apache\apache2.4.9\bin\httpd.exe -d E:/wamp/bin/apache/apache2.4.9

after that see the log of error and solve it.

How do you merge two Git repositories?

Given command is the best possible solution I suggest.

git subtree add --prefix=MY_PROJECT git://github.com/project/my_project.git master

Can I connect to SQL Server using Windows Authentication from Java EE webapp?

Unless you have some really compelling reason not to, I suggest ditching the MS JDBC driver.

Instead, use the jtds jdbc driver. Read the README.SSO file in the jtds distribution on how to configure for single-sign-on (native authentication) and where to put the native DLL to ensure it can be loaded by the JVM.

getResourceAsStream() vs FileInputStream

I am here by separating both the usages by marking them as File Read(java.io) and Resource Read(ClassLoader.getResourceAsStream()).

File Read - 1. Works on local file system. 2. Tries to locate the file requested from current JVM launched directory as root 3. Ideally good when using files for processing in a pre-determined location like,/dev/files or C:\Data.

Resource Read - 1. Works on class path 2. Tries to locate the file/resource in current or parent classloader classpath. 3. Ideally good when trying to load files from packaged files like war or jar.

How to install mod_ssl for Apache httpd?

Try installing mod_ssl using following command:

yum install mod_ssl

and then reload and restart your Apache server using following commands:

systemctl reload httpd.service
systemctl restart httpd.service

This should work for most of the cases.

Create iOS Home Screen Shortcuts on Chrome for iOS

The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.

How to convert milliseconds into human readable form?

In python 3 you could achieve your goal by using the following snippet:

from datetime import timedelta

ms = 536643021
td = timedelta(milliseconds=ms)

print(str(td))
# --> 6 days, 5:04:03.021000

Timedelta documentation: https://docs.python.org/3/library/datetime.html#datetime.timedelta

Source of the __str__ method of timedelta str: https://github.com/python/cpython/blob/33922cb0aa0c81ebff91ab4e938a58dfec2acf19/Lib/datetime.py#L607

Sorting Characters Of A C++ String

std::sort(str.begin(), str.end());

See here

Can I have two JavaScript onclick events in one element?

You could try something like this as well

<a href="#" onclick="one(); two();" >click</a>

<script type="text/javascript">
    function one(){
        alert('test');
    }

    function two(){
        alert('test2');
    }
</script>

R dplyr: Drop multiple columns

Beyond select(-one_of(drop.cols)) there are a couple other options for dropping columns using select() that do not involve defining all the specific column names (using the dplyr starwars sample data for some more variety in column names):

starwars %>% 
  select(-(name:mass)) %>%        # the range of columns from 'name' to 'mass'
  select(-contains('color')) %>%  # any column name that contains 'color'
  select(-starts_with('bi')) %>%  # any column name that starts with 'bi'
  select(-ends_with('er')) %>%    # any column name that ends with 'er'
  select(-matches('^f.+s$')) %>%  # any column name matching the regex pattern
  select_if(~!is.list(.)) %>%     # not by column name but by data type
  head(2)

# A tibble: 2 x 2
homeworld species
  <chr>     <chr>  
1 Tatooine  Human  
2 Tatooine  Droid 

Use find command but exclude files in two directories

Here is one way you could do it...

find . -type f -name "*_peaks.bed" | egrep -v "^(./tmp/|./scripts/)"

Replace part of a string in Python?

>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'

Skip the headers when editing a csv file using Python

Doing row=1 won't change anything, because you'll just overwrite that with the results of the loop.

You want to do next(reader) to skip one row.

iOS change navigation bar title font and color

It's a bit more readable using literals:

self.navigationController.navigationBar.titleTextAttributes = @{
                                                              NSFontAttributeName:[UIFont fontWithName:@"mplus-1c-regular" size:21],
                                                              NSForegroundColorAttributeName: [UIColor whiteColor]
                                                              };

git pull while not in a git directory

You may wrap it in a bash script or git alias:

cd /X/Y && git pull && cd -

HTTP Error 503, the service is unavailable

Start by looking in Event Viewer, either under the System or the Application log.

In my case the problem was that no worker process could be started for the App Pool because its configuration file couldn't be read - I had included an extra '.' at the end of its name.

How to get date in BAT file

%date% will give you the date.

%time% will give you the time.

The date and time /t commands may give you more detail.

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

How to enable/disable bluetooth programmatically in android

Add the following permissions into your manifest file:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Enable bluetooth use this

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (!mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.enable(); 
}else{Toast.makeText(getApplicationContext(), "Bluetooth Al-Ready Enable", Toast.LENGTH_LONG).show();}

Disable bluetooth use this

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.disable(); 
}

How to access parameters in a Parameterized Build?

As per Pipeline plugin tutorial:

If you have configured your pipeline to accept parameters when it is built — Build with Parameters — they are accessible as Groovy variables of the same name.

So try to access the variable directly, e.g.:

node()
{
     print "DEBUG: parameter foo = " + foo
     print "DEBUG: parameter bar = ${bar}"
}

How to insert TIMESTAMP into my MySQL table?

$insertation = "INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIMESTAMP(), '$comments')";

You can use this Query. CURRENT_TIMESTAMP

Remember to use the parenthesis CURRENT_TIMESTAMP()

Single huge .css file vs. multiple smaller specific .css files?

You want both worlds.

You want multiple CSS files because your sanity is a terrible thing to waste.

At the same time, it's better to have a single, large file.

The solution is to have some mechanism that combines the multiple files in to a single file.

One example is something like

<link rel="stylesheet" type="text/css" href="allcss.php?files=positions.css,buttons.css,copy.css" />

Then, the allcss.php script handles concatenating the files and delivering them.

Ideally, the script would check the mod dates on all the files, creates a new composite if any of them changes, then returns that composite, and then checks against the If-Modified HTTP headers so as to not send redundant CSS.

This gives you the best of both worlds. Works great for JS as well.

Remove an array element and shift the remaining ones

If you are most concerned about code size and/or performance (also for WCET analysis, if you need one), I think this is probably going to be one of the more transparent solutions (for finding and removing elements):

unsigned int l=0, removed=0;

for( unsigned int i=0; i<count; i++ ) {
    if( array[i] != to_remove )
        array[l++] = array[i];
    else
        removed++;
}

count -= removed;

Generating a random password in php

Here's my take at random plain password generation helper.

It ensures that password has numbers, upper and lower case letters as well as a minimum of 3 special characters.

Length of the password will be between 11 and 30.

function plainPassword(): string
{
    $numbers = array_rand(range(0, 9), rand(3, 9));
    $uppercase = array_rand(array_flip(range('A', 'Z')), rand(2, 8));
    $lowercase = array_rand(array_flip(range('a', 'z')), rand(3, 8));
    $special = array_rand(array_flip(['@', '#', '$', '!', '%', '*', '?', '&']), rand(3, 5));

    $password = array_merge(
        $numbers,
        $uppercase,
        $lowercase,
        $special
    );

    shuffle($password);

    return implode($password);
}

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

How do you build a Singleton in Dart?

Here is a simple answer:

class Singleton {
  static Singleton _instance;

  Singleton._();

  static Singleton get getInstance => _instance ??= Singleton._();
}

Convert python long/int to fixed size byte array

Python 2.7 does not implement the int.to- very slow_bytes() method.

I tried 3 methods:

  1. hex unpack/pack : very slow
  2. byte shifting 8 bits at a time: significantly faster.
  3. using a "C" module and packing into the lower (7 ia64 or 3 i32) bytes. This was about twice as fast as 2/ . It is the fastest option, but still too slow.

All these methods are very inefficient for two reasons:

  • Python 2.7 does not support this useful operation.
  • c does not support extended precision arithmetic using the carry/borrow/overflow flags available on most platforms.

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

Thanks to Erhun's answer I finally realised that my JSON mapper was returning the quotation marks around my data too! I needed to use "asText()" instead of "toString()"

It's not an uncommon issue - one's brain doesn't see anything wrong with the correct data, surrounded by quotes!

discoveryJson.path("some_endpoint").toString();
"https://what.the.com/heck"

discoveryJson.path("some_endpoint").asText();
https://what.the.com/heck

npm - EPERM: operation not permitted on Windows

I use Windows 10. I started the CMD as administrator, and it solved the problem.

Find CMD, right click, and click open as administrator.

Bootstrap 3 select input form inline

Based on spacebean's answer, this modification also changes the displayed text when the user selects a different item (just as a <select> would do):

http://www.bootply.com/VxVlaebtnL

HTML:

<div class="container">
  <div class="col-sm-7 pull-right well">
    <form class="form-inline" action="#" method="get">
      <div class="input-group col-sm-8">
        <input class="form-control" type="text" value="" placeholder="Search" name="q">
        <div class="input-group-btn">
          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span id="mydropdowndisplay">Choice 1</span> <span class="caret"></span></button>
          <ul class="dropdown-menu" id="mydropdownmenu">
            <li><a href="#">Choice 1</a></li>
            <li><a href="#">Choice 2</a></li>
            <li><a href="#">Choice 3</a></li>
          </ul>
          <input type="hidden" id="mydropwodninput" name="category">
        </div><!-- /btn-group -->
      </div>
    <button class="btn btn-primary col-sm-3 pull-right" type="submit">Search</button>
    </form>
  </div>
</div>

Jquery:

$('#mydropdownmenu > li').click(function(e){
  e.preventDefault();
  var selected = $(this).text();
  $('#mydropwodninput').val(selected);
  $('#mydropdowndisplay').text(selected);
});

Storing Python dictionaries

To write to a file:

import json
myfile.write(json.dumps(mydict))

To read from a file:

import json
mydict = json.loads(myfile.read())

myfile is the file object for the file that you stored the dict in.

Implementing a slider (SeekBar) in Android

How to implement a SeekBar

enter image description here

Add the SeekBar to your layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_margin="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <SeekBar
        android:id="@+id/seekBar"
        android:max="100"
        android:progress="50"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Notes

  • max is the highest value that the seek bar can go to. The default is 100. The minimum is 0. The xml min value is only available from API 26, but you can just programmatically convert the 0-100 range to whatever you need for earlier versions.
  • progress is the initial position of the slider dot (called a "thumb").
  • For a vertical SeekBar use android:rotation="270".

Listen for changes in code

public class MainActivity extends AppCompatActivity {

    TextView tvProgressLabel;

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

        // set a change listener on the SeekBar
        SeekBar seekBar = findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);

        int progress = seekBar.getProgress();
        tvProgressLabel = findViewById(R.id.textView);
        tvProgressLabel.setText("Progress: " + progress);
    }

    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // updated continuously as the user slides the thumb
            tvProgressLabel.setText("Progress: " + progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // called when the user first touches the SeekBar
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // called after the user finishes moving the SeekBar
        }
    };
}

Notes

  • If you don't need to do any updates while the user is moving the seekbar, then you can just update the UI in onStopTrackingTouch.

See also

Change application's starting activity

Yes, you use the AndroidManifest.xml file. You can actually even have more than one launcher activity specified in your application manifest. To make an activity seen on the launcher you add these attributes to your activity in the manifest:

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

Have a look at the handleEvent method
https://developer.mozilla.org/en-US/docs/Web/API/EventListener

"Raw" Javascript:

function MyObj() {
   this.abc = "ABC";
}
MyObj.prototype.handleEvent = function(e) {
   console.log("caught event: "+e.type);
   console.log(this.abc);
}

var myObj = new MyObj();

document.querySelector("#myElement").addEventListener('click', myObj);

Now click on your element (with id "myElement") and it should print the following in the console:

caught event: click
ABC

This allows you to have an object method as event handler, and have access to all the object properties in that method.

You can't just pass a method of an object to addEventListener directly (like that: element.addEventListener('click',myObj.myMethod);) and expect myMethod to act as if I was normally called on the object. I am guessing that any function passed to addEventListener is somehow copied instead of being referenced. For example, if you pass an event listener function reference to addEventListener (in the form of a variable) then unset this reference, the event listener is still executed when events are caught.

Another (less elegant) workaround to pass a method as event listener and stil this and still have access to object properties within the event listener would be something like that:

// see above for definition of MyObj

var myObj = new MyObj();

document.querySelector("#myElement").addEventListener('click', myObj.handleEvent.bind(myObj));

How to pass parameters to $http in angularjs?

Here is a simple mathed to pass values from a route provider

//Route Provider
$routeProvider.when("/page/:val1/:val2/:val3",{controller:pageCTRL, templateUrl: 'pages.html'});


//Controller
$http.get( 'page.php?val1='+$routeParams.val1 +'&val2='+$routeParams.val2 +'&val3='+$routeParams.val3 , { cache: true})
        .then(function(res){
            //....
        })

How to make an ImageView with rounded corners?

Another easy way is to use a CardView with the corner radius and an ImageView inside:

  <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:cardCornerRadius="8dp"
            android:layout_margin="5dp"
            android:elevation="10dp">

            <ImageView
                android:id="@+id/roundedImageView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/image"
                android:background="@color/white"
                android:scaleType="centerCrop"
                />
        </androidx.cardview.widget.CardView>

enter image description here

Alternative to iFrames with HTML5

You can use an XMLHttpRequest to load a page into a div (or any other element of your page really). An exemple function would be:

function loadPage(){
if (window.XMLHttpRequest){
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}else{
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById("ID OF ELEMENT YOU WANT TO LOAD PAGE IN").innerHTML=xmlhttp.responseText;
    }
}

xmlhttp.open("POST","WEBPAGE YOU WANT TO LOAD",true);
xmlhttp.send();
}

If your sever is capable, you could also use PHP to do this, but since you're asking for an HTML5 method, this should be all you need.

How to break out of a loop in Bash?

It's not that different in bash.

workdone=0
while : ; do
  ...
  if [ "$workdone" -ne 0 ]; then
      break
  fi
done

: is the no-op command; its exit status is always 0, so the loop runs until workdone is given a non-zero value.


There are many ways you could set and test the value of workdone in order to exit the loop; the one I show above should work in any POSIX-compatible shell.

Map vs Object in JavaScript

Additionally to being iterable in a well-defined order, and the ability to use arbitrary values as keys (except -0), maps can be useful because of the following reasons:

  • The spec enforces map operations to be sublinear on average.

    Any non-stupid implementation of object will use a hash table or similar, so property lookups will probably be constant on average. Then objects could be even faster than maps. But that is not required by the spec.

  • Objects can have nasty unexpected behaviors.

    For example, let's say you didn't set any foo property to a newly created object obj, so you expect obj.foo to return undefined. But foo could be built-in property inherited from Object.prototype. Or you attempt to create obj.foo by using an assignment, but some setter in Object.prototype runs instead of storing your value.

    Maps prevent these kind of things. Well, unless some script messes up with Map.prototype. And Object.create(null) would work too, but then you lose the simple object initializer syntax.

Find the line number where a specific word appears with "grep"

Or You can use

   grep -n . file1 |tail -LineNumberToStartWith|grep regEx

This will take care of numbering the lines in the file

   grep -n . file1 

This will print the last-LineNumberToStartWith

   tail -LineNumberToStartWith

And finally it will grep your desired lines(which will include line number as in orignal file)

grep regEX

My httpd.conf is empty

It seems to me, that it is by design that this file is empty.

A similar question has been asked here: https://stackoverflow.com/questions/2567432/ubuntu-apache-httpd-conf-or-apache2-conf

So, you should have a look for /etc/apache2/apache2.conf

How to check a string starts with numeric number?

See the isDigit(char ch) method:

https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Character.html

and pass it to the first character of the String using the String.charAt() method.

Character.isDigit(myString.charAt(0));

Android Facebook integration with invalid key hash

According Facebook Login for Android, you must provide the key hash value. In order to obtain it, you will need the key used to sign your application.

keytool \
    -exportcert \
    -alias YourKeyAlias \
    -storepass YourStoreKeyPassword \
    -keystore PathToYourKeyStoreFile | openssl sha1 -binary | openssl base64

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

try with

<form formGroup="userForm">

instead of

<form [formGroup]="userForm">

How to Code Double Quotes via HTML Codes

Google recommend that you don't use any of them, source.

There is no need to use entity references like &mdash, &rdquo, or &#x263a, assuming the same encoding (UTF-8) is used for files and editors as well as among teams.

Is there a reason you can't simply use "?

paint() and repaint() in Java

The paint() method supports painting via a Graphics object.

The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

python - find index position in list based of partial string

Your idea to use enumerate() was correct.

indices = []
for i, elem in enumerate(mylist):
    if 'aa' in elem:
        indices.append(i)

Alternatively, as a list comprehension:

indices = [i for i, elem in enumerate(mylist) if 'aa' in elem]

Creating an Array from a Range in VBA

Just define the variable as a variant, and make them equal:

Dim DirArray As Variant
DirArray = Range("a1:a5").Value

No need for the Array command.

Assign output of a program to a variable using a MS batch file

One way is:

application arg0 arg1 > temp.txt
set /p VAR=<temp.txt

Another is:

for /f %%i in ('application arg0 arg1') do set VAR=%%i

Note that the first % in %%i is used to escape the % after it and is needed when using the above code in a batch file rather than on the command line. Imagine, your test.bat has something like:

for /f %%i in ('c:\cygwin64\bin\date.exe +"%%Y%%m%%d%%H%%M%%S"') do set datetime=%%i
echo %datetime%

Form inside a form, is that alright?

No. HTML explicitly forbids nested forms.

From the HTML 5 draft:

Content model: Flow content, but with no form element descendants.

From the HTML 4.01 Recommendation:

<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->

(Note the -(FORM) section).

How to add colored border on cardview?

try doing:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:cardElevation="2dp"
    card_view:cardCornerRadius="5dp">

    <FrameLayout
        android:background="#FF0000"
        android:layout_width="4dp"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:orientation="vertical">

        <TextView
            style="@style/Base.TextAppearance.AppCompat.Headline"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Title" />

        <TextView
            style="@style/Base.TextAppearance.AppCompat.Body1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Content here" />

    </LinearLayout>

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

this removes the padding from the cardview and adds a FrameLayout with a color. You then need to fix the padding in the LinearLayout then for the other fields

Update

If you want to preserve the card corner radius create card_edge.xml in drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="#F00" />
    <size android:width="10dp"/>
    <padding android:bottom="0dp" android:left="0dp" android:right="0dp" android:top="0dp"/>
    <corners android:topLeftRadius="5dp" android:bottomLeftRadius="5dp"
        android:topRightRadius="0.1dp" android:bottomRightRadius="0.1dp"/>
</shape>

and in the frame layout use android:background="@drawable/card_edge"

Returning boolean if set is empty

"""
This function check if set is empty or not.
>>> c = set([])
>>> set_is_empty(c)
True

:param some_set: set to check if he empty or not.
:return True if empty, False otherwise.
"""
def set_is_empty(some_set):
    return some_set == set()

"document.getElementByClass is not a function"

Before jumping into any further error checking please first check whether its

document.getElementsByClassName() itself.

double check its getElements and not getElement

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

jQuery toggle animation

$('.login').toggle(
    function(){
        $('#panel').animate({
            height: "150", 
            padding:"20px 0",
            backgroundColor:'#000000',
            opacity:.8
        }, 500);
        $('#otherdiv').animate({
            //otherdiv properties here
        }, 500);
    },
    function(){
        $('#panel').animate({
            height: "0", 
            padding:"0px 0",
            opacity:.2
        }, 500);     
        $('#otherdiv').animate({
            //otherdiv properties here
        }, 500);
});

How can I change a file's encoding with vim?

Notice that there is a difference between

set encoding

and

set fileencoding

In the first case, you'll change the output encoding that is shown in the terminal. In the second case, you'll change the output encoding of the file that is written.

Count number of times value appears in particular column in MySQL

select name, count(*) from table group by name;

i think should do it

Replace new line/return with space using regex

Your regex is good altough I would replace it with the empty string

String resultString = subjectString.replaceAll("[\t\n\r]", "");

You expect a space between "text." and "And" right?

I get that space when I try the regex by copying your sample

"This is my text. "

So all is well here. Maybe if you just replace it with the empty string it will work. I don't know why you replace it with \s. And the alternation | is not necessary in a character class.

Can you force Visual Studio to always run as an Administrator in Windows 8?

NOTE in recent VS versions (2015+) it seems this extension no longer exists/has this feature.


You can also download VSCommands for VS2012 by Squared Infinity which has a feature to change it to run as admin (as well as some other cool bits and pieces)

enter image description here

Update

One can install the commands from the Visual Studio menu bar using Tools->Extensions and Updates selecting Online and searching for vscommands where then one selects VSCommands for Visual Studio 20XX depending on whether using 2012 or 2013 (or greater going forward) and download and install.

How to rebase local branch onto remote master

After committing changes to your branch, checkout master and pull it to get its latest changes from the repo:

git checkout master
git pull origin master

Then checkout your branch and rebase your changes on master:

git checkout RB
git rebase master

...or last two commands in one line:

git rebase master RB

When trying to push back to origin/RB, you'll probably get an error; if you're the only one working on RB, you can force push:

git push --force origin RB

...or as follows if you have git configured appropriately:

git push -f

How to check for the type of a template parameter?

I think todays, it is better to use, but only with C++17.

#include <type_traits>

template <typename T>
void foo() {
    if constexpr (std::is_same_v<T, animal>) {
        // use type specific operations... 
    } 
}

If you use some type specific operations in if expression body without constexpr, this code will not compile.

Python Git Module experiences?

An updated answer reflecting changed times:

GitPython currently is the easiest to use. It supports wrapping of many git plumbing commands and has pluggable object database (dulwich being one of them), and if a command isn't implemented, provides an easy api for shelling out to the command line. For example:

repo = Repo('.')
repo.checkout(b='new_branch')

This calls:

bash$ git checkout -b new_branch

Dulwich is also good but much lower level. It's somewhat of a pain to use because it requires operating on git objects at the plumbing level and doesn't have nice porcelain that you'd normally want to do. However, if you plan on modifying any parts of git, or use git-receive-pack and git-upload-pack, you need to use dulwich.

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

How to var_dump variables in twig templates?

You can use the debug tag, which is documented here.

{% debug expression.varname %}

Edit: As of Twig 1.5, this has been deprecated and replaced with the new dump function (note, it's now a function and no longer a tag). See also: The accepted answer above.

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps