Programs & Examples On #Nsurlprotocol

NSURLProtocol is an abstract class that provides the basic structure for performing protocol-specific loading of URL data.

Failing to run jar file from command line: “no main manifest attribute”

Try to run

java -cp ScrumTimeCaptureMaintenence.jar Main

Circle-Rectangle collision detection (intersection)

Here is the modfied code 100% working:

public static bool IsIntersected(PointF circle, float radius, RectangleF rectangle)
{
    var rectangleCenter = new PointF((rectangle.X +  rectangle.Width / 2),
                                     (rectangle.Y + rectangle.Height / 2));

    var w = rectangle.Width  / 2;
    var h = rectangle.Height / 2;

    var dx = Math.Abs(circle.X - rectangleCenter.X);
    var dy = Math.Abs(circle.Y - rectangleCenter.Y);

    if (dx > (radius + w) || dy > (radius + h)) return false;

    var circleDistance = new PointF
                             {
                                 X = Math.Abs(circle.X - rectangle.X - w),
                                 Y = Math.Abs(circle.Y - rectangle.Y - h)
                             };

    if (circleDistance.X <= (w))
    {
        return true;
    }

    if (circleDistance.Y <= (h))
    {
        return true;
    }

    var cornerDistanceSq = Math.Pow(circleDistance.X - w, 2) + 
                                    Math.Pow(circleDistance.Y - h, 2);

    return (cornerDistanceSq <= (Math.Pow(radius, 2)));
}

Bassam Alugili

Adding a Scrollable JTextArea (Java)

It doesn't work because you didn't attach the ScrollPane to the JFrame.

Also, you don't need 2 JScrollPanes:

JFrame frame = new JFrame ("Test");
JTextArea textArea = new JTextArea ("Test");

JScrollPane scroll = new JScrollPane (textArea, 
   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

frame.add(scroll);
frame.setVisible (true);

Difference between one-to-many and many-to-one relationship

From this page about Database Terminology

Most relations between tables are one-to-many.

Example:

  • One area can be the habitat of many readers.
  • One reader can have many subscriptions.
  • One newspaper can have many subscriptions.

A Many to One relation is the same as one-to-many, but from a different viewpoint.

  • Many readers live in one area.
  • Many subscriptions can be of one and the same reader.
  • Many subscriptions are for one and the same newspaper.

How do I find which program is using port 80 in Windows?

Use this nifty freeware utility:

CurrPorts is network monitoring software that displays the list of all currently opened TCP/IP and UDP ports on your local computer.

Enter image description here

Easy way to write contents of a Java InputStream to an OutputStream

As WMR mentioned, org.apache.commons.io.IOUtils from Apache has a method called copy(InputStream,OutputStream) which does exactly what you're looking for.

So, you have:

InputStream in;
OutputStream out;
IOUtils.copy(in,out);
in.close();
out.close();

...in your code.

Is there a reason you're avoiding IOUtils?

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

HTTP status code 0 - Error Domain=NSURLErrorDomain?

Status code '0' can occur because of three reasons
1) The Client cannot connect to the server
2) The Client cannot receive the response within the timeout period
3) The Request was "stopped(aborted)" by the Client.

But these three reasons are not standardized

HTML code for an apostrophe

Depends on which apostrophe you are talking about: there’s &apos;, &lsquo;, &rsquo; and probably numerous other ones, depending on the context and the language you’re intending to write. And with a declared character encoding of e.g. UTF-8 you can also write them directly into your HTML: ', , .

Auto detect mobile browser (via user-agent?)

Have you considered using css3 media queries? In most cases you can apply some css styles specifically for the targeted device without having to create a separate mobile version of the site.

@media screen and (max-width:1025px) {
   #content {
     width: 100%;
   }
}

You can set the width to whatever you want, but 1025 will catch the iPad landscape view.

You'll also want to add the following meta tag to your head:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Check out this article over at HTML5 Rocks for some good examples

How to merge 2 List<T> and removing duplicate values from it in C#

why not simply eg

var newList = list1.Union(list2)/*.Distinct()*//*.ToList()*/;

oh ... according to the documentation you can leave out the .Distinct()

This method excludes duplicates from the return set

Jquery check if element is visible in viewport

You can see this example.

// Is this element visible onscreen?
var visible = $(#element).visible( detectPartial );

detectPartial :

  • True : the entire element is visible
  • false : part of the element is visible

visible is boolean variable which indicates if the element is visible or not.

How to enable C# 6.0 feature in Visual Studio 2013?

It is possible to use full C# 6.0 features in Visual Studio 2013 if you have Resharper.
You have to enable Resharper Build and voilá! In Resharper Options -> Build - enable Resharper Build and in "Use MSBuild.exe version" choose "Latest Installed"

This way Resharper is going to build your C# 6.0 Projects and will also not underline C# 6.0 code as invalid.

I am also using this although I have Visual Studio 2015 because:

  1. Unit Tests in Resharper don't work for me with Visual Studio 2015 for some reason
  2. VS 2015 uses a lot more memory than VS 2013.

I am putting this here, as I was looking for a solution for this problem for some time now and maybe it will help someone else.

How do I put a clear button inside my HTML text input box like the iPhone does?

You can't actually put it inside the text box unfortunately, only make it look like its inside it, which unfortunately means some css is needed :P

Theory is wrap the input in a div, take all the borders and backgrounds off the input, then style the div up to look like the box. Then, drop in your button after the input box in the code and the jobs a good'un.

Once you've got it to work anyway ;)

CSS : center form in page horizontally and vertically

I suggest you using bootstrap which works perfectly:

_x000D_
_x000D_
@import url('http://getbootstrap.com/dist/css/bootstrap.css');_x000D_
 html, body, .container-table {_x000D_
    height: 100%;_x000D_
}_x000D_
.container-table {_x000D_
    display: table;_x000D_
}_x000D_
.vertical-center-row {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0" />_x000D_
<title>Login Page | ... </title>_x000D_
_x000D_
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
 <div class="container container-table">_x000D_
  <div class="row vertical-center-row">_x000D_
   <div class="text-center col-md-4 col-md-offset-4" style="">_x000D_
      <form id="login" action="dashboard.html" method="post">_x000D_
     _x000D_
     <div class="username">_x000D_
      <div class="usernameinner">_x000D_
       <input type="text" name="username" id="username" placeholder="Login" />_x000D_
      </div>_x000D_
     </div>_x000D_
     _x000D_
     <div class="password">_x000D_
      <div class="passwordinner">_x000D_
       <input type="password" name="password" id="password" placeholder="Mot de passe" />_x000D_
      </div>_x000D_
     </div>_x000D_
     _x000D_
     <button id="login-button">Connexion</button>_x000D_
     _x000D_
     <div class="keep"><input type="checkbox" /> Gardez moi connecté</div>_x000D_
    _x000D_
    </form>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to avoid "StaleElementReferenceException" in Selenium?

Try this

while (true) { // loops forever until break
    try { // checks code for exceptions
        WebElement ele=
        (WebElement)wait.until(ExpectedConditions.elementToBeClickable((By.xpath(Xpath))));  
        break; // if no exceptions breaks out of loop
    } 
    catch (org.openqa.selenium.StaleElementReferenceException e1) { 
        Thread.sleep(3000); // you can set your value here maybe 2 secs
        continue; // continues to loop if exception is found
    }
}

How to add a ListView to a Column in Flutter?

Actually, when you read docs the ListView should be inside Expanded Widget so it can work.

  Widget build(BuildContext context) {
return Scaffold(
    body: Column(
  children: <Widget>[
    Align(
      child: PayableWidget(),
    ),
    Expanded(
      child: _myListView(context),
    )
  ],
));

}

Will Google Android ever support .NET?

Update: Since I wrote this answer two years ago, we productized Mono to run on Android. The work included a few steps: porting Mono to Android, integrating it with Visual Studio, building plugins for MonoDevelop on Mac and Windows and exposing the Java Android APIs to .NET languages. This is now available at http://monodroid.net

Mono on Android is based on the Mono 2.10 runtime, and defaults to 4.0 profile with the C# 4.0 compiler and uses Mono's new SGen garbage collection engine, as well as our new distributed garbage collection system that performs GC across Java and Mono.


The links below reflect Mono on Android as of January of 2009, I have kept them for historical context

Mono now works on Android thanks to the work of Koushik Dutta and Marc Crichton.

You can see a video of it running here: http://www.koushikdutta.com/2009/01/mono-on-android-with-gratuitous-shaky.html

And you can get the instructions to build Mono yourself here: http://www.koushikdutta.com/2009/01/building-mono-for-android.html

You can get a benchmark comparing Mono's JIT vs Dalvik's interpreter here: http://www.koushikdutta.com/2009/01/dalvik-vs-mono.html

And of course, you can get a pre-configured image with Mono here (go to the bottom of the post for details on using that): http://www.koushikdutta.com/2009/01/building-mono-for-android.html

Javascript regular expression password validation having special characters

function validatePassword() {
    var p = document.getElementById('newPassword').value,
        errors = [];
    if (p.length < 8) {
        errors.push("Your password must be at least 8 characters"); 
    }
    if (p.search(/[a-z]/i) < 0) {
        errors.push("Your password must contain at least one letter.");
    }
    if (p.search(/[0-9]/) < 0) {
        errors.push("Your password must contain at least one digit."); 
    }
    if (errors.length > 0) {
        alert(errors.join("\n"));
        return false;
    }
    return true;
}

There is a certain issue in below answer as it is not checking whole string due to absence of [ ] while checking the characters and numerals, this is correct version

How do I connect C# with Postgres?

Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):

In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.

Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.

Authentication failed to bitbucket

I tried everything else and found helpless but this indeed worked for me "To update your credentials, go to Control Panel -> Credential Manager -> Generic Credentials. Find the credentials related to your git account and edit them to use the updated passwords".

Above Solution found in this link: https://cmatskas.com/how-to-update-your-git-credentials-on-windows/

How to perform a fade animation on Activity transition?

you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...

View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);

React Js conditionally applying class attributes

Replace:

<div className="btn-group pull-right {this.props.showBulkActions ? 'show' : 'hidden'}">`

with:

<div className={`btn-group pull-right ${this.props.showBulkActions ? 'show' : 'hidden'}`}

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

Expansion of the same answer

  1. This SO post outlines in detail the overheads and storage mechanisms.
  2. As noted from point (1), A VARCHAR should always be used instead of TINYTEXT. However, when using VARCHAR, the max rowsize should not exceeed 65535 bytes.
  3. As outlined here http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-utf8.html, max 3 bytes for utf-8.

THIS IS A ROUGH ESTIMATION TABLE FOR QUICK DECISIONS!

  1. So the worst case assumptions (3 bytes per utf-8 char) to best case (1 byte per utf-8 char)
  2. Assuming the english language has an average of 4.5 letters per word
  3. x is the number of bytes allocated

x-x

      Type | A= worst case (x/3) | B = best case (x) | words estimate (A/4.5) - (B/4.5)
-----------+---------------------------------------------------------------------------
  TINYTEXT |              85     | 255               | 18 - 56
      TEXT |          21,845     | 65,535            | 4,854.44 - 14,563.33  
MEDIUMTEXT |       5,592,415     | 16,777,215        | 1,242,758.8 - 3,728,270
  LONGTEXT |   1,431,655,765     | 4,294,967,295     | 318,145,725.5 - 954,437,176.6

Please refer to Chris V's answer as well : https://stackoverflow.com/a/35785869/1881812

Import pandas dataframe column as string not int

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

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

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

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

Update as it helps others:

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

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

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

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

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

Use permission symbols instead of numbers

Your problem would have been avoided if you had used the more semantically named permission symbols rather than raw magic numbers, e.g. for 664:

#!/usr/bin/env python3

import os
import stat

os.chmod(
    'myfile',
    stat.S_IRUSR |
    stat.S_IWUSR |
    stat.S_IRGRP |
    stat.S_IWGRP |
    stat.S_IROTH
)

This is documented at https://docs.python.org/3/library/os.html#os.chmod and the names are the same as the POSIX C API values documented at man 2 stat.

Another advantage is the greater portability as mentioned in the docs:

Note: Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.

chmod +x is demonstrated at: How do you do a simple "chmod +x" from within python?

Tested in Ubuntu 16.04, Python 3.5.2.

How do you use script variables in psql?

Another approach is to (ab)use the PostgreSQL GUC mechanism to create variables. See this prior answer for details and examples.

You declare the GUC in postgresql.conf, then change its value at runtime with SET commands and get its value with current_setting(...).

I don't recommend this for general use, but it could be useful in narrow cases like the one mentioned in the linked question, where the poster wanted a way to provide the application-level username to triggers and functions.

What is the best way to remove the first element from an array?

Keep an index of the first "live" element of the array. Removing (pretending to remove) the first element then becomes an O(1) time complexity operation.

How to unlock android phone through ADB

Below commands works both when screen is on and off

To lock the screen:

adb shell input keyevent 82 && adb shell input keyevent 26 && adb shell input keyevent 26

To lock the screen and turn it off

adb shell input keyevent 82 && adb shell input keyevent 26

To unlock the screen without pass

adb shell input keyevent 82 && adb shell input keyevent 66

To unlock the screen that has pass 1234

adb shell input keyevent 82 && adb shell input text 1234 && adb shell input keyevent 66

Get all child elements

Here is a code to get the child elements (In java):

String childTag = childElement.getTagName();
if(childTag.equals("html")) 
{
    return "/html[1]"+current;
}
WebElement parentElement = childElement.findElement(By.xpath("..")); 
List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
int count = 0;
for(int i=0;i<childrenElements.size(); i++) 
{
    WebElement childrenElement = childrenElements.get(i);
    String childrenElementTag = childrenElement.getTagName();
    if(childTag.equals(childrenElementTag)) 
    {
        count++;
    }
 }

Text-align class for inside a table

You can use this CSS below:

.text-right {text-align: right} /* For right align */
.text-left {text-align: left} /* For left align */
.text-center {text-align: center} /* For center align */

Syntax behind sorted(key=lambda: ...)

Since the usage of lambda was asked in the context of sorted(), take a look at this as well https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions

Are one-line 'if'/'for'-statements good Python style?

for a in someList:
    list.append(splitColon.split(a))

You can rewrite the above as:

newlist = [splitColon.split(a) for a in someList]

Convert String XML fragment to Document Node in Java

...and if you're using purely XOM, something like this:

    String xml = "<fakeRoot>" + xml + "</fakeRoot>";
    Document doc = new Builder( false ).build( xml, null );
    Nodes children = doc.getRootElement().removeChildren();
    for( int ix = 0; ix < children.size(); ix++ ) {
        otherDocumentElement.appendChild( children.get( ix ) );
    }

XOM uses fakeRoot internally to do pretty much the same, so it should be safe, if not exactly elegant.

HTML display result in text (input) field?

innerHTML sets the text (including html elements) inside an element. Normally we use it for elements like div, span etc to insert other html elements inside it.

For your case you want to set the value of an input element. So you should use the value attribute.

Change innerHTML to value

document.getElementById('add').value = sum;

How to put more than 1000 values into an Oracle IN clause

Instead of SELECT * FROM table1 WHERE ID IN (1,2,3,4,...,1000);

Use this :

SELECT * FROM table1 WHERE ID IN (SELECT rownum AS ID FROM dual connect BY level <= 1000);

*Note that you need to be sure the ID does not refer any other foreign IDS if this is a dependency. To ensure only existing ids are available then :

SELECT * FROM table1 WHERE ID IN (SELECT distinct(ID) FROM tablewhereidsareavailable);

Cheers

Calling Scalar-valued Functions in SQL

Are you sure it's not a Table-Valued Function?

The reason I ask:

CREATE FUNCTION dbo.chk_mgr(@mgr VARCHAR(50)) 
RETURNS @mgr_table TABLE (mgr_name VARCHAR(50))
AS
BEGIN 
  INSERT @mgr_table (mgr_name) VALUES ('pointy haired boss') 
  RETURN
END 
GO

SELECT dbo.chk_mgr('asdf')
GO

Result:

Msg 4121, Level 16, State 1, Line 1
Cannot find either column "dbo" or the user-defined function 
or aggregate "dbo.chk_mgr", or the name is ambiguous.

However...

SELECT * FROM dbo.chk_mgr('asdf') 

mgr_name
------------------
pointy haired boss

CSS: 100% font size - 100% of what?

The browser default which is something like 16pt for Firefox, You can check by going into Firefox options, clicking the Content tab, and checking the font size. You can do the same for other browsers as well.

I personally like to control the default font size of my websites, so in a CSS file that is included in every page I will set the BODY default, like so:

body {
    font-family: Helvetica, Arial, sans-serif;
    font-size: 14px
}

Now the font-size of all my HTML tags will inherit a font-size of 14px.

Say that I want a all divs to have a font size 10% bigger than body, I simply do:

div {
    font-size: 110%
}

Now any browser that view my pages will autmoatically make all divs 10% bigger than that of the body, which should be something like 15.4px.

If I want the font-size of all div's to be 10% smaller, I do:

div {
    font-size: 90%
}

This will make all divs have a font-size of 12.6px.

Also you should know that since font-size is inherited, that each nested div will decrease in font size by 10%, so:

<div>Outer DIV.
    <div>Inner DIV</div>
</div>

The inner div will have a font-size of 11.34px (90% of 12.6px), which may not have been intended.

This can help in the explanation: http://www.w3.org/TR/2011/REC-CSS2-20110607/syndata.html#value-def-percentage

What JSON library to use in Scala?

Here is a basic implementation of writing and then reading json file using json4s.

import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.JsonDSL._
import java.io._
import scala.io.Source


object MyObject { def main(args: Array[String]) {

  val myMap = Map("a" -> List(3,4), "b" -> List(7,8))

  // writing a file 
  val jsonString = pretty(render(myMap))

  val pw = new PrintWriter(new File("my_json.json"))
  pw.write(jsonString)
  pw.close()

  // reading a file 
  val myString = Source.fromFile("my_json.json").mkString
  println(myString)

  val myJSON = parse(myString)

  println(myJSON)

  // Converting from JOjbect to plain object
  implicit val formats = DefaultFormats
  val myOldMap = myJSON.extract[Map[String, List[Int]]]

  println(myOldMap)
 }
}

Oracle database: How to read a BLOB?

What client do you use? .Net, Java, Ruby, SQLPLUS, SQL DEVELOPER? Where did you write that simple select statement?

And why do you want to read the content of the blob, a blob contains binary data so that data is unreadable. You should use a clob instead of a blob if you want to store text instead of binary content.

I suggest that you download SQL DEVELOPER: http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html . With SQL DEVELOPER you can see the content.

how to convert rgb color to int in java

You want to use intvalue = Color.parseColor("#" + colorobject);

Changing upload_max_filesize on PHP

Are you using a shared hosting provider? It could be master settings overriding anything you're trying to change. Have you tried adding those into your .htaccess?

php_value upload_max_filesize 10M
php_value post_max_size 10M

org.hibernate.PersistentObjectException: detached entity passed to persist

Here you have used native and assigning value to the primary key, in native primary key is auto generated.

Hence the issue is coming.

How to configure Spring Security to allow Swagger URL to be accessed without authentication

More or less this page has answers but all are not at one place. I was dealing with the same issue and spent quite a good time on it. Now i have a better understanding and i would like to share it here:

I Enabling Swagger ui with Spring websecurity:

If you have enabled Spring Websecurity by default it will block all the requests to your application and returns 401. However for the swagger ui to load in the browser swagger-ui.html makes several calls to collect data. The best way to debug is open swagger-ui.html in a browser(like google chrome) and use developer options('F12' key ). You can see several calls made when the page loads and if the swagger-ui is not loading completely probably some of them are failing.

you may need to tell Spring websecurity to ignore authentication for several swagger path patterns. I am using swagger-ui 2.9.2 and in my case below are the patterns that i had to ignore:

However if you are using a different version your's might change. you may have to figure out yours with developer option in your browser as i said before.

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", 
            "/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
            , "/webjars/**", "/csrf", "/");
}
}

II Enabling swagger ui with interceptor

Generally you may not want to intercept requests that are made by swagger-ui.html. To exclude several patterns of swagger below is the code:

Most of the cases pattern for web security and interceptor will be same.

@Configuration
@EnableWebMvc
public class RetrieveCiamInterceptorConfiguration implements WebMvcConfigurer {

@Autowired
RetrieveInterceptor validationInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {

    registry.addInterceptor(validationInterceptor).addPathPatterns("/**")
    .excludePathPatterns("/v2/api-docs", "/configuration/ui", 
            "/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
            , "/webjars/**", "/csrf", "/");
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
      .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

}

Since you may have to enable @EnableWebMvc to add interceptors you may also have to add resource handlers to swagger similar to i have done in the above code snippet.

Global variables in Java

To define Global Variable you can make use of static Keyword

public final class Tools {
  public static int a;
  public static int b;
}

now you can access a and b from anywhere by calling

Tools.a;
Tools.b;

Yoy are right...specially in J2ME... You can avoid NullPointerException by putting inside your MidLet constructor (proggy initialization) this line of code:

new Tools();

This ensures that Tools will be allocated before any instruction that uses it.

That's it!

How to add dll in c# project

The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.

I usually create a libs folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.

(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)

PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...

What does "Git push non-fast-forward updates were rejected" mean?

Never do a git -f to do push as it can result in later disastrous consequences.

You just need to do a git pull of your local branch.

Ex:

git pull origin 'your_local_branch'

and then do a git push

stale element reference: element is not attached to the page document

In my case, I had a page where it was an input type='date' whose reference I had got on page load, but When I tried to interact with it, it showed this exception and that was quite meaningful as Javascript had manipulated my control hence it was detached from the document and I had to re-get its reference after the javascript had performed its job with the control. So, this is how my code looked before the exception:

if (elemDate != null)
{ 
    elemDate.Clear(); 
    elemDate.SendKeys(model.Age);
}

Code after the exception was raised:

int tries = 0;
do
{
    try
    {
        tries++;
        if (elemDate != null)
        {
            // these lines were causing the exception so I had break after these are successfully executed because if they are executed that means the control was found and attached to the document and we have taken the reference of it again.
            elemDate.Clear();
            elemDate.SendKeys(model.Age);
            break;
        }
    }
    catch (StaleElementReferenceException)
    {
        System.Threading.Thread.Sleep(10); // put minor fake delay so Javascript on page does its actions with controls
        elemDate = driver.FindElement(By.Id(dateId));
    }
} while (tries < 3); // Try it three times.

So, Now you can perform further actions with your code or you can quit the driver if it was unsuccessful in getting the control to work.

if(tries > 2)
{
   // element was not found, find out what is causing the control detachment.
   // driver.Quit();
   return;
}

// Hurray!! Control was attached and actions were performed.
// Do something with it...

Something that I have learnt so far is, catching exceptions to know about successful code execution is not a good idea, But, I had to do it and I found this work-around to be working well in this case.

PS: After writing all this, I just noticed the tags that this thread was for java. This code sample is just for demonstration purpose, It might help people who have issue in C# language. Or it can be easily translated to java as it doesn't have much C# specific code.

Drop all duplicate rows across multiple columns in Python Pandas

Try these various things

df = pd.DataFrame({"A":["foo", "foo", "foo", "bar","foo"], "B":[0,1,1,1,1], "C":["A","A","B","A","A"]})

>>>df.drop_duplicates( "A" , keep='first')

or

>>>df.drop_duplicates( keep='first')

or

>>>df.drop_duplicates( keep='last')

Tomcat Servlet: Error 404 - The requested resource is not available

For those stuck with "The requested resource is not available" in Java EE 7 and dynamic web module 3.x, maybe this could help: the "Create Servlet" wizard in Eclipse (tested in Mars) doesn't create the @Path annotation for the servlet class, but I had to include it to access successfuly to the public methods exposed.

Difference between Eclipse Europa, Helios, Galileo

They are successive, improved versions of the same product. Anyone noticed how the names of the last three and the next release are in alphabetical order (Galileo, Helios, Indigo, Juno)? This is probably how they will go in the future, in the same way that Ubuntu release codenames increase alphabetically (note Indigo is not a moon of Jupiter!).

Update Fragment from ViewPager

Update Fragment from ViewPager

You need to implement getItemPosition(Object obj) method.

This method is called when you call

notifyDataSetChanged()

on your ViewPagerAdaper. Implicitly this method returns POSITION_UNCHANGED value that means something like this: "Fragment is where it should be so don't change anything."

So if you need to update Fragment you can do it with:

  • Always return POSITION_NONE from getItemPosition() method. It which means: "Fragment must be always recreated"
  • You can create some update() method that will update your Fragment(fragment will handle updates itself)

Example of second approach:

public interface Updateable {
   public void update();
}


public class MyFragment extends Fragment implements Updateable {

   ...

   public void update() {
     // do your stuff
   }
}

And in FragmentPagerAdapter you'll do something like this:

@Override
public int getItemPosition(Object object) {
   MyFragment f = (MyFragment ) object;
   if (f != null) {
      f.update();
   }
  return super.getItemPosition(object);
}

And if you'll choose first approach it can looks like:

@Override
public int getItemPosition(Object object) {
   return POSITION_NONE;
}

Note: It's worth to think a about which approach you'll pick up.

Visual Studio 2015 installer hangs during install?

Mine got stuck applying the .NET 4.6.1 blah... Turning off the internet and disabling Microsoft Security Essentials Real-time protection got things moving again.

PHP - how to create a newline character?

Use chr (13) for carriage return and chr (10) for new line

echo $clientid;
echo ' ';
echo $lastname;
echo ' ';
echo chr (13). chr (10);

<hr> tag in Twitter Bootstrap not functioning correctly?

You may want one of these, so to correspond to the Bootstrap layout:

<div class="col-xs-12">
    <hr >
</div>

<!-- or -->

<div class="col-xs-12">
    <hr style="border-style: dashed; border-top-width: 2px;">
</div>

<!-- or -->

<div class="col-xs-12">
    <hr class="col-xs-1" style="border-style: dashed; border-top-width: 2px;">
</div>

Without a DIV grid element included, layout may brake on different devices.

What does "yield break;" do in C#?

It specifies that an iterator has come to an end. You can think of yield break as a return statement which does not return a value.

For example, if you define a function as an iterator, the body of the function may look like this:

for (int i = 0; i < 5; i++)
{
    yield return i;
}

Console.Out.WriteLine("You will see me");

Note that after the loop has completed all its cycles, the last line gets executed and you will see the message in your console app.

Or like this with yield break:

int i = 0;
while (true)
{
    if (i < 5)
    {
        yield return i;
    }
    else
    {
        // note that i++ will not be executed after this
        yield break;
    }
    i++;
}

Console.Out.WriteLine("Won't see me");

In this case the last statement is never executed because we left the function early.

How to transfer some data to another Fragment?

            First Fragment Sending String To Next Fragment
            public class MainActivity extends AppCompatActivity {
                    private Button Add;
                    private EditText edt;
                    FragmentManager fragmentManager;
                    FragClass1 fragClass1;


                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                        Add= (Button) findViewById(R.id.BtnNext);
                        edt= (EditText) findViewById(R.id.editText);

                        Add.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                fragClass1=new FragClass1();
                                Bundle bundle=new Bundle();

                                fragmentManager=getSupportFragmentManager();
                                fragClass1.setArguments(bundle);
                                bundle.putString("hello",edt.getText().toString());
                                FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
                                fragmentTransaction.add(R.id.activity_main,fragClass1,"");
                                fragmentTransaction.addToBackStack(null);
                                fragmentTransaction.commit();

                            }
                        });
                    }
                }
         Next Fragment to fetch the string.
            public class FragClass1 extends Fragment {
                  EditText showFrag1;


                    @Nullable
                    @Override
                    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

                        View view=inflater.inflate(R.layout.lay_frag1,null);
                        showFrag1= (EditText) view.findViewById(R.id.edtText);
                        Bundle bundle=getArguments();
                        String a=getArguments().getString("hello");//Use This or The Below Commented Code
                        showFrag1.setText(a);
                        //showFrag1.setText(String.valueOf(bundle.getString("hello")));
                        return view;
                    }
                }
    I used Frame Layout easy to use.
    Don't Forget to Add Background color or else fragment will overlap.
This is for First Fragment.
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@color/colorPrimary"
        tools:context="com.example.sumedh.fragmentpractice1.MainActivity">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:id="@+id/BtnNext"/>
    </FrameLayout>


Xml for Next Fragment.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
   android:background="@color/colorAccent"
    android:layout_height="match_parent">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edtText"/>

</LinearLayout>

How to create jobs in SQL Server Express edition

SQL Server Express doesn't include SQL Server Agent, so it's not possible to just create SQL Agent jobs.

What you can do is:
You can create jobs "manually" by creating batch files and SQL script files, and running them via Windows Task Scheduler.
For example, you can backup your database with two files like this:

backup.bat:

sqlcmd -i backup.sql

backup.sql:

backup database TeamCity to disk = 'c:\backups\MyBackup.bak'

Just put both files into the same folder and exeute the batch file via Windows Task Scheduler.

The first file is just a Windows batch file which calls the sqlcmd utility and passes a SQL script file.
The SQL script file contains T-SQL. In my example, it's just one line to backup a database, but you can put any T-SQL inside. For example, you could do some UPDATE queries instead.


If the jobs you want to create are for backups, index maintenance or integrity checks, you could also use the excellent Maintenance Solution by Ola Hallengren.

It consists of a bunch of stored procedures (and SQL Agent jobs for non-Express editions of SQL Server), and in the FAQ there’s a section about how to run the jobs on SQL Server Express:

How do I get started with the SQL Server Maintenance Solution on SQL Server Express?

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

  1. Download MaintenanceSolution.sql.

  2. Execute MaintenanceSolution.sql. This script creates the stored procedures that you need.

  3. Create cmd files to execute the stored procedures; for example:
    sqlcmd -E -S .\SQLEXPRESS -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'USER_DATABASES', @Directory = N'C:\Backup', @BackupType = 'FULL'" -b -o C:\Log\DatabaseBackup.txt

  4. In Windows Scheduled Tasks, create tasks to call the cmd files.

  5. Schedule the tasks.

  6. Start the tasks and verify that they are completing successfully.

A potentially dangerous Request.Path value was detected from the client (*)

This exception occurred in my application and was rather misleading.

It was thrown when I was calling an .aspx page Web Method using an ajax method call, passing a JSON array object. The Web Page method signature contained an array of a strongly-typed .NET object, OrderDetails. The Actual_Qty property was defined as an int, and the JSON object Actual_Qty property contained "4 " (extra space character). After removing the extra space, the conversion was made possible, the Web Page method was successfully reached by the ajax call.

How to disable sort in DataGridView?

I was looking for a way to disable my already existing DataGridView and came across several answers. Oddly enough, the first few results on google were some very old topics. This being the earliest one of them, I decide to put my answer here.

private void dgvDetails_ColumnStateChanged(object sender, DataGridViewColumnStateChangedEventArgs e)
{
    e.Column.SortMode = DataGridViewColumnSortMode.NotSortable;
}

The description when you click on ColumStateChanged in the properties window is:

"Occurs when a column changes state, such as gaining or loosing focus"

Granted there are many ways to do this but I thought I'd add this one here. Can't say I found it anywhere else but then again I only read the first 5 topics I found.

Configuring Hibernate logging using Log4j XML config file?

From http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-logging

Here's the list of logger categories:

Category                    Function

org.hibernate.SQL           Log all SQL DML statements as they are executed
org.hibernate.type          Log all JDBC parameters
org.hibernate.tool.hbm2ddl  Log all SQL DDL statements as they are executed
org.hibernate.pretty        Log the state of all entities (max 20 entities) associated with the session at flush time
org.hibernate.cache         Log all second-level cache activity
org.hibernate.transaction   Log transaction related activity
org.hibernate.jdbc          Log all JDBC resource acquisition
org.hibernate.hql.ast.AST   Log HQL and SQL ASTs during query parsing
org.hibernate.secure        Log all JAAS authorization requests
org.hibernate               Log everything (a lot of information, but very useful for troubleshooting) 

Formatted for pasting into a log4j XML configuration file:

<!-- Log all SQL DML statements as they are executed -->
<Logger name="org.hibernate.SQL" level="debug" />
<!-- Log all JDBC parameters -->
<Logger name="org.hibernate.type" level="debug" />
<!-- Log all SQL DDL statements as they are executed -->
<Logger name="org.hibernate.tool.hbm2ddl" level="debug" />
<!-- Log the state of all entities (max 20 entities) associated with the session at flush time -->
<Logger name="org.hibernate.pretty" level="debug" />
<!-- Log all second-level cache activity -->
<Logger name="org.hibernate.cache" level="debug" />
<!-- Log transaction related activity -->
<Logger name="org.hibernate.transaction" level="debug" />
<!-- Log all JDBC resource acquisition -->
<Logger name="org.hibernate.jdbc" level="debug" />
<!-- Log HQL and SQL ASTs during query parsing -->
<Logger name="org.hibernate.hql.ast.AST" level="debug" />
<!-- Log all JAAS authorization requests -->
<Logger name="org.hibernate.secure" level="debug" />
<!-- Log everything (a lot of information, but very useful for troubleshooting) -->
<Logger name="org.hibernate" level="debug" />

NB: Most of the loggers use the DEBUG level, however org.hibernate.type uses TRACE. In previous versions of Hibernate org.hibernate.type also used DEBUG, but as of Hibernate 3 you must set the level to TRACE (or ALL) in order to see the JDBC parameter binding logging.

And a category is specified as such:

<logger name="org.hibernate">
    <level value="ALL" />
    <appender-ref ref="FILE"/>
</logger>

It must be placed before the root element.

dll missing in JDBC

Alright guys, I found it out! I didn't really need to change the java.library.path but the "Native library location" of sqljdbc.jar

This is the best answer I could find: https://stackoverflow.com/a/958074/2000342

It works now, thanks for the support!

How do you count the elements of an array in java

There is no built-in functionality for this. This count is in its whole user-specific. Maintain a counter or whatever.

PuTTY scripting to log onto host

When you use the -m option putty does not allocate a tty, it runs the command and quits. If you want to run an interactive script (such as a sql client), you need to tell it to allocate a tty with -t, see 3.8.3.12 -t and -T: control pseudo-terminal allocation. You'll avoid keeping a script on the server, as well as having to invoke it once you're connected.

Here's what I'm using to connect to mysql from a batch file:

#mysql.bat start putty -t -load "sessionname" -l username -pw password -m c:\mysql.sh

#mysql.sh mysql -h localhost -u username --password="foo" mydb

https://superuser.com/questions/587629/putty-run-a-remote-command-after-login-keep-the-shell-running

Android Studio Gradle Already disposed Module

If gradle clean and/or Build -> Clean Project didn't help try to re-open the project:

  • Close the project
  • Click "Open an existing Android Studio project" on the "Welcome to Android Studio" screen enter image description here
  • Select gradle file to open

Warning Be aware it's a destructive operation - you're going to loose the project bookmarks, breakpoints and shelves

Set default option in mat-select

On your typescript file, just assign this domain on modeSelect on Your ngOnInit() method like below:



 ngOnInit() {
        this.modeSelect = "domain";
      }

And on your html, use your select list.

<mat-form-field>
        <mat-select  [(value)]="modeSelect" placeholder="Mode">
          <mat-option value="domain">Domain</mat-option>
          <mat-option value="exact">Exact</mat-option>
        </mat-select>
      </mat-form-field>

Android ListView not refreshing after notifyDataSetChanged

adpter.notifyDataSetInvalidated();

Try this in onPause() method of Activity class.

java.io.FileNotFoundException: (Access is denied)

You cannot open and read a directory, use the isFile() and isDirectory() methods to distinguish between files and folders. You can get the contents of folders using the list() and listFiles() methods (for filenames and Files respectively) you can also specify a filter that selects a subset of files listed.

How to get only the last part of a path in Python?

You could do

>>> import os
>>> os.path.basename('/folderA/folderB/folderC/folderD')

UPDATE1: This approach works in case you give it /folderA/folderB/folderC/folderD/xx.py. This gives xx.py as the basename. Which is not what you want I guess. So you could do this -

>>> import os
>>> path = "/folderA/folderB/folderC/folderD"
>>> if os.path.isdir(path):
        dirname = os.path.basename(path)

UPDATE2: As lars pointed out, making changes so as to accomodate trailing '/'.

>>> from os.path import normpath, basename
>>> basename(normpath('/folderA/folderB/folderC/folderD/'))
'folderD'

Rename specific column(s) in pandas

There are at least five different ways to rename specific columns in pandas, and I have listed them below along with links to the original answers. I also timed these methods and found them to perform about the same (though YMMV depending on your data set and scenario). The test case below is to rename columns A M N Z to A2 M2 N2 Z2 in a dataframe with columns A to Z containing a million rows.

# Import required modules
import numpy as np
import pandas as pd
import timeit

# Create sample data
df = pd.DataFrame(np.random.randint(0,9999,size=(1000000, 26)), columns=list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))

# Standard way - https://stackoverflow.com/a/19758398/452587
def method_1():
    df_renamed = df.rename(columns={'A': 'A2', 'M': 'M2', 'N': 'N2', 'Z': 'Z2'})

# Lambda function - https://stackoverflow.com/a/16770353/452587
def method_2():
    df_renamed = df.rename(columns=lambda x: x + '2' if x in ['A', 'M', 'N', 'Z'] else x)

# Mapping function - https://stackoverflow.com/a/19758398/452587
def rename_some(x):
    if x=='A' or x=='M' or x=='N' or x=='Z':
        return x + '2'
    return x
def method_3():
    df_renamed = df.rename(columns=rename_some)

# Dictionary comprehension - https://stackoverflow.com/a/58143182/452587
def method_4():
    df_renamed = df.rename(columns={col: col + '2' for col in df.columns[
        np.asarray([i for i, col in enumerate(df.columns) if 'A' in col or 'M' in col or 'N' in col or 'Z' in col])
    ]})

# Dictionary comprehension - https://stackoverflow.com/a/38101084/452587
def method_5():
    df_renamed = df.rename(columns=dict(zip(df[['A', 'M', 'N', 'Z']], ['A2', 'M2', 'N2', 'Z2'])))

print('Method 1:', timeit.timeit(method_1, number=10))
print('Method 2:', timeit.timeit(method_2, number=10))
print('Method 3:', timeit.timeit(method_3, number=10))
print('Method 4:', timeit.timeit(method_4, number=10))
print('Method 5:', timeit.timeit(method_5, number=10))

Output:

Method 1: 3.650640267
Method 2: 3.163998427
Method 3: 2.998530871
Method 4: 2.9918436889999995
Method 5: 3.2436501520000007

Use the method that is most intuitive to you and easiest for you to implement in your application.

Asking the user for input until they give a valid response

You can always apply simple if-else logic and add one more if logic to your code along with a for loop.

while True:
     age = int(input("Please enter your age: "))
     if (age >= 18)  : 
         print("You are able to vote in the United States!")
     if (age < 18) & (age > 0):
         print("You are not able to vote in the United States.")
     else:
         print("Wrong characters, the input must be numeric")
         continue

This will be an infinite loo and you would be asked to enter the age, indefinitely.

SQL command to display history of queries

Look at ~/.myslgui/query-browser/history.xml here you can find the last queries made with mysql_query_browser (some days old)

dplyr change many data types

Dplyr across function has superseded _if, _at, and _all. See vignette("colwise").

dat %>% 
mutate(across(all_of(l1), as.factor),
       across(all_of(l2), as.numeric))

Error CS1705: "which has a higher version than referenced assembly"

In our team we were working on different computers with git. Someone updated a dll and I didn't had it. I just updated my dependencies references and the problem solved.

SQL not a single-group group function

Well the problem simply-put is that the SUM(TIME) for a specific SSN on your query is a single value, so it's objecting to MAX as it makes no sense (The maximum of a single value is meaningless).

Not sure what SQL database server you're using but I suspect you want a query more like this (Written with a MSSQL background - may need some translating to the sql server you're using):

SELECT TOP 1 SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
ORDER BY 2 DESC

This will give you the SSN with the highest total time and the total time for it.

Edit - If you have multiple with an equal time and want them all you would use:

SELECT
SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
HAVING SUM(TIME)=(SELECT MAX(SUM(TIME)) FROM downloads GROUP BY SSN))

Getting year in moment.js

The year() function just retrieves the year component of the underlying Date object, so it returns a number.

Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY, then the result will be a string containing the year.

If all you need is the year, then use the year() function. It will be faster, as there is less work to do.

Do note that while years are the same in this regard, months are not! Calling format('M') will return months in the range 1-12. Calling month() will return months in the range 0-11. This is due to the same behavior of the underlying Date object.

How to check if a specific key is present in a hash or not?

While Hash#has_key? gets the job done, as Matz notes here, it has been deprecated in favour of Hash#key?.

hash.key?(some_key)

How can I get the value of a registry key from within a batch script?

For Windows 7 (Professional, 64-bit - can't speak for the others) I see that REG no longer spits out

! REG.EXE VERSION 3.0

as it does in XP. So the above needs to be modified to use

skip=2

instead of 4 - which makes things messy if you want your script to be portable. Although it's much more heavyweight and complex, a WMIC based solution may be better.

How do I rename the extension for a bunch of files?

Unfortunately it's not trivial to do portably. You probably need a bit of expr magic.

for file in *.html; do echo mv -- "$file" "$(expr "$file" : '\(.*\)\.html').txt"; done

Remove the echo once you're happy it does what you want.

Edit: basename is probably a little more readable for this particular case, although expr is more flexible in general.

How to ping a server only once from within a batch file?

Having 2 scripts called test.bat and ping.bat in same folder:

Script test.bat contains one line:

ping google.com

Script ping.bat contains below lines:

@echo off
echo Hello!
pause

Executing "test.bat" the result on CMD will be:

Hello!
Press any key to continue . . .

Why? Because "test.bat" is calling the "ping.bat" ("ping google.com" is interpreted as calling the "ping.bat" script). Same is happening if script "ping.bat" contains "ping google.com". The script will execute himself in a loop.

Easy ways to avoid this:

  1. Do not name your script "ping.bat".
  2. You can name the script as "ping.bat" but inside the script use "ping.exe google.com" instead of "ping google.com".

How to get the height of a body element

$(document).height() seems to do the trick and gives the total height including the area which is only visible through scrolling.

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

Another flexible way using classpath containing fat jar (-cp fat.jar) or all jars (-cp "$JARS_DIR/*") and another custom config classpath or folder containing configuration files usually elsewhere and outside jar. So instead of the limited java -jar, use the more flexible classpath way as follows:

java \
   -cp fat_app.jar \ 
   -Dloader.path=<path_to_your_additional_jars or config folder> \
   org.springframework.boot.loader.PropertiesLauncher

See Spring-boot executable jar doc and this link

If you do have multiple MainApps which is common, you can use How do I tell Spring Boot which main class to use for the executable jar?

You can add additional locations by setting an environment variable LOADER_PATH or loader.path in loader.properties (comma-separated list of directories, archives, or directories within archives). Basically loader.path works for both java -jar or java -cp way.

And as always you can override and exactly specify the application.yml it should pickup for debugging purpose

--spring.config.location=/some-location/application.yml --debug

Get event listeners attached to node using addEventListener

Chrome DevTools, Safari Inspector and Firebug support getEventListeners(node).

getEventListeners(document)

How to access the correct `this` inside a callback?

this in JS:

The value of this in JS is 100% determined by how a function is called, and not how it is defined. We can relatively easily find the value of this by the 'left of the dot rule':

  1. When the function is created using the function keyword the value of this is the object left of the dot of the function which is called
  2. If there is no object left of the dot then the value of this inside a function is often the global object (global in node, window in browser). I wouldn't recommend using the this keyword here because it is less explicit than using something like window!
  3. There exist certain constructs like arrow functions and functions created using the Function.prototype.bind() a function that can fix the value of this. These are exceptions of the rule but are really helpful to fix the value of this.

Example in nodeJS

module.exports.data = 'module data';
// This outside a function in node refers to module.exports object
console.log(this);

const obj1 = {
    data: "obj1 data",
    met1: function () {
        console.log(this.data);
    },
    met2: () => {
        console.log(this.data);
    },
};

const obj2 = {
    data: "obj2 data",
    test1: function () {
        console.log(this.data);
    },
    test2: function () {
        console.log(this.data);
    }.bind(obj1),
    test3: obj1.met1,
    test4: obj1.met2,
};

obj2.test1();
obj2.test2();
obj2.test3();
obj2.test4();
obj1.met1.call(obj2);

Output:

enter image description here

Let me walk you through the outputs 1 by 1 (ignoring the first log starting from the second):

  1. this is obj2 because of the left of the dot rule, we can see how test1 is called obj2.test1();. obj2 is left of the dot and thus the this value.
  2. Even though obj2 is left of the dot, test2 is bound to obj1 via the bind() method. So the this value is obj1.
  3. obj2 is left of the dot from the function which is called: obj2.test3(). Therefore obj2 will be the value of this.
  4. In this case: obj2.test4() obj2 is left of the dot. However, arrow functions don't have their own this binding. Therefore it will bind to the this value of the outer scope which is the module.exports an object which was logged in the beginning.
  5. We can also specify the value of this by using the call function. Here we can pass in the desired this value as an argument, which is obj2 in this case.

Type safety: Unchecked cast

As the messages above indicate, the List cannot be differentiated between a List<Object> and a List<String> or List<Integer>.

I've solved this error message for a similar problem:

List<String> strList = (List<String>) someFunction();
String s = strList.get(0);

with the following:

List<?> strList = (List<?>) someFunction();
String s = (String) strList.get(0);

Explanation: The first type conversion verifies that the object is a List without caring about the types held within (since we cannot verify the internal types at the List level). The second conversion is now required because the compiler only knows the List contains some sort of objects. This verifies the type of each object in the List as it is accessed.

What is the idiomatic Go equivalent of C's ternary operator?

The map ternary is easy to read without parentheses:

c := map[bool]int{true: 1, false: 0} [5 > 4]

set option "selected" attribute from dynamic created option

// Get <select> object
var sel = $('country');

// Loop through and look for value match, then break
for(i=0;i<sel.length;i++) { if(sel.value=="ID") { break; } }

// Select index 
sel.options.selectedIndex = i;

Begitu loh.

Remove Unnamed columns in pandas dataframe

First, find the columns that have 'unnamed', then drop those columns. Note: You should Add inplace = True to the .drop parameters as well.

df.drop(df.columns[df.columns.str.contains('unnamed',case = False)],axis = 1, inplace = True)

How to generate the "create table" sql statement for an existing table in postgreSQL

Generate the create table statement for a table in postgresql from linux commandline:

Create a table for a demo:

CREATE TABLE your_table(
    thekey   integer NOT NULL,  ticker   character varying(10) NOT NULL,
    date_val date,              open_val numeric(10,4) NOT NULL
); 

pg_dump can output the table-create psql:

pg_dump -U your_user your_database -t your_table --schema-only

Which prints:

-- pre-requisite database and table configuration omitted
CREATE TABLE your_table (                                                                                                      
    thekey integer NOT NULL,                                                                                                   
    ticker character varying(10) NOT NULL,                                                                                     
    date_val date,                                                                                                             
    open_val numeric(10,4) NOT NULL                                                                                            
);                                                                                                                   
-- post-requisite database and table configuration omitted
  

Explanation:

pg_dump helps us get information about the database itself. -U stands for username. My pgadmin user has no password set, so I don't have to put in a password. The -t option means specify for one table. --schema-only means print only data about the table, and not the data in the table. Here is the exact command I use:

Get the table name and datatype information from postgresql with SQL:

CREATE TABLE your_table(  thekey integer NOT NULL,
                          ticker character varying(10) NOT NULL,
                          date_val date,
                          open_val numeric(10,4) NOT NULL
); 

SELECT table_name, column_name, data_type 
FROM information_schema.columns 
WHERE table_name = 'your_table'; 

Which prints:

+----------------------------------------------+ 
¦ table_name ¦ column_name ¦     data_type     ¦ 
+------------+-------------+-------------------¦ 
¦ your_table ¦ thekey      ¦ integer           ¦ 
¦ your_table ¦ ticker      ¦ character varying ¦ 
¦ your_table ¦ date_val    ¦ date              ¦ 
¦ your_table ¦ open_val    ¦ numeric           ¦ 
+----------------------------------------------+ 

How can I maintain fragment state when added to the back stack?

onSaveInstanceState() is only called if there is configuration change.

Since changing from one fragment to another there is no configuration change so no call to onSaveInstanceState() is there. What state is not being save? Can you specify?

If you enter some text in EditText it will be saved automatically. Any UI item without any ID is the item whose view state shall not be saved.

Format date with Moment.js

You Probably Don't Need Moment.js Anymore

Moment is great time manipulation library but it's considered as a legacy project, and the team is recommending to use other libraries.

date-fns is one of the best lightweight libraries, it's modular, so you can pick the functions you need and reduce bundle size (issue & statement).

Another common argument against using Moment in modern applications is its size. Moment doesn't work well with modern "tree shaking" algorithms, so it tends to increase the size of web application bundles.

import { format } from 'date-fns' // 21K (gzipped: 5.8K)
import moment from 'moment' // 292.3K (gzipped: 71.6K)

Format date with date-fns:

// moment.js
moment().format('MM/DD/YYYY');
// => "12/18/2020"

// date-fns
import { format } from 'date-fns'
format(new Date(), 'MM/dd/yyyy');
// => "12/18/2020"

More on cheat sheet with the list of functions which you can use to replace moment.js: You-Dont-Need-Momentjs

How to execute cmd commands via Java

The code you posted starts three different processes each with it's own command. To open a command prompt and then run a command try the following (never tried it myself):

try {
    // Execute command
    String command = "cmd /c start cmd.exe";
    Process child = Runtime.getRuntime().exec(command);

    // Get output stream to write from it
    OutputStream out = child.getOutputStream();

    out.write("cd C:/ /r/n".getBytes());
    out.flush();
    out.write("dir /r/n".getBytes());
    out.close();
} catch (IOException e) {
}

How do I drop table variables in SQL-Server? Should I even do this?

Temp table variable is saved to the temp.db and the scope is limited to the current execution. Hence, unlike dropping a Temp tables e.g drop table #tempTable, we don't have to explicitly drop Temp table variable @tempTableVariable. It is automatically taken care by the sql server.

drop table @tempTableVariable -- Invalid

How do I capture response of form.submit

I am not sure that you understand what submit() does...

When you do form1.submit(); the form information is sent to the webserver.

The WebServer will do whatever its supposed to do and return a brand new webpage to the client(usually the same page with something changed).

So, there is no way you can "catch" the return of a form.submit() action.

How to automatically redirect HTTP to HTTPS on Apache servers?

I have actually followed this example and it worked for me :)

NameVirtualHost *:80
<VirtualHost *:80>
   ServerName mysite.example.com
   Redirect permanent / https://mysite.example.com/
</VirtualHost>

<VirtualHost _default_:443>
   ServerName mysite.example.com
  DocumentRoot /usr/local/apache2/htdocs
  SSLEngine On
 # etc...
</VirtualHost>

Then do:

/etc/init.d/httpd restart

How to return a class object by reference in C++?

I will show you some examples:

First example, do not return local scope object, for example:

const string &dontDoThis(const string &s)
{
    string local = s;
    return local;
}

You can't return local by reference, because local is destroyed at the end of the body of dontDoThis.

Second example, you can return by reference:

const string &shorterString(const string &s1, const string &s2)
{
    return (s1.size() < s2.size()) ? s1 : s2;
}

Here, you can return by reference both s1 and s2 because they were defined before shorterString was called.

Third example:

char &get_val(string &str, string::size_type ix)
{
    return str[ix];
}

usage code as below:

string s("123456");
cout << s << endl;
char &ch = get_val(s, 0); 
ch = 'A';
cout << s << endl; // A23456

get_val can return elements of s by reference because s still exists after the call.

Fourth example

class Student
{
public:
    string m_name;
    int age;    

    string &getName();
};

string &Student::getName()
{
    // you can return by reference
    return m_name;
}

string& Test(Student &student)
{
    // we can return `m_name` by reference here because `student` still exists after the call
    return stu.m_name;
}

usage example:

Student student;
student.m_name = 'jack';
string name = student.getName();
// or
string name2 = Test(student);

Fifth example:

class String
{
private:
    char *str_;

public:
    String &operator=(const String &str);
};

String &String::operator=(const String &str)
{
    if (this == &str)
    {
        return *this;
    }
    delete [] str_;
    int length = strlen(str.str_);
    str_ = new char[length + 1];
    strcpy(str_, str.str_);
    return *this;
}

You could then use the operator= above like this:

String a;
String b;
String c = b = a;

How to prune local tracking branches that do not exist on remote anymore

After pruning, you can get the list of remote branches with git branch -r. The list of branches with their remote tracking branch can be retrieved with git branch -vv. So using these two lists you can find the remote tracking branches that are not in the list of remotes.

This line should do the trick (requires bash or zsh, won't work with standard Bourne shell):

git branch -r | awk '{print $1}' | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk '{print $1}' | xargs git branch -d

This string gets the list of remote branches and passes it into egrep through the standard input. And filters the branches that have a remote tracking branch (using git branch -vv and filtering for those that have origin) then getting the first column of that output which will be the branch name. Finally passing all the branch names into the delete branch command.

Since it is using the -d option, it will not delete branches that have not been merged into the branch that you are on when you run this command.

Also remember that you'll need to run git fetch --prune first, otherwise git branch -r will still see the remote branches.

Create a text file for download on-the-fly

No need to store it anywhere. Just output the content with the appropriate content type.

<?php
    header('Content-type: text/plain');
?>Hello, world.

Add content-disposition if you wish to trigger a download prompt.

header('Content-Disposition: attachment; filename="default-filename.txt"');

C: scanf to array

int main()
{
  int array[11];
  printf("Write down your ID number!\n");
  for(int i=0;i<id_length;i++)
  scanf("%d", &array[i]);
  if (array[0]==1)
  {
    printf("\nThis person is a male.");
  }
  else if (array[0]==2)
  {
    printf("\nThis person is a female.");
  }
  return 0;
}

Google Map API - Removing Markers

Following code might be useful if someone is using React and has a different component of Marker and want to remove marker from map.

export default function useGoogleMapMarker(props) {
  const [marker, setMarker] = useState();

  useEffect(() => {
    // ...code
    const marker = new maps.Marker({ position, map, title, icon });
    // ...code
    setMarker(marker);
    return () => marker.setMap(null); // to remove markers when unmounts
  }, []);

  return marker;
}

Add a column to a table, if it does not already exist

Another alternative. I prefer this approach because it is less writing but the two accomplish the same thing.

IF COLUMNPROPERTY(OBJECT_ID('dbo.Person'), 'ColumnName', 'ColumnId') IS NULL
BEGIN
    ALTER TABLE Person 
    ADD ColumnName VARCHAR(MAX) NOT NULL
END

I also noticed yours is looking for where table does exist that is obviously just this

 if COLUMNPROPERTY( OBJECT_ID('dbo.Person'),'ColumnName','ColumnId') is not null

Java Webservice Client (Best way)

You can find some resources related to developing web services client using Apache axis2 here.

http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html

Below posts gives good explanations about developing web services using Apache axis2.

http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/

http://wso2.org/library/136

Writing data into CSV file in C#

Handling Commas

For handling commas inside of values when using string.Format(...), the following has worked for me:

var newLine = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                              first,
                              second,
                              third                                    
                              );
csv.AppendLine(newLine);

So to combine it with Johan's answer, it'd look like this:

//before your loop
var csv = new StringBuilder();

//in your loop
  var first = reader[0].ToString();
  var second = image.ToString();
  //Suggestion made by KyleMit
  var newLine = string.Format("\"{0}\",\"{1}\"", first, second);
  csv.AppendLine(newLine);  

//after your loop
File.WriteAllText(filePath, csv.ToString());

Returning CSV File

If you simply wanted to return the file instead of writing it to a location, this is an example of how I accomplished it:

From a Stored Procedure

public FileContentResults DownloadCSV()
{
  // I have a stored procedure that queries the information I need
  SqlConnection thisConnection = new SqlConnection("Data Source=sv12sql;User ID=UI_Readonly;Password=SuperSecure;Initial Catalog=DB_Name;Integrated Security=false");
  SqlCommand queryCommand = new SqlCommand("spc_GetInfoINeed", thisConnection);
  queryCommand.CommandType = CommandType.StoredProcedure;

  StringBuilder sbRtn = new StringBuilder();

  // If you want headers for your file
  var header = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                             "Name",
                             "Address",
                             "Phone Number"
                            );
  sbRtn.AppendLine(header);

  // Open Database Connection
  thisConnection.Open();
  using (SqlDataReader rdr = queryCommand.ExecuteReader())
  {
    while (rdr.Read())
    {
      // rdr["COLUMN NAME"].ToString();
      var queryResults = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                                        rdr["Name"].ToString(),
                                        rdr["Address"}.ToString(),
                                        rdr["Phone Number"].ToString()
                                       );
      sbRtn.AppendLine(queryResults);
    }
  }
  thisConnection.Close();

  return File(new System.Text.UTF8Encoding().GetBytes(sbRtn.ToString()), "text/csv", "FileName.csv");
}

From a List

/* To help illustrate */
public static List<Person> list = new List<Person>();

/* To help illustrate */
public class Person
{
  public string name;
  public string address;
  public string phoneNumber;
}

/* The important part */
public FileContentResults DownloadCSV()
{
  StringBuilder sbRtn = new StringBuilder();

  // If you want headers for your file
  var header = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                             "Name",
                             "Address",
                             "Phone Number"
                            );
  sbRtn.AppendLine(header);

  foreach (var item in list)
  {
      var listResults = string.Format("\"{0}\",\"{1}\",\"{2}\"",
                                        item.name,
                                        item.address,
                                        item.phoneNumber
                                       );
      sbRtn.AppendLine(listResults);
    }
  }

  return File(new System.Text.UTF8Encoding().GetBytes(sbRtn.ToString()), "text/csv", "FileName.csv");
}

Hopefully this is helpful.

Select all text inside EditText when it gets focus

SelectAllOnFocus works the first time the EditText gets focus, but if you want to select the text every time the user clicks on it, you need to call editText.clearFocus() in between times.

For example, if your app has one EditText and one button, clicking the button after changing the EditText leaves the focus in the EditText. Then the user has to use the cursor handle and the backspace key to delete what's in the EditText before they can enter a new value. So call editText.clearFocus() in the Button's onClick method.

How to specify function types for void (not Void) methods in Java8?

I feel you should be using the Consumer interface instead of Function<T, R>.

A Consumer is basically a functional interface designed to accept a value and return nothing (i.e void)

In your case, you can create a consumer elsewhere in your code like this:

Consumer<Integer> myFunction = x -> {
    System.out.println("processing value: " + x);    
    .... do some more things with "x" which returns nothing...
}

Then you can replace your myForEach code with below snippet:

public static void myForEach(List<Integer> list, Consumer<Integer> myFunction) 
{
  list.forEach(x->myFunction.accept(x));
}

You treat myFunction as a first-class object.

Force DOM redraw/refresh on Chrome/Mac

None of the above answers worked for me. I did notice that resizing my window did cause a redraw. So this did it for me:

$(window).trigger('resize');

how to change color of TextinputLayout's label and edittext underline android

Add this attribute in Edittext tag and enjoy:

 android:backgroundTint="@color/colorWhite"

How to put a link on a button with bootstrap?

You can call a function on click event of button.

<input type="button" class="btn btn-info" value="Input Button" onclick=" relocate_home()">

<script>
function relocate_home()
{
     location.href = "www.yoursite.com";
} 
</script>

OR Use this Code

<a href="#link" class="btn btn-info" role="button">Link Button</a>

How to get the separate digits of an int number?

Integer.toString(1100) gives you the integer as a string. Integer.toString(1100).getBytes() to get an array of bytes of the individual digits.

Edit:

You can convert the character digits into numeric digits, thus:

  String string = Integer.toString(1234);
  int[] digits = new int[string.length()];

  for(int i = 0; i<string.length(); ++i){
    digits[i] = Integer.parseInt(string.substring(i, i+1));
  }
  System.out.println("digits:" + Arrays.toString(digits));

Launching Spring application Address already in use

Right click in console and click Terminate/Disconnect All option.

OR

Click on 'Display selected console' icon on top right corner of the console window and, choose and terminate the console which holds the port still.

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

Command not found when using sudo

Permission denied

In order to run a script the file must have an executable permission bit set.

In order to fully understand Linux file permissions you can study the documentation for the chmod command. chmod, an abbreviation of change mode, is the command that is used to change the permission settings of a file.

To read the chmod documentation for your local system , run man chmod or info chmod from the command line. Once read and understood you should be able to understand the output of running ...

ls -l foo.sh

... which will list the READ, WRITE and EXECUTE permissions for the file owner, the group owner and everyone else who is not the file owner or a member of the group to which the file belongs (that last permission group is sometimes referred to as "world" or "other")

Here's a summary of how to troubleshoot the Permission Denied error in your case.

$ ls -l foo.sh                    # Check file permissions of foo
-rw-r--r-- 1 rkielty users 0 2012-10-21 14:47 foo.sh 
    ^^^ 
 ^^^ | ^^^   ^^^^^^^ ^^^^^
  |  |  |       |       | 
Owner| World    |       |
     |          |    Name of
   Group        |     Group
             Name of 
              Owner 

Owner has read and write access rw but the - indicates that the executable permission is missing

The chmod command fixes that. (Group and other only have read permission set on the file, they cannot write to it or execute it)

$ chmod +x foo.sh               # The owner can set the executable permission on foo.sh
$ ls -l foo.sh                  # Now we see an x after the rw 
-rwxr-xr-x 1 rkielty users 0 2012-10-21 14:47 foo.sh
   ^  ^  ^

foo.sh is now executable as far as Linux is concerned.

Using sudo results in Command not found

When you run a command using sudo you are effectively running it as the superuser or root.

The reason that the root user is not finding your command is likely that the PATH environment variable for root does not include the directory where foo.sh is located. Hence the command is not found.

The PATH environment variable contains a list of directories which are searched for commands. Each user sets their own PATH variable according to their needs. To see what it is set to run

env | grep ^PATH

Here's some sample output of running the above env command first as an ordinary user and then as the root user using sudo

rkielty@rkielty-laptop:~$ env | grep ^PATH
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

rkielty@rkielty-laptop:~$ sudo env | grep ^PATH
[sudo] password for rkielty: 
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin

Note that, although similar, in this case the directories contained in the PATH the non-privileged user (rkielty) and the super user are not the same.

The directory where foo.sh resides is not present in the PATH variable of the root user, hence the command not found error.

How to get label of select option with jQuery?

Hi first give an id to the select as

<select id=theid>
<option value="test">label </option>
</select>

then you can call the selected label like that:

jQuery('#theid option:selected').text()

Android WebView not loading URL

In my Case, Adding the below functions to WebViewClient fixed the error. the functions are:onReceivedSslError and Depricated and new api versions of shouldOverrideUrlLoading

        webView.setWebViewClient(new WebViewClient() {

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            Log.i(TAG, "loading: deprecation");
            return  true;
            //return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        @TargetApi(Build.VERSION_CODES.N)
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            Log.i(TAG, "loading: build.VERSION_CODES.N");
            return true;
            //return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(
                WebView view, String url, Bitmap favicon) {
            Log.i(TAG, "page started:"+url);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, final String url) {

            Log.i(TAG, "page finished:"+url);

        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError er) {
            handler.proceed();
        }

    });

jQuery detect if string contains something

use Contains of jquery Contains like this

if ($('.type:contains("> <")').length > 0)
{
 //do stuffs to change 
}

What is the difference between `git merge` and `git merge --no-ff`?

Graphic answer to this question

Here is a site with a clear explanation and graphical illustration of using git merge --no-ff:

difference between git merge --no-ff and git merge

Until I saw this, I was completely lost with git. Using --no-ff allows someone reviewing history to clearly see the branch you checked out to work on. (that link points to github's "network" visualization tool) And here is another great reference with illustrations. This reference complements the first one nicely with more of a focus on those less acquainted with git.


Basic info for newbs like me

If you are like me, and not a Git-guru, my answer here describes handling the deletion of files from git's tracking without deleting them from the local filesystem, which seems poorly documented but often occurrence. Another newb situation is getting current code, which still manages to elude me.


Example Workflow

I updated a package to my website and had to go back to my notes to see my workflow; I thought it useful to add an example to this answer.

My workflow of git commands:

git checkout -b contact-form
(do your work on "contact-form")
git status
git commit -am  "updated form in contact module"
git checkout master
git merge --no-ff contact-form
git branch -d contact-form
git push origin master

Below: actual usage, including explanations.
Note: the output below is snipped; git is quite verbose.

$ git status
# On branch master
# Changed but not updated:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   ecc/Desktop.php
#       modified:   ecc/Mobile.php
#       deleted:    ecc/ecc-config.php
#       modified:   ecc/readme.txt
#       modified:   ecc/test.php
#       deleted:    passthru-adapter.igs
#       deleted:    shop/mickey/index.php
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       ecc/upgrade.php
#       ecc/webgility-config.php
#       ecc/webgility-config.php.bak
#       ecc/webgility-magento.php

Notice 3 things from above:
1) In the output you can see the changes from the ECC package's upgrade, including the addition of new files.
2) Also notice there are two files (not in the /ecc folder) I deleted independent of this change. Instead of confusing those file deletions with ecc, I'll make a different cleanup branch later to reflect those files' deletion.
3) I didn't follow my workflow! I forgot about git while I was trying to get ecc working again.

Below: rather than do the all-inclusive git commit -am "updated ecc package" I normally would, I only wanted to add the files in the /ecc folder. Those deleted files weren't specifically part of my git add, but because they already were tracked in git, I need to remove them from this branch's commit:

$ git checkout -b ecc
$ git add ecc/*
$ git reset HEAD passthru-adapter.igs
$ git reset HEAD shop/mickey/index.php
Unstaged changes after reset:
M       passthru-adapter.igs
M       shop/mickey/index.php

$ git commit -m "Webgility ecc desktop connector files; integrates with Quickbooks"

$ git checkout master
D       passthru-adapter.igs
D       shop/mickey/index.php
Switched to branch 'master'
$ git merge --no-ff ecc
$ git branch -d ecc
Deleted branch ecc (was 98269a2).
$ git push origin master
Counting objects: 22, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (14/14), done.
Writing objects: 100% (14/14), 59.00 KiB, done.
Total 14 (delta 10), reused 0 (delta 0)
To [email protected]:me/mywebsite.git
   8a0d9ec..333eff5  master -> master



Script for automating the above

Having used this process 10+ times in a day, I have taken to writing batch scripts to execute the commands, so I made an almost-proper git_update.sh <branch> <"commit message"> script for doing the above steps. Here is the Gist source for that script.

Instead of git commit -am I am selecting files from the "modified" list produced via git status and then pasting those in this script. This came about because I made dozens of edits but wanted varied branch names to help group the changes.

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

Read only file system on Android

If there's a failure in copying the read-only file you can try locating the original file in the root directory and modify it with a root text editor (preferably) RB text editor, it comes with ROM Toolbox app.

Convert text into number in MySQL query

cast(REGEXP_REPLACE(NameNumber, '[^0-9]', '') as UNSIGNED)

MySQL Check if username and password matches in Database

1.) Storage of database passwords Use some kind of hash with a salt and then alter the hash, obfuscate it, for example add a distinct value for each byte. That way your passwords a super secured against dictionary attacks and rainbow tables.

2.) To check if the password matches, create your hash for the password the user put in. Then perform a query against the database for the username and just check if the two password hashes are identical. If they are, give the user an authentication token.

The query should then look like this:

select hashedPassword from users where username=?

Then compare the password to the input.

Further questions?

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

We had nearly this exact same issue occur recently and it turned out to be caused by Microsoft update KB980436 (http://support.microsoft.com/KB/980436) being installed on the calling computer. The fix for us, other than uninstalling it outright, was to follow the instructions at the KB site for setting the UseScsvForTls DWORD in the registry to 1. If you see this update is installed in your calling system you may want to give it a shot.

Is there a difference between "throw" and "throw ex"?

let's understand the difference between throw and throw ex. I heard that in many .net interviews this common asked is being asked.

Just to give an overview of these two terms, throw and throw ex are both used to understand where the exception has occurred. Throw ex rewrites the stack trace of exception irrespective where actually has been thrown.

Let's understand with an example.

Let's understand first Throw.

static void Main(string[] args) {
    try {
        M1();
    } catch (Exception ex) {
        Console.WriteLine(" -----------------Stack Trace Hierarchy -----------------");
        Console.WriteLine(ex.StackTrace.ToString());
        Console.WriteLine(" ---------------- Method Name / Target Site -------------- ");
        Console.WriteLine(ex.TargetSite.ToString());
    }
    Console.ReadKey();
}

static void M1() {
    try {
        M2();
    } catch (Exception ex) {
        throw;
    };
}

static void M2() {
    throw new DivideByZeroException();
}

output of the above is below.

shows complete hierarchy and method name where actually the exception has thrown.. it is M2 -> M2. along with line numbers

enter image description here

Secondly.. lets understand by throw ex. Just replace throw with throw ex in M2 method catch block. as below.

enter image description here

output of throw ex code is as below..

enter image description here

You can see the difference in the output.. throw ex just ignores all the previous hierarchy and resets stack trace with line/method where throw ex is written.

How to find the 'sizeof' (a pointer pointing to an array)?

There is a clean solution with C++ templates, without using sizeof(). The following getSize() function returns the size of any static array:

#include <cstddef>

template<typename T, size_t SIZE>
size_t getSize(T (&)[SIZE]) {
    return SIZE;
}

Here is an example with a foo_t structure:

#include <cstddef>

template<typename T, size_t SIZE>
size_t getSize(T (&)[SIZE]) {
    return SIZE;
}

struct foo_t {
    int ball;
};

int main()
{
    foo_t foos3[] = {{1},{2},{3}};
    foo_t foos5[] = {{1},{2},{3},{4},{5}};
    printf("%u\n", getSize(foos3));
    printf("%u\n", getSize(foos5));

    return 0;
}

Output:

3
5

Quick easy way to migrate SQLite3 to MySQL?

Probably the quick easiest way is using the sqlite .dump command, in this case create a dump of the sample database.

sqlite3 sample.db .dump > dump.sql

You can then (in theory) import this into the mysql database, in this case the test database on the database server 127.0.0.1, using user root.

mysql -p -u root -h 127.0.0.1 test < dump.sql

I say in theory as there are a few differences between grammars.

In sqlite transactions begin

BEGIN TRANSACTION;
...
COMMIT;

MySQL uses just

BEGIN;
...
COMMIT;

There are other similar problems (varchars and double quotes spring back to mind) but nothing find and replace couldn't fix.

Perhaps you should ask why you are migrating, if performance/ database size is the issue perhaps look at reoginising the schema, if the system is moving to a more powerful product this might be the ideal time to plan for the future of your data.

Search a string in a file and delete it from this file by Shell Script

This should do it:

sed -e s/deletethis//g -i *
sed -e "s/deletethis//g" -i.backup *
sed -e "s/deletethis//g" -i .backup *

it will replace all occurrences of "deletethis" with "" (nothing) in all files (*), editing them in place.

In the second form the pattern can be edited a little safer, and it makes backups of any modified files, by suffixing them with ".backup".

The third form is the way some versions of sed like it. (e.g. Mac OS X)

man sed for more information.

Get absolute path of initially run script

__DIR__

From the manual:

The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FILE__ always contains an absolute path with symlinks resolved whereas in older versions (than 4.0.2) it contained relative path under some circumstances.

Note: __DIR__ was added in PHP 5.3.0.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

The following steps are to reset the password for a user in case you forgot, this would also solve your mentioned error.

First, stop your MySQL:

sudo /etc/init.d/mysql stop

Now start up MySQL in safe mode and skip the privileges table:

sudo mysqld_safe --skip-grant-tables &

Login with root:

mysql -uroot

And assign the DB that needs to be used:

use mysql;

Now all you have to do is reset your root password of the MySQL user and restart the MySQL service:

update user set password=PASSWORD("YOURPASSWORDHERE") where User='root';

flush privileges;

quit and restart MySQL:

quit

sudo /etc/init.d/mysql stop sudo /etc/init.d/mysql start Now your root password should be working with the one you just set, check it with:

mysql -u root -p

What is the SSIS package and what does it do?

SSIS (SQL Server Integration Services) is an upgrade of DTS (Data Transformation Services), which is a feature of the previous version of SQL Server. SSIS packages can be created in BIDS (Business Intelligence Development Studio). These can be used to merge data from heterogeneous data sources into SQL Server. They can also be used to populate data warehouses, to clean and standardize data, and to automate administrative tasks.

SQL Server Integration Services (SSIS) is a component of Microsoft SQL Server 2005. It replaces Data Transformation Services, which has been a feature of SQL Server since Version 7.0. Unlike DTS, which was included in all versions, SSIS is only available in the "Standard" and "Enterprise" editions. Integration Services provides a platform to build data integration and workflow applications. The primary use for SSIS is data warehousing as the product features a fast and flexible tool for data extraction, transformation, and loading (ETL).). The tool may also be used to automate maintenance of SQL Server databases, update multidimensional cube data, and perform other functions.

Delete files older than 15 days using PowerShell

#----- Define parameters -----#
#----- Get current date ----#
$Now = Get-Date
$Days = "15" #----- define amount of days ----#
$Targetfolder = "C:\Logs" #----- define folder where files are located ----#
$Extension = "*.log" #----- define extension ----#
$Lastwrite = $Now.AddDays(-$Days)

#----- Get files based on lastwrite filter and specified folder ---#
$Files = Get-Children $Targetfolder -include $Extension -Recurse | where {$_.LastwriteTime -le "$Lastwrite"}

foreach ($File in $Files)
{
    if ($File -ne $Null)
    {
        write-host "Deleting File $File" backgroundcolor "DarkRed"
        Remove-item $File.Fullname | out-null
    }
    else
        write-host "No more files to delete" -forgroundcolor "Green"
    }
}

Determining complexity for recursive functions (Big O notation)

We can prove it mathematically which is something I was missing in the above answers.

It can dramatically help you understand how to calculate any method. I recommend reading it from top to bottom to fully understand how to do it:

  1. T(n) = T(n-1) + 1 It means that the time it takes for the method to finish is equal to the same method but with n-1 which is T(n-1) and we now add + 1 because it's the time it takes for the general operations to be completed (except T(n-1)). Now, we are going to find T(n-1) as follow: T(n-1) = T(n-1-1) + 1. It looks like we can now form a function that can give us some sort of repetition so we can fully understand. We will place the right side of T(n-1) = ... instead of T(n-1) inside the method T(n) = ... which will give us: T(n) = T(n-1-1) + 1 + 1 which is T(n) = T(n-2) + 2 or in other words we need to find our missing k: T(n) = T(n-k) + k. The next step is to take n-k and claim that n-k = 1 because at the end of the recursion it will take exactly O(1) when n<=0. From this simple equation we now know that k = n - 1. Let's place k in our final method: T(n) = T(n-k) + k which will give us: T(n) = 1 + n - 1 which is exactly n or O(n).
  2. Is the same as 1. You can test it your self and see that you get O(n).
  3. T(n) = T(n/5) + 1 as before, the time for this method to finish equals to the time the same method but with n/5 which is why it is bounded to T(n/5). Let's find T(n/5) like in 1: T(n/5) = T(n/5/5) + 1 which is T(n/5) = T(n/5^2) + 1. Let's place T(n/5) inside T(n) for the final calculation: T(n) = T(n/5^k) + k. Again as before, n/5^k = 1 which is n = 5^k which is exactly as asking what in power of 5, will give us n, the answer is log5n = k (log of base 5). Let's place our findings in T(n) = T(n/5^k) + k as follow: T(n) = 1 + logn which is O(logn)
  4. T(n) = 2T(n-1) + 1 what we have here is basically the same as before but this time we are invoking the method recursively 2 times thus we multiple it by 2. Let's find T(n-1) = 2T(n-1-1) + 1 which is T(n-1) = 2T(n-2) + 1. Our next place as before, let's place our finding: T(n) = 2(2T(n-2)) + 1 + 1 which is T(n) = 2^2T(n-2) + 2 that gives us T(n) = 2^kT(n-k) + k. Let's find k by claiming that n-k = 1 which is k = n - 1. Let's place k as follow: T(n) = 2^(n-1) + n - 1 which is roughly O(2^n)
  5. T(n) = T(n-5) + n + 1 It's almost the same as 4 but now we add n because we have one for loop. Let's find T(n-5) = T(n-5-5) + n + 1 which is T(n-5) = T(n - 2*5) + n + 1. Let's place it: T(n) = T(n-2*5) + n + n + 1 + 1) which is T(n) = T(n-2*5) + 2n + 2) and for the k: T(n) = T(n-k*5) + kn + k) again: n-5k = 1 which is n = 5k + 1 that is roughly n = k. This will give us: T(n) = T(0) + n^2 + n which is roughly O(n^2).

I now recommend reading the rest of the answers which now, will give you a better perspective. Good luck winning those big O's :)

Dark Theme for Visual Studio 2010 With Productivity Power Tools

There is a style that I've created based on dark style from VS 2015 to use on my VS 2010. You can download this style from Dark Style from VS 2015.

After download it, just import through menu Tools -> Import and Export Settings...

Java Array Sort descending?

I know that this is a quite old thread, but here is an updated version for Integers and Java 8:

Arrays.sort(array, (o1, o2) -> o2 - o1);

Note that it is "o1 - o2" for the normal ascending order (or Comparator.comparingInt()).

This also works for any other kinds of Objects. Say:

Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());

I cannot start SQL Server browser

Clicking Properties, going to the Service tab and setting Start Mode to Automatic fixed the problem for me. Now the Start item in the context menu is active again.

Get jQuery version from inspecting the jQuery object

FYI, for the cases where your page is loading with other javascript libraries like mootools that are conflicting with the $ symbol, you can use jQuery instead.

For instance, jQuery.fn.jquery or jQuery().jquery would work just fine:

screen shot for checking jQuery version

how to hide keyboard after typing in EditText in android?

I did not see anyone using this method:

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean focused) {
        InputMethodManager keyboard = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (focused)
            keyboard.showSoftInput(editText, 0);
        else
            keyboard.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }
});

And then just request focus to the editText:

editText.requestFocus();

Linq select object from list depending on objects attribute

if a.Correct is a bool flag for the correct answer then you need.

Answer answer = Answers.Single(a => a.Correct);

add onclick function to a submit button

I need to see your submit button html tag for better help. I am not familiar with php and how it handles the postback, but I guess depending on what you want to do, you have three options:

  1. Getting the handling onclick button on the client-side: In this case you only need to call a javascript function.

_x000D_
_x000D_
function foo() {_x000D_
   alert("Submit button clicked!");_x000D_
   return true;_x000D_
}
_x000D_
<input type="submit" value="submit" onclick="return foo();" />
_x000D_
_x000D_
_x000D_

  1. If you want to handle the click on the server-side, you should first make sure that the form tag method attribute is set to post:

    <form method="post">
    
  2. You can use onsubmit event from form itself to bind your function to it.

_x000D_
_x000D_
<form name="frm1" method="post" onsubmit="return greeting()">_x000D_
    <input type="text" name="fname">_x000D_
    <input type="submit" value="Submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Cannot find or open the PDB file in Visual Studio C++ 2010

Answer by Paul is right, I am just putting the visual to easily get there.

Go to Tools->Options->Debugging->Symbols

Set the checkbox marked in red and it will download the pdb files from microsoft. When you set the checkbox, it will also set a default path for the pdb files in the edit box under, you don't need to change that.

enter image description here

showDialog deprecated. What's the alternative?

From http://developer.android.com/reference/android/app/Activity.html

public final void showDialog (int id) Added in API level 1

This method was deprecated in API level 13. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.

Simple version of showDialog(int, Bundle) that does not take any arguments. Simply calls showDialog(int, Bundle) with null arguments.

Why

  • A fragment that displays a dialog window, floating on top of its activity's window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.
  • Here is a nice discussion Android DialogFragment vs Dialog
  • Another nice discussion DialogFragment advantages over AlertDialog

How to solve?

More

How to check if an item is selected from an HTML drop down list?

<script>
var card = document.getElementById("cardtype");
if(card.selectedIndex == 0) {
     alert('select one answer');
}
else {
    var selectedText = card.options[card.selectedIndex].text;
    alert(selectedText);
}
</script>

Launch Bootstrap Modal on page load

<div id="ModalStart" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-body">
          <p><i class="icon-spinner icon-spin icon-4x"></i></p>
    </div>
</div>

You can show it on start even without Javascript. Just delete the class "hide".

class="Modal"

How to use if-else logic in Java 8 stream forEach

The problem by using stream().forEach(..) with a call to add or put inside the forEach (so you mutate the external myMap or myList instance) is that you can run easily into concurrency issues if someone turns the stream in parallel and the collection you are modifying is not thread safe.

One approach you can take is to first partition the entries in the original map. Once you have that, grab the corresponding list of entries and collect them in the appropriate map and list.

Map<Boolean, List<Map.Entry<K, V>>> partitions =
    animalMap.entrySet()
             .stream()
             .collect(partitioningBy(e -> e.getValue() == null));

Map<K, V> myMap = 
    partitions.get(false)
              .stream()
              .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

List<K> myList =
    partitions.get(true)
              .stream()
              .map(Map.Entry::getKey) 
              .collect(toList());

... or if you want to do it in one pass, implement a custom collector (assuming a Tuple2<E1, E2> class exists, you can create your own), e.g:

public static <K,V> Collector<Map.Entry<K, V>, ?, Tuple2<Map<K, V>, List<K>>> customCollector() {
    return Collector.of(
            () -> new Tuple2<>(new HashMap<>(), new ArrayList<>()),
            (pair, entry) -> {
                if(entry.getValue() == null) {
                    pair._2.add(entry.getKey());
                } else {
                    pair._1.put(entry.getKey(), entry.getValue());
                }
            },
            (p1, p2) -> {
                p1._1.putAll(p2._1);
                p1._2.addAll(p2._2);
                return p1;
            });
}

with its usage:

Tuple2<Map<K, V>, List<K>> pair = 
    animalMap.entrySet().parallelStream().collect(customCollector());

You can tune it more if you want, for example by providing a predicate as parameter.

Spring MVC: How to perform validation?

I would like to extend nice answer of Jerome Dalbert. I found very easy to write your own annotation validators in JSR-303 way. You are not limited to have "one field" validation. You can create your own annotation on type level and have complex validation (see examples below). I prefer this way because I don't need mix different types of validation (Spring and JSR-303) like Jerome do. Also this validators are "Spring aware" so you can use @Inject/@Autowire out of box.

Example of custom object validation:

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { YourCustomObjectValidator.class })
public @interface YourCustomObjectValid {

    String message() default "{YourCustomObjectValid.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

public class YourCustomObjectValidator implements ConstraintValidator<YourCustomObjectValid, YourCustomObject> {

    @Override
    public void initialize(YourCustomObjectValid constraintAnnotation) { }

    @Override
    public boolean isValid(YourCustomObject value, ConstraintValidatorContext context) {

        // Validate your complex logic 

        // Mark field with error
        ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
        cvb.addNode(someField).addConstraintViolation();

        return true;
    }
}

@YourCustomObjectValid
public YourCustomObject {
}

Example of generic fields equality:

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { FieldsEqualityValidator.class })
public @interface FieldsEquality {

    String message() default "{FieldsEquality.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Name of the first field that will be compared.
     * 
     * @return name
     */
    String firstFieldName();

    /**
     * Name of the second field that will be compared.
     * 
     * @return name
     */
    String secondFieldName();

    @Target({ TYPE, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    public @interface List {
        FieldsEquality[] value();
    }
}




import java.lang.reflect.Field;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

public class FieldsEqualityValidator implements ConstraintValidator<FieldsEquality, Object> {

    private static final Logger log = LoggerFactory.getLogger(FieldsEqualityValidator.class);

    private String firstFieldName;
    private String secondFieldName;

    @Override
    public void initialize(FieldsEquality constraintAnnotation) {
        firstFieldName = constraintAnnotation.firstFieldName();
        secondFieldName = constraintAnnotation.secondFieldName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null)
            return true;

        try {
            Class<?> clazz = value.getClass();

            Field firstField = ReflectionUtils.findField(clazz, firstFieldName);
            firstField.setAccessible(true);
            Object first = firstField.get(value);

            Field secondField = ReflectionUtils.findField(clazz, secondFieldName);
            secondField.setAccessible(true);
            Object second = secondField.get(value);

            if (first != null && second != null && !first.equals(second)) {
                    ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(firstFieldName).addConstraintViolation();

          ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(someField).addConstraintViolation(secondFieldName);

                return false;
            }
        } catch (Exception e) {
            log.error("Cannot validate fileds equality in '" + value + "'!", e);
            return false;
        }

        return true;
    }
}

@FieldsEquality(firstFieldName = "password", secondFieldName = "confirmPassword")
public class NewUserForm {

    private String password;

    private String confirmPassword;

}

How can I select an element in a component template?

Selecting target element from the list. It is easy to select particular element from the list of same elements.

component code:

export class AppComponent {
  title = 'app';

  listEvents = [
    {'name':'item1', 'class': ''}, {'name':'item2', 'class': ''},
    {'name':'item3', 'class': ''}, {'name':'item4', 'class': ''}
  ];

  selectElement(item: string, value: number) {
    console.log("item="+item+" value="+value);
    if(this.listEvents[value].class == "") {
      this.listEvents[value].class='selected';
    } else {
      this.listEvents[value].class= '';
    }
  }
}

html code:

<ul *ngFor="let event of listEvents; let i = index">
   <li  (click)="selectElement(event.name, i)" [class]="event.class">
  {{ event.name }}
</li>

css code:

.selected {
  color: red;
  background:blue;
}

Can you create nested WITH clauses for Common Table Expressions?

You can do the following, which is referred to as a recursive query:

WITH y
AS
(
  SELECT x, y, z
  FROM MyTable
  WHERE [base_condition]

  UNION ALL

  SELECT x, y, z
  FROM MyTable M
  INNER JOIN y ON M.[some_other_condition] = y.[some_other_condition]
)
SELECT *
FROM y

You may not need this functionality. I've done the following just to organize my queries better:

WITH y 
AS
(
  SELECT * 
  FROM MyTable
  WHERE [base_condition]
),
x
AS
(
  SELECT * 
  FROM y
  WHERE [something_else]
)
SELECT * 
FROM x

.ssh directory not being created

Is there a step missing?

Yes. You need to create the directory:

mkdir ${HOME}/.ssh

Additionally, SSH requires you to set the permissions so that only you (the owner) can access anything in ~/.ssh:

% chmod 700 ~/.ssh

Should the .ssh dir be generated when I use the ssh-keygen command?

No. This command generates an SSH key pair but will fail if it cannot write to the required directory:

% ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): /Users/tmp/does_not_exist
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
open /Users/tmp/does_not_exist failed: No such file or directory.
Saving the key failed: /Users/tmp/does_not_exist.

Once you've created your keys, you should also restrict who can read those key files to just yourself:

% chmod -R go-wrx ~/.ssh/*

How to add leading zeros for for-loop in shell?

I'm not interested in outputting it to the screen (that's what printf is mainly used for, right?) The variable $num is going to be used as a parameter for another program but let me see what I can do with this.

You can still use printf:

for num in {1..5}
do
   value=$(printf "%02d" $num)
   ... Use $value for your purposes
done

Use :hover to modify the css of another class?

There are two approaches you can take, to have a hovered element affect (E) another element (F):

  1. F is a child-element of E, or
  2. F is a later-sibling (or sibling's descendant) element of E (in that E appears in the mark-up/DOM before F):

To illustrate the first of these options (F as a descendant/child of E):

.item:hover .wrapper {
    color: #fff;
    background-color: #000;
}?

To demonstrate the second option, F being a sibling element of E:

.item:hover ~ .wrapper {
    color: #fff;
    background-color: #000;
}?

In this example, if .wrapper was an immediate sibling of .item (with no other elements between the two) you could also use .item:hover + .wrapper.

JS Fiddle demonstration.

References:

How to "git clone" including submodules?

You can use the --recursive flag when cloning a repository. This parameter forces git to clone all defined submodules in the repository.

git clone --recursive [email protected]:your_repo.git

After cloning, sometimes submodules branches may be changed, so run this command after it:

git submodule foreach "git checkout master"

Auto-Submit Form using JavaScript

Try this,

HtmlElement head = _windowManager.ActiveBrowser.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = _windowManager.ActiveBrowser.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "window.onload = function() { document.forms[0].submit(); }";
head.AppendChild(scriptEl);
strAdditionalHeader = "";
_windowManager.ActiveBrowser.Document.InvokeScript("webBrowserControl");

$ is not a function - jQuery error

As RPM1984 refers to, this is mostly likely caused by the fact that your script is loading before jQuery is loaded.

How to make my font bold using css?

You could use a couple approaches. First would be to use the strong tag

Here is an <strong>example of that tag</strong>.

Another approach would be to use the font-weight property. You can achieve inline, or via a class or id. Let's say you're using a class.

.className {
  font-weight: bold;
}

Alternatively, you can also use a hard value for font-weight and most fonts support a value between 300 and 700, incremented by 100. For example, the following would be bold:

.className {
  font-weight: 700;
}

How do I query for all dates greater than a certain date in SQL Server?

We can use like below as well

SELECT * 
FROM dbo.March2010 A
WHERE CAST(A.Date AS Date) >= '2017-03-22';

SELECT * 
    FROM dbo.March2010 A
    WHERE CAST(A.Date AS Datetime) >= '2017-03-22 06:49:53.840';

Android Get Current timestamp?

java.time

I should like to contribute the modern answer.

    String ts = String.valueOf(Instant.now().getEpochSecond());
    System.out.println(ts);

Output when running just now:

1543320466

While division by 1000 won’t come as a surprise to many, doing your own time conversions can get hard to read pretty fast, so it’s a bad habit to get into when you can avoid it.

The Instant class that I am using is part of java.time, the modern Java date and time API. It’s built-in on new Android versions, API level 26 and up. If you are programming for older Android, you may get the backport, see below. If you don’t want to do that, understandably, I’d still use a built-in conversion:

    String ts = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
    System.out.println(ts);

This is the same as the answer by sealskej. Output is the same as before.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Can jQuery provide the tag name?

The best way to fix your problem, is to replace $(this).attr("tag") with either this.nodeName.toLowerCase() or this.tagName.toLowerCase().

Both produce the exact same result!

Inserting string at position x of another string

Using ES6 string literals, would be much shorter:

_x000D_
_x000D_
const insertAt = (str, sub, pos) => `${str.slice(0, pos)}${sub}${str.slice(pos)}`;_x000D_
    _x000D_
console.log(insertAt('I want apple', ' an', 6)) // logs 'I want an apple'
_x000D_
_x000D_
_x000D_

Can't install any package with node npm

If you're unlucky enough to be switching back and forth from a network behind a proxy and a network NOT behind a proxy, you may have forgotten that your NPM config is set to expect a proxy.

For me, I had to open up ~/.npmrc and comment out my proxy settings (while at home) and vice versa while at work (behind the proxy).

".addEventListener is not a function" why does this error occur?

document.getElementsByClassName returns an array of elements. so may be you want to target a specific index of them: var comment = document.getElementsByClassName('button')[0]; should get you what you want.

Update #1:

var comments = document.getElementsByClassName('button');
var numComments = comments.length;

function showComment() {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
}

for (var i = 0; i < numComments; i++) {
  comments[i].addEventListener('click', showComment, false);
}

Update #2: (with removeEventListener incorporated as well)

var comments = document.getElementsByClassName('button');
var numComments = comments.length;

function showComment(e) {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
  for (var i = 0; i < numComments; i++) {
    comments[i].removeEventListener('click', showComment, false);
  }
}

for (var i = 0; i < numComments; i++) {
  comments[i].addEventListener('click', showComment, false);
}

CSS last-child selector: select last-element of specific class, not last child inside of parent?

If you are floating the elements you can reverse the order

i.e. float: right; instead of float: left;

And then use this method to select the first-child of a class.

/* 1: Apply style to ALL instances */
#header .some-class {
  padding-right: 0;
}
/* 2: Remove style from ALL instances except FIRST instance */
#header .some-class~.some-class {
  padding-right: 20px;
}

This is actually applying the class to the LAST instance only because it's now in reversed order.

Here is a working example for you:

<!doctype html>
<head><title>CSS Test</title>
<style type="text/css">
.some-class { margin: 0; padding: 0 20px; list-style-type: square; }
.lfloat { float: left; display: block; }
.rfloat { float: right; display: block; }
/* apply style to last instance only */
#header .some-class {
  border: 1px solid red;
  padding-right: 0;
}
#header .some-class~.some-class {
  border: 0;
  padding-right: 20px;
}
</style>
</head>
<body>
<div id="header">
  <img src="some_image" title="Logo" class="lfloat no-border"/>
  <ul class="some-class rfloat">
    <li>List 1-1</li>
    <li>List 1-2</li>
    <li>List 1-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 2-1</li>
    <li>List 2-2</li>
    <li>List 2-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 3-1</li>
    <li>List 3-2</li>
    <li>List 3-3</li>
  </ul>
  <img src="some_other_img" title="Icon" class="rfloat no-border"/>
</div>
</body>
</html>

Laravel 5.4 Specific Table Migration

php artisan migrate --path=database/migrations/2020_04_10_130703_create_test_table.php

note: after --path no / before

How to reset a timer in C#?

I just assigned a new value to the timer:

mytimer.Change(10000, 0); // reset to 10 seconds

It works fine for me.

at the top of the code define the timer: System.Threading.Timer myTimer;

if (!active)
    myTimer = new Timer(new TimerCallback(TimerProc));

myTimer.Change(10000, 0);
active = true;

private void TimerProc(object state)
{
    // The state object is the Timer object.
    var t = (Timer)state;

    t.Dispose();
    Console.WriteLine("The timer callback executes.");
    active = false;
    
    // Action to do when timer is back to zero
}

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

As an exercise, I would suggest doing the following:

public void save(String fileName) throws FileNotFoundException {
    PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
    for (Club club : clubs)
        pw.println(club.getName());
    pw.close();
}

This will write the name of each club on a new line in your file.

Soccer
Chess
Football
Volleyball
...

I'll leave the loading to you. Hint: You wrote one line at a time, you can then read one line at a time.

Every class in Java extends the Object class. As such you can override its methods. In this case, you should be interested by the toString() method. In your Club class, you can override it to print some message about the class in any format you'd like.

public String toString() {
    return "Club:" + name;
}

You could then change the above code to:

public void save(String fileName) throws FileNotFoundException {
    PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
    for (Club club : clubs)
         pw.println(club); // call toString() on club, like club.toString()
    pw.close();
}

Open Source HTML to PDF Renderer with Full CSS Support

I've always used it on the command line and not as a library, but HTMLDOC gives me excellent results, and it handles at least some CSS (I couldn't easily see how much).

Here's a sample command line

htmldoc --webpage -t pdf --size letter --fontsize 10pt index.html > index.pdf

Linker Error C++ "undefined reference "

Your header file Hash.h declares "what class hash should look like", but not its implementation, which is (presumably) in some other source file we'll call Hash.cpp. By including the header in your main file, the compiler is informed of the description of class Hash when compiling the file, but not how class Hash actually works. When the linker tries to create the entire program, it then complains that the implementation (toHash::insert(int, char)) cannot be found.

The solution is to link all the files together when creating the actual program binary. When using the g++ frontend, you can do this by specifying all the source files together on the command line. For example:

g++ -o main Hash.cpp main.cpp

will create the main program called "main".

A TypeScript GUID class?

There is an implementation in my TypeScript utilities based on JavaScript GUID generators.

Here is the code:

_x000D_
_x000D_
class Guid {_x000D_
  static newGuid() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
      var r = Math.random() * 16 | 0,_x000D_
        v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
    });_x000D_
  }_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
  var id = Guid.newGuid();_x000D_
  console.log(id);_x000D_
}
_x000D_
_x000D_
_x000D_

Please note the following:

C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.

JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).

How to run vi on docker container?

login into container with the following command:

docker exec -it <container> bash

Then , run the following command .

apt-get update
apt-get install vim

Multi-line strings in PHP

Well,

$xml = "l
vv";

Works.

You can also use the following:

$xml = "l\nvv";

or

$xml = <<<XML
l
vv
XML;

Edit based on comment:

You can concatenate strings using the .= operator.

$str = "Hello";
$str .= " World";
echo $str; //Will echo out "Hello World";

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

To track down the correct parameters you need to go first to ?plot.default, which refers you to ?par and ?axis:

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=1.5,    #  for the xlab and ylab
           col="green")                   #  for the points

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

This exception is also thrown when a non-existent property is being updated dynamically, using reflection.

If one is using reflection to dynamically update property values, it's worth checking to make sure the passed PropertyName is identical to the actual property.

In my case, I was attempting to update Employee.firstName, but the property was actually Employee.FirstName.

Worth keeping in mind. :)

how to replace an entire column on Pandas.DataFrame

If the indices match then:

df['B'] = df1['E']

should work otherwise:

df['B'] = df1['E'].values

will work so long as the length of the elements matches

How to rename a file using Python

os.rename(old, new)

This is found in the Python docs: http://docs.python.org/library/os.html

How do I set headers using python's urllib?

adding HTTP headers using urllib2:

from the docs:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
resp = urllib2.urlopen(req)
content = resp.read()

How do you print in a Go test using the "testing" package?

t.Log and t.Logf do print out in your test but can often be missed as it prints on the same line as your test. What I do is Log them in a way that makes them stand out, ie

t.Run("FindIntercomUserAndReturnID should find an intercom user", func(t *testing.T) {

    id, err := ic.FindIntercomUserAndReturnID("[email protected]")
    assert.Nil(t, err)
    assert.NotNil(t, id)

    t.Logf("\n\nid: %v\n\n", *id)
})

which prints it to the terminal as,

=== RUN   TestIntercom
=== RUN   TestIntercom/FindIntercomUserAndReturnID_should_find_an_intercom_user
    TestIntercom/FindIntercomUserAndReturnID_should_find_an_intercom_user: intercom_test.go:34:

        id: 5ea8caed05a4862c0d712008

--- PASS: TestIntercom (1.45s)
    --- PASS: TestIntercom/FindIntercomUserAndReturnID_should_find_an_intercom_user (1.45s)
PASS
ok      github.com/RuNpiXelruN/third-party-delete-service   1.470s

How to add fonts to create-react-app based projects?

I was making mistakes like this.

@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i&amp;subset=cyrillic,cyrillic-ext,latin-ext";
@import "https://use.fontawesome.com/releases/v5.3.1/css/all.css";

It works properly this way

@import url(https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i&amp;subset=cyrillic,cyrillic-ext,latin-ext);
@import url(https://use.fontawesome.com/releases/v5.3.1/css/all.css);

Django CharField vs TextField

I had an strange problem and understood an unpleasant strange difference: when I get an URL from user as an CharField and then and use it in html a tag by href, it adds that url to my url and that's not what I want. But when I do it by Textfield it passes just the URL that user entered. look at these: my website address: http://myweb.com

CharField entery: http://some-address.com

when clicking on it: http://myweb.comhttp://some-address.com

TextField entery: http://some-address.com

when clicking on it: http://some-address.com

I must mention that the URL is saved exactly the same in DB by two ways but I don't know why result is different when clicking on them

"break;" out of "if" statement?

break interacts solely with the closest enclosing loop or switch, whether it be a for, while or do .. while type. It is frequently referred to as a goto in disguise, as all loops in C can in fact be transformed into a set of conditional gotos:

for (A; B; C) D;
// translates to
A;
goto test;
loop: D;
iter: C;
test: if (B) goto loop;
end:

while (B) D;          // Simply doesn't have A or C
do { D; } while (B);  // Omits initial goto test
continue;             // goto iter;
break;                // goto end;

The difference is, continue and break interact with virtual labels automatically placed by the compiler. This is similar to what return does as you know it will always jump ahead in the program flow. Switches are slightly more complicated, generating arrays of labels and computed gotos, but the way break works with them is similar.

The programming error the notice refers to is misunderstanding break as interacting with an enclosing block rather than an enclosing loop. Consider:

for (A; B; C) {
   D;
   if (E) {
       F;
       if (G) break;   // Incorrectly assumed to break if(E), breaks for()
       H;
   }
   I;
}
J;

Someone thought, given such a piece of code, that G would cause a jump to I, but it jumps to J. The intended function would use if (!G) H; instead.

Notepad++ cached files location

I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.

Property 'catch' does not exist on type 'Observable<any>'

With RxJS 5.5+, the catch operator is now deprecated. You should now use the catchError operator in conjunction with pipe.

RxJS v5.5.2 is the default dependency version for Angular 5.

For each RxJS Operator you import, including catchError you should now import from 'rxjs/operators' and use the pipe operator.

Example of catching error for an Http request Observable

import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
...

export class ExampleClass {
  constructor(private http: HttpClient) {
    this.http.request(method, url, options).pipe(
      catchError((err: HttpErrorResponse) => {
        ...
      }
    )
  }
  ...
}

Notice here that catch is replaced with catchError and the pipe operator is used to compose the operators in similar manner to what you're used to with dot-chaining.


See the rxjs documentation on pipable (previously known as lettable) operators for more info.

How to find the nearest parent of a Git branch?

Anyone wanting to do this these days - Atlassian's SourceTree application shows you a great visual representation of how your branches relate to one another, i.e. Where they began and where they currently sit in the commit order (e.g. HEAD or 4 commits behind, etc.).

Swift: Display HTML data in a label or textView

Swift 3

extension String {


var html2AttributedString: NSAttributedString? {
    guard
        let data = data(using: String.Encoding.utf8)
        else { return nil }
    do {
        return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:String.Encoding.utf8], documentAttributes: nil)
    } catch let error as NSError {
        print(error.localizedDescription)
        return  nil
    }
}
var html2String: String {
    return html2AttributedString?.string ?? ""
 }
}

Android emulator: How to monitor network traffic?

I would suggest you use Wireshark.

Steps:

  1. Install Wireshark.
  2. Select the network connection that you are using for the calls(for eg, select the Wifi if you are using it)
  3. There will be many requests and responses, close extra applications.
  4. Usually the requests are in green color, once you spot your request, copy the destination address and use the filter on top by typing ip.dst==52.187.182.185 by putting the destination address.

You can make use of other filtering techniques mentioned here to get specific traffic.

How to "perfectly" override a dict?

How can I make as "perfect" a subclass of dict as possible?

The end goal is to have a simple dict in which the keys are lowercase.

  • If I override __getitem__/__setitem__, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?

  • Am I preventing pickling from working, and do I need to implement __setstate__ etc?

  • Do I need repr, update and __init__?

  • Should I just use mutablemapping (it seems one shouldn't use UserDict or DictMixin)? If so, how? The docs aren't exactly enlightening.

The accepted answer would be my first approach, but since it has some issues, and since no one has addressed the alternative, actually subclassing a dict, I'm going to do that here.

What's wrong with the accepted answer?

This seems like a rather simple request to me:

How can I make as "perfect" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase.

The accepted answer doesn't actually subclass dict, and a test for this fails:

>>> isinstance(MyTransformedDict([('Test', 'test')]), dict)
False

Ideally, any type-checking code would be testing for the interface we expect, or an abstract base class, but if our data objects are being passed into functions that are testing for dict - and we can't "fix" those functions, this code will fail.

Other quibbles one might make:

  • The accepted answer is also missing the classmethod: fromkeys.
  • The accepted answer also has a redundant __dict__ - therefore taking up more space in memory:

    >>> s.foo = 'bar'
    >>> s.__dict__
    {'foo': 'bar', 'store': {'test': 'test'}}
    

Actually subclassing dict

We can reuse the dict methods through inheritance. All we need to do is create an interface layer that ensures keys are passed into the dict in lowercase form if they are strings.

If I override __getitem__/__setitem__, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?

Well, implementing them each individually is the downside to this approach and the upside to using MutableMapping (see the accepted answer), but it's really not that much more work.

First, let's factor out the difference between Python 2 and 3, create a singleton (_RaiseKeyError) to make sure we know if we actually get an argument to dict.pop, and create a function to ensure our string keys are lowercase:

from itertools import chain
try:              # Python 2
    str_base = basestring
    items = 'iteritems'
except NameError: # Python 3
    str_base = str, bytes, bytearray
    items = 'items'

_RaiseKeyError = object() # singleton for no-default behavior

def ensure_lower(maybe_str):
    """dict keys can be any hashable object - only call lower if str"""
    return maybe_str.lower() if isinstance(maybe_str, str_base) else maybe_str

Now we implement - I'm using super with the full arguments so that this code works for Python 2 and 3:

class LowerDict(dict):  # dicts take a mapping or iterable as their optional first argument
    __slots__ = () # no __dict__ - that would be redundant
    @staticmethod # because this doesn't make sense as a global function.
    def _process_args(mapping=(), **kwargs):
        if hasattr(mapping, items):
            mapping = getattr(mapping, items)()
        return ((ensure_lower(k), v) for k, v in chain(mapping, getattr(kwargs, items)()))
    def __init__(self, mapping=(), **kwargs):
        super(LowerDict, self).__init__(self._process_args(mapping, **kwargs))
    def __getitem__(self, k):
        return super(LowerDict, self).__getitem__(ensure_lower(k))
    def __setitem__(self, k, v):
        return super(LowerDict, self).__setitem__(ensure_lower(k), v)
    def __delitem__(self, k):
        return super(LowerDict, self).__delitem__(ensure_lower(k))
    def get(self, k, default=None):
        return super(LowerDict, self).get(ensure_lower(k), default)
    def setdefault(self, k, default=None):
        return super(LowerDict, self).setdefault(ensure_lower(k), default)
    def pop(self, k, v=_RaiseKeyError):
        if v is _RaiseKeyError:
            return super(LowerDict, self).pop(ensure_lower(k))
        return super(LowerDict, self).pop(ensure_lower(k), v)
    def update(self, mapping=(), **kwargs):
        super(LowerDict, self).update(self._process_args(mapping, **kwargs))
    def __contains__(self, k):
        return super(LowerDict, self).__contains__(ensure_lower(k))
    def copy(self): # don't delegate w/ super - dict.copy() -> dict :(
        return type(self)(self)
    @classmethod
    def fromkeys(cls, keys, v=None):
        return super(LowerDict, cls).fromkeys((ensure_lower(k) for k in keys), v)
    def __repr__(self):
        return '{0}({1})'.format(type(self).__name__, super(LowerDict, self).__repr__())

We use an almost boiler-plate approach for any method or special method that references a key, but otherwise, by inheritance, we get methods: len, clear, items, keys, popitem, and values for free. While this required some careful thought to get right, it is trivial to see that this works.

(Note that haskey was deprecated in Python 2, removed in Python 3.)

Here's some usage:

>>> ld = LowerDict(dict(foo='bar'))
>>> ld['FOO']
'bar'
>>> ld['foo']
'bar'
>>> ld.pop('FoO')
'bar'
>>> ld.setdefault('Foo')
>>> ld
{'foo': None}
>>> ld.get('Bar')
>>> ld.setdefault('Bar')
>>> ld
{'bar': None, 'foo': None}
>>> ld.popitem()
('bar', None)

Am I preventing pickling from working, and do I need to implement __setstate__ etc?

pickling

And the dict subclass pickles just fine:

>>> import pickle
>>> pickle.dumps(ld)
b'\x80\x03c__main__\nLowerDict\nq\x00)\x81q\x01X\x03\x00\x00\x00fooq\x02Ns.'
>>> pickle.loads(pickle.dumps(ld))
{'foo': None}
>>> type(pickle.loads(pickle.dumps(ld)))
<class '__main__.LowerDict'>

__repr__

Do I need repr, update and __init__?

We defined update and __init__, but you have a beautiful __repr__ by default:

>>> ld # without __repr__ defined for the class, we get this
{'foo': None}

However, it's good to write a __repr__ to improve the debugability of your code. The ideal test is eval(repr(obj)) == obj. If it's easy to do for your code, I strongly recommend it:

>>> ld = LowerDict({})
>>> eval(repr(ld)) == ld
True
>>> ld = LowerDict(dict(a=1, b=2, c=3))
>>> eval(repr(ld)) == ld
True

You see, it's exactly what we need to recreate an equivalent object - this is something that might show up in our logs or in backtraces:

>>> ld
LowerDict({'a': 1, 'c': 3, 'b': 2})

Conclusion

Should I just use mutablemapping (it seems one shouldn't use UserDict or DictMixin)? If so, how? The docs aren't exactly enlightening.

Yeah, these are a few more lines of code, but they're intended to be comprehensive. My first inclination would be to use the accepted answer, and if there were issues with it, I'd then look at my answer - as it's a little more complicated, and there's no ABC to help me get my interface right.

Premature optimization is going for greater complexity in search of performance. MutableMapping is simpler - so it gets an immediate edge, all else being equal. Nevertheless, to lay out all the differences, let's compare and contrast.

I should add that there was a push to put a similar dictionary into the collections module, but it was rejected. You should probably just do this instead:

my_dict[transform(key)]

It should be far more easily debugable.

Compare and contrast

There are 6 interface functions implemented with the MutableMapping (which is missing fromkeys) and 11 with the dict subclass. I don't need to implement __iter__ or __len__, but instead I have to implement get, setdefault, pop, update, copy, __contains__, and fromkeys - but these are fairly trivial, since I can use inheritance for most of those implementations.

The MutableMapping implements some things in Python that dict implements in C - so I would expect a dict subclass to be more performant in some cases.

We get a free __eq__ in both approaches - both of which assume equality only if another dict is all lowercase - but again, I think the dict subclass will compare more quickly.

Summary:

  • subclassing MutableMapping is simpler with fewer opportunities for bugs, but slower, takes more memory (see redundant dict), and fails isinstance(x, dict)
  • subclassing dict is faster, uses less memory, and passes isinstance(x, dict), but it has greater complexity to implement.

Which is more perfect? That depends on your definition of perfect.

How to add a class to a given element?

When the work I'm doing doesn't warrant using a library, I use these two functions:

function addClass( classname, element ) {
    var cn = element.className;
    //test for existance
    if( cn.indexOf( classname ) != -1 ) {
        return;
    }
    //add a space if the element already has class
    if( cn != '' ) {
        classname = ' '+classname;
    }
    element.className = cn+classname;
}

function removeClass( classname, element ) {
    var cn = element.className;
    var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" );
    cn = cn.replace( rxp, '' );
    element.className = cn;
}

What is the most efficient way to create HTML elements using jQuery?

You don't need raw performance from an operation you will perform extremely infrequently from the point of view of the CPU.

Linq: GroupBy, Sum and Count

I don't understand where the first "result with sample data" is coming from, but the problem in the console app is that you're using SelectMany to look at each item in each group.

I think you just want:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new ResultLine
            {
                ProductName = cl.First().Name,
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

The use of First() here to get the product name assumes that every product with the same product code has the same product name. As noted in comments, you could group by product name as well as product code, which will give the same results if the name is always the same for any given code, but apparently generates better SQL in EF.

I'd also suggest that you should change the Quantity and Price properties to be int and decimal types respectively - why use a string property for data which is clearly not textual?

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

git push rejected: error: failed to push some refs

Just do

git pull origin [branch]

and then you should be able to push.

If you have commits on your own and didn't push it the branch yet, try

git pull --rebase origin [branch]

and then you should be able to push.

Read more about handling branches with Git.

How do I debug jquery AJAX calls?

here is what I would do in order to debug and get the php errors into javascript console.log after an ajax call:

    $('#ChangePermission').click(function () {
    $.ajax({
        url: 'change_permission.php',
        type: 'POST',
        data: {
            'user': document.GetElementById("user").value,
            'perm': document.GetElementById("perm").value
        },
        success: function (data) {
            console.log(data);  
        },
        error: function (data) {
            console.log(data);
        }
    });
});

on the php side I would start by asking for all error returned to string concat and echo as a json encoded response that will includes php error messages as well if any.

<?php

error_reporting(E_ALL);
require_once(functions . php);
$result = "true";
$DBH = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DBH->prepare("INSERT INTO people ( username, permissions ) values (?, ?)");

if (isset($_POST["user"]) && isset($_POST["perm"])) {
    $STH->bindParam(1, $_POST["user"], PDO::PARAM_STR);
    $STH->bindParam(2, $_POST["perm"], PDO::PARAM_STR);
}
try {
    $STH->execute();
} catch (PDOException $e) {
    $result .= $e->getMessage;
}
echo json_encode($result);
?>

How to load a jar file at runtime

Reloading existing classes with existing data is likely to break things.

You can load new code into new class loaders relatively easily:

ClassLoader loader = URLClassLoader.newInstance(
    new URL[] { yourURL },
    getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
doRun.run();

Class loaders no longer used can be garbage collected (unless there is a memory leak, as is often the case with using ThreadLocal, JDBC drivers, java.beans, etc).

If you want to keep the object data, then I suggest a persistence mechanism such as Serialisation, or whatever you are used to.

Of course debugging systems can do fancier things, but are more hacky and less reliable.

It is possible to add new classes into a class loader. For instance, using URLClassLoader.addURL. However, if a class fails to load (because, say, you haven't added it), then it will never load in that class loader instance.

How should I copy Strings in Java?

Your second version is less efficient because it creates an extra string object when there is simply no need to do so.

Immutability means that your first version behaves the way you expect and is thus the approach to be preferred.

Change width of select tag in Twitter Bootstrap

I did a workaround by creating a new css class in my custom stylesheet as follows:

.selectwidthauto
{
     width:auto !important;
}

And then applied this class to all my select elements either manually like:

<select id="State" class="selectwidthauto">
...
</select>

Or using jQuery:

$('select').addClass('selectwidthauto');

How to save a dictionary to a file?

file_name = open("data.json", "w")
json.dump(test_response, file_name)
file_name.close()

or use context manager, which is better:

with open("data.json", "w") as file_name:
    json.dump(test_response, file_name)

SQL - Query to get server's IP address

It's in the @@SERVERNAME variable;

SELECT @@SERVERNAME;

Convert .class to .java

I'm guessing that either the class name is wrong - be sure to use the fully-resolved class name, with all packages - or it's not in the CLASSPATH so javap can't find it.

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

compile ("com.android.support:support-v4:22.2.0")
compile ("com.android.support:appcompat-v7:22.2.0")
compile ("com.android.support:support-annotations:22.2.0")
compile ("com.android.support:recyclerview-v7:22.2.0")
compile ("com.android.support:design:22.2.0")

paste the above code in your app gradle.

and while setting up the project select empty activity instead of blank activity.

jQuery issue in Internet Explorer 8

OK! I know that jQuery is loading. I know that jQuery.textshadow.js is loading. I can find both of the scripts in Developer Tools.

The weird part: this code is working in the content area but not in the banner. Even with a dedicated fixIE.css. AND it works when I put the css inline. (That, of course, messes up FireFox.)

I have even put in a conditional IE span around the text field in the banner with no luck.

I found no difference and had the same errors in both jquery-1.4.2.min.js and jquery-1.2.6.min.js. jquery.textshadow.js was downloaded from the jQuery site while trying to find a solution to this problem.

This is not posted to the Website