Programs & Examples On #Quartz.net

Quartz.NET is an open source job scheduling library for .NET. A job scheduler is a system that is responsible for executing (or notifying) other software components when a predetermined (scheduled) time arrives.

How to call a method daily, at specific time, in C#?

Solution with System.Threading.Timer:

    private void nameOfMethod()
    {
        //do something
    }

    /// <summary>
    /// run method at 22:00 every day
    /// </summary>
    private void runMethodEveryDay()
    {
        var runAt = DateTime.Today + TimeSpan.FromHours(22);

        if(runAt.Hour>=22)
            runAt = runAt.AddDays(1.00d); //if aplication is started after 22:00 

        var dueTime = runAt - DateTime.Now; //time before first run ; 

        long broj3 = (long)dueTime.TotalMilliseconds;
        TimeSpan ts2 = new TimeSpan(24, 0, 1);//period of repeating method
        long broj4 = (long)ts2.TotalMilliseconds;
        timer2 = new System.Threading.Timer(_ => nameOfMethod(), null, broj3, broj4);
    }

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

Unable to open a file with fopen()

Your executable's working directory is probably set to something other than the directory where it is saved. Check your IDE settings.

How to read a file in reverse order?

def previous_line(self, opened_file):
        opened_file.seek(0, os.SEEK_END)
        position = opened_file.tell()
        buffer = bytearray()
        while position >= 0:
            opened_file.seek(position)
            position -= 1
            new_byte = opened_file.read(1)
            if new_byte == self.NEW_LINE:
                parsed_string = buffer.decode()
                yield parsed_string
                buffer = bytearray()
            elif new_byte == self.EMPTY_BYTE:
                continue
            else:
                new_byte_array = bytearray(new_byte)
                new_byte_array.extend(buffer)
                buffer = new_byte_array
        yield None

to use:

opened_file = open(filepath, "rb")
iterator = self.previous_line(opened_file)
line = next(iterator) #one step
close(opened_file)

Moment.js - how do I get the number of years since a date, not rounded up?

If you dont want to use any module for age calculation

var age = Math.floor((new Date() - new Date(date_of_birth)) / 1000 / 60 / 60 / 24 / 365.25)

How can I get the UUID of my Android phone in an application?

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

This Row already belongs to another table error when trying to add rows?

This isn't the cleanest/quickest/easiest/most elegant solution, but it is a brute force one that I created to get the job done in a similar scenario:

DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();

// Create new DataColumns for dtSpecificOrders that are the same as in "dt"
DataColumn dcID = new DataColumn("ID", typeof(int));
DataColumn dcName = new DataColumn("Name", typeof(string));
dtSpecificOrders.Columns.Add(dtID);
dtSpecificOrders.Columns.Add(dcName);

DataRow[] orderRows = dt.Select("CustomerID = 2");

foreach (DataRow dr in orderRows)
{
    DataRow myRow = dtSpecificOrders.NewRow();  // <-- create a brand-new row
    myRow[dcID] = int.Parse(dr["ID"]);
    myRow[dcName] = dr["Name"].ToString();
    dtSpecificOrders.Rows.Add(myRow);   // <-- this will add the new row
}

The names in the DataColumns must match those in your original table for it to work. I just used "ID" and "Name" as examples.

What is the best/safest way to reinstall Homebrew?

Process is to clean up and then reinstall with the following commands:

rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install )"

Notes:

String comparison using '==' vs. 'strcmp()'

Always remember, when comparing strings, you should use === operator (strict comparison) and not == operator (loose comparison).

Selenium WebDriver How to Resolve Stale Element Reference Exception?

When a Stale Element Exception occurs!!

Stale element exception can happen when the libraries supporting those textboxes/ buttons/ links has changed which means the elements are same but the reference has now changed in the website without affecting the locators. Thus the reference which we stored in our cache including the library reference has now become old or stale because the page has been refreshed with updated libraries.

for(int j=0; j<5;j++)
try {
    WebElement elementName=driver.findElement(By.name(“createForm:dateInput_input”));
    break;
} catch(StaleElementReferenceException e){
e.toString();
System.out.println(“Stale element error, trying ::  ” + e.getMessage());
}
elementName.sendKeys(“20/06/2018”);

Include PHP inside JavaScript (.js) files

7 years later update: This is terrible advice. Please don't do this.

If you just need to pass variables from PHP to the javascript, you can have a tag in the php/html file using the javascript to begin with.

<script type="text/javascript">
    phpVars = new Array();
    <?php foreach($vars as $var) {
        echo 'phpVars.push("' . $var . '");';
    };
    ?>
</script>
<script type="text/javascript" src="yourScriptThatUsesPHPVars.js"></script>

If you're trying to call functions, then you can do this like this

<script type="text/javascript" src="YourFunctions.js"></script>
<script type="text/javascript">
    functionOne(<?php echo implode(', ', $arrayWithVars); ?>);
    functionTwo(<?php echo $moreVars; ?>, <?php echo $evenMoreVars; ?>);
</script>

Public class is inaccessible due to its protection level

This error is a result of the protection level of ClassB's constructor, not ClassB itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal by default. Declaring the constructor public will fix this problem:

public ClassB() { } 

* One could also say that constructors have no name, only a type; this does not change the essence of the problem.

Creating an array from a text file in Bash

You can do this too:

oldIFS="$IFS"
IFS=$'\n' arr=($(<file))
IFS="$oldIFS"
echo "${arr[1]}" # It will print `A Dog`.

Note:

Filename expansion still occurs. For example, if there's a line with a literal * it will expand to all the files in current folder. So use it only if your file is free of this kind of scenario.

Android WebView style background-color:transparent ignored on android 2.2

myWebView.setAlpha(0);

is the best answer. It works!

Is PowerShell ready to replace my Cygwin shell on Windows?

The cmdlets in PowerShell are very nice and work reliably. Their object-orientedness appeals to me a lot since I'm a Java/C# developer, but it's not at all a complete set. Since it's object oriented, it's missed out on a lot of the text stream maturity of the POSIX tool set (awk and sed to name a few).

The best answer I've found to the dilemma of loving OO techniques and loving the maturity in the POSIX tools is to use both! One great aspect of PowerShell is that it does an excellent job piping objects to standard streams. PowerShell by default uses an object pipeline to transport its objects around. These aren't the standard streams (standard out, standard error, and standard in). When PowerShell needs to pass output to a standard process that doesn't have an object pipeline, it first converts the objects to a text stream. Since it does this so well, PowerShell makes an excellent place to host POSIX tools!

The best POSIX tool set is GnuWin32. It does take more than 5 seconds to install, but it's worth the trouble, and as far as I can tell, it doesn't modify your system (registry, c:\windows\* folders, etc.) except copying files to the directories you specify. This is extra nice because if you put the tools in a shared directory, many people can access them concurrently.

GnuWin32 Installation Instructions

Download and execute the exe (it's from the SourceForge site) pointing it to a suitable directory (I'll be using C:\bin). It will create a GetGnuWin32 directory there in which you will run download.bat, then install.bat (without parameters), after which, there will be a C:\bin\GetGnuWin32\gnuwin32\bin directory that is the most useful folder that has ever existed on a Windows machine. Add that directory to your path, and you're ready to go.

PHP - how to create a newline character?

Only double quoted strings interpret the escape sequences \r and \n as '0x0D' and '0x0A' respectively, so you want:

"\r\n"

Single quoted strings, on the other hand, only know the escape sequences \\ and \'.

So unless you concatenate the single quoted string with a line break generated elsewhere (e. g., using double quoted string "\r\n" or using chr function chr(0x0D).chr(0x0A)), the only other way to have a line break within a single quoted string is to literally type it with your editor:

$s = 'some text before the line break
some text after';

Make sure to check your editor for its line break settings if you require some specific character sequence (\r\n for example).

How to determine the first and last iteration in a foreach loop?

You could remove the first and last elements off the array and process them separately.

Like this:

<?php
$array = something();
$first = array_shift($array);
$last = array_pop($array);

// do something with $first
foreach ($array as $item) {
 // do something with $item
}
// do something with $last
?>

Removing all the formatting to CSS instead of inline tags would improve your code and speed up load time.

You could also avoid mixing HTML with php logic whenever possible.

Your page could be made a lot more readable and maintainable by separating things like this:

<?php
function create_menu($params) {
  //retrieve menu items 
  //get collection 
  $collection = get('xxcollection') ;
  foreach($collection as $c) show_collection($c);
}

function show_subcat($val) {
  ?>
    <div class="sub_node" style="display:none">
      <img src="../images/dtree/join.gif" align="absmiddle" style="padding-left:2px;" />
      <a id="'.$val['xsubcatid'].'" href="javascript:void(0)" onclick="getProduct(this , event)" class="sub_node_links"  >
        <?php echo $val['xsubcatname']; ?>
      </a>
    </div>
  <?php
}

function show_cat($item) {
  ?>
    <div class="node" >
      <img src="../images/dtree/plus.gif" align="absmiddle" class="node_item" id="plus" />
      <img src="../images/dtree/folder.gif" align="absmiddle" id="folder">
      <?php echo $item['xcatname']; ?>
      <?php 
        $subcat = get_where('xxsubcategory' , array('xcatid'=>$item['xcatid'])) ;
        foreach($subcat as $val) show_subcat($val);
      ?>
    </div>
  <?php
}

function show_collection($c) {
  ?>
    <div class="parent" style="direction:rtl">
      <img src="../images/dtree/minus.gif" align="absmiddle" class="parent_item" id="minus" />
      <img src="../images/dtree/base.gif" align="absmiddle" id="base">
      <?php echo $c['xcollectionname']; ?>
      <?php
        //get categories 
        $cat = get_where('xxcategory' , array('xcollectionid'=>$c['xcollectionid']));
        foreach($cat as $item) show_cat($item);
      ?>
    </div>
  <?php
}
?>

An URL to a Windows shared folder

If you are allowed to go further then javascript/html facilities - I would use the apache web server to represent your directory listing via http.

If this solution is appropriate. these are the steps:

  1. download apache hhtp server from one of the mirrors http://httpd.apache.org/download.cgi

  2. unzip/install (if msi) it to the directory e.g C:\opt\Apache (the instruction is for windows)

  3. map the network forlder as a local drive on windows (\server\folder to let's say drive H:)

  4. open conf/httpd.conf file

  5. make sure the next line is present and not commented

    LoadModule autoindex_module modules/mod_autoindex.so

  6. Add directory configuration

<Directory "H:/path">

Options +Indexes

AllowOverride None

Order allow,deny

Allow from all

</Directory> 7. Start the web server and make sure the directory listingof the remote folder is available by http. hit localhost/path 8. use a frame inside your web page to access the listing

What is missed: 1. you mignt need more fancy configuration for the host name, refer to Apache Web Server docs. Register the host name in DNS server

  1. the mapping to the network drive might not work, i did not check. As a posible resolution - host your web server on the same machine as smb server.

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

By default login failed error message is nothing but a client user connection has been refused by the server due to mismatch of login credentials. First task you might check is to see whether that user has relevant privileges on that SQL Server instance and relevant database too, thats good. Obviously if the necessary prvileges are not been set then you need to fix that issue by granting relevant privileges for that user login.

Althought if that user has relevant grants on database & server if the Server encounters any credential issues for that login then it will prevent in granting the authentication back to SQL Server, the client will get the following error message:

Msg 18456, Level 14, State 1, Server <ServerName>, Line 1
Login failed for user '<Name>'

Ok now what, by looking at the error message you feel like this is non-descriptive to understand the Level & state. By default the Operating System error will show 'State' as 1 regardless of nature of the issues in authenticating the login. So to investigate further you need to look at relevant SQL Server instance error log too for more information on Severity & state of this error. You might look into a corresponding entry in log as:

2007-05-17 00:12:00.34 Logon     Error: 18456, Severity: 14, State: 8.
or

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

As defined above the Severity & State columns on the error are key to find the accurate reflection for the source of the problem. On the above error number 8 for state indicates authentication failure due to password mismatch. Books online refers: By default, user-defined messages of severity lower than 19 are not sent to the Microsoft Windows application log when they occur. User-defined messages of severity lower than 19 therefore do not trigger SQL Server Agent alerts.

Sung Lee, Program Manager in SQL Server Protocols (Dev.team) has outlined further information on Error state description:The common error states and their descriptions are provided in the following table:

ERROR STATE       ERROR DESCRIPTION
------------------------------------------------------------------------------
2 and 5           Invalid userid
6                 Attempt to use a Windows login name with SQL Authentication
7                 Login disabled and password mismatch
8                 Password mismatch
9                 Invalid password
11 and 12         Valid login but server access failure
13                SQL Server service paused
18                Change password required


Well I'm not finished yet, what would you do in case of error:

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

You can see there is no severity or state level defined from that SQL Server instance's error log. So the next troubleshooting option is to look at the Event Viewer's security log [edit because screen shot is missing but you get the

idea, look in the event log for interesting events].

MongoDB: How to find the exact version of installed MongoDB

To check mongodb version use the mongod command with --version option.

To check MongoDB Server version, Open the command line via your terminal program and execute the following command:

Path : C:\Program Files\MongoDB\Server\3.2\bin Open Cmd and execute the following command: mongod --version To Check MongoDB Shell version, Type:

mongo --version

HTTP 1.0 vs 1.1

HTTP 1.1 comes with the host header in its specification while the HTTP 1.0 doesn't officially have a host header, but it doesn't refuse to add one.

The host header is useful because it allows the client to route a message throughout the proxy server, and the major difference between 1.0 and 1.1 versions HTTP are:

  1. HTTP 1.1 comes with persistent connections which define that we can have more than one request or response on the same HTTP connection.
  2. while in HTTP 1.0 you have to open a new connection for each request and response
  3. In HTTP 1.0 it has a pragma while in HTTP 1.1 it has Cache-Control this is similar to pragma

open a url on click of ok button in android

create an intent and set an action for it while passing the url to the intent

yourbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String theurl = "http://google.com";
                Uri urlstr = Uri.parse(theurl);
                Intent urlintent = new Intent();
                urlintent.setData(urlstr);
                urlintent.setAction(Intent.ACTION_VIEW);
                startActivity(urlintent);

How do I force detach Screen from another SSH session?

As Jose answered, screen -d -r should do the trick. This is a combination of two commands, as taken from the man page.

screen -d detaches the already-running screen session, and screen -r reattaches the existing session. By running screen -d -r, you force screen to detach it and then resume the session.

If you use the capital -D -RR, I quote the man page because it's too good to pass up.

Attach here and now. Whatever that means, just do it.

Note: It is always a good idea to check the status of your sessions by means of "screen -list".

Multiple conditions in WHILE loop

You need to change || to && so that both conditions must be true to enter the loop.

while(myChar != 'n' && myChar != 'N')

How to add files/folders to .gitignore in IntelliJ IDEA?

Intellij had .ignore plugin to support this. https://plugins.jetbrains.com/plugin/7495?pr=idea

After you install the plugin, you right click on the project and select new -> .ignore file -> .gitignore file (Git) enter image description here

Then, select the type of project you have to generate a template and click Generate. enter image description here

Function to convert timestamp to human date in javascript

This is what I did for the instagram API. converted timestamp with date method by multiplying by 1000. and then added all entity individually like (year, months, etc)

created the custom month list name and mapped with getMonth() method which returns the index of the month.

convertStampDate(unixtimestamp){

// Unixtimestamp

// Months array
var months_arr = ['January','February','March','April','May','June','July','August','September','October','November','December'];

// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);

// Year
var year = date.getFullYear();

// Month
var month = months_arr[date.getMonth()];

// Day
var day = date.getDate();

// Hours
var hours = date.getHours();

// Minutes
var minutes = "0" + date.getMinutes();

// Seconds
var seconds = "0" + date.getSeconds();

// Display date time in MM-dd-yyyy h:m:s format
var fulldate = month+' '+day+'-'+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);

// filtered fate
var convdataTime = month+' '+day;
return convdataTime;
}

Call with stamp argument convertStampDate('1382086394000')

and thats it.

How do I change the default index page in Apache?

You can also set DirectoryIndex in apache's httpd.conf file.

CentOS keeps this file in /etc/httpd/conf/httpd.conf Debian: /etc/apache2/apache2.conf

Open the file in your text editor and find the line starting with DirectoryIndex

To load landing.html as a default (but index.html if that's not found) change this line to read:

DirectoryIndex  landing.html index.html

How can I share Jupyter notebooks with non-programmers?

Google has recently made public its internal Collaboratory project (link here). You can start a notebook in the same way as starting a Google Sheet or Google Doc, and then simply share the notebook or add collaborators..

For now, this is the easiest way for me.

Most efficient way to append arrays in C#?

Concatenating arrays is simple using linq extensions which come standard with .Net 4

Biggest thing to remember is that linq works with IEnumerable<T> objects, so in order to get an array back as your result then you must use the .ToArray() method at the end

Example of concatenating two byte arrays:

byte[] firstArray = {2,45,79,33};
byte[] secondArray = {55,4,7,81};
byte[] result = firstArray.Concat(secondArray).ToArray();

Remove a git commit which has not been pushed

I believe that one of those will fit your need

1 - Undo commit and keep all files staged: git reset --soft HEAD~;

2 - Undo commit and unstage all files: git reset HEAD~;

3 - Undo the commit and completely remove all changes: git reset --hard HEAD~;

here is were I found the answer

Cannot perform runtime binding on a null reference, But it is NOT a null reference

Found solution: I had typo in my view, ViewBag.Typo <-- this caused the error, but the debugger placed the exception at a irrelevant place.

how to generate a unique token which expires after 24 hours?

Use Dictionary<string, DateTime> to store token with timestamp:

static Dictionary<string, DateTime> dic = new Dictionary<string, DateTime>();

Add token with timestamp whenever you create new token:

dic.Add("yourToken", DateTime.Now);

There is a timer running to remove any expired tokens out of dic:

 timer = new Timer(1000*60); //assume run in 1 minute
 timer.Elapsed += timer_Elapsed;

 static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        var expiredTokens = dic.Where(p => p.Value.AddDays(1) <= DateTime.Now)
                              .Select(p => p.Key);

        foreach (var key in expiredTokens)
            dic.Remove(key);
    }

So, when you authenticate token, just check whether token exists in dic or not.

How to create web service (server & Client) in Visual Studio 2012?

When creating a New Project, under the language of your choice, select Web and then change to .NET Framework 3.5 and you will get the option of creating an ASP.NET WEB Service Application.

enter image description here

Checking if an input field is required using jQuery

$('form#register input[required]')

It will only return inputs which have required attribute.

Setting "checked" for a checkbox with jQuery

To check and uncheck

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

How to find and replace string?

like some say boost::replace_all

here a dummy example:

    #include <boost/algorithm/string/replace.hpp>

    std::string path("file.gz");
    boost::replace_all(path, ".gz", ".zip");

python pandas extract year from datetime: df['year'] = df['date'].year is not working

Probably already too late to answer but since you have already parse the dates while loading the data, you can just do this to get the day

df['date'] = pd.DatetimeIndex(df['date']).year

Javascript - Open a given URL in a new tab by clicking a button

Use this:

<input type="button" value="button name" onclick="window.open('http://www.website.com/page')" />

Worked for me and it will open an actual new 'popup' window rather than a new full browser or tab. You can also add variables to it to stop it from showing specific browser traits as follows:

onclick="window.open(this.href,'popUpWindow','height=400,width=600,left=10,top=10,,scrollbars=yes,menubar=no'); return false;"

Default instance name of SQL Server Express

Should be .\SQLExpress or localhost\SQLExpress no $ sign at the end

See also here http://www.connectionstrings.com/sql-server-2008

How to POST raw whole JSON in the body of a Retrofit request?

Using JsonObject is the way it is:

  1. Create your interface like this:

    public interface laInterfaz{ 
        @POST("/bleh/blah/org")
        void registerPayer(@Body JsonObject bean, Callback<JsonObject> callback);
    }
    
  2. Make the JsonObject acording to the jsons structure.

    JsonObject obj = new JsonObject();
    JsonObject payerReg = new JsonObject();
    payerReg.addProperty("crc","aas22");
    payerReg.addProperty("payerDevManufacturer","Samsung");
    obj.add("payerReg",payerReg);
    /*json/*
        {"payerReg":{"crc":"aas22","payerDevManufacturer":"Samsung"}}
    /*json*/
    
  3. Call the service:

    service.registerPayer(obj, callBackRegistraPagador);
    
    Callback<JsonObject> callBackRegistraPagador = new Callback<JsonObject>(){
        public void success(JsonObject object, Response response){
            System.out.println(object.toString());
        }
    
        public void failure(RetrofitError retrofitError){
            System.out.println(retrofitError.toString());
        }
    };
    

And that its! In my personal opinion, its a lot better than making pojos and working with the class mess. This is a lot more cleaner.

Cannot open include file with Visual Studio

I had this same issue going from e.g gcc to visual studio for C programming. Make sure your include file is actually in the directory -- not just shown in the VS project tree. For me in other languages copying into a folder in the project tree would indeed move the file in. With Visual Studio 2010, pasting into "Header Files" was NOT putting the .h file there.

Please check your actual directory for the presence of the include file. Putting it into the "header files" folder in project/solution explorer was not enough.

How to set label size in Bootstrap

if you have

<span class="label label-default">New</span>

just add the style="font-size:XXpx;", ej.

<span class="label label-default" style="font-size:15px;">New</span>

How can I disable all views inside the layout?

I like to have a control over the root view so I added the includeSelf flag to deepForEach

fun ViewGroup.deepForEach(includeSelf: Boolean = true, function: View.() -> Unit) {
    if (includeSelf) function()
    forEach {
        it.apply {
            function()
            (this as? ViewGroup)?.apply { deepForEach(includeSelf, function) }
        }
    }
}

Creating dummy variables in pandas for python

You can create dummy variables to handle the categorical data

# Creating dummy variables for categorical datatypes
trainDfDummies = pd.get_dummies(trainDf, columns=['Col1', 'Col2', 'Col3', 'Col4'])

This will drop the original columns in trainDf and append the column with dummy variables at the end of the trainDfDummies dataframe.

It automatically creates the column names by appending the values at the end of the original column name.

Forbidden You don't have permission to access / on this server

Found my solution on Apache/2.2.15 (Unix).

And Thanks for answer from @QuantumHive:

First: I finded all

Order allow,deny
Deny from all

instead of

Order allow,deny

Allow from all

and then:

I setted

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory /var/www/html>
#    AllowOverride FileInfo AuthConfig Limit
#    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
#    <Limit GET POST OPTIONS>
#        Order allow,deny
#        Allow from all
#    </Limit>
#    <LimitExcept GET POST OPTIONS>
#        Order deny,allow
#        Deny from all
#    </LimitExcept>
#</Directory>

Remove the previous "#" annotation to

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
<Directory /var/www/html>
    AllowOverride FileInfo AuthConfig Limit
    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    <Limit GET POST OPTIONS>
        Order allow,deny
        Allow from all
    </Limit>
    <LimitExcept GET POST OPTIONS>
        Order deny,allow
        Deny from all
    </LimitExcept>
</Directory>

ps. my WebDir is: /var/www/html

Best way to use multiple SSH private keys on one client

IMPORTANT: You must start ssh-agent

You must start ssh-agent (if it is not running already) before using ssh-add as follows:

eval `ssh-agent -s` # start the agent

ssh-add id_rsa_2 # Where id_rsa_2 is your new private key file

Note that the eval command starts the agent on Git Bash on Windows. Other environments may use a variant to start the SSH agent.

Javascript event handler with parameters

let obj = MyObject();

elem.someEvent( function(){ obj.func(param) } );

//calls the MyObject.func, passing the param.

Embed HTML5 YouTube video without iframe?

Here is a example of embedding without an iFrame:

_x000D_
_x000D_
<div style="width: 560px; height: 315px; float: none; clear: both; margin: 2px auto;">
  <embed
    src="https://www.youtube.com/embed/J---aiyznGQ?autohide=1&autoplay=1"
    wmode="transparent"
    type="video/mp4"
    width="100%" height="100%"
    allow="autoplay; encrypted-media; picture-in-picture"
    allowfullscreen
    title="Keyboard Cat"
  >
</div>
_x000D_
_x000D_
_x000D_

compare to regular iframe "embed" code from YouTube:

_x000D_
_x000D_
<iframe
  width="560"
  height="315"
  src="https://www.youtube.com/embed/J---aiyznGQ?autoplay=1"
  frameborder="0"
  allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
  allowfullscreen>
</iframe>
_x000D_
_x000D_
_x000D_

and as far as HTML5 goes, use <object> tag like so (corrected):

_x000D_
_x000D_
<object
  style="width: 820px; height: 461.25px; float: none; clear: both; margin: 2px auto;"
  data="http://www.youtube.com/embed/J---aiyznGQ?autoplay=1">
</object>
_x000D_
_x000D_
_x000D_

Github Windows 'Failed to sync this branch'

Along the lines of the HTTP Proxy answers, this can also happen due to a VPN connection. Disconnecting my VPN connection solved it for me.

How to set value of input text using jQuery

$(document).ready(function () {
    $('#EmployeeId').val("fgg");

    //Or
    $('.textBoxEmployeeNumber > input').val("fgg");

    //Or
    $('.textBoxEmployeeNumber').find('input').val("fgg");
});

What is the volatile keyword useful for?

Yes, volatile must be used whenever you want a mutable variable to be accessed by multiple threads. It is not very common usecase because typically you need to perform more than a single atomic operation (e.g. check the variable state before modifying it), in which case you would use a synchronized block instead.

PHP strtotime +1 month adding an extra month

Maybe because its 2013-01-29 so +1 month would be 2013-02-29 which doesn't exist so it would be 2013-03-01

You could try

date('m/d/y h:i a',(strtotime('next month',strtotime(date('m/01/y')))));

from the comments on http://php.net/manual/en/function.strtotime.php

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

From the JIRA knowledge base:

Symptoms

Workflow actions may be inaccessible

  1. JIRA may throw exceptions on screen
  2. One or both of the following conditions may exist:

The following appears in the atlassian-jira.log:

     2007-12-06 10:55:05,327 http-8080-Processor20 ERROR [500ErrorPage] 
     Exception caught in500 page Unable to compile class for JSP
    org.apache.jasper.JasperException: Unable to compile class for JSP
   at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:572)
   at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:305)

_

Cause:

The Tomcat container caches .java and .class files generated by the JSP parser they are used by the web application. Sometimes these get corrupted or cannot be found. This may occur after a patch or upgrade that contains modifications to JSPs.

Resolution

1.Delete the contents of the /work folder if using standalone JIRA or /work if using EAR/WAR installation . 2. Verify the user running the JIRA application process has Read/Write permission to the /work directory. 3. Restart the JIRA application container to rebuild the files.

Showing data values on stacked bar chart in ggplot2

As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.

It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.

library(grid)
library(gridExtra)
library(plyr)

# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))

# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") + 
  xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category)) 
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") + 
  labs(title = "Proportion of total Frequency accounted by each Category in given Year")

# bring them together
grid.arrange(totals,proportion)

This will give you a 2 panel display like this:

Vertically stacked 2 panel graphic

If you want to add Frequency values a table is the best format.

MVC3 DropDownListFor - a simple example?

You should do like this:

@Html.DropDownListFor(m => m.ContribType, 
                new SelectList(Model.ContribTypeOptions, 
                               "ContribId", "Value"))

Where:

m => m.ContribType

is a property where the result value will be.

Why is Visual Studio 2010 not able to find/open PDB files?

I've found that these errors sometimes are from lack of permissions when compiling a project - so I run as administrator to get it to work properly.

Can an ASP.NET MVC controller return an Image?

Yes you can return Image

public ActionResult GetImage(string imageFileName)
{
    var path = Path.Combine(Server.MapPath("/Images"), imageFileName + ".jpg"); 
    return base.File(path, "image/jpeg");
}

(Please don't forget to mark this as answer)

What are the differences between using the terminal on a mac vs linux?

If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.

Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.

If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.

There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd on Mac and ifconfig works differently.

The following table is useful for knowing the various unix shells.

sh      The original Bourne shell   Present on every unix system 
ksh     Original Korn shell         Richer shell programming environment than sh 
csh     Original C-shell            C-like syntax; early versions buggy 
tcsh    Enhanced C-shell            User-friendly and less buggy csh implementation 
bash    GNU Bourne-again shell      Enhanced and free sh implementation 
zsh     Z shell                     Enhanced, user-friendly ksh-like shell

You may also find these guides helpful:

http://homepage.mac.com/rgriff/files/TerminalBasics.pdf

http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html

On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile on OSX) file with aliases, some examples below. I now placed all my aliases in a separate .bash_aliases file and include it with:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

in the .bashrc or .bash_profile file.

Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto. The first time I did this (without knowing) I redefined ls to be invalid which was a bit alarming until I removed --auto-color !

You may also find https://unix.stackexchange.com/q/127799/10043 useful

# ~/.bash_aliases
# ls variants
#alias l='ls -CF' 
alias la='ls -A' 
alias l='ls -alFtr' 
alias lsd='ls -d .*' 
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i' 
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed' 
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status' 
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'

How do you create a daemon in Python?

An alternative -- create a normal, non-daemonized Python program then externally daemonize it using supervisord. This can save a lot of headaches, and is *nix- and language-portable.

Difference between "read commited" and "repeatable read"

Please note that, the repeatable in repeatable read regards to a tuple, but not to the entire table. In ANSC isolation levels, phantom read anomaly can occur, which means read a table with the same where clause twice may return different return different result sets. Literally, it's not repeatable.

What is trunk, branch and tag in Subversion?

If you're new to Subversion you may want to check out this post on SmashingMagazine.com, appropriately titled Ultimate Round-Up for Version Control with SubVersion.

It covers getting started with SubVersion with links to tutorials, reference materials, & book suggestions.

It covers tools (many are compatible windows), and it mentions AnkhSVN as a Visual Studio compatible plugin. The comments also mention VisualSVN as an alternative.

how to read value from string.xml in android?

while u write R. you are referring to the R.java class created by eclipse, use getResources().getString() and pass the id of the resource from which you are trying to read inside the getString() method.

Example : String[] yourStringArray = getResources().getStringArray(R.array.Your_array);

Unescape HTML entities in Javascript?

I use this in my project: inspired by other answers but with an extra secure parameter, can be useful when you deal with decorated characters

var decodeEntities=(function(){

    var el=document.createElement('div');
    return function(str, safeEscape){

        if(str && typeof str === 'string'){

            str=str.replace(/\</g, '&lt;');

            el.innerHTML=str;
            if(el.innerText){

                str=el.innerText;
                el.innerText='';
            }
            else if(el.textContent){

                str=el.textContent;
                el.textContent='';
            }

            if(safeEscape)
                str=str.replace(/\</g, '&lt;');
        }
        return str;
    }
})();

And it's usable like:

var label='safe <b> character &eacute;ntity</b>';
var safehtml='<div title="'+decodeEntities(label)+'">'+decodeEntities(label, true)+'</div>';

Read Excel sheet in Powershell

This assumes that the content is in column B on each sheet (since it's not clear how you determine the column on each sheet.) and the last row of that column is also the last row of the sheet.

$xlCellTypeLastCell = 11 
$startRow = 5 
$col = 2 

$excel = New-Object -Com Excel.Application
$wb = $excel.Workbooks.Open("C:\Users\Administrator\my_test.xls")

for ($i = 1; $i -le $wb.Sheets.Count; $i++)
{
    $sh = $wb.Sheets.Item($i)
    $endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
    $city = $sh.Cells.Item($startRow, $col).Value2
    $rangeAddress = $sh.Cells.Item($startRow + 1, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
    $sh.Range($rangeAddress).Value2 | foreach 
    {
        New-Object PSObject -Property @{ City = $city; Area = $_ }
    }
}

$excel.Workbooks.Close()

Python: Fetch first 10 results from a list

check this

 list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

 list[0:10]

Outputs:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

POST string to ASP.NET Web Api application - returns null

Web API works very nicely if you accept the fact that you are using HTTP. It's when you start trying to pretend that you are sending objects over the wire that it starts to get messy.

 public class TextController : ApiController
    {
        public HttpResponseMessage Post(HttpRequestMessage request) {

            var someText = request.Content.ReadAsStringAsync().Result;
            return new HttpResponseMessage() {Content = new StringContent(someText)};

        }

    }

This controller will handle a HTTP request, read a string out of the payload and return that string back.

You can use HttpClient to call it by passing an instance of StringContent. StringContent will be default use text/plain as the media type. Which is exactly what you are trying to pass.

    [Fact]
    public void PostAString()
    {

        var client = new HttpClient();

        var content = new StringContent("Some text");
        var response = client.PostAsync("http://oak:9999/api/text", content).Result;

        Assert.Equal("Some text",response.Content.ReadAsStringAsync().Result);

    }

JAVA_HOME is set to an invalid directory:

I found this while googling the issue with android licences when installing Flutter.

For Linux, update Your ~/.bashrc (or other shell config) file by adding this line at the end:

JAVA_HOME=/usr/local/android-studio/jre

Note: I installed Android studio by following the official installation guide for Linux (link).

For Windows, use the android studio's path to the jre directory and update the environment variable with the right value.

Then, run flutter doctor --android-licenses and press y to review the licences which are not accepted. Press y for each of the licences. It will ask Accept? (y/N): at the end of the license file. After You accept all unaccepted licences, You should see:

All SDK package licenses accepted

Concatenate in jQuery Selector

There is nothing wrong with syntax of

$('#part' + number).html(text);

jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.

In your case you should pass a String to $() that is

$(<a string>)

Make sure you have access to the variables number and text.

To test do:

function(){
    alert(number + ":" + text);//or use console.log(number + ":" + text)
    $('#part' + number).html(text);
}); 

If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

Pass connection string to code-first DbContext

After reading the docs, I have to pass the name of the connection string instead:

var db = new NerdDinners("NerdDinnerDb");

Android TextView padding between lines

You can use TextView.setLineSpacing(n,m) function.

How to remove special characters from a string?

If you just want to do a literal replace in java, use Pattern.quote(string) to escape any string to a literal.

myString.replaceAll(Pattern.quote(matchingStr), replacementStr)

How do I get a value of a <span> using jQuery?

$('#item1').text(); or $('#item1').html(); works fine for id="item1"

Getting request payload from POST request in Java servlet

With Apache Commons IO you can do this in one line.

IOUtils.toString(request.getReader())

change image opacity using javascript

You could use Jquery indeed or plain good old javascript:

var opacityPercent=30;
document.getElementById("id").style.cssText="opacity:0."+opacityPercent+"; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+opacityPercent+");";

You put this in a function that you call on a setTimeout until the desired opacity is reached

Git: How to remove remote origin from Git repo

I don't have enough reputation to comment answer of @user1615903, so add this as answer: "git remote remove" does not exist, should use "rm" instead of "remove". So the correct way is:

git remote rm origin

How to access child's state in React?

Now You can access the InputField's state which is the child of FormEditor .

Basically whenever there is a change in the state of the input field(child) we are getting the value from the event object and then passing this value to the Parent where in the state in the Parent is set.

On button click we are just printing the state of the Input fields.

The key point here is that we are using the props to get the Input Field's id/value and also to call the functions which are set as attributes on the Input Field while we generate the reusable child Input fields.

class InputField extends React.Component{
  handleChange = (event)=> {
    const val = event.target.value;
    this.props.onChange(this.props.id , val);
  }

  render() {
    return(
      <div>
        <input type="text" onChange={this.handleChange} value={this.props.value}/>
        <br/><br/>
      </div>
    );
  }
}       


class FormEditorParent extends React.Component {
  state = {};
  handleFieldChange = (inputFieldId , inputFieldValue) => {
    this.setState({[inputFieldId]:inputFieldValue});
  }
  //on Button click simply get the state of the input field
  handleClick = ()=>{
    console.log(JSON.stringify(this.state));
  }

  render() {
    const fields = this.props.fields.map(field => (
      <InputField
        key={field}
        id={field}
        onChange={this.handleFieldChange}
        value={this.state[field]}
      />
    ));

    return (
      <div>
        <div>
          <button onClick={this.handleClick}>Click Me</button>
        </div>
        <div>
          {fields}
        </div>
      </div>
    );
  }
}

const App = () => {
  const fields = ["field1", "field2", "anotherField"];
  return <FormEditorParent fields={fields} />;
};

ReactDOM.render(<App/>, mountNode);

Understanding the Gemfile.lock file

Bundler is a Gem manager which provides a consistent environment for Ruby projects by tracking and installing the exact gems and versions that are needed.

Gemfile and Gemfile.lock are primary products given by Bundler gem (Bundler itself is a gem).

Gemfile contains your project dependency on gem(s), that you manually mention with version(s) specified, but those gem(s) inturn depends on other gem(s) which is resolved by bundler automatically.

Gemfile.lock contain complete snapshot of all the gem(s) in Gemfile along with there associated dependency.

When you first call bundle install, it will create this Gemfile.lock and uses this file in all subsequent calls to bundle install, which ensures that you have all the dependencies installed and will skip dependency installation.

Same happens when you share your code with different machines

You share your Gemfile.lock along with Gemfile, when you run bundle install on other machine it will refer to your Gemfile.lock and skip dependency resolution step, instead it will install all of the same dependent gem(s) that you used on the original machine, which maintains consistency across multiple machines

Why do we need to maintain consistency along multiple machines ?

  • Running different versions on different machines could lead to broken code

  • Suppose, your app used the version 1.5.3 and it works 14 months ago
    without any problems, and you try to install on different machine
    without Gemfile.lock now you get the version 1.5.8. Maybe it's broken with the latest version of some gem(s) and your application will
    fail. Maintaining consistency is of utmost importance (preferred
    practice).

It is also possible to update gem(s) in Gemfile.lock by using bundle update.

This is based on the concept of conservative updating

Could not open input file: artisan

Just make sure you are in the project folder by typing

ls

If not then go to the project folder by typing

 cd folder_name

for example:

cd laravel

And then type

php artisan serve

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

Need to get a string after a "word" in a string in c#

string toBeSearched = "code : ";
string code = myString.Substring(myString.IndexOf(toBeSearched) + toBeSearched.Length);

Something like this?

Perhaps you should handle the case of missing code :...

string toBeSearched = "code : ";
int ix = myString.IndexOf(toBeSearched);

if (ix != -1) 
{
    string code = myString.Substring(ix + toBeSearched.Length);
    // do something here
}

How to count the number of rows in excel with data?

For greater clarity, I want to add a clear example and running

            openFileDialog1.FileName = "Select File"; 
            openFileDialog1.DefaultExt = ".xls"; 
            openFileDialog1.Filter = "Excel documents (.xls)|*.xls"; 


            DialogResult result = openFileDialog1.ShowDialog();


            if (result==DialogResult.OK)
            {

                string filename = openFileDialog1.FileName;


                Excel.Application xlApp;
                Excel.Workbook xlWorkBook;
                Excel.Worksheet xlWorkSheet;
                object misValue = System.Reflection.Missing.Value;

                xlApp = new Excel.Application();
                xlApp.Visible = false;
                xlApp.DisplayAlerts = false;



                xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

                var numRows = xlWorkSheet.Range["A1"].Offset[xlWorkSheet.Rows.Count - 1, 0].End[Excel.XlDirection.xlUp].Row;

                MessageBox.Show("Number of max row is : "+ numRows.ToString());

                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();

            }

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

You could use a regex, yes, but a simple string.Replace() will probably suffice.

 myString = myString.Replace("\r\n", string.Empty);

Imported a csv-dataset to R but the values becomes factors

for me the solution was to include skip = 0 (number of rows to skip at the top of the file. Can be set >0)

mydata <- read.csv(file = "file.csv", header = TRUE, sep = ",", skip = 22)

find filenames NOT ending in specific extensions on Unix?

Other solutions on this page aren't desirable if you have a long list of extensions -- maintaining a long sequence of -not -name 'this' -not -name 'that' -not -name 'other' would be tedious and error-prone -- or if the search is programmatic and the list of extensions is built at runtime.

For those situations, a solution that more clearly separates data (the list of extensions) and code (the parameters to find) may be desirable. Given a directory & file structure that looks like this:

.
+-- a
    +-- 1.txt
    +-- 15.xml
    +-- 8.dll
    +-- b
    ¦   +-- 16.xml
    ¦   +-- 2.txt
    ¦   +-- 9.dll
    ¦   +-- c
    ¦       +-- 10.dll
    ¦       +-- 17.xml
    ¦       +-- 3.txt
    +-- d
    ¦   +-- 11.dll
    ¦   +-- 18.xml
    ¦   +-- 4.txt
    ¦   +-- e
    ¦       +-- 12.dll
    ¦       +-- 19.xml
    ¦       +-- 5.txt
    +-- f
        +-- 13.dll
        +-- 20.xml
        +-- 6.txt
        +-- g
            +-- 14.dll
            +-- 21.xml
            +-- 7.txt

You can do something like this:

## data section, list undesired extensions here
declare -a _BADEXT=(xml dll)

## code section, this never changes
BADEXT="$( IFS="|" ; echo "${_BADEXT[*]}" | sed 's/|/\\|/g' )"
find . -type f ! -regex ".*\.\($BADEXT\)"

Which results in:

./a/1.txt
./a/b/2.txt
./a/b/c/3.txt
./a/d/4.txt
./a/d/e/5.txt
./a/f/6.txt
./a/f/g/7.txt

You can change the extensions list without changing the code block.

NOTE doesn't work with native OSX find - use gnu find instead.

Reverse Contents in Array

Both answers look correct to me.

  1. The first arr[i] = temp; should be removed

  2. You should do a second loop to print all elements, not just half the array. The loop that does the reverse doesn't need to print it.

Can .NET load and parse a properties file equivalent to Java Properties class?

C# generally uses xml-based config files rather than the *.ini-style file like you said, so there's nothing built-in to handle this. However, google returns a number of promising results.

Using Server.MapPath() inside a static field in ASP.NET MVC

Try HostingEnvironment.MapPath, which is static.

See this SO question for confirmation that HostingEnvironment.MapPath returns the same value as Server.MapPath: What is the difference between Server.MapPath and HostingEnvironment.MapPath?

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

Your not applying Date formator. rather you are just parsing the date. to get output in this format

yyyy-MM-dd HH:mm:ss.SSSSSS

we have to use format() method here is full example:- Here is full example:- it will take Date in this format yyyy-MM-dd HH:mm:ss.SSSSSS and as result we will get output as same as this format yyyy-MM-dd HH:mm:ss.SSSSSS

 import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//TODO OutPut should LIKE in this format yyyy-MM-dd HH:mm:ss.SSSSSS.
public class TestDateExample {

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

    SimpleDateFormat changeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");

    java.util.Date temp = changeFormat.parse("2012-07-10 14:58:00.000000");
     Date thisDate = changeFormat.parse("2012-07-10 14:58:00.000000");  
    System.out.println(thisDate);
    System.out.println("----------------------------"); 
    System.out.println("After applying formating :");
    String strDateOutput = changeFormat.format(temp);
    System.out.println(strDateOutput);

}

}

Working example screen

How to refresh a page with jQuery by passing a parameter to URL

var singleText = "single";
var s = window.location.search;

if (s.indexOf(singleText) == -1) {
    window.location.href += (s.substring(0,1) == "?") ? "&" : "?" + singleText;
}

How to get a .csv file into R?

You can use

df <- read.csv("filename.csv", header=TRUE)

# To loop each column
for (i in 1:ncol(df))
    {
    dosomething(df[,i])
    }
# To loop each row
for (i in 1:nrow(df))
    {
    dosomething(df[i,])
    }

Also, you may want to have a look to the apply function (type ?apply or help(apply))if you want to use the same function on each row/column

Java: Detect duplicates in ArrayList?

I needed to do a similar operation for a Stream, but couldn't find a good example. Here's what I came up with.

public static <T> boolean areUnique(final Stream<T> stream) {
    final Set<T> seen = new HashSet<>();
    return stream.allMatch(seen::add);
}

This has the advantage of short-circuiting when duplicates are found early rather than having to process the whole stream and isn't much more complicated than just putting everything in a Set and checking the size. So this case would roughly be:

List<T> list = ...
boolean allDistinct = areUnique(list.stream());

Simple If/Else Razor Syntax

To get rid of the if/else awkwardness you could use a using block:

@{
    var count = 0;
    foreach (var item in Model)
    {
        using(Html.TableRow(new { @class = (count++ % 2 == 0) ? "alt-row" : "" }))
        {
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.Truncate(item.Details, 75)
            </td>
            <td>
                <img src="@Url.Content("~/Content/Images/Projects/")@item.Images.Where(i => i.IsMain == true).Select(i => i.Name).Single()" 
                    alt="@item.Images.Where(i => i.IsMain == true).Select(i => i.AltText).Single()" class="thumb" />
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.ProjectId }) |
                @Html.ActionLink("Details", "Details", new { id = item.ProjectId }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.ProjectId })
            </td>
        }
    }
}

Reusable element that make it easier to add attributes:

//Block is take from http://www.codeducky.org/razor-trick-using-block/
public class TableRow : Block
{
    private object _htmlAttributes;
    private TagBuilder _tr;

    public TableRow(HtmlHelper htmlHelper, object htmlAttributes) : base(htmlHelper)
    {
        _htmlAttributes = htmlAttributes;
    }

    public override void BeginBlock()
    {
        _tr = new TagBuilder("tr");
        _tr.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(_htmlAttributes));
        this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.StartTag));
    }

    protected override void EndBlock()
    {
        this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.EndTag));
    }
}

Helper method to make razor syntax clearer:

public static TableRow TableRow(this HtmlHelper self, object htmlAttributes)
{
    var tableRow = new TableRow(self, htmlAttributes);
    tableRow.BeginBlock();
    return tableRow;
}

How to check a radio button with jQuery?

I use this code:

I'm sorry for English.

_x000D_
_x000D_
var $j = jQuery.noConflict();

$j(function() {
    // add handler
    $j('#radio-1, #radio-2').click(function(){

        // find all checked and cancel checked
        $j('input:radio:checked').prop('checked', false);

        // this radio add cheked
        $j(this).prop('checked', true);
    });
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="section">
  <legend>Radio buttons</legend>
  <label>
    <input type="radio" id="radio-1" checked>
    Option one is this and that&mdash;be sure to include why it's great
  </label>
  <br>
  <label>
    <input type="radio" id="radio-2">
    Option two can be something else
  </label>
</fieldset>
_x000D_
_x000D_
_x000D_

How to read a Parquet file into Pandas DataFrame?

Update: since the time I answered this there has been a lot of work on this look at Apache Arrow for a better read and write of parquet. Also: http://wesmckinney.com/blog/python-parquet-multithreading/

There is a python parquet reader that works relatively well: https://github.com/jcrobak/parquet-python

It will create python objects and then you will have to move them to a Pandas DataFrame so the process will be slower than pd.read_csv for example.

Magento How to debug blank white screen

I was also facing this error. The error has been fixed by changing content of core function getRowUrl in app\code\core\Mage\Adminhtml\Block\Widget\Grid.php The core function is :

public function getRowUrl($item) 
{ 
$res = parent::getRowUrl($item); 
return ($res ? $res : ‘#’); 
}

Replaced with :

public function getRowUrl($item) 
{ 
return $this->getUrl(’*/*/edit’, array(’id’ => $item->getId())); 
}

For more detail : http://bit.ly/iTKcer

Enjoy!!!!!!!!!!!!!

Passing parameter using onclick or a click binding with KnockoutJS

I know this is an old question, but here is my contribution. Instead of all these tricks, you can just simply wrap a function inside another function. Like I have done here:

<div data-bind="click: function(){ f('hello parameter'); }">Click me once</div>
<div data-bind="click: function(){ f('no no parameter'); }">Click me twice</div>

var VM = function(){
   this.f = function(param){
     console.log(param);
   }
}
ko.applyBindings(new VM());

And here is the fiddle

How to render an ASP.NET MVC view as a string?

Additional tip for ASP NET CORE:

Interface:

public interface IViewRenderer
{
  Task<string> RenderAsync<TModel>(Controller controller, string name, TModel model);
}

Implementation:

public class ViewRenderer : IViewRenderer
{
  private readonly IRazorViewEngine viewEngine;

  public ViewRenderer(IRazorViewEngine viewEngine) => this.viewEngine = viewEngine;

  public async Task<string> RenderAsync<TModel>(Controller controller, string name, TModel model)
  {
    ViewEngineResult viewEngineResult = this.viewEngine.FindView(controller.ControllerContext, name, false);

    if (!viewEngineResult.Success)
    {
      throw new InvalidOperationException(string.Format("Could not find view: {0}", name));
    }

    IView view = viewEngineResult.View;
    controller.ViewData.Model = model;

    await using var writer = new StringWriter();
    var viewContext = new ViewContext(
       controller.ControllerContext,
       view,
       controller.ViewData,
       controller.TempData,
       writer,
       new HtmlHelperOptions());

       await view.RenderAsync(viewContext);

       return writer.ToString();
  }
}

Registration in Startup.cs

...
 services.AddSingleton<IViewRenderer, ViewRenderer>();
...

And usage in controller:

public MyController: Controller
{
  private readonly IViewRenderer renderer;
  public MyController(IViewRendere renderer) => this.renderer = renderer;
  public async Task<IActionResult> MyViewTest
  {
    var view = await this.renderer.RenderAsync(this, "MyView", model);
    return new OkObjectResult(view);
  }
}

Where can I get Google developer key

Go to https://code.google.com/p/google-api-php-client/wiki/OAuth2

Scroll down to where it says 'Visit the Google API Console to generate your developer key, OAuth2 client id, OAuth2 client secret, and register your OAuth2 redirect uri. Copy their values since your will need to input them in your application.'

Click on the 'Google API Console' link.

When it pops up and says 'Welcome to the new Google Developers Console! Prefer the old console? Go back | Dismiss' Click on 'GO BACK'

What is the proper way to re-throw an exception in C#?

The first is better. If you try to debug the second and look at the call stack you won't see where the original exception came from. There are tricks to keep the call-stack intact (try search, it's been answered before) if you really need to rethrow.

Can I clear cell contents without changing styling?

You should use the ClearContents method if you want to clear the content but preserve the formatting.

Worksheets("Sheet1").Range("A1:G37").ClearContents

Inserting code in this LaTeX document with indentation

You could also use the verbatim environment

\begin{verbatim}
your
code
example
\end{verbatim}

Difference between Groovy Binary and Source release?

The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.

Reverse order of foreach list items

If your array is populated through an SQL Query consider reversing the result in MySQL, ie :

SELECT * FROM model_input order by creation_date desc

How do I test for an empty JavaScript object?

You can define you own object prototype, just before its usage or at the beginning of your code.

The definition should look like this:

_x000D_
_x000D_
Object.prototype.hasOwnProperties = function()_x000D_
{ _x000D_
  for (var k in this)_x000D_
  { _x000D_
    if ( this.hasOwnProperty(k) )_x000D_
    { _x000D_
      return true;_x000D_
    } _x000D_
  }_x000D_
  return false;_x000D_
}
_x000D_
_x000D_
_x000D_

Here is a usage example:

_x000D_
_x000D_
var a = {};_x000D_
_x000D_
while ( a.status !== "finished" )_x000D_
{  _x000D_
  if ( status === "processing" )_x000D_
  {_x000D_
    a.status = "finished";  _x000D_
  }_x000D_
  _x000D_
  if ( status === "starting" )_x000D_
  {_x000D_
    a.status = "processing";  _x000D_
  }_x000D_
  _x000D_
  if ( !a.hasOwnProperties() )_x000D_
  {_x000D_
    a.status = "starting";_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Enjoy! :-)

How to run a specific Android app using Terminal?

I used all the above answers and it was giving me errors so I tried

adb shell monkey -p com.yourpackage.name -c android.intent.category.LAUNCHER 1

and it worked. One advantage is you dont have to specify your launcher activity if you use this command.

Getting data-* attribute for onclick event for an html element

You can achieve this $(identifier).data('id') using jquery,

    <script type="text/javascript">

        function goDoSomething(identifier){     
            alert("data-id:"+$(identifier).data('id')+", data-option:"+$(identifier).data('option'));               
        }

    </script>

    <a id="option1" 
       data-id="10" 
       data-option="21" 
       href="#" 
       onclick="goDoSomething(this);">
           Click to do something
    </a>

javascript : You can use getAttribute("attributename") if want to use javascript tag,

    <script type="text/javascript">

        function goDoSomething(d){
            alert(d.getAttribute("data-id"));
        }

    </script>

    <a id="option1" 
       data-id="10" 
       data-option="21" 
       href="#" 
       onclick="goDoSomething(this);">
           Click to do something
    </a>

Or:

    <script type="text/javascript">

        function goDoSomething(data_id, data_option){       

            alert("data-id:"+data_id+", data-option:"+data_option);
        }

    </script>

    <a id="option1" 
       data-id="10" 
       data-option="21" 
       href="#" 
       onclick="goDoSomething(this.getAttribute('data-id'), this.getAttribute('data-option'));">
           Click to do something
    </a>

How to upsert (update or insert) in SQL Server 2005

You could do this with an INSTEAD OF INSERT trigger on the table, that checks for the existance of the row and then updates/inserts depending on whether it exists already. There is an example of how to do this for SQL Server 2000+ on MSDN here:

CREATE TRIGGER IO_Trig_INS_Employee ON Employee
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
-- Check for duplicate Person. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT P.SSN
      FROM Person P, inserted I
      WHERE P.SSN = I.SSN))
   INSERT INTO Person
      SELECT SSN,Name,Address,Birthdate
      FROM inserted
ELSE
-- Log attempt to insert duplicate Person row in PersonDuplicates table.
   INSERT INTO PersonDuplicates
      SELECT SSN,Name,Address,Birthdate,SUSER_SNAME(),GETDATE()
      FROM inserted
-- Check for duplicate Employee. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT E.SSN
      FROM EmployeeTable E, inserted
      WHERE E.SSN = inserted.SSN))
   INSERT INTO EmployeeTable
      SELECT EmployeeID,SSN, Department, Salary
      FROM inserted
ELSE
--If duplicate, change to UPDATE so that there will not
--be a duplicate key violation error.
   UPDATE EmployeeTable
      SET EmployeeID = I.EmployeeID,
          Department = I.Department,
          Salary = I.Salary
   FROM EmployeeTable E, inserted I
   WHERE E.SSN = I.SSN
END

Search and get a line in Python

If you prefer a one-liner:

matched_lines = [line for line in my_string.split('\n') if "substring" in line]

Switching the order of block elements with CSS

This method worked for me without flexbox:

_x000D_
_x000D_
#blockA,_x000D_
#blockB,_x000D_
#blockC {_x000D_
    border: 1px solid black;_x000D_
    padding: 20px;_x000D_
}_x000D_
_x000D_
_x000D_
.reverseOrder,_x000D_
#blockA,_x000D_
#blockB,_x000D_
#blockC {_x000D_
    -webkit-transform: rotate(180deg);_x000D_
       -moz-transform: rotate(180deg);_x000D_
        -ms-transform: rotate(180deg);_x000D_
         -o-transform: rotate(180deg);_x000D_
            transform: rotate(180deg);_x000D_
}
_x000D_
<div class="reverseOrder">_x000D_
    <div id="blockA">Block A</div>_x000D_
    <div id="blockB">Block B</div>_x000D_
    <div id="blockC">Block C</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Regex to remove letters, symbols except numbers

Simple:

var removedText = self.val().replace(/[^0-9]+/, '');

^ - means NOT

How to display databases in Oracle 11g using SQL*Plus

Oracle does not have a simple database model like MySQL or MS SQL Server. I find the closest thing is to query the tablespaces and the corresponding users within them.

For example, I have a DEV_DB tablespace with all my actual 'databases' within them:

SQL> SELECT TABLESPACE_NAME FROM USER_TABLESPACES;

Resulting in:

SYSTEM
SYSAUX
UNDOTBS1
TEMP
USERS
EXAMPLE
DEV_DB

It is also possible to query the users in all tablespaces:

SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS;

Or within a specific tablespace (using my DEV_DB tablespace as an example):

SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS where DEFAULT_TABLESPACE = 'DEV_DB';

ROLES DEV_DB
DATAWARE DEV_DB
DATAMART DEV_DB
STAGING DEV_DB

How to keep the header static, always on top while scrolling?

_x000D_
_x000D_
.header {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 88px;_x000D_
  z-index: 10;_x000D_
  background: #eeeeee;_x000D_
  -webkit-box-shadow: 0 7px 8px rgba(0, 0, 0, 0.12);_x000D_
  -moz-box-shadow: 0 7px 8px rgba(0, 0, 0, 0.12);_x000D_
  box-shadow: 0 7px 8px rgba(0, 0, 0, 0.12);_x000D_
}_x000D_
_x000D_
.header__content-text {_x000D_
  text-align: center;_x000D_
  padding: 15px 20px;_x000D_
}_x000D_
_x000D_
.page__content-container {_x000D_
  margin: 100px auto;_x000D_
  width: 975px;_x000D_
  padding: 30px;_x000D_
}
_x000D_
<div class="header">_x000D_
  <h1 class="header__content-text">_x000D_
    Header content will come here_x000D_
  </h1>_x000D_
</div>_x000D_
<div class="page__content-container">_x000D_
  <div style="height:600px;">_x000D_
    <a href="http://imgur.com/k9hz3">_x000D_
      <img src="http://i.imgur.com/k9hz3.jpg" title="Hosted by imgur.com" alt="" />_x000D_
    </a>_x000D_
  </div>_x000D_
  <div style="height:600px;">_x000D_
    <a href="http://imgur.com/TXuFQ">_x000D_
      <img src="http://i.imgur.com/TXuFQ.jpg" title="Hosted by imgur.com" alt="" />_x000D_
    </a>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

git: can't push (unpacker error) related to permission issues

I was having trouble with this too, thinking my remote gitolite-admin was corrupted or something wrong.

My setup is Mac OS X (10.6.6) laptop with remote Ubuntu 10 server with gitolite.

It turned out that the problem was with my local checkout of gitolite-admin.

Despite the "unpack failed" error, it turned out the the problem was local.

I figured this out by checking it out again as gitolite-admin2, making a change, and the pushing.

Voila! It worked!

PHP Sort a multidimensional array by element containing date

For 'd/m/Y' dates:

usort($array, function ($a, $b, $i = 'datetime') { 
    $t1 = strtotime(str_replace('/', '-', $a[$i]));
    $t2 = strtotime(str_replace('/', '-', $b[$i]));

    return $t1 > $t2;
});

where $i is the array index

How to pass a null variable to a SQL Stored Procedure from C#.net code

SqlParameters[1] = new SqlParameter("Date1", SqlDbType.SqlDateTime);
SqlParameters[1].Value = DBNull.Value;
SqlParameters[1].Direction = ParameterDirection.Input;

...then copy for the second.

How can I set a dynamic model name in AngularJS?

http://jsfiddle.net/DrQ77/

You can simply put javascript expression in ng-model.

Is it ok to run docker from inside docker?

Yes, we can run docker in docker, we'll need to attach the unix sockeet "/var/run/docker.sock" on which the docker daemon listens by default as volume to the parent docker using "-v /var/run/docker.sock:/var/run/docker.sock". Sometimes, permissions issues may arise for docker daemon socket for which you can write "sudo chmod 757 /var/run/docker.sock".

And also it would require to run the docker in privileged mode, so the commands would be:

sudo chmod 757 /var/run/docker.sock

docker run --privileged=true -v /var/run/docker.sock:/var/run/docker.sock -it ...

How is the default max Java heap size determined?

Finally!

As of Java 8u191 you now have the options:

-XX:InitialRAMPercentage
-XX:MaxRAMPercentage
-XX:MinRAMPercentage

that can be used to size the heap as a percentage of the usable physical RAM. (which is same as the RAM installed less what the kernel uses).

See Release Notes for Java8 u191 for more information. Note that the options are mentioned under a Docker heading but in fact they apply whether you are in Docker environment or in a traditional environment.

The default value for MaxRAMPercentage is 25%. This is extremely conservative.

My own rule: If your host is more or less dedicated to running the given java application, then you can without problems increase dramatically. If you are on Linux, only running standard daemons and have installed RAM from somewhere around 1 Gb and up then I wouldn't hesitate to use 75% for the JVM's heap. Again, remember that this is 75% of the RAM available, not the RAM installed. What is left is the other user land processes that may be running on the host and the other types of memory that the JVM needs (eg for stack). All together, this will typically fit nicely in the 25% that is left. Obviously, with even more installed RAM the 75% is a safer and safer bet. (I wish the JDK folks had implemented an option where you could specify a ladder)

Setting the MaxRAMPercentage option look like this:

java -XX:MaxRAMPercentage=75.0  ....

Note that these percentage values are of 'double' type and therefore you must specify them with a decimal dot. You get a somewhat odd error if you use "75" instead of "75.0".

python time + timedelta equivalent

Workaround:

t = time()
t2 = time(t.hour+1, t.minute, t.second, t.microsecond)

You can also omit the microseconds, if you don't need that much precision.

Batch file to delete folders older than 10 days in Windows 7

If you want using it with parameter (ie. delete all subdirs under the given directory), then put this two lines into a *.bat or *.cmd file:

@echo off
for /f "delims=" %%d in ('dir %1 /s /b /ad ^| sort /r') do rd "%%d" 2>nul && echo rmdir %%d

and add script-path to your PATH environment variable. In this case you can call your batch file from any location (I suppose UNC path should work, too).

Eg.:

YourBatchFileName c:\temp

(you may use quotation marks if needed)

will remove all empty subdirs under c:\temp folder

YourBatchFileName

will remove all empty subdirs under the current directory.

Java unsupported major minor version 52.0

Your code was compiled with Java Version 1.8 while it is being executed with Java Version 1.7 or below.

In your case it seems that two different Java installations are used, the newer to compile and the older to execute your code.

Try recompiling your code with Java 1.7 or upgrade your Java Plugin.

Javascript/DOM: How to remove all events of a DOM object?

May be the browser will do it for you if you do something like:

Copy the div and its attributes and insert it before the old one, then move the content from the old to the new and delete the old?

What are the lengths of Location Coordinates, latitude and longitude?

The ideal datatype for storing Lat Long values in SQL Server is decimal(9,6)

As others have said, this is at approximately 10cm precision, whilst only using 5 bytes of storage.

e.g. CAST(123.456789 as decimal(9,6)) as [LatOrLong]

AngularJS: factory $http.get JSON file

++ This worked for me. It's vanilla javascirpt and good for use cases such as de-cluttering when testing with ngMocks library:

<!-- specRunner.html - keep this at the top of your <script> asset loading so that it is available readily -->
<!--  Frienly tip - have all JSON files in a json-data folder for keeping things organized-->
<script src="json-data/findByIdResults.js" charset="utf-8"></script>
<script src="json-data/movieResults.js" charset="utf-8"></script>

This is your javascript file that contains the JSON data

// json-data/JSONFindByIdResults.js
var JSONFindByIdResults = {
     "Title": "Star Wars",
     "Year": "1983",
     "Rated": "N/A",
     "Released": "01 May 1983",
     "Runtime": "N/A",
     "Genre": "Action, Adventure, Sci-Fi",
     "Director": "N/A",
     "Writer": "N/A",
     "Actors": "Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones",
     "Plot": "N/A",
     "Language": "English",
     "Country": "USA",
     "Awards": "N/A",
     "Poster": "N/A",
     "Metascore": "N/A",
     "imdbRating": "7.9",
     "imdbVotes": "342",
     "imdbID": "tt0251413",
     "Type": "game",
     "Response": "True"
};

Finally, work with the JSON data anywhere in your code

// working with JSON data in code
var findByIdResults = window.JSONFindByIdResults;

Note:- This is great for testing and even karma.conf.js accepts these files for running tests as seen below. Also, I recommend this only for de-cluttering data and testing/development environment.

// extract from karma.conf.js
files: [
     'json-data/JSONSearchResultHardcodedData.js',
     'json-data/JSONFindByIdResults.js'
     ...
]

Hope this helps.

++ Built on top of this answer https://stackoverflow.com/a/24378510/4742733

UPDATE

An easier way that worked for me is just include a function at the bottom of the code returning whatever JSON.

// within test code
let movies = getMovieSearchJSON();
.....
...
...
....
// way down below in the code
function getMovieSearchJSON() {
      return {
         "Title": "Bri Squared",
         "Year": "2011",
         "Rated": "N/A",
         "Released": "N/A",
         "Runtime": "N/A",
         "Genre": "Comedy",
         "Director": "Joy Gohring",
         "Writer": "Briana Lane",
         "Actors": "Brianne Davis, Briana Lane, Jorge Garcia, Gabriel Tigerman",
         "Plot": "N/A",
         "Language": "English",
         "Country": "USA",
         "Awards": "N/A",
         "Poster": "http://ia.media-imdb.com/images/M/MV5BMjEzNDUxMDI4OV5BMl5BanBnXkFtZTcwMjE2MzczNQ@@._V1_SX300.jpg",
         "Metascore": "N/A",
         "imdbRating": "8.2",
         "imdbVotes": "5",
         "imdbID": "tt1937109",
         "Type": "movie",
         "Response": "True"
   }
}

Node.js EACCES error when listening on most ports

My error got resolved just by changing port number in server.js Specially in this line

const port = process.env.PORT || 8085;

I changed my port number to 8085 from 8080.

Hope it helps.

How do I create a basic UIButton programmatically?

Objective-C

UIButton *but= [UIButton buttonWithType:UIButtonTypeRoundedRect];
[but addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
 [but setFrame:CGRectMake(52, 252, 215, 40)];
[but setTitle:@"Login" forState:UIControlStateNormal];
[but setExclusiveTouch:YES];

 // if you like to add backgroundImage else no need
   [but setbackgroundImage:[UIImage imageNamed:@"XXX.png"] forState:UIControlStateNormal];

[self.view addSubview:but];

-(void) buttonClicked:(UIButton*)sender
 {
NSLog(@"you clicked on button %@", sender.tag);
 }

Swift

    let myButton = UIButton() // if you want to set the type use like UIButton(type: .RoundedRect) or UIButton(type: .Custom)
    myButton.setTitle("Hai Touch Me", forState: .Normal)
    myButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
    myButton.frame = CGRectMake(15, 50, 300, 500)
    myButton.addTarget(self, action: "pressedAction:", forControlEvents: .TouchUpInside)

    self.view.addSubview( myButton)


func pressedAction(sender: UIButton!) {
   // do your stuff here 
  NSLog("you clicked on button %@", sender.tag)
}

Swift3 and above

  let myButton = UIButton() // if you want to set the type use like UIButton(type: .RoundedRect) or UIButton(type: .Custom)
    myButton.setTitle("Hi, Click me", for: .normal)
    myButton.setTitleColor(UIColor.blue, for: .normal)
    myButton.frame = CGRect(x: 15, y: 50, width: 300, height: 500)

    myButton.addTarget(self, action: #selector(pressedAction(_:)), for: .touchUpInside)
    self.view.addSubview( myButton)



func pressedAction(_ sender: UIButton) {
   // do your stuff here 
  print("you clicked on button \(sender.tag)")
}

SwiftUI

for example you get the step by step implemntation from SwiftUI Developer portal

import SwiftUI

struct ContentView : View {
    var body: some View {
        VStack {

            Text("Target Color Black")
             Button(action: { 
                 /* handle button action here */ })
            {
         Text("your Button Name")
          .color(.white)
                        .padding(10)
                        .background(Color.blue)
                        .cornerRadius(5)
                        .shadow(radius: 5)
                        .clipShape(RoundedRectangle(cornerRadius: 5))
     }


        }
    }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif

Installing Git on Eclipse

Try with this link: http://download.eclipse.org/egit/github/updates

1)Go to Help-> Install new Software

2)Click on Add...

3)Name: eGit Location:http://download.eclipse.org/egit/github/updates

4)Click on OK

5)Accept the licence.

You are good to go

Cannot drop database because it is currently in use

Using MS SQL Server 2008, in DELETE dialog with Close connection options, this is the generated script, I guess it is the best:

EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'YOUR_DATABASE_NAME'
GO
USE [master]
GO
ALTER DATABASE [YOUR_DATABASE_NAME] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
/****** Object:  Database [YOUR_DATABASE_NAME]    Script Date: 01/08/2014 21:36:29 ******/
DROP DATABASE [YOUR_DATABASE_NAME]
GO

Detecting which UIButton was pressed in a UITableView

Though I like the tag way... if you don't want to use tags for whatever reason, you could create a member NSArray of premade buttons:

NSArray* buttons ;

then create those buttons before rendering the tableView and push them into the array.

Then inside of the tableView:cellForRowAtIndexPath: function you can do:

UIButton* button = [buttons objectAtIndex:[indexPath row] ] ;
[cell.contentView addSubview:button];

Then in the buttonPressedAction: function, you can do

- (void)buttonPressedAction:(id)sender {
   UIButton* button = (UIButton*)sender ;
   int row = [buttons indexOfObject:button] ;
   // Do magic
}

Two models in one view in ASP MVC 3

Beside of one view model in asp.net you can also make multiple partial views and assign different model view to every view, for example:

   @{
        Layout = null;
    }

    @model Person;

    <input type="text" asp-for="PersonID" />
    <input type="text" asp-for="PersonName" />

then another partial view Model for order model

    @{
        Layout = null;
     }

    @model Order;

    <input type="text" asp-for="OrderID" />
    <input type="text" asp-for="TotalSum" />

then in your main view load both partial view by

<partial name="PersonPartialView" />
<partial name="OrderPartialView" />

Is an empty href valid?

Indeed, you can leave it empty (W3 validator doesn't complain).

Taking the idea one step further: leave out the ="". The advantage of this is that the link isn't treated as an anchor to the current page.

<a href>sth</a>

Ruby send JSON request

This works on ruby 2.4 HTTPS Post with JSON object and the response body written out.

require 'net/http' #net/https does not have to be required anymore
require 'json'
require 'uri'

uri = URI('https://your.secure-url.com')
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
  request = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
  request.body = {parameter: 'value'}.to_json
  response = http.request request # Net::HTTPResponse object
  puts "response #{response.body}"
end

Correct way to work with vector of arrays

Use:

vector<vector<float>> vecArray; //both dimensions are open!

calling parent class method from child class object in java

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.

public class PolyTest{
    public static void main(String args[]){
        new Child().foo();
    }

}
class Parent{
    public void foo(){
        System.out.println("I'm the parent.");
    }
}

class Child extends Parent{
    @Override
    public void foo(){
        //super.foo();
        System.out.println("I'm the child.");
    }
}

This would print:

I'm the child.

Uncomment the commented line and it would print:

I'm the parent.

I'm the child.

You should look for the concept of Polymorphism.

How to link external javascript file onclick of button

You can load all your scripts in the head tag, and whatever your script is doing in function braces. But make sure you change the scope of the variables if you are using those variables outside the script.

How can I open a popup window with a fixed size using the HREF tag?

Since many browsers block popups by default and popups are really ugly, I recommend using lightbox or thickbox.

They are prettier and are not popups. They are extra HTML markups that are appended to your document's body with the appropriate CSS content.

http://jquery.com/demo/thickbox/

Call Class Method From Another Class

In Python function are first class citezens, so you can just assign it to a property like any other value. Here we are assigning the method of A's hello to a property on B. After __init__, hello will be attached to B as self.hello, which is actually a reference to A's hello:

class A:
    def hello(self, msg):
        print(f"Hello {msg}")
    
class B:
    hello = A.hello

print(A.hello)
print(B.hello)

b = B()
b.hello("good looking!")

Prints:

<function A.hello at 0x7fcce55b9e50>
<function A.hello at 0x7fcce55b9e50>
Hello good looking!

Position one element relative to another in CSS

position: absolute will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static.

Have your four divs nested inside the target div, give the target div position: relative, and use position: absolute on the others.

Structure your HTML similar to this:

<div id="container">
  <div class="top left"></div>
  <div class="top right"></div>
  <div class="bottom left"></div>
  <div class="bottom right"></div>
</div>

And this CSS should work:

#container {
  position: relative;
}

#container > * {
  position: absolute;
}

.left {
  left: 0;
}

.right {
  right: 0;
}

.top {
  top: 0;
}

.bottom {
  bottom: 0;
}

...

What is the difference between window, screen, and document in Javascript?

Well, the window is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.

What about the document object then? The document object is your html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc. What does this really mean? That means if you want to access a property for the window it is window.property, if it is document it is window.document.property which is also available in short as document.property.

dom

That seems simple enough. But what happens once an IFRAME is introduced?

iframe

How do I get the value of a registry key and ONLY the value using powershell

NONE of these answers work for situations where the value name contains spaces, dots, or other characters that are reserved in PowerShell. In that case you have to wrap the name in double quotes as per http://blog.danskingdom.com/accessing-powershell-variables-with-periods-in-their-name/ - for example:

PS> Get-ItemProperty Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7

14.0         : C:\Program Files (x86)\Microsoft Visual Studio 14.0\
12.0         : C:\Program Files (x86)\Microsoft Visual Studio 12.0\
11.0         : C:\Program Files (x86)\Microsoft Visual Studio 11.0\
15.0         : C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\V
               S7
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS
PSChildName  : VS7
PSProvider   : Microsoft.PowerShell.Core\Registry

If you want to access any of the 14.0, 12.0, 11.0, 15.0 values, the solution from the accepted answer will not work - you will get no output:

PS> (Get-ItemProperty Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7 -Name 15.0).15.0
PS>

What does work is quoting the value name, which you should probably be doing anyway for safety:

PS> (Get-ItemProperty "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7" -Name "15.0")."15.0"
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
PS> 

Thus, the accepted answer should be modified as such:

PS> $key = "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7"
PS> $value = "15.0"
PS> (Get-ItemProperty -Path $key -Name $value).$value
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
PS> 

This works in PowerShell 2.0 through 5.0 (although you should probably be using Get-ItemPropertyValue in v5).

The best node module for XML parsing

This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.

So, which XML parsing module to pick?

Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.

Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.

Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692

Android - Best and safe way to stop thread

The thing is you need to check whether the thread is running or not !?

Field:

private boolean runningThread = false;

In the thread:

new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep((long) Math.floor(speed));
                        if (!runningThread) {
                            return;
                        }
                        yourWork();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

If you want to stop the thread you should make the below field

private boolean runningThread = false;

C++ equivalent of StringBuffer/StringBuilder?

I wanted to add something new because of the following:

At a first attemp I failed to beat

std::ostringstream 's operator<<

efficiency, but with more attemps I was able to make a StringBuilder that is faster in some cases.

Everytime I append a string I just store a reference to it somewhere and increase the counter of the total size.

The real way I finally implemented it (Horror!) is to use a opaque buffer(std::vector < char > ):

  • 1 byte header (2 bits to tell if following data is :moved string, string or byte[])
  • 6 bits to tell lenght of byte[]

for byte [ ]

  • I store directly bytes of short strings (for sequential memory access)

for moved strings (strings appended with std::move)

  • The pointer to a std::string object (we have ownership)
  • set a flag in the class if there are unused reserved bytes there

for strings

  • The pointer to a std::string object (no ownership)

There's also one small optimization, if last inserted string was mov'd in, it checks for free reserved but unused bytes and store further bytes in there instead of using the opaque buffer (this is to save some memory, it actually make it slightly slower, maybe depend also on the CPU, and it is rare to see strings with extra reserved space anyway)

This was finally slightly faster than std::ostringstream but it has few downsides:

  • I assumed fixed lenght char types (so 1,2 or 4 bytes, not good for UTF8), I'm not saying it will not work for UTF8, Just I don't checked it for laziness.
  • I used bad coding practise (opaque buffer, easy to make it not portable, I believe mine is portable by the way)
  • Lacks all features of ostringstream
  • If some referenced string is deleted before mergin all the strings: undefined behaviour.

conclusion? use std::ostringstream

It already fix the biggest bottleneck while ganing few % points in speed with mine implementation is not worth the downsides.

DbEntityValidationException - How can I easily tell what caused the error?

To view the EntityValidationErrors collection, add the following Watch expression to the Watch window.

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

I'm using visual studio 2013

How to delete images from a private docker registry?

The current v2 registry now supports deleting via DELETE /v2/<name>/manifests/<reference>

See: https://github.com/docker/distribution/blob/master/docs/spec/api.md#deleting-an-image

Working usage: https://github.com/byrnedo/docker-reg-tool

Edit: The manifest <reference> above can be retrieved from requesting to

GET /v2/<name>/manifests/<tag>

and checking the Docker-Content-Digest header in the response.

Edit 2: You may have to run your registry with the following env set:

REGISTRY_STORAGE_DELETE_ENABLED="true"

Edit3: You may have to run garbage collection to free this disk space: https://docs.docker.com/registry/garbage-collection/

How to Select Every Row Where Column Value is NOT Distinct

How about

SELECT EmailAddress, CustomerName FROM Customers a
WHERE Exists ( SELECT emailAddress FROM customers c WHERE a.customerName != c.customerName AND a.EmailAddress = c.EmailAddress)

How can I check that JButton is pressed? If the isEnable() is not work?

JButton#isEnabled changes the user interactivity of a component, that is, whether a user is able to interact with it (press it) or not.

When a JButton is pressed, it fires a actionPerformed event.

You are receiving Add button is pressed when you press the confirm button because the add button is enabled. As stated, it has nothing to do with the pressed start of the button.

Based on you code, if you tried to check the "pressed" start of the add button within the confirm button's ActionListener it would always be false, as the button will only be in the pressed state while the add button's ActionListeners are being called.

Based on all this information, I would suggest you might want to consider using a JCheckBox which you can then use JCheckBox#isSelected to determine if it has being checked or not.

Take a closer look at How to Use Buttons for more details

Windows batch script launch program and exit console

Use start notepad.exe.

More info with start /?.

What is Join() in jQuery?

You would probably use your example like this

var newText = "<span>" + $("p").text().split(" ").join("</span> <span>") + "</span>";

This will put span tags around all the words in you paragraphs, turning

<p>Test is a demo.</p>

into

<p><span>Test</span> <span>is</span> <span>a</span> <span>demo.</span></p>

I do not know what the practical use of this could be.

Custom checkbox image android

Copy the btn_check.xml from android-sdk/platforms/android-#/data/res/drawable to your project's drawable folder and change the 'on' and 'off' image states to your custom images.

Then your xml will just need android:button="@drawable/btn_check"

<CheckBox
    android:button="@drawable/btn_check"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true" />

If you want to use different default android icons, you can use android:button="@android:drawable/..."

Using stored procedure output parameters in C#

Before changing stored procedure please check what is the output of your current one. In SQL Server Management run following:

DECLARE @NewId int
EXEC    @return_value = [dbo].[usp_InsertContract]
            N'Gary',
            @NewId OUTPUT
SELECT  @NewId

See what it returns. This may give you some hints of why your out param is not filled.

Palindrome check in Javascript

function myPolidrome(polidrome){
 var string=polidrome.split('').join(',');
 for(var i=0;i<string.length;i++){
    if(string.length==1){
     console.log("is polidrome");
   }else if(string[i]!=string.charAt(string.length-1)){
     console.log("is not polidrome");
     break;
  }else{
     return  myPolidrome(polidrome.substring(1,polidrome.length-1));
  }
  }
  }
myPolidrome("asasdsdsa");

How to use pip with Python 3.x alongside Python 2.x

This worked for me on OS X: (I say this because sometimes is a pain that mac has "its own" version of every open source tool, and you cannot remove it because "its improvements" make it unique for other apple stuff to work, and if you remove it things start falling appart)

I followed the steps provided by @Lennart Regebro to get pip for python 3, nevertheless pip for python 2 was still first on the path, so... what I did is to create a symbolic link to python 3 inside /usr/bin (in deed I did the same to have my 2 pythons running in peace):

ln -s /Library/Frameworks/Python.framework/Versions/3.4/bin/pip /usr/bin/pip3

Notice that I added a 3 at the end, so basically what you have to do is to use pip3 instead of just pip.

The post is old but I hope this helps someone someday. this should theoretically work for any LINUX system.

How to use XMLReader in PHP?

For xml formatted with attributes...

data.xml:

<building_data>
<building address="some address" lat="28.902914" lng="-71.007235" />
<building address="some address" lat="48.892342" lng="-75.0423423" />
<building address="some address" lat="58.929753" lng="-79.1236987" />
</building_data>

php code:

$reader = new XMLReader();

if (!$reader->open("data.xml")) {
    die("Failed to open 'data.xml'");
}

while($reader->read()) {
  if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'building') {
    $address = $reader->getAttribute('address');
    $latitude = $reader->getAttribute('lat');
    $longitude = $reader->getAttribute('lng');
}

$reader->close();

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

Did you try adding

'trace'=>1,

to SoapClient creation parameters and then:

var_dump($client->__getLastRequest());
var_dump($client->__getLastResponse());

to see what is going on?

Button text toggle in jquery

$(".pushme").click(function () {
  var button = $(this);
  button.text(button.text() == "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME")           
});

This ternary operator has an implicit return. If the expression before ? is true it returns "DON'T PUSH ME", else returns "PUSH ME"

This if-else statement:

if (condition) { return A }
else { return B }

has the equivalent ternary expression:

condition ? A : B

sql server convert date to string MM/DD/YYYY

select convert(varchar(10), cast(fmdate as date), 101) from sery

Without cast I was not getting fmdate converted, so fmdate was a string.

How can I pass request headers with jQuery's getJSON() method?

I agree with sunetos that you'll have to use the $.ajax function in order to pass request headers. In order to do that, you'll have to write a function for the beforeSend event handler, which is one of the $.ajax() options. Here's a quick sample on how to do that:

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $.ajax({
          url: 'service.svc/Request',
          type: 'GET',
          dataType: 'json',
          success: function() { alert('hello!'); },
          error: function() { alert('boo!'); },
          beforeSend: setHeader
        });
      });

      function setHeader(xhr) {
        xhr.setRequestHeader('securityCode', 'Foo');
        xhr.setRequestHeader('passkey', 'Bar');
      }
    </script>
  </head>
  <body>
    <h1>Some Text</h1>
  </body>
</html>

If you run the code above and watch the traffic in a tool like Fiddler, you'll see two requests headers passed in:

  • securityCode with a value of Foo
  • passkey with a value of Bar

The setHeader function could also be inline in the $.ajax options, but I wanted to call it out.

Hope this helps!

What are all the differences between src and data-src attributes?

Well the data src attribute is just used for binding data for example ASP.NET ...

W3School src attribute

MSDN datasrc attribute

How to vertically align text with icon font?

to center vertically and horizontally use this:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.

:: Check your local date format
echo %date%

    :: Output is Mon 08/15/2016

:: get day (start index, number of characters)
::         (index starts with zero)
set myday=%DATE:~0,4%
echo %myday%
    :: output is Mon 

:: get month
set mymonth=%DATE:~4,2%
echo %mymonth%
    :: output is 08

:: get date 
set mydate=%DATE:~7,2% 
echo %mydate%
    :: output is 15

:: get year
set myyear=%DATE:~10,4%
echo %myyear%
    :: output is 2016

How do I convert NSMutableArray to NSArray?

NSArray *array = [mutableArray copy];

Copy makes immutable copies. This is quite useful because Apple can make various optimizations. For example sending copy to a immutable array only retains the object and returns self.

If you don't use garbage collection or ARC remember that -copy retains the object.

Why should I use a container div in HTML?

The container div, and sometimes content div, are almost always used to allow for more sophisticated CSS styling. The body tag is special in some ways. Browsers don't treat it like a normal div; its position and dimensions are tied to the browser window.

But a container div is just a div and you can style it with margins and borders. You can give it a fixed width, and you can center it with margin-left: auto; margin-right: auto.

Plus, content, like a copyright notice for example, can go on the outside of the container div, but it can't go on the outside of the body, allowing for content on the outside of a border.

MS Access VBA: Sending an email through Outlook

Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.

Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")

Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing


End Sub

Table fixed header and scrollable body

You can place two div where 1st div (Header) will have transparent scroll bar and 2nd div will be have data with visible/auto scroll bar. Sample has angular code snippet for looping through the data.

Below code worked for me -

<div id="transparentScrollbarDiv" class="container-fluid" style="overflow-y: scroll;">
    <div class="row">
        <div class="col-lg-3 col-xs-3"><strong>{{col1}}</strong></div>
        <div class="col-lg-6 col-xs-6"><strong>{{col2}}</strong></div>
        <div class="col-lg-3 col-xs-3"><strong>{{col3}}</strong></div>
    </div>
</div>
<div class="container-fluid" style="height: 150px; overflow-y: auto">
    <div>
        <div class="row" ng-repeat="row in rows">
            <div class="col-lg-3 col-xs-3">{{row.col1}}</div>
            <div class="col-lg-6 col-xs-6">{{row.col2}}</div>
            <div class="col-lg-3 col-xs-3">{{row.col3}}</div>
        </div>
    </div>
</div>

Additional style to hide header scroll bar -

<style>
        #transparentScrollbarDiv::-webkit-scrollbar {
            width: inherit;
        }

        /* this targets the default scrollbar (compulsory) */

        #transparentScrollbarDiv::-webkit-scrollbar-track {
            background-color: transparent;
        }

        /* the new scrollbar will have a flat appearance with the set background color */

        #transparentScrollbarDiv::-webkit-scrollbar-thumb {
            background-color: transparent;
        }

        /* this will style the thumb, ignoring the track */

        #transparentScrollbarDiv::-webkit-scrollbar-button {
            background-color: transparent;
        }

        /* optionally, you can style the top and the bottom buttons (left and right for horizontal bars) */

        #transparentScrollbarDiv::-webkit-scrollbar-corner {
            background-color: transparent;
        }

        /* if both the vertical and the horizontal bars appear, then perhaps the right bottom corner also needs to be styled */
    </style>

How to empty/destroy a session in rails?

To clear only certain parameters, you can use:

[:param1, :param2, :param3].each { |k| session.delete(k) }

How to convert a Map to List in Java?

a list of what ?

Assuming map is your instance of Map

  • map.values() will return a Collection containing all of the map's values.
  • map.keySet() will return a Set containing all of the map's keys.

How to test if a file is a directory in a batch script?

A very simple way is to check if the child exists.

If a child does not have any child, the exist command will return false.

IF EXIST %1\. (
  echo %1 is a folder
) else (
  echo %1 is a file
)

You may have some false negative if you don't have sufficient access right (I have not tested it).

Nodejs convert string into UTF-8

When you want to change the encoding you always go from one into another. So you might go from Mac Roman to UTF-8 or from ASCII to UTF-8.

It's as important to know the desired output encoding as the current source encoding. For example if you have Mac Roman and you decode it from UTF-16 to UTF-8 you'll just make it garbled.

If you want to know more about encoding this article goes into a lot of details:

What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text

The npm pacakge encoding which uses node-iconv or iconv-lite should allow you to easily specify which source and output encoding you want:

var resultBuffer = encoding.convert(nameString, 'ASCII', 'UTF-8');

Find the smallest positive integer that does not occur in a given sequence

Here is a simple and fast code in PHP.

  • Task Score: 100%
  • Correctness: 100%
  • Performance: 100%
  • Detected time complexity: O(N) or O(N * log(N))
function solution($A) {

    $x = 1;

    sort($A);

    foreach($A as $i){

        if($i <=0) continue;

        if($x < $i) return $x;

        else $x = $i+1; 

    }

    return $x;
}

Performance tests

How can Bash execute a command in a different directory context?

(cd /path/to/your/special/place;/bin/your-special-command ARGS)

Converting JSON data to Java object

Depending on the input JSON format(string/file) create a jSONString. Sample Message class object corresponding to JSON can be obtained as below:

Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);

Change Placeholder Text using jQuery

change placeholder text using jquery

try this

$('#selector').attr("placeholder", "Type placeholder");

How can I tell how many objects I've stored in an S3 bucket?

The easiest way is to use the developer console, for example, if you are on chrome, choose Developer Tools, and you can see following, you can either find and count or do some match, like 280-279 + 1 = 2

...

Download file and automatically save it to folder

Why not just bypass the WebClient's file handling pieces altogether. Perhaps something similar to this:

    private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
    {
        e.Cancel = true;
        WebClient client = new WebClient();

        client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);

        client.DownloadDataAsync(e.Url);
    }

    void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
        string filepath = textBox1.Text;
        File.WriteAllBytes(filepath, e.Result);
        MessageBox.Show("File downloaded");
    }

Ring Buffer in Java

Use a Queue

Queue<String> qe=new LinkedList<String>();

qe.add("a");
qe.add("b");
qe.add("c");
qe.add("d");

System.out.println(qe.poll()); //returns a
System.out.println(qe.poll()); //returns b
System.out.println(qe.poll()); //returns c
System.out.println(qe.poll()); //returns d

There's five simple methods of a Queue

  • element() -- Retrieves, but does not remove, the head of this queue.

  • offer(E o) -- Inserts the specified element into this queue, if
    possible.

  • peek() -- Retrieves, but does not remove, the head of this queue, returning null if this queue is empty.

  • poll() -- Retrieves and removes the head of this queue, or null if this queue is empty.

  • remove() -- Retrieves and removes the head of this queue.

Converting pixels to dp

To convert dp to pixel

public static int dp2px(Resources resource, int dp) {
    return (int) TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        dp,resource.getDisplayMetrics()
    );
}

To convert pixel to dp.

public static float px2dp(Resources resource, float px)  {
    return (float)TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_PX,
        px,
        resource.getDisplayMetrics()
    );
}

where resource is context.getResources().

An object reference is required to access a non-static member

Make your audioSounds and minTime variables as static variables, as you are using them in a static method (playSound).

Marking a method as static prevents the usage of non-static (instance) members in that method.

To understand more , please read this SO QA:

Static keyword in c#

How to set the first option on a select box using jQuery?

This is the most flexible/reusable way to reset all select boxes in your form.

      var $form = $('form') // Replace with your form selector
      $('select', $form).each(function() {
        $(this).val($(this).prop('defaultSelected'));
      });

TypeScript - Append HTML to container element in Angular 2

You could do something like this:

htmlComponent.ts

htmlVariable: string = "<b>Some html.</b>"; //this is html in TypeScript code that you need to display

htmlComponent.html

<div [innerHtml]="htmlVariable"></div> //this is how you display html code from TypeScript in your html

Getting a map() to return a list in Python 3.x

Do this:

list(map(chr,[66,53,0,94]))

In Python 3+, many processes that iterate over iterables return iterators themselves. In most cases, this ends up saving memory, and should make things go faster.

If all you're going to do is iterate over this list eventually, there's no need to even convert it to a list, because you can still iterate over the map object like so:

# Prints "ABCD"
for ch in map(chr,[65,66,67,68]):
    print(ch)

How to run an EXE file in PowerShell with parameters with spaces and quotes

I had the following code working perfect on my laptop:

& $msdeploy `
-source:package="$publishFile" `
-dest:auto,computerName="$server",includeAcls="False",UserName="$username",Password="$password",AuthType="$auth" `
-allowUntrusted  `
-verb:sync  `
-enableRule:DoNotDeleteRule `
-disableLink:AppPoolExtension  `
-disableLink:ContentExtension  `
-disableLink:CertificateExtension  `
-skip:objectName=filePath,absolutePath="^(.*Web\.config|.*Environment\.config)$" `
-setParam:name=`"IIS Web Application Name`",value="$appName"

Then when I tried to run that directly on one server I started getting those errors "Unrecognized argument ...etc.... All arguments must begin with "-". "

After trying all possible workarounds (no success), I found out that Powershell on the server (Windows 2008 R2) was version 3.0, while my laptop has 5.0. (you can use "$PSVersionTable" to see version).

After upgrading Powershell to latest version it started working again.

Add column to dataframe with constant value

Single liner works

df['Name'] = 'abc'

Creates a Name column and sets all rows to abc value

WPF global exception handler

A quick example of code for Application.Dispatcher.UnhandledException:

public App() {
    this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}

void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) {
    string errorMessage = string.Format("An unhandled exception occurred: {0}", e.Exception.Message);
    MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    // OR whatever you want like logging etc. MessageBox it's just example
    // for quick debugging etc.
    e.Handled = true;
}

I added this code in App.xaml.cs

Redirect from an HTML page

JavaScript

<script type="text/javascript">
    window.location.href = "http://example.com";
</script>

Meta tag

<meta http-equiv="refresh" content="0;url=http://example.com">

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

you are confusing the concept of appending and prepending. the following code is prepending:

sys.path.insert(1,'/thePathToYourFolder/')

it places the new information at the beginning (well, second, to be precise) of the search sequence that your interpreter will go through. sys.path.append() puts things at the very end of the search sequence.

it is advisable that you use something like virtualenv instead of manually coding your package directories into the PYTHONPATH everytime. for setting up various ecosystems that separate your site-packages and possible versions of python, read these two blogs:

  1. python ecosystems introduction

  2. bootstrapping python virtual environments

if you do decide to move down the path to environment isolation you would certainly benefit by looking into virtualenvwrapper: http://www.doughellmann.com/docs/virtualenvwrapper/

SQL Server after update trigger

you can call INSERTED, SQL Server uses these tables to capture the data of the modified row before and after the event occurs.I assume in your table the name of the key is Id

I think the following code can help you

CREATE TRIGGER [dbo].[after_update]
ON [dbo].[MYTABLE]
   AFTER UPDATE
AS
BEGIN
    UPDATE dbo.[MYTABLE]
    SET    dbo.[MYTABLE].CHANGED_ON = GETDATE(),
           dbo.[MYTABLE].CHANGED_BY = USER_NAME(USER_ID())
    FROM   INSERTED
    WHERE  INSERTED.Id = dbo.[MYTABLE].[Id]
END

How to directly initialize a HashMap (in a literal way)?

An alternative, using plain Java 7 classes and varargs: create a class HashMapBuilder with this method:

public static HashMap<String, String> build(String... data){
    HashMap<String, String> result = new HashMap<String, String>();

    if(data.length % 2 != 0) 
        throw new IllegalArgumentException("Odd number of arguments");      

    String key = null;
    Integer step = -1;

    for(String value : data){
        step++;
        switch(step % 2){
        case 0: 
            if(value == null)
                throw new IllegalArgumentException("Null key value"); 
            key = value;
            continue;
        case 1:             
            result.put(key, value);
            break;
        }
    }

    return result;
}

Use the method like this:

HashMap<String,String> data = HashMapBuilder.build("key1","value1","key2","value2");

Center text in div?

div {
    height: 256px;
    width: 256px;
    display: table-cell;
    text-align: center;
    line-height: 256px;
}

The trick is to set the line-height equal to the height of the div.

How to put an image in div with CSS?

you can do this:

<div class="picture1">&nbsp;</div>

and put this into your css file:

div.picture1 {
   width:100px; /*width of your image*/
   height:100px; /*height of your image*/
   background-image:url('yourimage.file');
   margin:0; /* If you want no margin */
   padding:0; /*if your want to padding */
}

otherwise, just use them as plain

IntelliJ cannot find any declarations

One of the reason can be that it is not able to detect the pom.xml(or gradle file) and thats why not able to set it as a maven project(or gradle).

You can manually set it up as a maven(or gradle) project by selecting your pom.xml(or gradle file)

How does jQuery work when there are multiple elements with the same ID value?

From the id Selector jQuery page:

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.

Naughty Google. But they don't even close their <html> and <body> tags I hear. The question is though, why Misha's 2nd and 3rd queries return 2 and not 1 as well.

Adjusting HttpWebRequest Connection Timeout in C#

Sorry for tacking on to an old thread, but I think something that was said above may be incorrect/misleading.

From what I can tell .Timeout is NOT the connection time, it is the TOTAL time allowed for the entire life of the HttpWebRequest and response. Proof:

I Set:

.Timeout=5000
.ReadWriteTimeout=32000

The connect and post time for the HttpWebRequest took 26ms

but the subsequent call HttpWebRequest.GetResponse() timed out in 4974ms thus proving that the 5000ms was the time limit for the whole send request/get response set of calls.

I didn't verify if the DNS name resolution was measured as part of the time as this is irrelevant to me since none of this works the way I really need it to work--my intention was to time out quicker when connecting to systems that weren't accepting connections as shown by them failing during the connect phase of the request.

For example: I'm willing to wait 30 seconds on a connection request that has a chance of returning a result, but I only want to burn 10 seconds waiting to send a request to a host that is misbehaving.

unique combinations of values in selected columns in pandas data frame and count

You can groupby on cols 'A' and 'B' and call size and then reset_index and rename the generated column:

In [26]:

df1.groupby(['A','B']).size().reset_index().rename(columns={0:'count'})
Out[26]:
     A    B  count
0   no   no      1
1   no  yes      2
2  yes   no      4
3  yes  yes      3

update

A little explanation, by grouping on the 2 columns, this groups rows where A and B values are the same, we call size which returns the number of unique groups:

In[202]:
df1.groupby(['A','B']).size()

Out[202]: 
A    B  
no   no     1
     yes    2
yes  no     4
     yes    3
dtype: int64

So now to restore the grouped columns, we call reset_index:

In[203]:
df1.groupby(['A','B']).size().reset_index()

Out[203]: 
     A    B  0
0   no   no  1
1   no  yes  2
2  yes   no  4
3  yes  yes  3

This restores the indices but the size aggregation is turned into a generated column 0, so we have to rename this:

In[204]:
df1.groupby(['A','B']).size().reset_index().rename(columns={0:'count'})

Out[204]: 
     A    B  count
0   no   no      1
1   no  yes      2
2  yes   no      4
3  yes  yes      3

groupby does accept the arg as_index which we could have set to False so it doesn't make the grouped columns the index, but this generates a series and you'd still have to restore the indices and so on....:

In[205]:
df1.groupby(['A','B'], as_index=False).size()

Out[205]: 
A    B  
no   no     1
     yes    2
yes  no     4
     yes    3
dtype: int64

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

Building on the excellent answers by rafx and Sina, here is a snippet that only targets Firefox and replaces the default button with a down-caret copied from Bootstrap's icon theme.

Before:

default select

After:

styled select

@-moz-document url-prefix() {
  select.form-control {
    padding-right: 25px;
    background-image: url("data:image/svg+xml,\
      <svg version='1.1' xmlns='http://www.w3.org/2000/svg' width='14px'\
           height='14px' viewBox='0 0 1200 1000' fill='rgb(51,51,51)'>\
        <path d='M1100 411l-198 -199l-353 353l-353 -353l-197 199l551 551z'/>\
      </svg>");
    background-repeat: no-repeat;
    background-position: calc(100% - 7px) 50%;
    -moz-appearance: none;
    appearance: none;
  }
}

(The inline SVG has backslashes and newlines for readability. Remove them if they cause trouble in your asset pipeline.)

Here is the JSFiddle

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

I got this error when I was messing around with string and dictionary.

dict1 = {'taras': 'vaskiv', 'iruna': 'vaskiv'}
str1 = str(dict1)
dict(str1)
*** ValueError: dictionary update sequence element #0 has length 1; 2 is required

So what you actually got to do to get dict from string is:

dic2 = eval(str1)
dic2
{'taras': 'vaskiv', 'iruna': 'vaskiv'}

Or in matter of security we can use literal_eval

from ast import literal_eval

Nested JSON objects - do I have to use arrays for everything?

You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.

use each() wrap within another each() until the last array.

for result.data[0].stuff[0].onetype[0] in jQuery you could do the following:

`

$.each(data.result.data, function(index0, v) {
    $.each(v, function (index1, w) {
        $.each(w, function (index2, x) {
            alert(x.id);
        });
    });

});

`