Programs & Examples On #Quicklaunch

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

As others have pointed out, the only way to change the browser's behavior is to make sure the response either does not contain a 401 status code or if it does, not include the WWW-Authenticate: Basic header. Since changing the status code is not very semantic and undesirable, a good approach is to remove the WWW-Authenticate header. If you can't or don't want to modify your web server application, you can always serve or proxy it through Apache (if you are not using Apache already).

Here is a configuration for Apache to rewrite the response to remove the WWW-Authenticate header IFF the request contains contains the header X-Requested-With: XMLHttpRequest (which is set by default by major Javascript frameworks such as JQuery/AngularJS, etc...) AND the response contains the header WWW-Authenticate: Basic.

Tested on Apache 2.4 (not sure if it works with 2.2). This relies on the mod_headers module being installed. (On Debian/Ubuntu, sudo a2enmod headers and restart Apache)

    <Location />
            # Make sure that if it is an XHR request,
            # we don't send back basic authentication header.
            # This is to prevent the browser from displaying a basic auth login dialog.
            Header unset WWW-Authenticate "expr=req('X-Requested-With') == 'XMLHttpRequest' && resp('WWW-Authenticate') =~ /^Basic/"
    </Location>   

How do I put an image into my picturebox using ImageLocation?

Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

For example, if your .exe is located at:

<project folder>/bin/Debug/app.exe

The image would have to be at:

<project folder>/bin/Image/1.jpg


Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

At this point the image file will be copied when you build the application and you can use

picture.ImageLocation = @"Image\1.jpg"; 

String is immutable. What exactly is the meaning?

String is immutable it means that,the content of the String Object can't be change, once it is created. If you want to modify the content then you can go for StringBuffer/StringBuilder instead of String. StringBuffer and StringBuilder are mutable classes.

An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server

For if you want to insert your values from one table to another through a stored procedure. I used this and this, the latter which is almost like Andomar's answer.

CREATE procedure [dbo].[RealTableMergeFromTemp]
    with execute as owner
AS
BEGIN
BEGIN TRANSACTION RealTableDataMerge
SET XACT_ABORT ON

    DECLARE @columnNameList nvarchar(MAX) =
     STUFF((select ',' + a.name
      from sys.all_columns a
      join sys.tables t on a.object_id = t.object_id 
       where t.object_id = object_id('[dbo].[RealTable]') 
    order by a.column_id
    for xml path ('')
    ),1,1,'')

    DECLARE @SQLCMD nvarchar(MAX) =N'INSERT INTO [dbo].[RealTable] (' + @columnNameList + N') SELECT * FROM [#Temp]'

    SET IDENTITY_INSERT [dbo].[RealTable] ON;
    exec(@sqlcmd)
    SET IDENTITY_INSERT [dbo].[RealTable] OFF

COMMIT TRANSACTION RealTableDataMerge
END

GO

Find difference between timestamps in seconds in PostgreSQL

Try: 

SELECT EXTRACT(EPOCH FROM (timestamp_B - timestamp_A))
FROM TableA

Details here: EXTRACT.

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

form_for but to post to a different action

new syntax

<%= form_for :user, url: custom_user_path, method: :post do |f|%>
<%end%>

How to add months to a date in JavaScript?

I took a look at the datejs and stripped out the code necessary to add months to a date handling edge cases (leap year, shorter months, etc):

Date.isLeapYear = function (year) { 
    return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); 
};

Date.getDaysInMonth = function (year, month) {
    return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};

Date.prototype.isLeapYear = function () { 
    return Date.isLeapYear(this.getFullYear()); 
};

Date.prototype.getDaysInMonth = function () { 
    return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
};

Date.prototype.addMonths = function (value) {
    var n = this.getDate();
    this.setDate(1);
    this.setMonth(this.getMonth() + value);
    this.setDate(Math.min(n, this.getDaysInMonth()));
    return this;
};

This will add "addMonths()" function to any javascript date object that should handle edge cases. Thanks to Coolite Inc!

Use:

var myDate = new Date("01/31/2012");
var result1 = myDate.addMonths(1);

var myDate2 = new Date("01/31/2011");
var result2 = myDate2.addMonths(1);

->> newDate.addMonths -> mydate.addMonths

result1 = "Feb 29 2012"

result2 = "Feb 28 2011"

CSS :selected pseudo class similar to :checked, but for <select> elements

Actually you can only style few CSS properties on :modified option elements. color does not work, background-color either, but you can set a background-image.

You can couple this with gradients to do the trick.

_x000D_
_x000D_
option:hover,_x000D_
option:focus,_x000D_
option:active,_x000D_
option:checked {_x000D_
  background: linear-gradient(#5A2569, #5A2569);_x000D_
}
_x000D_
<select>_x000D_
  <option>A</option>_x000D_
  <option>B</option>_x000D_
  <option>C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Works on gecko/webkit.

"Register" an .exe so you can run it from any command line in Windows

Windows 10, 8.1, 8

Open start menu,

  1. Type Edit environment variables
  2. Open the option Edit the system environment variables
  3. Click Environment variables... button
  4. There you see two boxes, in System Variables box find path variable
  5. Click Edit
  6. a window pops up, click New
  7. Type the Directory path of your .exe or batch file ( Directory means exclude the file name from path)
  8. Click Ok on all open windows and restart your system restart the command prompt.

How to get data by SqlDataReader.GetValue by column name

You can also do this.

//find the index of the CompanyName column
int columnIndex = thisReader.GetOrdinal("CompanyName"); 
//Get the value of the column. Will throw if the value is null.
string companyName = thisReader.GetString(columnIndex);

How do I make Java register a string input with spaces?

This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)

/* AUTHOR: MIKEQ
 * DATE: 04/29/2016
 * DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-) 
 * Added example of error check on salary input.
 * TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2) 
 */

import java.util.Scanner;

public class userInputVersion1 {

    public static void main(String[] args) {

    System.out.println("** Taking in User input **");

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter your name : ");
    String s = input.nextLine(); // getting a String value (full line)
    //String s = input.next(); // getting a String value (issues with spaces in line)

    System.out.println("Please enter your age : ");
    int i = input.nextInt(); // getting an integer

    // version with Fault Tolerance:
    System.out.println("Please enter your salary : ");
    while (!input.hasNextDouble())
    {
        System.out.println("Invalid input\n Type the double-type number:");
        input.next();
    }
    double d = input.nextDouble();    // need to check the data type?

    System.out.printf("\nName %s" +
            "\nAge: %d" +
            "\nSalary: %f\n", s, i, d);

    // close the scanner
    System.out.println("Closing Scanner...");
    input.close();
    System.out.println("Scanner Closed.");      
}
}

How to Kill A Session or Session ID (ASP.NET/C#)

Session.Abandon() this will destroy the data.

Note, this won't necessarily truly remove the session token from a user, and that same session token at a later point might get picked up and created as a new session with the same id because it's deemed to be fair game to be used.

How do I prevent site scraping?

Sue 'em.

Seriously: If you have some money, talk to a good, nice, young lawyer who knows their way around the Internets. You could really be able to do something here. Depending on where the sites are based, you could have a lawyer write up a cease & desist or its equivalent in your country. You may be able to at least scare the bastards.

Document the insertion of your dummy values. Insert dummy values that clearly (but obscurely) point to you. I think this is common practice with phone book companies, and here in Germany, I think there have been several instances when copycats got busted through fake entries they copied 1:1.

It would be a shame if this would drive you into messing up your HTML code, dragging down SEO, validity and other things (even though a templating system that uses a slightly different HTML structure on each request for identical pages might already help a lot against scrapers that always rely on HTML structures and class/ID names to get the content out.)

Cases like this are what copyright laws are good for. Ripping off other people's honest work to make money with is something that you should be able to fight against.

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

This works for me:

TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String uuid = tManager.getDeviceId();

EDIT :

You also need android.permission.READ_PHONE_STATE set in your Manifest. Since Android M, you need to ask this permission at runtime.

See this anwser : https://stackoverflow.com/a/38782876/1339179

How to encrypt and decrypt file in Android?

You could use java-aes-crypto or Facebook's Conceal

java-aes-crypto

Quoting from the repo

A simple Android class for encrypting & decrypting strings, aiming to avoid the classic mistakes that most such classes suffer from.

Facebook's conceal

Quoting from the repo

Conceal provides easy Android APIs for performing fast encryption and authentication of data

How to get the current user in ASP.NET MVC

We can use following code to get the current logged in User in ASP.Net MVC:

var user= System.Web.HttpContext.Current.User.Identity.GetUserName();

Also

var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //will give 'Domain//UserName'

Environment.UserName - Will Display format : 'Username'

Using Exit button to close a winform program

If you only want to Close the form than you can use this.Close(); else if you want the whole application to be closed use Application.Exit();

CSS: background-color only inside the margin

I needed something similar, and came up with using the :before (or :after) pseudoclasses:

#mydiv {
   background-color: #fbb;
   margin-top: 100px;
   position: relative;
}
#mydiv:before {
   content: "";
   background-color: #bfb;
   top: -100px;
   height: 100px;
   width: 100%;
   position: absolute;
}

JSFiddle

SQL multiple columns in IN clause

Ensure you have an index on your firstname and lastname columns and go with 1. This really won't have much of a performance impact at all.

EDIT: After @Dems comment regarding spamming the plan cache ,a better solution might be to create a computed column on the existing table (or a separate view) which contained a concatenated Firstname + Lastname value, thus allowing you to execute a query such as

SELECT City 
FROM User 
WHERE Fullname in (@fullnames)

where @fullnames looks a bit like "'JonDoe', 'JaneDoe'" etc

Angular 6 Material mat-select change method removed

For me (selectionChange) and the suggested (onSelectionChange) didn't work and I'm not using ReactiveForms. What I ended up doing was using the (valueChange) event like:

<mat-select (valueChange)="someFunction()">

And this worked for me

Convert text into number in MySQL query

You can use CAST() to convert from string to int. e.g. SELECT CAST('123' AS INTEGER);

How do I remove objects from an array in Java?

EDIT:

The point with the nulls in the array has been cleared. Sorry for my comments.

Original:

Ehm... the line

array = list.toArray(array);

replaces all gaps in the array where the removed element has been with null. This might be dangerous, because the elements are removed, but the length of the array remains the same!

If you want to avoid this, use a new Array as parameter for toArray(). If you don`t want to use removeAll, a Set would be an alternative:

        String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };

        System.out.println(Arrays.toString(array));

        Set<String> asSet = new HashSet<String>(Arrays.asList(array));
        asSet.remove("a");
        array = asSet.toArray(new String[] {});

        System.out.println(Arrays.toString(array));

Gives:

[a, bc, dc, a, ef]
[dc, ef, bc]

Where as the current accepted answer from Chris Yester Young outputs:

[a, bc, dc, a, ef]
[bc, dc, ef, null, ef]

with the code

    String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };

    System.out.println(Arrays.toString(array));

    List<String> list = new ArrayList<String>(Arrays.asList(array));
    list.removeAll(Arrays.asList("a"));
    array = list.toArray(array);        

    System.out.println(Arrays.toString(array));

without any null values left behind.

Printing 1 to 1000 without loop or conditionals

With plain C:

#include<stdio.h>

/* prints number  i */ 
void print1(int i) {
    printf("%d\n",i);
}

/* prints 10 numbers starting from i */ 
void print10(int i) {
    print1(i);
    print1(i+1);
    print1(i+2);
    print1(i+3);
    print1(i+4);
    print1(i+5);
    print1(i+6);
    print1(i+7);
    print1(i+8);
    print1(i+9);
}

/* prints 100 numbers starting from i */ 
void print100(int i) {
    print10(i);
    print10(i+10);
    print10(i+20);
    print10(i+30);
    print10(i+40);
    print10(i+50);
    print10(i+60);
    print10(i+70);
    print10(i+80);
    print10(i+90);
}

/* prints 1000 numbers starting from i */ 
void print1000(int i) {
    print100(i);
    print100(i+100);
    print100(i+200);
    print100(i+300);
    print100(i+400);
    print100(i+500);
    print100(i+600);
    print100(i+700);
    print100(i+800);
    print100(i+900);
}


int main() {
        print1000(1);
        return 0;
}

Of course, you can implement the same idea for other bases (2: print2 print4 print8 ...) but the number 1000 here suggested base 10. You can also reduce a little the number of lines adding intermediate functions: print2() print10() print20() print100() print200() print1000() and other equivalent alternatives.

How to save as a new file and keep working on the original one in Vim?

After save new file press

Ctrl-6

This is shortcut to alternate file

Trying to add adb to PATH variable OSX

The answer for MAC should be:

  1. Open your bash_profile with the following commands: open ~/.bash_profile

  2. In case base profile file doesn't exist, create a new one with the following command: touch .bash_profile then repeat phase 1.

  3. Add the following line: export PATH=/Users/"YOURUSER"/Library/Android/sdk/platform-tools:$PATH

  4. Restart your bash window and test by typing adb shell

Good luck! :-)

How to set variables in HIVE scripts

You need to use the special hiveconf for variable substitution. e.g.

hive> set CURRENT_DATE='2012-09-16';
hive> select * from foo where day >= ${hiveconf:CURRENT_DATE}

similarly, you could pass on command line:

% hive -hiveconf CURRENT_DATE='2012-09-16' -f test.hql

Note that there are env and system variables as well, so you can reference ${env:USER} for example.

To see all the available variables, from the command line, run

% hive -e 'set;'

or from the hive prompt, run

hive> set;

Update: I've started to use hivevar variables as well, putting them into hql snippets I can include from hive CLI using the source command (or pass as -i option from command line). The benefit here is that the variable can then be used with or without the hivevar prefix, and allow something akin to global vs local use.

So, assume have some setup.hql which sets a tablename variable:

set hivevar:tablename=mytable;

then, I can bring into hive:

hive> source /path/to/setup.hql;

and use in query:

hive> select * from ${tablename}

or

hive> select * from ${hivevar:tablename}

I could also set a "local" tablename, which would affect the use of ${tablename}, but not ${hivevar:tablename}

hive> set tablename=newtable;
hive> select * from ${tablename} -- uses 'newtable'

vs

hive> select * from ${hivevar:tablename} -- still uses the original 'mytable'

Probably doesn't mean too much from the CLI, but can have hql in a file that uses source, but set some of the variables "locally" to use in the rest of the script.

SQL: parse the first, middle and last name from a fullname field

This query is working fine.

SELECT name
    ,Ltrim(SubString(name, 1, Isnull(Nullif(CHARINDEX(' ', name), 0), 1000))) AS FirstName
    ,Ltrim(SUBSTRING(name, CharIndex(' ', name), CASE 
                WHEN (CHARINDEX(' ', name, CHARINDEX(' ', name) + 1) - CHARINDEX(' ', name)) <= 0
                    THEN 0
                ELSE CHARINDEX(' ', name, CHARINDEX(' ', name) + 1) - CHARINDEX(' ', name)
                END)) AS MiddleName
    ,Ltrim(SUBSTRING(name, Isnull(Nullif(CHARINDEX(' ', name, Charindex(' ', name) + 1), 0), CHARINDEX(' ', name)), CASE 
                WHEN Charindex(' ', name) = 0
                    THEN 0
                ELSE LEN(name)
                END)) AS LastName
FROM yourtableName

Git merge develop into feature branch outputs "Already up-to-date" while it's not

You should first pull the changes from the develop branch and only then merge them to your branch:

git checkout develop 
git pull 
git checkout branch-x
git rebase develop

Or, when on branch-x:

git fetch && git rebase origin/develop

I have an alias that saves me a lot of time. Add to your ~/.gitconfig:

[alias]
    fr = "!f() { git fetch && git rebase origin/"$1"; }; f"

Now, all that you have to do is:

git fr develop

Change arrow colors in Bootstraps carousel

To customize the colors for the carousel controls, captions, and indicators using Sass you can include these variables

    $carousel-control-color: 
    $carousel-caption-color: 
    $carousel-indicator-active-bg: 

All ASP.NET Web API controllers return 404

I had the same problem, then I found out that I had duplicate api controller class names in other project and despite the fact that the "routePrefix" and namespace and project name were different but still they returned 404, I changed the class names and it worked.

java howto ArrayList push, pop, shift, and unshift

ArrayList is unique in its naming standards. Here are the equivalencies:

Array.push    -> ArrayList.add(Object o); // Append the list
Array.pop     -> ArrayList.remove(int index); // Remove list[index]
Array.shift   -> ArrayList.remove(0); // Remove first element
Array.unshift -> ArrayList.add(int index, Object o); // Prepend the list

Note that unshift does not remove an element, but instead adds one to the list. Also note that corner-case behaviors are likely to be different between Java and JS, since they each have their own standards.

Jersey Exception : SEVERE: A message body reader for Java class

Try adding:

<dependency>
    <groupId>com.owlike</groupId>
    <artifactId>genson</artifactId>
    <version>1.4</version>
</dependency>

Also this problem may occur if you're using HTTP GET with message body so in this case adding jersey-json lib, @XmlRootElement or modifying web.xml won't help. You should use URL QueryParam or HTTP POST.

Is there a way to delete all the data from a topic or delete the topic before every run?

I use the utility below to cleanup after my integration test run.

It uses the latest AdminZkClient api. The older api has been deprecated.

import javax.inject.Inject
import kafka.zk.{AdminZkClient, KafkaZkClient}
import org.apache.kafka.common.utils.Time

class ZookeeperUtils @Inject() (config: AppConfig) {

  val testTopic = "users_1"

  val zkHost = config.KafkaConfig.zkHost
  val sessionTimeoutMs = 10 * 1000
  val connectionTimeoutMs = 60 * 1000
  val isSecure = false
  val maxInFlightRequests = 10
  val time: Time = Time.SYSTEM

  def cleanupTopic(config: AppConfig) = {

    val zkClient = KafkaZkClient.apply(zkHost, isSecure, sessionTimeoutMs, connectionTimeoutMs, maxInFlightRequests, time)
    val zkUtils = new AdminZkClient(zkClient)

    val pp = new Properties()
    pp.setProperty("delete.retention.ms", "10")
    pp.setProperty("file.delete.delay.ms", "1000")
    zkUtils.changeTopicConfig(testTopic , pp)
    //    zkUtils.deleteTopic(testTopic)

    println("Waiting for topic to be purged. Then reset to retain records for the run")
    Thread.sleep(60000L)

    val resetProps = new Properties()
    resetProps.setProperty("delete.retention.ms", "3000000")
    resetProps.setProperty("file.delete.delay.ms", "4000000")
    zkUtils.changeTopicConfig(testTopic , resetProps)

  }


}

There is an option delete topic. But, it marks the topic for deletion. Zookeeper later deletes the topic. Since this can be unpredictably long, I prefer the retention.ms approach

What is "Advanced" SQL?

Check out SQL For Smarties. I thought I was pretty good with SQL too, until I read that book... Goes into tons of depth, talks about things I've not seen elsewhere (I.E. difference between 3'rd and 4'th normal form, Boyce Codd Normal Form, etc)...

Static methods - How to call a method from another method?

You can’t call non-static methods from static methods, but by creating an instance inside the static method.

It should work like that

class test2(object):
    def __init__(self):
        pass

    @staticmethod
    def dosomething():
        print "do something"
        # Creating an instance to be able to
        # call dosomethingelse(), or you
        # may use any existing instance
        a = test2()
        a.dosomethingelse()

    def dosomethingelse(self):
        print "do something else"

test2.dosomething()

Set selected item of spinner programmatically

Why don't you use your values from the DB and store them on an ArrayList and then just use:

yourSpinner.setSelection(yourArrayList.indexOf("Category 1"));

How can I display a tooltip message on hover using jQuery?

As recommended qTip and other projects are quite old I recommend using qTip2 as it is most up-to-date.

Compare objects in Angular

Bit late on this thread. angular.equals does deep check, however does anyone know that why its behave differently if one of the member contain "$" in prefix ?

You can try this Demo with following input

var obj3 = {}
obj3.a=  "b";
obj3.b={};
obj3.b.$c =true;

var obj4 = {}
obj4.a=  "b";
obj4.b={};
obj4.b.$c =true;

angular.equals(obj3,obj4);

C++ convert string to hexadecimal and vice versa

string ToHex(const string& s, bool upper_case /* = true */)
{
    ostringstream ret;

    for (string::size_type i = 0; i < s.length(); ++i)
        ret << std::hex << std::setfill('0') << std::setw(2) << (upper_case ? std::uppercase : std::nouppercase) << (int)s[i];

    return ret.str();
}

int FromHex(const string &s) { return strtoul(s.c_str(), NULL, 16); }

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

Add bean declaration in bean.xml file or in any other configuration file . It will resolve the error

<bean  class="com.demo.dao.RailwayDao"></bean>
<bean  class="com.demo.service.RailwayService"></bean>
<bean  class="com.demo.model.RailwayReservation"></bean>

How to use 'cp' command to exclude a specific directory?

I assume you're using bash or dash. Would this work?

shopt -s extglob  # sets extended pattern matching options in the bash shell
cp $(ls -laR !(subdir/file1|file2|subdir2/file3)) destination

Doing an ls excluding the files you don't want, and using that as the first argument for cp

How can I print the contents of an array horizontally?

public static void Main(string[] args)
{
    int[] numbers = new int[10];

    Console.Write("index ");

    for (int i = 0; i < numbers.Length; i++)
    {
        numbers[i] = i;
        Console.Write(numbers[i] + " ");
    }

    Console.WriteLine("");
    Console.WriteLine("");
    Console.Write("value ");

    for (int i = 0; i < numbers.Length; i++)
    {
        numbers[i] = numbers.Length - i;
        Console.Write(numbers[i] + " ");
    }

    Console.ReadKey();
}

What exactly is the difference between Web API and REST API in MVC?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

REST

RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

Reference: http://spf13.com/post/soap-vs-rest

And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/

MVC Razor Hidden input and passing values

As you may have already figured, Asp.Net MVC is a different paradigm than Asp.Net (webforms). Accessing form elements between the server and client take a different approach in Asp.Net MVC.

You can google more reading material on this on the web. For now, I would suggest using Ajax to get or post data to the server. You can still employ input type="hidden", but initialize it with a value from the ViewData or for Razor, ViewBag.

For example, your controller may look like this:

public ActionResult Index()
{
     ViewBag.MyInitialValue = true;
     return View();
} 

In your view, you can have an input elemet that is initialized by the value in your ViewBag:

<input type="hidden" name="myHiddenInput" id="myHiddenInput" value="@ViewBag.MyInitialValue" />

Then you can pass data between the client and server via ajax. For example, using jQuery:

$.get('GetMyNewValue?oldValue=' + $('#myHiddenInput').val(), function (e) {
   // blah
});

You can alternatively use $.ajax, $.getJSON, $.post depending on your requirement.

MySQLi prepared statements error reporting

Each method of mysqli can fail. You should test each return value. If one fails, think about whether it makes sense to continue with an object that is not in the state you expect it to be. (Potentially not in a "safe" state, but I think that's not an issue here.)

Since only the error message for the last operation is stored per connection/statement you might lose information about what caused the error if you continue after something went wrong. You might want to use that information to let the script decide whether to try again (only a temporary issue), change something or to bail out completely (and report a bug). And it makes debugging a lot easier.

$stmt = $mysqli->prepare("INSERT INTO testtable VALUES (?,?,?)");
// prepare() can fail because of syntax errors, missing privileges, ....
if ( false===$stmt ) {
  // and since all the following operations need a valid/ready statement object
  // it doesn't make sense to go on
  // you might want to use a more sophisticated mechanism than die()
  // but's it's only an example
  die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}

$rc = $stmt->bind_param('iii', $x, $y, $z);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if ( false===$rc ) {
  // again execute() is useless if you can't bind the parameters. Bail out somehow.
  die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}

$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if ( false===$rc ) {
  die('execute() failed: ' . htmlspecialchars($stmt->error));
}

$stmt->close();

Just a few notes six years later...

The mysqli extension is perfectly capable of reporting operations that result in an (mysqli) error code other than 0 via exceptions, see mysqli_driver::$report_mode.
die() is really, really crude and I wouldn't use it even for examples like this one anymore.
So please, only take away the fact that each and every (mysql) operation can fail for a number of reasons; even if the exact same thing went well a thousand times before....

How to make a <svg> element expand or contract to its parent container?

The viewBox isn't the height of the container, it's the size of your drawing. Define your viewBox to be 100 units in width, then define your rect to be 10 units. After that, however large you scale the SVG, the rect will be 10% the width of the image.

How to take off line numbers in Vi?

Display line numbers:

:set nu

Stop showing the line numbers:

:set nonu

Its short for :set nonumber

ps. These commands are to be run in normal mode.

Python + Django page redirect

Depending on what you want (i.e. if you do not want to do any additional pre-processing), it is simpler to just use Django's redirect_to generic view:

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

See documentation for more advanced examples.


For Django 1.3+ use:

from django.views.generic import RedirectView

urlpatterns = patterns('',
    (r'^one/$', RedirectView.as_view(url='/another/')),
)

How do I send an HTML email?

I found this way not sure it works for all the CSS primitives

By setting the header property "Content-Type" to "text/html"

mimeMessage.setHeader("Content-Type", "text/html");

now I can do stuff like

mimeMessage.setHeader("Content-Type", "text/html");

mimeMessage.setText ("`<html><body><h1 style =\"color:blue;\">My first Header<h1></body></html>`")

Regards

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

If by "Ignore Duplicate Error statments", to abort the current statement and continue to the next statement without aborting the trnsaction then just put BEGIN TRY.. END TRY around each statement:

BEGIN TRY
    INSERT ...
END TRY
BEGIN CATCH /*required, but you dont have to do anything */ END CATCH
...

Create a circular button in BS3

With Font Awesome ICONS, I used the following code to produce a round button/image with the color of your choice.

<code>

<span class="fa fa-circle fa-lg" style="color:#ff0000;"></span>

</code>

How do you add an action to a button programmatically in xcode

IOS 14 SDK: you can add action with closure callback:

let button = UIButton(type: .system, primaryAction: UIAction(title: "Button Title", handler: { _ in
            print("Button tapped!")
        }))

Getting a reference to the control sender

let textField = UITextField()
textField.addAction(UIAction(title: "", handler: { action in
    let textField = action.sender as! UITextField
    print("Text is \(textField.text)")
}), for: .editingChanged)

source

How to read strings from a Scanner in a Java console application?

Replace:

System.out.println("Enter EmployeeName:");
                 ename=(scanner.next());

with:

System.out.println("Enter EmployeeName:");
                 ename=(scanner.nextLine());

This is because next() grabs only the next token, and the space acts as a delimiter between the tokens. By this, I mean that the scanner reads the input: "firstname lastname" as two separate tokens. So in your example, ename would be set to firstname and the scanner is attempting to set the supervisorId to lastname

Why am I getting a NoClassDefFoundError in Java?

NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:

try {
    // Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
    Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}

Check if a string is null or empty in XSLT

What about?

test="not(normalize-space(categoryName)='')"

What is the difference between a candidate key and a primary key?

There is no difference. A primary key is a candidate key. By convention one candidate key in a relation is usually chosen to be the "primary" one but the choice is essentially arbitrary and a matter of convenience for database users/designers/developers. It doesn't make a "primary" key fundamentally any different to any other candidate key.

Difference between string and StringBuilder in C#

From the StringBuilder Class documentation:

The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

How to create a file with a given size in Linux?

Just to follow up Tom's post, you can use dd to create sparse files as well:

dd if=/dev/zero of=the_file bs=1 count=0 seek=12345

This will create a file with a "hole" in it on most unixes - the data won't actually be written to disk, or take up any space until something other than zero is written into it.

JQuery Validate Dropdown list

This was my solution:

I added required to the select tag:

                <div class="col-lg-10">
                <select class="form-control" name="HoursEntry" id="HoursEntry" required>
                    <option value="">Select.....</option>
                    <option value="0.25">0.25</option>
                    <option value="0.5">0.50</option>
                    <option value="1">1.00</option>
                    <option value="1.25">1.25</option>
                    <option value="1.5">1.50</option>
                    <option value="2">2.00</option>
                    <option value="2.25">2.25</option>
                    <option value="2.5">2.50</option>
                    <option value="3">3.00</option>
                    <option value="3.25">3.25</option>
                    <option value="3.5">3.50</option>
                    <option value="4">4.00</option>
                    <option value="4.25">4.25</option>
                    <option value="4.5">4.50</option>
                    <option value="5">5.00</option>
                    <option value="5.25">5.25</option>
                    <option value="5.5">5.50</option>
                    <option value="6">6.00</option>
                    <option value="6.25">6.25</option>
                    <option value="6.5">6.50</option>
                    <option value="7">7.00</option>
                    <option value="7.25">7.25</option>
                    <option value="7.5">7.50</option>
                    <option value="8">8.00</option>
                </select>

How do I add python3 kernel to jupyter (IPython)

I was getting same error with python-2. I wanted to run python-2 jupyter notebook session but by default I was getting python-3. So easiest work around is open Anaconda terminal for python-2 and type 'jupyter notebook' , it will launch jupyter-notebook session without any problem. Similary it could be tried with python-3

jQuery remove selected option from this

 $('#some_select_box').click(function() {
     $(this).find('option:selected').remove();
 });

Using the find method.

Get specific line from text file using just shell script

line=5; prep=`grep -ne ^ file.txt | grep -e ^$line:`; echo "${prep#$line:}"

Pass in an array of Deferreds to $.when()

I want to propose other one with using $.each:

  1. We may to declare ajax function like:

    function ajaxFn(someData) {
        this.someData = someData;
        var that = this;
        return function () {
            var promise = $.Deferred();
            $.ajax({
                method: "POST",
                url: "url",
                data: that.someData,
                success: function(data) {
                    promise.resolve(data);
                },
                error: function(data) {
                    promise.reject(data);
                }
            })
            return promise;
        }
    }
    
  2. Part of code where we creating array of functions with ajax to send:

    var arrayOfFn = [];
    for (var i = 0; i < someDataArray.length; i++) {
        var ajaxFnForArray = new ajaxFn(someDataArray[i]);
        arrayOfFn.push(ajaxFnForArray);
    }
    
  3. And calling functions with sending ajax:

    $.when(
        $.each(arrayOfFn, function(index, value) {
            value.call()
        })
    ).then(function() {
            alert("Cheer!");
        }
    )
    

How to get value by key from JObject?

Try this:

private string GetJArrayValue(JObject yourJArray, string key)
{
    foreach (KeyValuePair<string, JToken> keyValuePair in yourJArray)
    {
        if (key == keyValuePair.Key)
        {
            return keyValuePair.Value.ToString();
        }
    }
}

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

MongoDB Aggregation: How to get total records count?

If you don't want to group, then use the following method:

db.collection.aggregate( [ { $match : { score : { $gt : 70, $lte : 90 } } }, { $count: 'count' } ] );

Sum values in foreach loop php

$total=0;
foreach($group as $key=>$value)
{
   echo $key. " = " .$value. "<br>"; 
   $total+= $value;
}
echo $total;

CSS: fixed position on x-axis but not y?

On parent div you can add

overflow-y: scroll; 
overflow-x: hidden;

Update row values where certain condition is met in pandas

You can do the same with .ix, like this:

In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))

In [2]: df
Out[2]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484 -0.905302 -0.435821  1.934512
3  0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

In [3]: df.ix[df.a>0, ['b','c']] = 0

In [4]: df
Out[4]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484  0.000000  0.000000  1.934512
3  0.266113  0.000000  0.000000 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

EDIT

After the extra information, the following will return all columns - where some condition is met - with halved values:

>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)

I hope this helps!

How to use shell commands in Makefile

Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.

If you're on GNU Make, use the := assignment instead of =. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.

FILES := $(shell ...)  # expand now; FILES is now the result of $(shell ...)

FILES = $(shell ...)   # expand later: FILES holds the syntax $(shell ...)

If you use the = assignment, it means that every single occurrence of $(FILES) will be expanding the $(shell ...) syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.

What's the best way to loop through a set of elements in JavaScript?

Also see my comment on Andrew Hedges' test ...

I just tried to run a test to compare a simple iteration, the optimization I introduced and the reverse do/while, where the elements in an array was tested in every loop.

And alas, no surprise, the three browsers I tested had very different results, though the optimized simple iteration was fastest in all !-)

Test:

An array with 500,000 elements build outside the real test, for every iteration the value of the specific array-element is revealed.

Test run 10 times.

IE6:

Results:

Simple: 984,922,937,984,891,907,906,891,906,906

Average: 923.40 ms.

Optimized: 766,766,844,797,750,750,765,765,766,766

Average: 773.50 ms.

Reverse do/while: 3375,1328,1516,1344,1375,1406,1688,1344,1297,1265

Average: 1593.80 ms. (Note one especially awkward result)

Opera 9.52:

Results:

Simple: 344,343,344,359,343,359,344,359,359,359

Average: 351.30 ms.

Optimized: 281,297,297,297,297,281,281,297,281,281

Average: 289.00 ms

Reverse do/while: 391,407,391,391,500,407,407,406,406,406

Average: 411.20 ms.

FireFox 3.0.1:

Results:

Simple: 278,251,259,245,243,242,259,246,247,256

Average: 252.60 ms.

Optimized: 267,222,223,226,223,230,221,231,224,230

Average: 229.70 ms.

Reverse do/while: 414,381,389,383,388,389,381,387,400,379

Average: 389.10 ms.

How to copy sheets to another workbook using vba?

You could saveAs xlsx. Then you will loose the macros and generate a new workbook with a little less work.

ThisWorkbook.saveas Filename:=NewFileNameWithPath, Format:=xlOpenXMLWorkbook

"UnboundLocalError: local variable referenced before assignment" after an if statement

To Solve this Error just initialize that variable above that loop or statement. For Example var a =""

How to save a pandas DataFrame table as a png

I had the same requirement for a project I am doing. But none of the answers came elegant to my requirement. Here is something which finally helped me, and might be useful for this case:

from bokeh.io import export_png, export_svgs
from bokeh.models import ColumnDataSource, DataTable, TableColumn

def save_df_as_image(df, path):
    source = ColumnDataSource(df)
    df_columns = [df.index.name]
    df_columns.extend(df.columns.values)
    columns_for_table=[]
    for column in df_columns:
        columns_for_table.append(TableColumn(field=column, title=column))

    data_table = DataTable(source=source, columns=columns_for_table,height_policy="auto",width_policy="auto",index_position=None)
    export_png(data_table, filename = path)

enter image description here

How to declare a vector of zeros in R

You have several options

integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)

Eclipse Workspaces: What for and why?

Basically the scope of workspace(s) is divided in two points.

First point (and primary) is the eclipse it self and is related with the settings and metadata configurations (plugin ctr). Each time you create a project, eclipse collects all the configurations and stores them on that workspace and if somehow in the same workspace a conflicting project is present you might loose some functionality or even stability of eclipse it self.

And second (secondary) the point of development strategy one can adopt. Once the primary scope is met (and mastered) and there's need for further adjustments regarding project relations (as libraries, perspectives ctr) then initiate separate workspace(s) could be appropriate based on development habits or possible language/frameworks "behaviors". DLTK for examples is a beast that should be contained in a separate cage. Lots of complains at forums for it stopped working (properly or not at all) and suggested solution was to clean the settings of the equivalent plugin from the current workspace.

Personally, I found myself lean more to language distinction when it comes to separate workspaces which is relevant to known issues that comes with the current state of the plugins are used. Preferably I keep them in the minimum numbers as this is leads to less frustration when the projects are become... plenty and version control is not the only version you keep your projects. Finally, loading speed and performance is an issue that might come up if lots of (unnecessary) plugins are loaded due to presents of irrelevant projects. Bottom line; there is no one solution to every one, no master blue print that solves the issue. It's something that grows with experience, Less is more though!

Converting a JS object to an array using jQuery

I made a custom function:

    Object.prototype.toArray=function(){
    var arr=new Array();
    for( var i in this ) {
        if (this.hasOwnProperty(i)){
            arr.push(this[i]);
        }
    }
    return arr;
};

Visual Studio 2012 Web Publish doesn't copy files

My problem was in wrong configuration of myproject.csproj file. '_address-step1-stored.cshtml' file did not copy on publish. 'None' changed to 'Content', now it's ok. enter image description here

Convert Rows to columns using 'Pivot' in SQL Server

I'm writing an sp that could be useful for this purpose, basically this sp pivot any table and return a new table pivoted or return just the set of data, this is the way to execute it:

Exec dbo.rs_pivot_table @schema=dbo,@table=table_name,@column=column_to_pivot,@agg='sum([column_to_agg]),avg([another_column_to_agg]),',
        @sel_cols='column_to_select1,column_to_select2,column_to_select1',@new_table=returned_table_pivoted;

please note that in the parameter @agg the column names must be with '[' and the parameter must end with a comma ','

SP

Create Procedure [dbo].[rs_pivot_table]
    @schema sysname=dbo,
    @table sysname,
    @column sysname,
    @agg nvarchar(max),
    @sel_cols varchar(max),
    @new_table sysname,
    @add_to_col_name sysname=null
As
--Exec dbo.rs_pivot_table dbo,##TEMPORAL1,tip_liq,'sum([val_liq]),sum([can_liq]),','cod_emp,cod_con,tip_liq',##TEMPORAL1PVT,'hola';
Begin

    Declare @query varchar(max)='';
    Declare @aggDet varchar(100);
    Declare @opp_agg varchar(5);
    Declare @col_agg varchar(100);
    Declare @pivot_col sysname;
    Declare @query_col_pvt varchar(max)='';
    Declare @full_query_pivot varchar(max)='';
    Declare @ind_tmpTbl int; --Indicador de tabla temporal 1=tabla temporal global 0=Tabla fisica

    Create Table #pvt_column(
        pivot_col varchar(100)
    );

    Declare @column_agg table(
        opp_agg varchar(5),
        col_agg varchar(100)
    );

    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@table) AND type in (N'U'))
        Set @ind_tmpTbl=0;
    ELSE IF OBJECT_ID('tempdb..'+ltrim(rtrim(@table))) IS NOT NULL
        Set @ind_tmpTbl=1;

    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@new_table) AND type in (N'U')) OR 
        OBJECT_ID('tempdb..'+ltrim(rtrim(@new_table))) IS NOT NULL
    Begin
        Set @query='DROP TABLE '+@new_table+'';
        Exec (@query);
    End;

    Select @query='Select distinct '+@column+' From '+(case when @ind_tmpTbl=1 then 'tempdb.' else '' end)+@schema+'.'+@table+' where '+@column+' is not null;';
    Print @query;

    Insert into #pvt_column(pivot_col)
    Exec (@query)

    While charindex(',',@agg,1)>0
    Begin
        Select @aggDet=Substring(@agg,1,charindex(',',@agg,1)-1);

        Insert Into @column_agg(opp_agg,col_agg)
        Values(substring(@aggDet,1,charindex('(',@aggDet,1)-1),ltrim(rtrim(replace(substring(@aggDet,charindex('[',@aggDet,1),charindex(']',@aggDet,1)-4),')',''))));

        Set @agg=Substring(@agg,charindex(',',@agg,1)+1,len(@agg))

    End

    Declare cur_agg cursor read_only forward_only local static for
    Select 
        opp_agg,col_agg
    from @column_agg;

    Open cur_agg;

    Fetch Next From cur_agg
    Into @opp_agg,@col_agg;

    While @@fetch_status=0
    Begin

        Declare cur_col cursor read_only forward_only local static for
        Select 
            pivot_col 
        From #pvt_column;

        Open cur_col;

        Fetch Next From cur_col
        Into @pivot_col;

        While @@fetch_status=0
        Begin

            Select @query_col_pvt='isnull('+@opp_agg+'(case when '+@column+'='+quotename(@pivot_col,char(39))+' then '+@col_agg+
            ' else null end),0) as ['+lower(Replace(Replace(@opp_agg+'_'+convert(varchar(100),@pivot_col)+'_'+replace(replace(@col_agg,'[',''),']',''),' ',''),'&',''))+
                (case when @add_to_col_name is null then space(0) else '_'+isnull(ltrim(rtrim(@add_to_col_name)),'') end)+']'
            print @query_col_pvt
            Select @full_query_pivot=@full_query_pivot+@query_col_pvt+', '

            --print @full_query_pivot

            Fetch Next From cur_col
            Into @pivot_col;        

        End     

        Close cur_col;
        Deallocate cur_col;

        Fetch Next From cur_agg
        Into @opp_agg,@col_agg; 
    End

    Close cur_agg;
    Deallocate cur_agg;

    Select @full_query_pivot=substring(@full_query_pivot,1,len(@full_query_pivot)-1);

    Select @query='Select '+@sel_cols+','+@full_query_pivot+' into '+@new_table+' From '+(case when @ind_tmpTbl=1 then 'tempdb.' else '' end)+
    @schema+'.'+@table+' Group by '+@sel_cols+';';

    print @query;
    Exec (@query);

End;
GO

This is an example of execution:

Exec dbo.rs_pivot_table @schema=dbo,@table=##TEMPORAL1,@column=tip_liq,@agg='sum([val_liq]),avg([can_liq]),',@sel_cols='cod_emp,cod_con,tip_liq',@new_table=##TEMPORAL1PVT;

then Select * From ##TEMPORAL1PVT would return:

enter image description here

How to use localization in C#

In addition to @Eric Bole-Feysot answer:

Thanks to satellite assemblies, localization can be created based on .dll/.exe files. This way:

  • source code (VS project) could be separated from language project,
  • adding a new language does not require recompiling the project,
  • translation could be made even by the end-user.

There is a little known tool called LSACreator (free for non-commercial use or buy option) which allows you to create localization based on .dll/.exe files. In fact, internally (in language project's directory) it creates/manages localized versions of resx files and compiles an assembly in similar way as @Eric Bole-Feysot described.

Center/Set Zoom of Map to cover all visible Markers?

The size of array must be greater than zero. ?therwise you will have unexpected results.

function zoomeExtends(){
  var bounds = new google.maps.LatLngBounds();
  if (markers.length>0) { 
      for (var i = 0; i < markers.length; i++) {
         bounds.extend(markers[i].getPosition());
        }    
        myMap.fitBounds(bounds);
    }
}

How to convert CharSequence to String?

You can directly use String.valueOf()

String.valueOf(charSequence)

Though this is same as toString() it does a null check on the charSequence before actually calling toString.

This is useful when a method can return either a charSequence or null value.

How to determine if binary tree is balanced?

Post order solution, traverse the tree only once. Time complexity is O(n), space is O(1), it's better than top-down solution. I give you a java version implementation.

public static <T> boolean isBalanced(TreeNode<T> root){
    return checkBalance(root) != -1;
}

private static <T> int checkBalance(TreeNode<T> node){
    if(node == null) return 0;
    int left = checkBalance(node.getLeft());

    if(left == -1) return -1;

    int right = checkBalance(node.getRight());

    if(right == -1) return -1;

    if(Math.abs(left - right) > 1){
        return -1;
    }else{
        return 1 + Math.max(left, right);
    }
}

save a pandas.Series histogram plot to file

You can use ax.figure.savefig():

import pandas as pd

s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')

This has no practical benefit over ax.get_figure().savefig() as suggested in Philip Cloud's answer, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure() simply returns self.figure:

# Source from snippet linked above
def get_figure(self):
    """Return the `.Figure` instance the artist belongs to."""
    return self.figure

MySQL does not start when upgrading OSX to Yosemite or El Capitan

Way simplest: copy and paste this into Terminal (but be sure to read more first):

bash <(curl -Ls http://git.io/eUx7rg)

This will install and configure everything automagically. The script is provided by MacMiniVault and is available on Github. More information about the mySQL install script on http://www.macminivault.com/mysql-yosemite/.

How to escape apostrophe (') in MySql?

just write '' in place of ' i mean two times '

How to load GIF image in Swift?

This is working for me

Podfile:

platform :ios, '9.0'
use_frameworks!

target '<Your Target Name>' do
pod 'SwiftGifOrigin', '~> 1.7.0'
end

Usage:

// An animated UIImage
let jeremyGif = UIImage.gif(name: "jeremy")

// A UIImageView with async loading
let imageView = UIImageView()
imageView.loadGif(name: "jeremy")

// A UIImageView with async loading from asset catalog(from iOS9)
let imageView = UIImageView()
imageView.loadGif(asset: "jeremy")

For more information follow this link: https://github.com/swiftgif/SwiftGif

How to format an inline code in Confluence?

Easiest way for me is to Insert Markup.

Confluence Insert Markup

Then in text box type the text between curly braces.

It will insert the formatted text in a new line but you can copy it anywhere, even inline.

How to parse JSON with VBA without external libraries?

I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):

Sub getData()

    Dim Movie As Object
    Dim scriptControl As Object

    Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
    scriptControl.Language = "JScript"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
        .send
        Set Movie = scriptControl.Eval("(" + .responsetext + ")")
        .abort
        With Sheets(2)
            .Cells(1, 1).Value = Movie.Title
            .Cells(1, 2).Value = Movie.Year
            .Cells(1, 3).Value = Movie.Rated
            .Cells(1, 4).Value = Movie.Released
            .Cells(1, 5).Value = Movie.Runtime
            .Cells(1, 6).Value = Movie.Director
            .Cells(1, 7).Value = Movie.Writer
            .Cells(1, 8).Value = Movie.Actors
            .Cells(1, 9).Value = Movie.Plot
            .Cells(1, 10).Value = Movie.Language
            .Cells(1, 11).Value = Movie.Country
            .Cells(1, 12).Value = Movie.imdbRating
        End With
    End With

End Sub

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

In my case,

sudo chmod ug+wx .git -R

this command works.

How to change the Eclipse default workspace?

If you mean to change the directory in which the program execution will occur, go to "Run configurations" in the Run tab.

Then select your project and go to the "Arguments" tab, you can change the directory there. By default it is the root directory of your project.

maven "cannot find symbol" message unhelpful

update to 3.1 :

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
        <source>1.7</source>
        <target>1.7</target>
    </configuration>
</plugin>

How to undo 'git reset'?

My situation was slightly different, I did git reset HEAD~ three times.

To undo it I had to do

git reset HEAD@{3}

so you should be able to do

git reset HEAD@{N}

But if you have done git reset using

git reset HEAD~3

you will need to do

git reset HEAD@{1}

{N} represents the number of operations in reflog, as Mark pointed out in the comments.

How do I create HTML table using jQuery dynamically?

FOR EXAMPLE YOU HAVE RECIEVED JASON DATA FROM SERVER.

                var obj = JSON.parse(msg);
                var tableString ="<table id='tbla'>";
                tableString +="<th><td>Name<td>City<td>Birthday</th>";


                for (var i=0; i<obj.length; i++){
                    //alert(obj[i].name);
                    tableString +=gg_stringformat("<tr><td>{0}<td>{1}<td>{2}</tr>",obj[i].name, obj[i].age, obj[i].birthday);
                }
                tableString +="</table>";
                alert(tableString);
                $('#divb').html(tableString);

HERE IS THE CODE FOR gg_stringformat

function gg_stringformat() {
var argcount = arguments.length,
    string,
    i;

if (!argcount) {
    return "";
}
if (argcount === 1) {
    return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
    string = string.replace(new RegExp('\\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;

}

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

Is the file being blocked? I had the same issue and was able to resolve it by right clicking the .PS1 file, Properties and choosing Unblock.

Link to "pin it" on pinterest without generating a button

I had the same question. This works great in Wordpress!

<a href="//pinterest.com/pin/create/link/?url=<?php the_permalink();?>&amp;description=<?php the_title();?>">Pin this</a>

Conditional operator in Python?

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"

Drop Down Menu/Text Field in one

Inspired by the js fiddle by @ajdeguzman (made my day), here is my node/React derivative:

 <div style={{position:"relative",width:"200px",height:"25px",border:0,
              padding:0,margin:0}}>
    <select style={{position:"absolute",top:"0px",left:"0px",
                    width:"200px",height:"25px",lineHeight:"20px",
                    margin:0,padding:0}} onChange={this.onMenuSelect}>
            <option></option>
            <option value="starttime">Filter by Start Time</option>
            <option value="user"     >Filter by User</option>
            <option value="buildid"  >Filter by Build Id</option>
            <option value="invoker"  >Filter by Invoker</option>
    </select>
    <input name="displayValue" id="displayValue" 
           style={{position:"absolute",top:"2px",left:"3px",width:"180px",
                   height:"21px",border:"1px solid #A9A9A9"}}
           onfocus={this.select} type="text" onChange={this.onIdFilterChange}
           onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp} 
           placeholder="Filter by Build ID"/>
 </div>

Looks like this:

enter image description here

Handle spring security authentication exceptions with @ExceptionHandler

In ResourceServerConfigurerAdapter class, below code snipped worked for me. http.exceptionHandling().authenticationEntryPoint(new AuthFailureHandler()).and.csrf().. did not work. That's why I wrote it as separate call.

public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.exceptionHandling().authenticationEntryPoint(new AuthFailureHandler());

        http.csrf().disable()
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers("/subscribers/**").authenticated()
                .antMatchers("/requests/**").authenticated();
    }

Implementation of AuthenticationEntryPoint for catching token expiry and missing authorization header.


public class AuthFailureHandler implements AuthenticationEntryPoint {

  @Override
  public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e)
      throws IOException, ServletException {
    httpServletResponse.setContentType("application/json");
    httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    if( e instanceof InsufficientAuthenticationException) {

      if( e.getCause() instanceof InvalidTokenException ){
        httpServletResponse.getOutputStream().println(
            "{ "
                + "\"message\": \"Token has expired\","
                + "\"type\": \"Unauthorized\","
                + "\"status\": 401"
                + "}");
      }
    }
    if( e instanceof AuthenticationCredentialsNotFoundException) {

      httpServletResponse.getOutputStream().println(
          "{ "
              + "\"message\": \"Missing Authorization Header\","
              + "\"type\": \"Unauthorized\","
              + "\"status\": 401"
              + "}");
    }

  }
}

Where does gcc look for C and C++ header files?

In addition, gcc will look in the directories specified after the -I option.


How to get the title of HTML page with JavaScript?

Can use getElementsByTagName

var x = document.getElementsByTagName("title")[0];

alert(x.innerHTML)

// or

alert(x.textContent)

// or

document.querySelector('title')

Edits as suggested by Paul

When to use throws in a Java method declaration?

This is not an answer, but a comment, but I could not write a comment with a formatted code, so here is the comment.

Lets say there is

public static void main(String[] args) {
  try {
    // do nothing or throw a RuntimeException
    throw new RuntimeException("test");
  } catch (Exception e) {
    System.out.println(e.getMessage());
    throw e;
  }
}

The output is

test
Exception in thread "main" java.lang.RuntimeException: test
    at MyClass.main(MyClass.java:10)

That method does not declare any "throws" Exceptions, but throws them! The trick is that the thrown exceptions are RuntimeExceptions (unchecked) that are not needed to be declared on the method. It is a bit misleading for the reader of the method, since all she sees is a "throw e;" statement but no declaration of the throws exception

Now, if we have

public static void main(String[] args) throws Exception {
  try {
    throw new Exception("test");
  } catch (Exception e) {
    System.out.println(e.getMessage());
    throw e;
  }
}

We MUST declare the "throws" exceptions in the method otherwise we get a compiler error.

Sibling package imports

Seven years after

Since I wrote the answer below, modifying sys.path is still a quick-and-dirty trick that works well for private scripts, but there has been several improvements

  • Installing the package (in a virtualenv or not) will give you what you want, though I would suggest using pip to do it rather than using setuptools directly (and using setup.cfg to store the metadata)
  • Using the -m flag and running as a package works too (but will turn out a bit awkward if you want to convert your working directory into an installable package).
  • For the tests, specifically, pytest is able to find the api package in this situation and takes care of the sys.path hacks for you

So it really depends on what you want to do. In your case, though, since it seems that your goal is to make a proper package at some point, installing through pip -e is probably your best bet, even if it is not perfect yet.

Old answer

As already stated elsewhere, the awful truth is that you have to do ugly hacks to allow imports from siblings modules or parents package from a __main__ module. The issue is detailed in PEP 366. PEP 3122 attempted to handle imports in a more rational way but Guido has rejected it one the account of

The only use case seems to be running scripts that happen to be living inside a module's directory, which I've always seen as an antipattern.

(here)

Though, I use this pattern on a regular basis with

# Ugly hack to allow absolute import from the root folder
# whatever its name is. Please forgive the heresy.
if __name__ == "__main__" and __package__ is None:
    from sys import path
    from os.path import dirname as dir

    path.append(dir(path[0]))
    __package__ = "examples"

import api

Here path[0] is your running script's parent folder and dir(path[0]) your top level folder.

I have still not been able to use relative imports with this, though, but it does allow absolute imports from the top level (in your example api's parent folder).

Changing factor levels with dplyr mutate

Can't comment because I don't have enough reputation points, but recode only works on a vector, so the above code in @Stefano's answer should be

df <- iris %>%
  mutate(Species = recode(Species, 
     setosa = "SETOSA",
     versicolor = "VERSICOLOR",
     virginica = "VIRGINICA")
  )

jQuery - prevent default, then continue default

Use jQuery.one()

Attach a handler to an event for the elements. The handler is executed at most once per element per event type

$('form').one('submit', function(e) {
    e.preventDefault();
    // do your things ...

    // and when you done:
    $(this).submit();
});

The use of one prevent also infinite loop because this custom submit event is detatched after the first submit.

What is the string length of a GUID?

GUIDs are 128bits, or

0 through ffffffffffffffffffffffffffffffff (hex) or 
0 through 340282366920938463463374607431768211455 (decimal) or 
0 through 11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 (binary, base 2) or 
0 through 91"<b.PX48m!wVmVA?1y (base 95)

So yes, min 20 characters long, which is actually wasting more than 4.25 bits, so you can be just as efficient using smaller bases than 95 as well; base 85 being the smallest possible one that still fits into 20 chars:

0 through -r54lj%NUUO[Hi$c2ym0 (base 85, using 0-9A-Za-z!"#$%&'()*+,- chars)

:-)

Fatal error: "No Target Architecture" in Visual Studio

Solve it by placing the following include files and definition first:

#define WIN32_LEAN_AND_MEAN      // Exclude rarely-used stuff from Windows headers

#include <windows.h>

How to add parameters to an external data query in Excel which can't be displayed graphically?

YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".

save and open in excel, try refresh data and excel will be monit about parameters.

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

I ran into the same error, but I was not using model-first. It turned out that somehow my EDMX file contained a reference to a table even though it did not show up in the designer. Interestingly, when I did a text search for the table name in Visual Studio (2013) the table was not found.

To solve the issue, I used an external editor (Notepad++) to find the reference to the offending table in the EDMX file, and then (carefully) removed all references to the table. I am sorry to say that I do not know how the EDMX file got into this state in the first place.

Remove credentials from Git

The Git credential cache runs a daemon process which caches your credentials in memory and hands them out on demand. So killing your git-credential-cache--daemon process throws all these away and results in re-prompting you for your password if you continue to use this as the cache.helper option.

You could also disable use of the Git credential cache using git config --global --unset credential.helper. Then reset this, and you would continue to have the cached credentials available for other repositories (if any). You may also need to do git config --system --unset credential.helper if this has been set in the system configuration file (for example, Git for Windows 2).

On Windows you might be better off using the manager helper (git config --global credential.helper manager). This stores your credentials in the Windows credential store which has a Control Panel interface where you can delete or edit your stored credentials. With this store, your details are secured by your Windows login and can persist over multiple sessions. The manager helper included in Git for Windows 2.x has replaced the earlier wincred helper that was added in Git for Windows 1.8.1.1. A similar helper called winstore is also available online and was used with GitExtensions as it offers a more GUI driven interface. The manager helper offers the same GUI interface as winstore.

Extract from the Windows 10 support page detailing the Windows credential manager:

To open Credential Manager, type "credential manager" in the search box on the taskbar and select Credential Manager Control panel.

And then select Windows Credentials to edit (=remove or modify) the stored git credentials for a given URL.

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

Little known: the GO sql statement can take an integer for the number of times to repeat previous command.

So if you:

ALTER DATABASE [DATABASENAME] SET SINGLE_USER
GO

Then:

USE [DATABASENAME]
GO 2000

This will repeat the USE command 2000 times, force deadlock on all other connections, and take ownership of the single connection. (Giving your query window sole access to do as you wish.)

Split string with string as delimiter

I expanded Magoos answer to get both desired strings:

@ECHO OFF
SETLOCAL enabledelayedexpansion
SET "string=string1 by string2.txt"
SET "s2=%string:* by =%"
set "s1=!string: by %s2%=!"
set "s2=%s2:.txt=%"
ECHO +%s1%+%s2%+

EDIT: just to prove, my solution also works with the additional requirements:

@ECHO OFF
SETLOCAL enabledelayedexpansion
SET "string=string&1 more words by string&2 with spaces.txt"
SET "s2=%string:* by =%"
set "s1=!string: by %s2%=!"
set "s2=%s2:.txt=%"
ECHO "+%s1%+%s2%+"
set s1
set s2

Output:

"+string&1 more words+string&2 with spaces+"
s1=string&1 more words
s2=string&2 with spaces

javax.naming.NameNotFoundException

The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.

As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:

/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml

The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.

BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is

@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
   public void bussinesMethod(){

   }
}

No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.

Now in your client code you need to lookup "MyComponentName".

How to place a JButton at a desired location in a JFrame using Java

You should set layout first by syntax pnlButton.setLayout(), and then choose the most suitable layout which u want. Ex: pnlButton.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));. And then, take that JButton into JPanel.

Lombok added but getters and setters not recognized in Intellij IDEA

Actually the lombok is working (if you run the project even with the IDE red alerts, you will see the project will run without error), but the IDE is not recognizing all the resources generated by the lombok annotations. So you have to install the lombok plugin, that's all!

How to hide image broken Icon using only CSS/HTML?

in case you like to keep/need the image as a placeholder, you could change the opacity to 0 with an onerror and some CSS to set the image size. This way you will not see the broken link, but the page loads as normal.

<img src="<your-image-link->" onerror="this.style.opacity='0'" />

img {
    width: 75px;
    height: 100px;
}

Java TreeMap Comparator

you can swipe the key and the value. For example

        String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
        int[] v = {341, 273, 278, 329, 445};
        TreeMap<Integer,String>a=new TreeMap();
        for (int i = 0; i < k.length; i++) 
           a.put(v[i],k[i]);            
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
        a.remove(a.firstEntry().getKey());
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());

Finding rows containing a value (or values) in any column

How about

apply(df, 1, function(r) any(r %in% c("M017", "M018")))

The ith element will be TRUE if the ith row contains one of the values, and FALSE otherwise. Or, if you want just the row numbers, enclose the above statement in which(...).

error: member access into incomplete type : forward declaration of

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}

How can I restore the MySQL root user’s full privileges?

If the GRANT ALL doesn't work, try:

  1. Stop mysqld and restart it with the --skip-grant-tables option.
  2. Connect to the mysqld server with just: mysql (i.e. no -p option, and username may not be required).
  3. Issue the following commands in the mysql client:

    UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';

    FLUSH PRIVILEGES;

After that, you should be able to run GRANT ALL ON *.* TO 'root'@'localhost'; and have it work.

Easiest way to flip a boolean value?

The codegolf'ish solution would be more like:

flipVal = (wParam == VK_F11) ? !flipVal : flipVal;
otherVal = (wParam == VK_F12) ? !otherVal : otherVal;

Regular Expression to match string starting with a specific word

If you wish to match only lines beginning with stop use

^stop

If you wish to match lines beginning with the word stop followed by a space

^stop\s

Or, if you wish to match lines beginning with the word stop but followed by either a space or any other non word character you can use (your regex flavor permitting)

^stop\W

On the other hand, what follows matches a word at the beginning of a string on most regex flavors (in these flavors \w matches the opposite of \W)

^\w

If your flavor does not have the \w shortcut, you can use

^[a-zA-Z0-9]+

Be wary that this second idiom will only match letters and numbers, no symbol whatsoever.

Check your regex flavor manual to know what shortcuts are allowed and what exactly do they match (and how do they deal with Unicode.)

How do I to insert data into an SQL table using C# as well as implement an upload function?

You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();

Exploits of a Mom

(xkcd)

Disabling swap files creation in vim

I agree with those who question why vim needs all this 'disaster recovery' stuff when no other text editors bother with it. I don't want vim creating ANY extra files in the edited file's directory when I'm editing it, thank you very much. To that end, I have this in my _vimrc to disable swap files, and move irritating 'backup' files to the Temp dir:

" Uncomment below to prevent 'tilde backup files' (eg. myfile.txt~) from being created
"set nobackup

" Uncomment below to cause 'tilde backup files' to be created in a different dir so as not to clutter up the current file's directory (probably a better idea than disabling them altogether)
set backupdir=C:\Windows\Temp

" Uncomment below to disable 'swap files' (eg. .myfile.txt.swp) from being created
set noswapfile

How to get records randomly from the oracle database?

In case of huge tables standard way with sorting by dbms_random.value is not effective because you need to scan whole table and dbms_random.value is pretty slow function and requires context switches. For such cases, there are 3 additional methods:


1: Use sample clause:

for example:

select *
from s1 sample block(1)
order by dbms_random.value
fetch first 1 rows only

ie get 1% of all blocks, then sort them randomly and return just 1 row.


2: if you have an index/primary key on the column with normal distribution, you can get min and max values, get random value in this range and get first row with a value greater or equal than that randomly generated value.

Example:

--big table with 1 mln rows with primary key on ID with normal distribution:
Create table s1(id primary key,padding) as 
   select level, rpad('x',100,'x')
   from dual 
   connect by level<=1e6;

select *
from s1 
where id>=(select 
              dbms_random.value(
                 (select min(id) from s1),
                 (select max(id) from s1) 
              )
           from dual)
order by id
fetch first 1 rows only;

3: get random table block, generate rowid and get row from the table by this rowid:

select * 
from s1
where rowid = (
   select
      DBMS_ROWID.ROWID_CREATE (
         1, 
         objd,
         file#,
         block#,
         1) 
   from    
      (
      select/*+ rule */ file#,block#,objd
      from v$bh b
      where b.objd in (select o.data_object_id from user_objects o where object_name='S1' /* table_name */)
      order by dbms_random.value
      fetch first 1 rows only
      )
);

Using malloc for allocation of multi-dimensional arrays with different row lengths

malloc does not allocate on specific boundaries, so it must be assumed that it allocates on a byte boundary.

The returned pointer can then not be used if converted to any other type, since accessing that pointer will probably produce a memory access violation by the CPU, and the application will be immediately shut down.

How to know if docker is already logged in to a docker registry server

Use command like below:

docker info | grep 'name'

WARNING: No swap limit support
Username: <strong>jonasm2009</strong>

Classes residing in App_Code is not accessible

make sure that you are using the same namespace as your pages

ReactJS: Warning: setState(...): Cannot update during an existing state transition

If you are trying to add arguments to a handler in recompose, make sure that you're defining your arguments correctly in the handler. It is essentially a curried function, so you want to be sure to require the correct number of arguments. This page has a good example of using arguments with handlers.

Example (from the link):

withHandlers({
  handleClick: props => (value1, value2) => event => {
    console.log(event)
    alert(value1 + ' was clicked!')
    props.doSomething(value2)
  },
})

for your child HOC and in the parent

class MyComponent extends Component {
  static propTypes = {
    handleClick: PropTypes.func, 
  }
  render () {
    const {handleClick} = this.props
    return (
      <div onClick={handleClick(value1, value2)} />
    )
  }
}

this avoids writing an anonymous function out of your handler to patch fix the problem with not supplying enough parameter names on your handler.

How to find the maximum value in an array?

Have a max int and set it to the first value in the array. Then in a for loop iterate through the whole array and see if the max int is larger than the int at the current index.

int max = array.get(0);

for (int i = 1; i < array.length; i++) {
    if (array.get(i) > max) {
      max = array.get(i);
    }
}

Basic example of using .ajax() with JSONP?

In response to the OP, there are two problems with your code: you need to set jsonp='callback', and adding in a callback function in a variable like you did does not seem to work.

Update: when I wrote this the Twitter API was just open, but they changed it and it now requires authentication. I changed the second example to a working (2014Q1) example, but now using github.

This does not work any more - as an exercise, see if you can replace it with the Github API:

$('document').ready(function() {
    var pm_url = 'http://twitter.com/status';
    pm_url += '/user_timeline/stephenfry.json';
    pm_url += '?count=10&callback=photos';
    $.ajax({
        url: pm_url,
        dataType: 'jsonp',
        jsonpCallback: 'photos',
        jsonp: 'callback',
    });
});
function photos (data) {
    alert(data);
    console.log(data);
};

although alert()ing an array like that does not really work well... The "Net" tab in Firebug will show you the JSON properly. Another handy trick is doing

alert(JSON.stringify(data));

You can also use the jQuery.getJSON method. Here's a complete html example that gets a list of "gists" from github. This way it creates a randomly named callback function for you, that's the final "callback=?" in the url.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>JQuery (cross-domain) JSONP Twitter example</title>
        <script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.getJSON('https://api.github.com/gists?callback=?', function(response){
                    $.each(response.data, function(i, gist){
                        $('#gists').append('<li>' + gist.user.login + " (<a href='" + gist.html_url + "'>" + 
                            (gist.description == "" ? "undescribed" : gist.description) + '</a>)</li>');
                    });
                });
            });
        </script>
    </head>
    <body>
        <ul id="gists"></ul>
    </body>
</html>

JQuery ajax call default timeout value

The XMLHttpRequest.timeout property represents a number of milliseconds a request can take before automatically being terminated. The default value is 0, which means there is no timeout. An important note the timeout shouldn't be used for synchronous XMLHttpRequests requests, used in a document environment or it will throw an InvalidAccessError exception. You may not use a timeout for synchronous requests with an owning window.

IE10 and 11 do not support synchronous requests, with support being phased out in other browsers too. This is due to detrimental effects resulting from making them.

More info can be found here.

MySQL Like multiple values

Why not you try REGEXP. Try it like this:

SELECT * FROM table WHERE interests REGEXP 'sports|pub'

How do I bottom-align grid elements in bootstrap fluid layout

.align-bottom {
    position: absolute;
    bottom: 10px;
    right: 10px;
}

How to repair a serialized string which has been corrupted by an incorrect byte count length?

Quick Fix

Recalculating the length of the elements in serialized array - but don't use (preg_replace) it's deprecated - better use preg_replace_callback:

Edit: New Version now not just wrong length but it also fix line-breaks and count correct characters with aczent (thanks to mickmackusa)

// New Version
$data = preg_replace_callback('!s:\d+:"(.*?)";!s', function($m) { return "s:" . strlen($m[1]) . ':"'.$m[1].'";'; }, $data);

GetType used in PowerShell, difference between variables

Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():

PS > $a.GetType().fullname
System.DayOfWeek

PS > $b.GetType().fullname
System.Management.Automation.PSCustomObject

Standard deviation of a list

The other answers cover how to do std dev in python sufficiently, but no one explains how to do the bizarre traversal you've described.

I'm going to assume A-Z is the entire population. If not see Ome's answer on how to inference from a sample.

So to get the standard deviation/mean of the first digit of every list you would need something like this:

#standard deviation
numpy.std([A_rank[0], B_rank[0], C_rank[0], ..., Z_rank[0]])

#mean
numpy.mean([A_rank[0], B_rank[0], C_rank[0], ..., Z_rank[0]])

To shorten the code and generalize this to any nth digit use the following function I generated for you:

def getAllNthRanks(n):
    return [A_rank[n], B_rank[n], C_rank[n], D_rank[n], E_rank[n], F_rank[n], G_rank[n], H_rank[n], I_rank[n], J_rank[n], K_rank[n], L_rank[n], M_rank[n], N_rank[n], O_rank[n], P_rank[n], Q_rank[n], R_rank[n], S_rank[n], T_rank[n], U_rank[n], V_rank[n], W_rank[n], X_rank[n], Y_rank[n], Z_rank[n]] 

Now you can simply get the stdd and mean of all the nth places from A-Z like this:

#standard deviation
numpy.std(getAllNthRanks(n))

#mean
numpy.mean(getAllNthRanks(n))

Access to the path denied error in C#

If your problem persist with all those answers, try to change the file attribute to:

File.SetAttributes(yourfile, FileAttributes.Normal);

Change Text Color of Selected Option in a Select Box

JQuery Code:

$('#mySelect').change(function () {
    $('#mySelect').css("background", $("select option:selected").css("background-color"));
});

This will replace the select's background-color with selected option's background-color.

Here is an example fiddle.

Running stages in parallel with Jenkins workflow / pipeline

As @Quartz mentioned, you can do something like

stage('Tests') {
    parallel(
        'Unit Tests': {
            container('node') {
                sh("npm test --cat=unit")
            }
        },
        'API Tests': {
            container('node') {
                sh("npm test --cat=acceptance")
            }
        }
    )
}

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

Your @Entity class has a String type for its @Id field, so it can't generate ids for you.

If you change it to an auto increment in the DB and a Long in java, and add the @GeneratedValue annotation:

@Id
@Column(name="U_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long U_id;

it will handle incrementing id generation for you.

Ajax success event not working

You must declare both Success AND Error callback. Adding

error: function(err) {...} 

should fix the problem

How do I delete a local repository in git?

To piggyback on rkj's answer, to avoid endless prompts (and force the command recursively), enter the following into the command line, within the project folder:

$ rm -rf .git

Or to delete .gitignore and .gitmodules if any (via @aragaer):

$ rm -rf .git*

Then from the same ex-repository folder, to see if hidden folder .git is still there:

$ ls -lah

If it's not, then congratulations, you've deleted your local git repo, but not a remote one if you had it. You can delete GitHub repo on their site (github.com).

To view hidden folders in Finder (Mac OS X) execute these two commands in your terminal window:

defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder

Source: http://lifehacker.com/188892/show-hidden-files-in-finder.

PowerShell: Run command from script's directory

If you're calling native apps, you need to worry about [Environment]::CurrentDirectory not about PowerShell's $PWD current directory. For various reasons, PowerShell does not set the process' current working directory when you Set-Location or Push-Location, so you need to make sure you do so if you're running applications (or cmdlets) that expect it to be set.

In a script, you can do this:

$CWD = [Environment]::CurrentDirectory

Push-Location $MyInvocation.MyCommand.Path
[Environment]::CurrentDirectory = $PWD
##  Your script code calling a native executable
Pop-Location

# Consider whether you really want to set it back:
# What if another runspace has set it in-between calls?
[Environment]::CurrentDirectory = $CWD

There's no foolproof alternative to this. Many of us put a line in our prompt function to set [Environment]::CurrentDirectory ... but that doesn't help you when you're changing the location within a script.

Two notes about the reason why this is not set by PowerShell automatically:

  1. PowerShell can be multi-threaded. You can have multiple Runspaces (see RunspacePool, and the PSThreadJob module) running simultaneously withinin a single process. Each runspace has it's own $PWD present working directory, but there's only one process, and only one Environment.
  2. Even when you're single-threaded, $PWD isn't always a legal CurrentDirectory (you might CD into the registry provider for instance).

If you want to put it into your prompt (which would only run in the main runspace, single-threaded), you need to use:

[Environment]::CurrentDirectory = Get-Location -PSProvider FileSystem

Calculate distance in meters when you know longitude and latitude in java

You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.

Implementation goes like this:

import org.gavaghan.geodesy.*;

...

GeodeticCalculator geoCalc = new GeodeticCalculator();

Ellipsoid reference = Ellipsoid.WGS84;  

GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A

GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B

double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B

The resulting distance is in meters.

How to detect scroll direction

I managed to figure it out in the end, so if anyone is looking for the answer:

 //Firefox
 $('#elem').bind('DOMMouseScroll', function(e){
     if(e.originalEvent.detail > 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

 //IE, Opera, Safari
 $('#elem').bind('mousewheel', function(e){
     if(e.originalEvent.wheelDelta < 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

Enforcing the type of the indexed members of a Typescript object?

interface AccountSelectParams {
  ...
}
const params = { ... };

const tmpParams: { [key in keyof AccountSelectParams]: any } | undefined = {};
  for (const key of Object.keys(params)) {
    const customKey = (key as keyof typeof params);
    if (key in params && params[customKey] && !this.state[customKey]) {
      tmpParams[customKey] = params[customKey];
    }
  }

please commented if you get the idea of this concept

Comparing two collections for equality irrespective of the order of items in them

In many cases the only suitable answer is the one of Igor Ostrovsky , other answers are based on objects hash code. But when you generate an hash code for an object you do so only based on his IMMUTABLE fields - such as object Id field (in case of a database entity) - Why is it important to override GetHashCode when Equals method is overridden?

This means , that if you compare two collections , the result might be true of the compare method even though the fields of the different items are non-equal . To deep compare collections , you need to use Igor's method and implement IEqualirity .

Please read the comments of me and mr.Schnider's on his most voted post.

James

PIG how to count a number of rows in alias

What you want is to count all the lines in a relation (dataset in Pig Latin)

This is very easy following the next steps:

logs = LOAD 'log'; --relation called logs, using PigStorage with tab as field delimiter
logs_grouped = GROUP logs ALL;--gives a relation with one row with logs as a bag
number = FOREACH LOGS_GROUP GENERATE COUNT_STAR(logs);--show me the number

I have to say it is important Kevin's point as using COUNT instead of COUNT_STAR we would have only the number of lines which first field is not null.

Also I like Jerome's one line syntax it is more concise but in order to be didactic I prefer to divide it in two and add some comment.

In general I prefer:

numerito = FOREACH (GROUP CARGADOS3 ALL) GENERATE COUNT_STAR(CARGADOS3);

over

name = GROUP CARGADOS3 ALL
number = FOREACH name GENERATE COUNT_STAR(CARGADOS3);

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

Android TextView Justify Text

UPDATED

We have created a simple class for this. There are currently two methods to achieve what you are looking for. Both require NO WEBVIEW and SUPPORTS SPANNABLES.

LIBRARY: https://github.com/bluejamesbond/TextJustify-Android

SUPPORTS: Android 2.0 to 5.X

SETUP

// Please visit Github for latest setup instructions.

SCREENSHOT

Comparison.png

Git error: src refspec master does not match any

You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:

 git add a_text_file.txt 

... do:

 git commit -m "Initial commit."

... and those errors should go away.

Copy files on Windows Command Line with Progress

I used the copy command with the /z switch for copying over network drives. Also works for copying between local drives. Tested on XP Home edition.

HTML5 iFrame Seamless Attribute

Use the frameborder attribute on your iframe and set it to frameborder="0" . That produces the seamless look. Now you maybe saying I want the nested iframe to control rather I have scroll bars. Then you need to whip up a JavaScript script file that calculates height minus any headers and set the height. Debounce is javascript plugin needed to make sure resize works appropriately in older browsers and sometimes chrome. That will get you in the right direction.

How to get logged-in user's name in Access vba?

In a Form, Create a text box, with in text box properties select data tab

Default value =CurrentUser()

Current source "select table field name"

It will display current user log on name in text box / label as well as saves the user name in the table field

Eclipse: All my projects disappeared from Project Explorer

None of the answers provided here worked for me. My Enterprise Explorer was completely grey and I couldn't even import or reimport projects.

In my .metadata.log I saw this error:

assertion failed: working set with same name already registered

So I deleted these file:

.metadata.plugins\org.eclipse.ui.workbench\workingsets.xml

Now I can see all my projects. I didn't have to add them back again.

python: how to check if a line is an empty line

line.strip() == ''

Or, if you don't want to "eat up" lines consisting of spaces:

line in ('\n', '\r\n')

How to generate an MD5 file hash in JavaScript?

CryptoJS is a crypto library which can generate md5 hash among others:

Usage with Script tag:

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/md5.js"></script>
<script>
   var hash = CryptoJS.MD5("Message");
   alert(hash);
</script>

Alternatively with ES6:

npm install crypto-js

import MD5 from "crypto-js/md5";
console.log(MD5("Message").toString());

You can also use modular imports:

var MD5 = require("crypto-js/md5");
console.log(MD5("Message").toString());

Github: https://github.com/brix/crypto-js

CDN: https://cdnjs.com/libraries/crypto-js

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

Count number of rows per group and add result to original data frame

Another way that generalizes more:

df$count <- unsplit(lapply(split(df, df[c("name","type")]), nrow), df[c("name","type")])

How to remove \n from a list element?

from this link:

you can use rstrip() method. Example

mystring = "hello\n"    
print(mystring.rstrip('\n'))

How to copy a folder via cmd?

xcopy  e:\source_folder f:\destination_folder /e /i /h

The /h is just in case there are hidden files. The /i creates a destination folder if there are muliple source files.

remove inner shadow of text input

All browsers, including Safari (+ mobile):

input[type=text] {   
    /* Remove */
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    
    /* Optional */
    border: solid;
    box-shadow: none;
    /*etc.*/
}

Getting XML Node text value with Java DOM

I'd print out the result of an2.getNodeName() as well for debugging purposes. My guess is that your tree crawling code isn't crawling to the nodes that you think it is. That suspicion is enhanced by the lack of checking for node names in your code.

Other than that, the javadoc for Node defines "getNodeValue()" to return null for Nodes of type Element. Therefore, you really should be using getTextContent(). I'm not sure why that wouldn't give you the text that you want.

Perhaps iterate the children of your tag node and see what types are there?

Tried this code and it works for me:

String xml = "<add job=\"351\">\n" +
             "    <tag>foobar</tag>\n" +
             "    <tag>foobar2</tag>\n" +
             "</add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
Document doc = db.parse(bis);
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;

for (int i=0; i < nl.getLength(); i++) {
    an = nl.item(i);
    if(an.getNodeType()==Node.ELEMENT_NODE) {
        NodeList nl2 = an.getChildNodes();

        for(int i2=0; i2<nl2.getLength(); i2++) {
            an2 = nl2.item(i2);
            // DEBUG PRINTS
            System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getTextContent());
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getNodeValue());
            System.out.println(an2.getTextContent());
            System.out.println(an2.getNodeValue());
        }
    }
}

Output was:

#text: type (3): foobar foobar
#text: type (3): foobar2 foobar2

Regular Expression: Any character that is NOT a letter or number

To match anything other than letter or number or letter with diacritics like é you could try this:

[^\wÀ-úÀ-ÿ]

And to replace:

var str = 'dfj,dsf7é@lfsd .sdklfàj1';
str = str.replace(/[^\wÀ-úÀ-ÿ]/g, '_');

Inspired by the top post with support for diacritics

source

Wait for a void async method

I know this is an old question, but this is still a problem I keep walking into, and yet there is still no clear solution to do this correctly when using async/await in an async void signature method.

However, I noticed that .Wait() is working properly inside the void method.

and since async void and void have the same signature, you might need to do the following.

void LoadBlahBlah()
{
    blah().Wait(); //this blocks
}

Confusingly enough async/await does not block on the next code.

async void LoadBlahBlah()
{
    await blah(); //this does not block
}

When you decompile your code, my guess is that async void creates an internal Task (just like async Task), but since the signature does not support to return that internal Tasks

this means that internally the async void method will still be able to "await" internally async methods. but externally unable to know when the internal Task is complete.

So my conclusion is that async void is working as intended, and if you need feedback from the internal Task, then you need to use the async Task signature instead.

hopefully my rambling makes sense to anybody also looking for answers.

Edit: I made some example code and decompiled it to see what is actually going on.

static async void Test()
{
    await Task.Delay(5000);
}

static async Task TestAsync()
{
    await Task.Delay(5000);
}

Turns into (edit: I know that the body code is not here but in the statemachines, but the statemachines was basically identical, so I didn't bother adding them)

private static void Test()
{
    <Test>d__1 stateMachine = new <Test>d__1();
    stateMachine.<>t__builder = AsyncVoidMethodBuilder.Create();
    stateMachine.<>1__state = -1;
    AsyncVoidMethodBuilder <>t__builder = stateMachine.<>t__builder;
    <>t__builder.Start(ref stateMachine);
}
private static Task TestAsync()
{
    <TestAsync>d__2 stateMachine = new <TestAsync>d__2();
    stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
    stateMachine.<>1__state = -1;
    AsyncTaskMethodBuilder <>t__builder = stateMachine.<>t__builder;
    <>t__builder.Start(ref stateMachine);
    return stateMachine.<>t__builder.Task;
}

neither AsyncVoidMethodBuilder or AsyncTaskMethodBuilder actually have any code in the Start method that would hint of them to block, and would always run asynchronously after they are started.

meaning without the returning Task, there would be no way to check if it is complete.

as expected, it only starts the Task running async, and then it continues in the code. and the async Task, first it starts the Task, and then it returns it.

so I guess my answer would be to never use async void, if you need to know when the task is done, that is what async Task is for.

position fixed is not working

you need to give width explicitly to header and footer

width: 100%;

Working fiddle

If you want the middle section not to be hidden then give position: absolute;width: 100%; and set top and bottom properties (related to header and footer heights) to it and give parent element position: relative. (ofcourse, remove height: 700px;.) and to make it scrollable, give overflow: auto.

How do I make a simple crawler in PHP?

Here my implementation based on the above example/answer.

  1. It is class based
  2. uses Curl
  3. support HTTP Auth
  4. Skip Url not belonging to the base domain
  5. Return Http header Response Code for each page
  6. Return time for each page

CRAWL CLASS:

class crawler
{
    protected $_url;
    protected $_depth;
    protected $_host;
    protected $_useHttpAuth = false;
    protected $_user;
    protected $_pass;
    protected $_seen = array();
    protected $_filter = array();

    public function __construct($url, $depth = 5)
    {
        $this->_url = $url;
        $this->_depth = $depth;
        $parse = parse_url($url);
        $this->_host = $parse['host'];
    }

    protected function _processAnchors($content, $url, $depth)
    {
        $dom = new DOMDocument('1.0');
        @$dom->loadHTML($content);
        $anchors = $dom->getElementsByTagName('a');

        foreach ($anchors as $element) {
            $href = $element->getAttribute('href');
            if (0 !== strpos($href, 'http')) {
                $path = '/' . ltrim($href, '/');
                if (extension_loaded('http')) {
                    $href = http_build_url($url, array('path' => $path));
                } else {
                    $parts = parse_url($url);
                    $href = $parts['scheme'] . '://';
                    if (isset($parts['user']) && isset($parts['pass'])) {
                        $href .= $parts['user'] . ':' . $parts['pass'] . '@';
                    }
                    $href .= $parts['host'];
                    if (isset($parts['port'])) {
                        $href .= ':' . $parts['port'];
                    }
                    $href .= $path;
                }
            }
            // Crawl only link that belongs to the start domain
            $this->crawl_page($href, $depth - 1);
        }
    }

    protected function _getContent($url)
    {
        $handle = curl_init($url);
        if ($this->_useHttpAuth) {
            curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
            curl_setopt($handle, CURLOPT_USERPWD, $this->_user . ":" . $this->_pass);
        }
        // follows 302 redirect, creates problem wiht authentication
//        curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE);
        // return the content
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);

        /* Get the HTML or whatever is linked in $url. */
        $response = curl_exec($handle);
        // response total time
        $time = curl_getinfo($handle, CURLINFO_TOTAL_TIME);
        /* Check for 404 (file not found). */
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);

        curl_close($handle);
        return array($response, $httpCode, $time);
    }

    protected function _printResult($url, $depth, $httpcode, $time)
    {
        ob_end_flush();
        $currentDepth = $this->_depth - $depth;
        $count = count($this->_seen);
        echo "N::$count,CODE::$httpcode,TIME::$time,DEPTH::$currentDepth URL::$url <br>";
        ob_start();
        flush();
    }

    protected function isValid($url, $depth)
    {
        if (strpos($url, $this->_host) === false
            || $depth === 0
            || isset($this->_seen[$url])
        ) {
            return false;
        }
        foreach ($this->_filter as $excludePath) {
            if (strpos($url, $excludePath) !== false) {
                return false;
            }
        }
        return true;
    }

    public function crawl_page($url, $depth)
    {
        if (!$this->isValid($url, $depth)) {
            return;
        }
        // add to the seen URL
        $this->_seen[$url] = true;
        // get Content and Return Code
        list($content, $httpcode, $time) = $this->_getContent($url);
        // print Result for current Page
        $this->_printResult($url, $depth, $httpcode, $time);
        // process subPages
        $this->_processAnchors($content, $url, $depth);
    }

    public function setHttpAuth($user, $pass)
    {
        $this->_useHttpAuth = true;
        $this->_user = $user;
        $this->_pass = $pass;
    }

    public function addFilterPath($path)
    {
        $this->_filter[] = $path;
    }

    public function run()
    {
        $this->crawl_page($this->_url, $this->_depth);
    }
}

USAGE:

// USAGE
$startURL = 'http://YOUR_URL/';
$depth = 6;
$username = 'YOURUSER';
$password = 'YOURPASS';
$crawler = new crawler($startURL, $depth);
$crawler->setHttpAuth($username, $password);
// Exclude path with the following structure to be processed 
$crawler->addFilterPath('customer/account/login/referer');
$crawler->run();

How can I assign an ID to a view programmatically?

Android id overview

An Android id is an integer commonly used to identify views; this id can be assigned via XML (when possible) and via code (programmatically.) The id is most useful for getting references for XML-defined Views generated by an Inflater (such as by using setContentView.)

Assign id via XML

  • Add an attribute of android:id="@+id/somename" to your view.
  • When your application is built, the android:id will be assigned a unique int for use in code.
  • Reference your android:id's int value in code using "R.id.somename" (effectively a constant.)
  • this int can change from build to build so never copy an id from gen/package.name/R.java, just use "R.id.somename".
  • (Also, an id assigned to a Preference in XML is not used when the Preference generates its View.)

Assign id via code (programmatically)

  • Manually set ids using someView.setId(int);
  • The int must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)
  • For example, if creating and numbering several views representing items, you could use their item number.

Uniqueness of ids

  • XML-assigned ids will be unique.
  • Code-assigned ids do not have to be unique
  • Code-assigned ids can (theoretically) conflict with XML-assigned ids.
  • These conflicting ids won't matter if queried correctly (keep reading).

When (and why) conflicting ids don't matter

  • findViewById(int) will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View it finds with a matching id.
  • As long as there are no code-assigned ids assigned before an XML-defined id in the hierarchy, findViewById(R.id.somename) will always return the XML-defined View so id'd.

Dynamically Creating Views and Assigning IDs

  • In layout XML, define an empty ViewGroup with id.
  • Such as a LinearLayout with android:id="@+id/placeholder".
  • Use code to populate the placeholder ViewGroup with Views.
  • If you need or want, assign any ids that are convenient to each view.
  • Query these child views using placeholder.findViewById(convenientInt);

  • API 17 introduced View.generateViewId() which allows you to generate a unique ID.

If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext() and be sure to set each reference to null in onDestroy. Apparently leaking the Activity (hanging onto it after is is destroyed) is wasteful.. :)

Reserve an XML android:id for use in code

API 17 introduced View.generateViewId() which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*

If your ViewGroup cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:

Here, values/ids.xml defines a custom id:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="reservedNamedId" type="id"/>
</resources>

Then once the ViewGroup or View has been created, you can attach the custom id

myViewGroup.setId(R.id.reservedNamedId);

Conflicting id example

For clarity by way of obfuscating example, lets examine what happens when there is an id conflict behind the scenes.

layout/mylayout.xml

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

To simulate a conflict, lets say our latest build assigned R.id.placeholder(@+id/placeholder) an int value of 12..

Next, MyActivity.java defines some adds views programmatically (via code):

int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
    TextView tv = new TextView(this.getApplicationContext());
    // One new TextView will also be assigned an id==12:
    tv.setId(i);
    placeholder.addView(tv);
}

So placeholder and one of our new TextViews both have an id of 12! But this isn't really a problem if we query placeholder's child views:

// Will return a generated TextView:
 placeholder.findViewById(12);

// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12: 
Activity.this.findViewById(12);

*Not so bad

Get current user id in ASP.NET Identity 2.0

Just in case you are like me and the Id Field of the User Entity is an Int or something else other than a string,

using Microsoft.AspNet.Identity;

int userId = User.Identity.GetUserId<int>();

will do the trick

How to import multiple csv files in a single load?

Reader's Digest: (Spark 2.x)

For Example, if you have 3 directories holding csv files:

dir1, dir2, dir3

You then define paths as a string of comma delimited list of paths as follows:

paths = "dir1/,dir2/,dir3/*"

Then use the following function and pass it this paths variable

def get_df_from_csv_paths(paths):

        df = spark.read.format("csv").option("header", "false").\
            schema(custom_schema).\
            option('delimiter', '\t').\
            option('mode', 'DROPMALFORMED').\
            load(paths.split(','))
        return df

By then running:

df = get_df_from_csv_paths(paths)

You will obtain in df a single spark dataframe containing the data from all the csvs found in these 3 directories.

===========================================================================

Full Version:

In case you want to ingest multiple CSVs from multiple directories you simply need to pass a list and use wildcards.

For Example:

if your data_path looks like this:

's3://bucket_name/subbucket_name/2016-09-*/184/*,
s3://bucket_name/subbucket_name/2016-10-*/184/*,
s3://bucket_name/subbucket_name/2016-11-*/184/*,
s3://bucket_name/subbucket_name/2016-12-*/184/*, ... '

you can use the above function to ingest all the csvs in all these directories and subdirectories at once:

This would ingest all directories in s3 bucket_name/subbucket_name/ according to the wildcard patterns specified. e.g. the first pattern would look in

bucket_name/subbucket_name/

for all directories with names starting with

2016-09-

and for each of those take only the directory named

184

and within that subdirectory look for all csv files.

And this would be executed for each of the patterns in the comma delimited list.

This works way better than union..

Replace line break characters with <br /> in ASP.NET MVC Razor view

Omar's third solution as an HTML Helper would be:

public static IHtmlString FormatNewLines(this HtmlHelper helper, string input)
{
    return helper.Raw(helper.Encode(input).Replace("\n", "<br />"));
}

How to use wget in php?

lots of methods available in php to read a file like exec, file_get_contents, curl and fopen but it depend on your requirement and file permission

Visit this file_get_contents vs cUrl

Basically file_get_contents for for you

$data = file_get_contents($file_url);

undefined reference to boost::system::system_category() when compiling

...and in case you wanted to link your main statically, in your Jamfile add the following to requirements:

<link>static
<library>/boost/system//boost_system

and perhaps also:

<linkflags>-static-libgcc
<linkflags>-static-libstdc++

Test if characters are in a string

Use this function from stringi package:

> stri_detect_fixed("test",c("et","es"))
[1] FALSE  TRUE

Some benchmarks:

library(stringi)
set.seed(123L)
value <- stri_rand_strings(10000, ceiling(runif(10000, 1, 100))) # 10000 random ASCII strings
head(value)

chars <- "es"
library(microbenchmark)
microbenchmark(
   grepl(chars, value),
   grepl(chars, value, fixed=TRUE),
   grepl(chars, value, perl=TRUE),
   stri_detect_fixed(value, chars),
   stri_detect_regex(value, chars)
)
## Unit: milliseconds
##                               expr       min        lq    median        uq       max neval
##                grepl(chars, value) 13.682876 13.943184 14.057991 14.295423 15.443530   100
##  grepl(chars, value, fixed = TRUE)  5.071617  5.110779  5.281498  5.523421 45.243791   100
##   grepl(chars, value, perl = TRUE)  1.835558  1.873280  1.956974  2.259203  3.506741   100
##    stri_detect_fixed(value, chars)  1.191403  1.233287  1.309720  1.510677  2.821284   100
##    stri_detect_regex(value, chars)  6.043537  6.154198  6.273506  6.447714  7.884380   100

iPad/iPhone hover problem causes the user to double click a link

You can use click touchend ,

example:

$('a').on('click touchend', function() {
    var linkToAffect = $(this);
    var linkToAffectHref = linkToAffect.attr('href');
    window.location = linkToAffectHref;
});

Above example will affect all links on touch devices.

If you want to target only specific links, you can do this by setting a class on them, ie:

HTML:

<a href="example.html" class="prevent-extra-click">Prevent extra click on touch device</a>

Jquery:

$('a.prevent-extra-click').on('click touchend', function() {
    var linkToAffect = $(this);
    var linkToAffectHref = linkToAffect.attr('href');
    window.location = linkToAffectHref;
});

Cheers,

Jeroen

git: Switch branch and ignore any changes without committing

You need a clean state to change branches. The branch checkout will only be allowed if it does not affect the 'dirty files' (as Charles Bailey remarks in the comments).

Otherwise, you should either:

  • stash your current change or
  • reset --hard HEAD (if you do not mind losing those minor changes) or
  • checkout -f (When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes. )

Or, more recently:

Proceed even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.

This differs from git switch -m <branch-name>, which triggers a three-way merge between the current branch, your working tree contents, and the new branch is done: you won't loose your work in progress that way.

Xcode 10: A valid provisioning profile for this executable was not found

[edit] Note 2020: I used to manual sign this project. In projects where I automatically signed, I never had this issue. [/edit]

I had the same problem, and spent hours searching for an answer, removing profiles, cleaning project, and so on.

Have you distributed your app? You need to switch back to your developer profile, but not in General under the project settings, but in Build settings.

Under Signing, look at your Code Signing Identity.

Make sure that both your Debug and Release are set your iOS Developer, and not iOS Distribution; or your iOS Developer Provisioning profile, if not set to the automatic values.

The same goes with Provisioning Profile. It should be your developing profile, and not your distribution profile. enter image description here

Hope this will help future developers in need.

Use of True, False, and None as return values in Python functions

In the examples in PEP 8 (Style Guide for Python Code) document, I have seen that foo is None or foo is not None are being used instead of foo == None or foo != None.

Also using if boolean_value is recommended in this document instead of if boolean_value == True or if boolean_value is True. So I think if this is the official Python way. We Python guys should go on this way, too.

Running a command as Administrator using PowerShell?

A number of the answers here are close, but a little more work than needed.

Create a shortcut to your script and configure it to "Run as Administrator":

  • Create the shortcut.
  • Right-click shortcut and open Properties...
  • Edit Target from <script-path> to powershell <script-path>
  • Click Advanced... and enable Run as administrator

If Browser is Internet Explorer: run an alternative script instead

You can do something like this to include IE-specific javascript:

<!--[IF IE]>
    <script type="text/javascript">
        // IE stuff
    </script>
<![endif]-->

How to handle the new window in Selenium WebDriver using Java?

                string BaseWindow = driver.CurrentWindowHandle;
                ReadOnlyCollection<string> handles = driver.WindowHandles;
                foreach (string handle in handles)
                {
                    if (handle != BaseWindow)
                    {
                        string title = driver.SwitchTo().Window(handle).Title;
                        Thread.Sleep(3000);
                        driver.SwitchTo().Window(handle).Title.Equals(title);
                        Thread.Sleep(3000);
                    }
                }

How to convert HTML to PDF using iText

You can do it with the HTMLWorker class (deprecated) like this:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

or using the XMLWorker, (download from this jar) using this code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);
    document.open();
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

How to add elements of a string array to a string array list?

I prefer this,

List<String> temp = Arrays.asList(speciesArr);
species.addAll(temp);

The reason is Arrays.asList() method will create a fixed sized List. So if you directly store it into species then you will not be able to add any more element, still its not read-only. You can surely edit your items. So take it into temporary list.

Alternative for this is,

Collections.addAll(species, speciesArr);

In this case, you can add, edit, remove your items.

What's the difference between subprocess Popen and call (how can I use them)?

The other answer is very complete, but here is a rule of thumb:

  • call is blocking:

    call('notepad.exe')
    print('hello')  # only executed when notepad is closed
    
  • Popen is non-blocking:

    Popen('notepad.exe')
    print('hello')  # immediately executed
    

How to change angular port from 4200 to any other

It is not recommended to change in node modules as updates or re-installation may remove those changes. So better to change in angular cli

Angular 9 in angular.json

{
    "projects": {
            "targets": {
                "serve": {
                    "options": {
                         "port": 5000
                     }
                }     
            }     
    }
}  

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

Try this:

 >>> f = open('goodlines.txt')
 >>> mylist = f.readlines()

open() function returns a file object. And for file object, there is no method like splitlines() or split(). You could use dir(f) to see all the methods of file object.

Binding ComboBox SelectedItem using MVVM

I had a similar problem where the SelectedItem-binding did not update when I selected something in the combobox. My problem was that I had to set UpdateSourceTrigger=PropertyChanged for the binding.

<ComboBox ItemsSource="{Binding SalesPeriods}" 
          SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" />

Babel command not found

There are two problems here. First, you need a package.json file. Telling npm to install without one will throw the npm WARN enoent ENOENT: no such file or directory error. In your project directory, run npm init to generate a package.json file for the project.

Second, local binaries probably aren't found because the local ./node_modules/.bin is not in $PATH. There are some solutions in How to use package installed locally in node_modules?, but it might be easier to just wrap your babel-cli commands in npm scripts. This works because npm run adds the output of npm bin (node_modules/.bin) to the PATH provided to scripts.

Here's a stripped-down example package.json which returns the locally installed babel-cli version:

{
  "scripts": {
    "babel-version": "babel --version"
  },
  "devDependencies": {
    "babel-cli": "^6.6.5"
  }
}

Call the script with this command: npm run babel-version.

Putting scripts in package.json is quite useful but often overlooked. Much more in the docs: How npm handles the "scripts" field

SQL, Postgres OIDs, What are they and why are they useful?

OIDs basically give you a built-in id for every row, contained in a system column (as opposed to a user-space column). That's handy for tables where you don't have a primary key, have duplicate rows, etc. For example, if you have a table with two identical rows, and you want to delete the oldest of the two, you could do that using the oid column.

OIDs are implemented using 4-byte unsigned integers. They are not unique–OID counter will wrap around at 2³²-1. OID are also used to identify data types (see /usr/include/postgresql/server/catalog/pg_type_d.h).

In my experience, the feature is generally unused in most postgres-backed applications (probably in part because they're non-standard), and their use is essentially deprecated:

In PostgreSQL 8.1 default_with_oids is off by default; in prior versions of PostgreSQL, it was on by default.

The use of OIDs in user tables is considered deprecated, so most installations should leave this variable disabled. Applications that require OIDs for a particular table should specify WITH OIDS when creating the table. This variable can be enabled for compatibility with old applications that do not follow this behavior.

Case Statement Equivalent in R

I am using in those cases you are referring switch(). It looks like a control statement but actually, it is a function. The expression is evaluated and based on this value, the corresponding item in the list is returned.

switch works in two distinct ways depending whether the first argument evaluates to a character string or a number.

What follows is a simple string example which solves your problem to collapse old categories to new ones.

For the character-string form, have a single unnamed argument as the default after the named values.

newCat <- switch(EXPR = category,
       cat1   = catX,
       cat2   = catX,
       cat3   = catY,
       cat4   = catY,
       cat5   = catZ,
       cat6   = catZ,
       "not available")

How do I write out a text file in C# with a code page other than UTF-8?

Simple!

System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591));

In what cases do I use malloc and/or new?

Always use new in C++. If you need a block of untyped memory, you can use operator new directly:

void *p = operator new(size);
   ...
operator delete(p);

Percentage calculation

Using Math.Round():

int percentComplete = (int)Math.Round((double)(100 * complete) / total);

or manually rounding:

int percentComplete = (int)(0.5f + ((100f * complete) / total));

Google Chrome redirecting localhost to https

A simple solution to this is to edit your /etc/hosts file and establish one alias per project.

127.0.0.1   project1 project2 project3

These domainless names will never have the problem with HSTS unless you send the HSTS response mentioned by @bigjump and with the added benefit of maintaining your login session if you change back and forth between projects.