Programs & Examples On #Setuptools

Setuptools builds on Python’s distutils to provide easier building, distribution, and installation of libraries and applications.

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

Requirements files use an expanded pip format, which is only useful if you need to complement your setup.py with stronger constraints, for example specifying the exact urls some of the dependencies must come from, or the output of pip freeze to freeze the entire package set to known-working versions. If you don't need the extra constraints, use only a setup.py. If you feel like you really need to ship a requirements.txt anyway, you can make it a single line:

.

It will be valid and refer exactly to the contents of the setup.py that is in the same directory.

Installing SetupTools on 64-bit Windows

Create a file named python2.7.reg (registry file) and put this content into it:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Help]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Help\MainPythonDocumentation]
@="C:\\Python27\\Doc\\python26.chm"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\InstallPath]
@="C:\\Python27\\"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\InstallPath\InstallGroup]
@="Python 2.7"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Modules]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\PythonPath]
@="C:\\Python27\\Lib;C:\\Python27\\DLLs;C:\\Python27\\Lib\\lib-tk"

And make sure every path is right!

Then run (merge) it and done :)

Why can I not create a wheel in python?

Throwing in another answer: Try checking your PYTHONPATH.

First, try to install wheel again:

pip install wheel

This should tell you where wheel is installed, eg:

Requirement already satisfied: wheel in /usr/local/lib/python3.5/dist-packages

Then add the location of wheel to your PYTHONPATH:

export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python3.5/dist-packages/wheel

Now building a wheel should work fine.

python setup.py bdist_wheel

What's the proper way to install pip, virtualenv, and distribute for Python?

You can do this without installing anything into python itself.

You don't need sudo or any privileges.

You don't need to edit any files.

Install virtualenv into a bootstrap virtual environment. Use the that virtual environment to create more. Since virtualenv ships with pip and distribute, you get everything from one install.

  1. Download virtualenv:
  2. Unpack the source tarball
  3. Use the unpacked tarball to create a clean virtual environment. This virtual environment will be used to "bootstrap" others. All of your virtual environments will automatically contain pip and distribute.
  4. Using pip, install virtualenv into that bootstrap environment.
  5. Use that bootstrap environment to create more!

Here is an example in bash:

# Select current version of virtualenv:
VERSION=12.0.7
# Name your first "bootstrap" environment:
INITIAL_ENV=bootstrap
# Set to whatever python interpreter you want for your first environment:
PYTHON=$(which python)
URL_BASE=https://pypi.python.org/packages/source/v/virtualenv

# --- Real work starts here ---
curl -O $URL_BASE/virtualenv-$VERSION.tar.gz
tar xzf virtualenv-$VERSION.tar.gz
# Create the first "bootstrap" environment.
$PYTHON virtualenv-$VERSION/virtualenv.py $INITIAL_ENV
# Don't need this anymore.
rm -rf virtualenv-$VERSION
# Install virtualenv into the environment.
$INITIAL_ENV/bin/pip install virtualenv-$VERSION.tar.gz

Now you can use your "bootstrap" environment to create more:

# Create a second environment from the first:
$INITIAL_ENV/bin/virtualenv py-env1
# Create more:
$INITIAL_ENV/bin/virtualenv py-env2

Go nuts!

Note

This assumes you are not using a really old version of virtualenv. Old versions required the flags --no-site-packges (and depending on the version of Python, --distribute). Now you can create your bootstrap environment with just python virtualenv.py path-to-bootstrap or python3 virtualenv.py path-to-bootstrap.

Python setup.py develop vs install

Another thing that people may find useful when using the develop method is the --user option to install without sudo. Ex:

python setup.py develop --user

instead of

sudo python setup.py develop

How to install pip with Python 3?

And for Windows 8.1/10 OS Users just open cmd (command prompt)

write this : C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python36-32\Scripts

then

just write this : pip3 install {name of package}

Hint: the location of folder Python36-32 may get different for new python 3.x versions

No module named pkg_resources

On windows, I installed pip downloaded from www.lfd.uci.edu/~gohlke/pythonlibs/ then encontered this problem.

So I should have installed setuptools(easy_install) first.

How do I remove packages installed with Python's easy_install?

Official(?) instructions: http://peak.telecommunity.com/DevCenter/EasyInstall#uninstalling-packages

If you have replaced a package with another version, then you can just delete the package(s) you don't need by deleting the PackageName-versioninfo.egg file or directory (found in the installation directory).

If you want to delete the currently installed version of a package (or all versions of a package), you should first run:

easy_install -mxN PackageName

This will ensure that Python doesn't continue to search for a package you're planning to remove. After you've done this, you can safely delete the .egg files or directories, along with any scripts you wish to remove.

What is the official "preferred" way to install pip and virtualenv systemwide?

The former method is fine. The only problem I can see is that you might end up with an old version of setuptools (if the apt repository hasn't been kept up-to-date..

Why use pip over easy_install?

UPDATE: setuptools has absorbed distribute as opposed to the other way around, as some thought. setuptools is up-to-date with the latest distutils changes and the wheel format. Hence, easy_install and pip are more or less on equal footing now.

Source: http://pythonhosted.org/setuptools/merge-faq.html#why-setuptools-and-not-distribute-or-another-name

ActiveMQ or RabbitMQ or ZeroMQ or

ZeroMQ is really with zero queues! It is a really mistake! It does not hav queues, topics, persistence, nothing! It is only a middleware for sockets API. If it is what you are looking cool! otherwise forget it! it is not like activeMQ or rabbitmq.

Change image source with JavaScript

Under the TODOs, i am trying to implement your code in this posting. I am trying to take the large div on the left and make it change to reflect selections on the right. there are two selections, Ambient Temperature and Body Temperature

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title> Temperature Selection </title>_x000D_
<!-- css -->_x000D_
 <link rel="stylesheet" href="bootstrap-3/css/bootstrap.min.css">_x000D_
 <link rel="stylesheet" href="css/main.css">_x000D_
_x000D_
<!-- end css -->_x000D_
<!-- Java script files -->_x000D_
<!-- Date.js date os javascript helper -->_x000D_
    <script src="js/date.js"> </script>_x000D_
_x000D_
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->_x000D_
 <script src="js/jquery-2.1.1.min.js"></script>_x000D_
_x000D_
<!-- Include all compiled plugins (below), or include individual files as needed -->_x000D_
 <script src="bootstrap-3/js/bootstrap.min.js"> </script>_x000D_
 <script src="js/library.js"> </script>_x000D_
 <script src="js/sfds.js"> </script>_x000D_
_x000D_
 <script src="js/main.js"> </script>_x000D_
_x000D_
<!-- End Java script files -->_x000D_
_x000D_
<!--TODO: need to integrate this code into the project:-->_x000D_
<script type="text/javascript">_x000D_
    function changeImage(a) {_x000D_
        document.getElementById("img").src=a;_x000D_
    }_x000D_
</script>_x000D_
 <script>_x000D_
 _x000D_
 _x000D_
 $(document).ready(function() {_x000D_
 _x000D_
  $("#ambient").click(function(event){_x000D_
   var $this= $(this);_x000D_
   if($this.hasClass('clicked')){_x000D_
    $this.removeClass('clicked');_x000D_
    SFDS.setTemperatureType(0);_x000D_
    $this.find('h2').text('Select Ambient Temperature 21 Degrees C');_x000D_
    <!--added on 05/20/2015-->_x000D_
   }else{_x000D_
    SFDS.setTemperatureType(1);_x000D_
    $this.addClass('clicked');_x000D_
    $this.find('h2').text('Ambient Temperature 21 Degrees C Selected');_x000D_
_x000D_
_x000D_
   }_x000D_
  });_x000D_
  _x000D_
  $("#body").click(function(event){_x000D_
   var $this= $(this);_x000D_
   if($this.hasClass('clicked')){_x000D_
    $this.removeClass('clicked');_x000D_
    SFDS.setTemperatureType(0);_x000D_
    $this.find('h2').text('Select Body Temperature 37 Degrees C');_x000D_
    <!--added on 05/20/2015-->_x000D_
   }else{_x000D_
    SFDS.setTemperatureType(1);_x000D_
    $this.addClass('clicked');_x000D_
    $this.find('h2').text('Body Temperature 37 Degrees C Selected');_x000D_
_x000D_
_x000D_
   }_x000D_
  });_x000D_
  _x000D_
  _x000D_
  _x000D_
 });_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="container-fluid">_x000D_
 <header>_x000D_
  <div class="row">_x000D_
   <div class="col-xs-6">_x000D_
    <div id="date"><span class="date_time"></span></div>_x000D_
   </div>_x000D_
   <div class="col-xs-6">_x000D_
    <div id="time" class="text-right"><span class="date_time"></span></div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </header>_x000D_
 <div class="row">_x000D_
  <div class="col-md-offset-1 col-sm-3 col-xs-8 col-xs-offset-2 col-sm-offset-0">_x000D_
   <div id="temperature" class="main_button center-block">_x000D_
    <div class="large_circle_button"> _x000D_
     <h2>Select<br/>Temperature</h2>_x000D_
     <img class="center-block large_button_image" src="images/thermometer.png" alt=""> _x000D_
                    <!-- TODO <img src='images/dropsterilewater.png'  onclick='changeImage("images/dropsterilewater.png");'>_x000D_
                                <img src='images/imagecansterilesaline.png'  onclick='changeImage("images/imagecansterilesaline.png");'>-->_x000D_
    </div>_x000D_
    <h1></h1>_x000D_
   </div>_x000D_
  </div>_x000D_
  <div class=" col-md-6 col-sm-offset-1 col-sm-8 col-xs-12">_x000D_
   <div class="row">_x000D_
    <div class="col-xs-12">_x000D_
     <div id="ambient" class="large_rectangle_button">_x000D_
      <div class="label_wrapper">_x000D_
       <h2>Ambient<br/>Temperature<br/>21<sup>o</sup>C</h2>_x000D_
      </div>_x000D_
      <div class="image_wrapper">_x000D_
       <img src="images/house.png" alt="" class="ambient_temp_image">_x000D_
      </div>_x000D_
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
     </div>_x000D_
    </div>_x000D_
    <div class="col-xs-12">_x000D_
     <div id="body" class="large_rectangle_button">_x000D_
      <div class="label_wrapper">_x000D_
       <h2>Body<br/>Temperature<br/>37<sup>o</sup>C</h2>_x000D_
      </div>_x000D_
      <div class="image_wrapper">_x000D_
       <img src="images/bodytempman.png" alt="" class="body_temp_image">_x000D_
      </div>_x000D_
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
     </div>_x000D_
    </div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
_x000D_
    _x000D_
</div>_x000D_
<footer class="footer navbar-fixed-bottom">_x000D_
 <div class="container-fluid">_x000D_
  <div class="row cols-bottom">_x000D_
   <div class="col-sm-3">_x000D_
    <a href="main.html">_x000D_
    <div class="small_circle_button">     _x000D_
     <img src="images/buttonback.png" alt="back to home" class="settings"/> <!--  width="49" height="48" -->_x000D_
    </div>_x000D_
   </div></a><div class=" col-sm-6">_x000D_
    <div id="stop_button" >_x000D_
     <img src="images/stop.png" alt="stop" class="center-block stop_button" /> <!-- width="140" height="128" -->_x000D_
    </div>_x000D_
     _x000D_
   </div><div class="col-sm-3">_x000D_
    <div id="parker" class="pull-right">_x000D_
     <img src="images/#" alt="logo" /> <!-- width="131" height="65" -->_x000D_
    </div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
</footer>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Convert SVG image to PNG with PHP

I do not know of a standalone PHP / Apache solution, as this would require a PHP library that can read and render SVG images. I'm not sure such a library exists - I don't know any.

ImageMagick is able to rasterize SVG files, either through the command line or the PHP binding, IMagick, but seems to have a number of quirks and external dependencies as shown e.g. in this forum thread. I think it's still the most promising way to go, it's the first thing I would look into if I were you.

Scroll / Jump to id without jQuery

if you want smooth scrolling add behavior configuration.

document.getElementById('id').scrollIntoView({
  behavior: 'smooth'
});

What is middleware exactly?

From my own experience with webwork, a middleware was stuff between users (the web browser) and the backend database. It was the software that took stuff that users put in (example: orders for iPads, did some magical business logic, i.e. check if there are enough iPads available to fill the order) and updated the backend database to reflect those changes.

How to get the previous URL in JavaScript?

If you want to go to the previous page without knowing the url, you could use the new History api.

history.back(); //Go to the previous page
history.forward(); //Go to the next page in the stack
history.go(index); //Where index could be 1, -1, 56, etc.

But you can't manipulate the content of the history stack on browser that doesn't support the HTML5 History API

For more information see the doc

Position a CSS background image x pixels from the right?

Its been loong since this question has been asked, but I just ran into this problem and I got it by doing :

background-position:95% 50%;

Parse v. TryParse

The TryParse method allows you to test whether something is parseable. If you try Parse as in the first instance with an invalid int, you'll get an exception while in the TryParse, it returns a boolean letting you know whether the parse succeeded or not.

As a footnote, passing in null to most TryParse methods will throw an exception.

How to use onBlur event on Angular2?

you can use directly (blur) event in input tag.

<div>
   <input [value] = "" (blur) = "result = $event.target.value" placeholder="Type Something">
   {{result}}
</div>

and you will get output in "result"

Drop view if exists

your exists syntax is wrong and you should seperate DDL with go like below

if exists(select 1 from sys.views where name='tst' and type='v')
drop view tst;
go

create view tst
as
select * from test

you also can check existence test, with object_id like below

if object_id('tst','v') is not null
drop view tst;
go

create view tst
as
select * from test

In SQL 2016,you can use below syntax to drop

Drop view  if exists dbo.tst

From SQL2016 CU1,you can do below

create or alter view vwTest
as
 select 1 as col;
go

Add another class to a div

Well you just need to use document.getElementById('hello').setAttribute('class', 'someclass');.

Also innerHTML can lead to unexpected results! Consider the following;

var myParag = document.createElement('p');

if(under certain age)
{
    myParag.text="Good Bye";
    createCookie('age', 'not13', 0);
    return false;
{
else
{
    myParag.text="Hello";
    return true;
}

document.getElementById('hello').appendChild(myParag);

How to check if a value exists in a dictionary (python)

Use dictionary views:

if x in d.viewvalues():
    dosomething()..

Redirect on select option in select box

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value=""></option>
    <option value="http://google.com">Google</option>
    <option value="http://gmail.com">Gmail</option>
    <option value="http://youtube.com">Youtube</option>
</select>

Using "label for" on radio buttons

(Firstly read the other answers which has explained the for in the <label></label> tags. Well, both the tops answers are correct, but for my challenge, it was when you have several radio boxes, you should select for them a common name like name="r1" but with different ids id="r1_1" ... id="r1_2"

So this way the answer is more clear and removes the conflicts between name and ids as well.

You need different ids for different options of the radio box.

_x000D_
_x000D_
<input type="radio" name="r1" id="r1_1" />_x000D_
_x000D_
       <label for="r1_1">button text one</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_2" />_x000D_
_x000D_
       <label for="r1_2">button text two</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_3" />_x000D_
_x000D_
       <label for="r1_3">button text three</label>
_x000D_
_x000D_
_x000D_

Converting integer to binary in python

You can use just:

"{0:b}".format(n)

In my opinion this is the easiest way!

Hibernate: "Field 'id' doesn't have a default value"

"Field 'id' doesn't have a default value" because you didn't declare GenerationType.IDENTITY in GeneratedValue Annotation.

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

Count number of rows within each group

dplyr package does this with count/tally commands, or the n() function:

First, some data:

df <- data.frame(x = rep(1:6, rep(c(1, 2, 3), 2)), year = 1993:2004, month = c(1, 1:11))

Now the count:

library(dplyr)
count(df, year, month)
#piping
df %>% count(year, month)

We can also use a slightly longer version with piping and the n() function:

df %>% 
  group_by(year, month) %>%
  summarise(number = n())

or the tally function:

df %>% 
  group_by(year, month) %>%
  tally()

Java for loop syntax: "for (T obj : objects)"

The variable objectSummary holds the current object of type S3ObjectSummary returned from the objectListing.getObjectSummaries() and iterate over the collection.

Here is an example of this enhanced for loop from Java Tutorials

class EnhancedForDemo {
 public static void main(String[] args){
      int[] numbers = {1,2,3,4,5,6,7,8,9,10};
      for (int item : numbers) {
        System.out.println("Count is: " + item);
      }
 }
}

In this example, the variable item holds the current value from the numbers array.

Output is as follows:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Hope this helps !

Regex: ignore case sensitivity

The i flag is normally used for case insensitivity. You don't give a language here, but it'll probably be something like /G[ab].*/i or /(?i)G[ab].*/.

Email and phone Number Validation in android

in Kotlin you can use Extension function to validate input

// for Email validation

 fun String.isValidEmail(): Boolean =
        this.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches()

// for Phone validation

fun String.isValidMobile(phone: String): Boolean {
    return Patterns.PHONE.matcher(phone).matches()
}

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

As mentioned by others here, that you could have two adb's running ... And to add to these answers from a Linux box perspective ( for the next newbie who is working from Linux );

  1. Uninstall your distro's android-tools ( use zypper or yum etc )

    # zypper -v rm android-tools
    
  2. Find where your other adb is

    # find /home -iname "*adb"|grep -i android
    

    Say it was at ;

    /home/developer/Android/Sdk/platform-tools/adb

  3. Then Make a softlink to it in the /usr/bin folder

     ln -s /home/developer/Android/Sdk/platform-tools/adb  /usr/bin/adb
    
  4. Then;

     # adb start-server
    

How to work with progress indicator in flutter?

You can use FutureBuilder widget instead. This takes an argument which must be a Future. Then you can use a snapshot which is the state at the time being of the async call when loging in, once it ends the state of the async function return will be updated and the future builder will rebuild itself so you can then ask for the new state.

FutureBuilder(
  future:  myFutureFunction(),
  builder: (context, AsyncSnapshot<List<item>> snapshot) {
    if (!snapshot.hasData) {
      return Center(
        child: CircularProgressIndicator(),
      );
    } else {
     //Send the user to the next page.
  },
);

Here you have an example on how to build a Future

Future<void> myFutureFunction() async{
 await callToApi();}

Deprecated Java HttpClient - How hard can it be?

Use HttpClientBuilder to build the HttpClient instead of using DefaultHttpClient

ex:

MinimalHttpClient httpclient = new HttpClientBuilder().build();

 // Prepare a request object
 HttpGet httpget = new HttpGet("http://www.apache.org/");

How can I uninstall Ruby on ubuntu?

Run the following command on the terminal:

sudo apt-get autoremove ruby

Using Java to find substring of a bigger string using Regular Expression

I think your regular expression would look like:

/FOO\[(.+)\]/

Assuming that FOO going to be constant.

So, to put this in Java:

Pattern p = Pattern.compile("FOO\\[(.+)\\]");
Matcher m = p.matcher(inputLine);

With android studio no jvm found, JAVA_HOME has been set

Just delete the folder highlighted below. Depending on your Android Studio version, mine is 3.5 and reopen Android studio.

enter image description here

HTTP Get with 204 No Content: Is that normal

I use GET/204 with a RESTful collection that is a positional array of known fixed length but with holes.

GET /items
    200: ["a", "b", null]

GET /items/0
    200: "a"

GET /items/1
    200: "b"

GET /items/2
    204:

GET /items/3
    404: Not Found

How to convert a JSON string to a Map<String, String> with Jackson JSON

The following works for me:

Map<String, String> propertyMap = getJsonAsMap(json);

where getJsonAsMap is defined like so:

public HashMap<String, String> getJsonAsMap(String json)
{
    try
    {
        ObjectMapper mapper = new ObjectMapper();
        TypeReference<Map<String,String>> typeRef = new TypeReference<Map<String,String>>() {};
        HashMap<String, String> result = mapper.readValue(json, typeRef);

        return result;
    }
    catch (Exception e)
    {
        throw new RuntimeException("Couldnt parse json:" + json, e);
    }
}

Note that this will fail if you have child objects in your json (because they're not a String, they're another HashMap), but will work if your json is a key value list of properties like so:

{
    "client_id": "my super id",
    "exp": 1481918304,
    "iat": "1450382274",
    "url": "http://www.example.com"
}

How to replace comma (,) with a dot (.) using java

Your problem is not with the match / replacement, but that String is immutable, you need to assign the result:

str = str.replaceAll(",","."); // or "\\.", it doesn't matter...

jsPDF multi page PDF with HTML renderer

$( document ).ready(function() {    
$('#cmd').click(function() {
      var options = {
              pagesplit: true //include this in your code
      };
      var pdf = new jsPDF('p', 'pt', 'a4');
      pdf.addHTML($("#pdfContent"), 15, 15, options, function() {
        pdf.save('Menu.pdf');
      });
    });
});

How can I create a Java method that accepts a variable number of arguments?

The variable arguments must be the last of the parameters specified in your function declaration. If you try to specify another parameter after the variable arguments, the compiler will complain since there is no way to determine how many of the parameters actually belong to the variable argument.

void print(final String format, final String... arguments) {
    System.out.format( format, arguments );
}

Which browsers support <script async="async" />?

From your referenced page:

http://googlecode.blogspot.com/2009/12/google-analytics-launches-asynchronous.html

Firefox 3.6 is the first browser to officially offer support for this new feature. If you're curious, here are more details on the official HTML5 async specification.

How to set the title text color of UIButton?

This is swift 5 compatible answer. If you want to use one of the built-in colours then you can simply use

button.setTitleColor(.red, for: .normal)

If you want some custom colours, then create an extension for a UIColor as below first.

import UIKit
extension UIColor {
    static var themeMoreButton = UIColor.init(red: 53/255, green: 150/255, blue: 36/255, alpha: 1)
}

Then use it for your button as below.

button.setTitleColor(UIColor.themeMoreButton, for: .normal)

Tip: You can use this method to store custom colours from rgba colour code and reuse it throughout your application.

Unicode, UTF, ASCII, ANSI format differences

Going down your list:

  • "Unicode" isn't an encoding, although unfortunately, a lot of documentation imprecisely uses it to refer to whichever Unicode encoding that particular system uses by default. On Windows and Java, this often means UTF-16; in many other places, it means UTF-8. Properly, Unicode refers to the abstract character set itself, not to any particular encoding.
  • UTF-16: 2 bytes per "code unit". This is the native format of strings in .NET, and generally in Windows and Java. Values outside the Basic Multilingual Plane (BMP) are encoded as surrogate pairs. These used to be relatively rarely used, but now many consumer applications will need to be aware of non-BMP characters in order to support emojis.
  • UTF-8: Variable length encoding, 1-4 bytes per code point. ASCII values are encoded as ASCII using 1 byte.
  • UTF-7: Usually used for mail encoding. Chances are if you think you need it and you're not doing mail, you're wrong. (That's just my experience of people posting in newsgroups etc - outside mail, it's really not widely used at all.)
  • UTF-32: Fixed width encoding using 4 bytes per code point. This isn't very efficient, but makes life easier outside the BMP. I have a .NET Utf32String class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)
  • ASCII: Single byte encoding only using the bottom 7 bits. (Unicode code points 0-127.) No accents etc.
  • ANSI: There's no one fixed ANSI encoding - there are lots of them. Usually when people say "ANSI" they mean "the default locale/codepage for my system" which is obtained via Encoding.Default, and is often Windows-1252 but can be other locales.

There's more on my Unicode page and tips for debugging Unicode problems.

The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.

How to use onClick event on react Link component?

You are passing hello() as a string, also hello() means execute hello immediately.

try

onClick={hello}

How to delete a stash created with git stash create?

The Document is here (in Chinese)please click.

you can use

git stash list

git stash drop stash@{0}

enter image description here

Adjust width and height of iframe to fit with content in it

I figured out another solution after some experimenting. I originally tried the code marked as 'best answer' to this question and it didn't work. My guess is because my iframe in my program at the time was dynamically generated. Here is the code I used (it worked for me):

Javascript inside the iframe that is being loaded:

window.onload = function()
    {
        parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
        parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
    };

It is necessary to add 4 or more pixels to the height to remove scroll bars (some weird bug/effect of iframes). The width is even stranger, you are safe to add 18px to the width of the body. Also make sure that you have the css for the iframe body applied (below).

html, body {
   margin:0;
   padding:0;
   display:table;
}

iframe {
   border:0;
   padding:0;
   margin:0;
}

Here is the html for the iframe:

<iframe id="fileUploadIframe" src="php/upload/singleUpload.html"></iframe>

Here is all the code within my iframe:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>File Upload</title>
    <style type="text/css">
    html, body {
        margin:0;
        padding:0;
        display:table;
    }
    </style>
    <script type="text/javascript">
    window.onload = function()
    {
        parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
        parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
    };
    </script>
</head>
<body>
    This is a test.<br>
    testing
</body>
</html>

I have done testing in chrome and a little in firefox (in windows xp). I still have more testing to do, so please tell me how this works for you.

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

Try enclosing your date into a character string.

 select * 
 from dbo.March2010 A
 where A.Date >= '2010-04-01';

mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

Simply put, you need to rewrite all of your database connections and queries.

You are using mysql_* functions which are now deprecated and will be removed from PHP in the future. So you need to start using MySQLi or PDO instead, just as the error notice warned you.

A basic example of using PDO (without error handling):

<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();
?>

A basic example of using MySQLi (without error handling):

$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$result = $db->query("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");

Here's a handy little PDO tutorial to get you started. There are plenty of others, and ones about the PDO alternative, MySQLi.

How do I generate sourcemaps when using babel and webpack?

Maybe someone else has this problem at one point. If you use the UglifyJsPlugin in webpack 2 you need to explicitly specify the sourceMap flag. For example:

new webpack.optimize.UglifyJsPlugin({ sourceMap: true })

How to handle floats and decimal separators with html5 input type number

When you call $("#my_input").val(); it returns as string variable. So use parseFloat and parseIntfor converting. When you use parseFloat your desktop or phone ITSELF understands the meaning of variable.

And plus you can convert a float to string by using toFixed which has an argument the count of digits as below:

var i = 0.011;
var ss = i.toFixed(2); //It returns 0.01

How to get everything after a certain character?

Here is the method by using explode:

$text = explode('_', '233718_This_is_a_string', 2)[1]; // Returns This_is_a_string

or:

$text = @end((explode('_', '233718_This_is_a_string', 2)));

By specifying 2 for the limit parameter in explode(), it returns array with 2 maximum elements separated by the string delimiter. Returning 2nd element ([1]), will give the rest of string.


Here is another one-liner by using strpos (as suggested by @flu):

$needle = '233718_This_is_a_string';
$text = substr($needle, (strpos($needle, '_') ?: -1) + 1); // Returns This_is_a_string

How to get only time from date-time C#

This works for me. I discovered it when I had to work with DateTime.Date to get only the date part.

var wholeDate = DateTime.Parse("6/22/2009 10:00:00 AM");
var time = wholeDate - wholeDate.Date;

What's the environment variable for the path to the desktop?

you could also open a DOS command prompt and execute the set command.

This will give you an idea what environment variables are available on your system.

E.g. - since you where specifically asking for a non-english Windows - heres is an example of my own German Edition (Window7-64bit) :

set > env.txt
type env.txt

ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\SOF\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=VMSOF
ComSpec=C:\Windows\system32\cmd.exe
FP_NO_HOST_CHECK=NO
HOMEDRIVE=C:
HOMEPATH=\Users\SOF
LOCALAPPDATA=C:\Users\SOF\AppData\Local
LOGONSERVER=\\VMSOF
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;C:\Program Files (x86)\CMake 2.8\bin;C:\Program Files (x86)\emacs-22.3\bin;C:\Program Files (x86)\GnuWin32\bin;
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=AMD64 Family 15 Model 67 Stepping 3, AuthenticAMD
PROCESSOR_LEVEL=15
PROCESSOR_REVISION=4303
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\Windows
TEMP=C:\Users\SOF\AppData\Local\Temp
TMP=C:\Users\SOF\AppData\Local\Temp
USERDOMAIN=VMSOF
USERNAME=SOF
USERPROFILE=C:\Users\SOF
VBOX_INSTALL_PATH=C:\Program Files\Sun\VirtualBox\
VS90COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\
windir=C:\Windows

Set attribute without value

Perhaps try:

var body = document.getElementsByTagName('body')[0];
body.setAttribute("data-body","");

Static vs class functions/variables in Swift classes?

static and class both associate a method with a class, rather than an instance of a class. The difference is that subclasses can override class methods; they cannot override static methods.

class properties will theoretically function in the same way (subclasses can override them), but they're not possible in Swift yet.

Multi-Column Join in Hibernate/JPA Annotations

This worked for me . In my case 2 tables foo and boo have to be joined based on 3 different columns.Please note in my case ,in boo the 3 common columns are not primary key

i.e., one to one mapping based on 3 different columns

@Entity
@Table(name = "foo")
public class foo implements Serializable
{
    @Column(name="foocol1")
    private String foocol1;
    //add getter setter
    @Column(name="foocol2")
    private String foocol2;
    //add getter setter
    @Column(name="foocol3")
    private String foocol3;
    //add getter setter
    private Boo boo;
    private int id;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "brsitem_id", updatable = false)
    public int getId()
    {
        return this.id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    @OneToOne
    @JoinColumns(
    {
        @JoinColumn(updatable=false,insertable=false, name="foocol1", referencedColumnName="boocol1"),
        @JoinColumn(updatable=false,insertable=false, name="foocol2", referencedColumnName="boocol2"),
        @JoinColumn(updatable=false,insertable=false, name="foocol3", referencedColumnName="boocol3")
    }
    )
    public Boo getBoo()
    {
        return boo;
    }
    public void setBoo(Boo boo)
    {
        this.boo = boo;
    }
}





@Entity
@Table(name = "boo")
public class Boo implements Serializable
{
    private int id;
    @Column(name="boocol1")
    private String boocol1;
    //add getter setter
    @Column(name="boocol2")
    private String boocol2;
    //add getter setter
    @Column(name="boocol3")
    private String boocol3;
    //add getter setter
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "item_id", updatable = false)
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
}

How can I generate a list of consecutive numbers?

Note :- Certainly in python-3x you need to use Range function It works to generate numbers on demand, standard method to use Range function to make a list of consecutive numbers is

x=list(range(10))
#"list"_will_make_all_numbers_generated_by_range_in_a_list
#number_in_range_(10)_is_an_option_you_can_change_as_you_want
print (x)
#Output_is_ [0,1,2,3,4,5,6,7,8,9]

Also if you want to make an function to generate a list of consecutive numbers by using Range function watch this code !

def  consecutive_numbers(n) :
    list=[i for i in range(n)]
    return (list)
print(consecutive_numbers(10))

Good Luck!

CSS Animation onClick

You can achieve this by binding an onclick listener and then adding the animate class like this:

$('#button').onClick(function(){
    $('#target_element').addClass('animate_class_name');
});

JSON.Net Self referencing loop detected

If using ASP.NET Core MVC, add this to the ConfigureServices method of your startup.cs file:

services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling =            
        Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );

How do I print out the value of this boolean? (Java)

There are several problems.

One is of style; always capitalize class names. This is a universally observed Java convention. Failing to do so confuses other programmers.

Secondly, the line

System.out.println(boolean isLeapYear);

is a syntax error. Delete it.

Thirdly.

You never call the function from your main routine. That is why you never see any reply to the input.

React proptype array with shape

There's a ES6 shorthand import, you can reference. More readable and easy to type.

import React, { Component } from 'react';
import { arrayOf, shape, number } from 'prop-types';

class ExampleComponent extends Component {
  static propTypes = {
    annotationRanges: arrayOf(shape({
      start: number,
      end: number,
    })).isRequired,
  }

  static defaultProps = {
     annotationRanges: [],
  }
}

Fastest way to convert a dict's keys & values from `unicode` to `str`?

I know I'm late on this one:

def convert_keys_to_string(dictionary):
    """Recursively converts dictionary keys to strings."""
    if not isinstance(dictionary, dict):
        return dictionary
    return dict((str(k), convert_keys_to_string(v)) 
        for k, v in dictionary.items())

What's the simplest way to print a Java array?

// array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};

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

output: [1, 2, 3, 4, 5]

// array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};

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

output: [John, Mary, Bob]

How to refer environment variable in POM.xml?

You can use <properties> tag to define a custom variable and ${variable} pattern to use it

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <!-- define -->
    <properties>
        <property.name>1.0</property.name>
    </properties>

    <!-- using -->
    <version>${property.name}</version>

</project>

What is java pojo class, java bean, normal class?

POJO = Plain Old Java Object. It has properties, getters and setters for respective properties. It may also override Object.toString() and Object.equals().

Java Beans : See Wiki link.

Normal Class : Any java Class.

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

While other answers nicely described all differences between C++ casts, I would like to add a short note why you should not use C-style casts (Type) var and Type(var).

For C++ beginners C-style casts look like being the superset operation over C++ casts (static_cast<>(), dynamic_cast<>(), const_cast<>(), reinterpret_cast<>()) and someone could prefer them over the C++ casts. In fact C-style cast is the superset and shorter to write.

The main problem of C-style casts is that they hide developer real intention of the cast. The C-style casts can do virtually all types of casting from normally safe casts done by static_cast<>() and dynamic_cast<>() to potentially dangerous casts like const_cast<>(), where const modifier can be removed so the const variables can be modified and reinterpret_cast<>() that can even reinterpret integer values to pointers.

Here is the sample.

int a=rand(); // Random number.

int* pa1=reinterpret_cast<int*>(a); // OK. Here developer clearly expressed he wanted to do this potentially dangerous operation.

int* pa2=static_cast<int*>(a); // Compiler error.
int* pa3=dynamic_cast<int*>(a); // Compiler error.

int* pa4=(int*) a; // OK. C-style cast can do such cast. The question is if it was intentional or developer just did some typo.

*pa4=5; // Program crashes.

The main reason why C++ casts were added to the language was to allow a developer to clarify his intentions - why he is going to do that cast. By using C-style casts which are perfectly valid in C++ you are making your code less readable and more error prone especially for other developers who didn't create your code. So to make your code more readable and explicit you should always prefer C++ casts over C-style casts.

Here is a short quote from Bjarne Stroustrup's (the author of C++) book The C++ Programming Language 4th edition - page 302.

This C-style cast is far more dangerous than the named conversion operators because the notation is harder to spot in a large program and the kind of conversion intended by the programmer is not explicit.

Returning from a void function

The first way is "more correct", what intention could there be to express? If the code ends, it ends. That's pretty clear, in my opinion.

I don't understand what could possibly be confusing and need clarification. If there's no looping construct being used, then what could possibly happen other than that the function stops executing?

I would be severly annoyed by such a pointless extra return statement at the end of a void function, since it clearly serves no purpose and just makes me feel the original programmer said "I was confused about this, and now you can be too!" which is not very nice.

Is Python interpreted, or compiled, or both?

According to the official Python site, it's interpreted.

https://www.python.org/doc/essays/blurb/

Python is an interpreted, object-oriented, high-level programming language...

...

Since there is no compilation step ...

...

The Python interpreter and the extensive standard library are available...

...

Instead, when the interpreter discovers an error, it raises an exception. When the program doesn't catch the exception, the interpreter prints a stack trace.

Assigning a function to a variable

When you assign a function to a variable you don't use the () but simply the name of the function.

In your case given def x(): ..., and variable silly_var you would do something like this:

silly_var = x

and then you can call the function either with

x()

or

silly_var()

When do you use the "this" keyword?

[C++]

this is used in the assignment operator where most of the time you have to check and prevent strange (unintentional, dangerous, or just a waste of time for the program) things like:

A a;
a = a;

Your assignment operator will be written:

A& A::operator=(const A& a) {
    if (this == &a) return *this;

    // we know both sides of the = operator are different, do something...

    return *this;
}

Get program path in VB.NET?

For that you can use the Application object.

Startup path, just the folder, use Application.StartupPath()

Dim appPath As String = Application.StartupPath()

Full .exe path, including the program.exe name on the end:, use Application.ExecutablePath()

Dim exePath As String = Application.ExecutablePath()

How to use jQuery with Angular?

To Use Jquery in Angular2(4)

Follow these setps

install the Jquery and Juqry type defination

For Jquery Installation npm install jquery --save

For Jquery Type defination Installation npm install @types/jquery --save-dev

and then simply import the jquery

import { Component } from '@angular/core';
import * as $ from 'jquery';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent { 
  console.log($(window)); // jquery is accessible 
}

Calling pylab.savefig without display in ipython

This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

plt.plot([1,2,3])
plt.savefig('/tmp/test.png')

EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show() when you are ready to display the plots:

import matplotlib.pyplot as plt

# Turn interactive plotting off
plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')

# Display all "open" (non-closed) figures
plt.show()

Windows ignores JAVA_HOME: how to set JDK as default?

Set Path environment variable to your desired jdk/bin directory

Core Data: Quickest way to delete all instances of an entity

In Swift 2.0:

func deleteAllData(entity: String)
{
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: entity)
    fetchRequest.returnsObjectsAsFaults = false

    do 
    {
        let results = try managedContext.executeFetchRequest(fetchRequest)
        for managedObject in results
        {
            let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
            managedContext.deleteObject(managedObjectData)
        }
    } catch let error as NSError {
        print("Detele all data in \(entity) error : \(error) \(error.userInfo)")
    }
}

Checking if an object is a given type in Swift

If you only want to know if an object is a subtype of a given type then there is a simpler approach:

class Shape {}
class Circle : Shape {}
class Rectangle : Shape {}

func area (shape: Shape) -> Double {
  if shape is Circle { ... }
  else if shape is Rectangle { ... }
}

“Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.” Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.

In the above the phrase 'of a certain subclass type' is important. The use of is Circle and is Rectangle is accepted by the compiler because that value shape is declared as Shape (a superclass of Circle and Rectangle).

If you are using primitive types, the superclass would be Any. Here is an example:

 21> func test (obj:Any) -> String {
 22.     if obj is Int { return "Int" }
 23.     else if obj is String { return "String" }
 24.     else { return "Any" }
 25. } 
 ...  
 30> test (1)
$R16: String = "Int"
 31> test ("abc")
$R17: String = "String"
 32> test (nil)
$R18: String = "Any"

How to tag docker image with docker-compose

you can try:

services:
  nameis:
    container_name: hi_my
    build: .
    image: hi_my_nameis:v1.0.0

Getting rid of bullet points from <ul>

The following code

_x000D_
_x000D_
#menu li{
  list-style-type: none;
}
_x000D_
<ul id="menu">
    <li>Root node 1</li>
    <li>Root node 2</li>
</ul>
_x000D_
_x000D_
_x000D_

will produce this output:

output is

PHP Fatal error: Class 'PDO' not found

you can just find-out loaded config file by executing below command,

 php -i | grep 'php.ini'

Then add below lines to correct php.ini file

extension=pdo.so
extension=pdo_sqlite.so
extension=pdo_mysql.so
extension=sqlite.so

Then restart web server,

service httpd restart

How to define hash tables in Bash?

This is what I was looking for here:

declare -A hashmap
hashmap["key"]="value"
hashmap["key2"]="value2"
echo "${hashmap["key"]}"
for key in ${!hashmap[@]}; do echo $key; done
for value in ${hashmap[@]}; do echo $value; done
echo hashmap has ${#hashmap[@]} elements

This did not work for me with bash 4.1.5:

animals=( ["moo"]="cow" )

How to window.scrollTo() with a smooth effect

2018 Update

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
  top: 400,_x000D_
  behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
  height: 1000px;_x000D_
  background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
  <button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Older solutions

You can do something like this:

_x000D_
_x000D_
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
  var i = 10;_x000D_
  var int = setInterval(function() {_x000D_
    window.scrollTo(0, i);_x000D_
    i += 10;_x000D_
    if (i >= 200) clearInterval(int);_x000D_
  }, 20);_x000D_
})
_x000D_
body {_x000D_
  background: #3a2613;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
_x000D_
_x000D_

ES6 recursive approach:

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
  let i = h || 0;_x000D_
  if (i < 200) {_x000D_
    setTimeout(() => {_x000D_
      window.scrollTo(0, i);_x000D_
      smoothScroll(i + 10);_x000D_
    }, 10);_x000D_
  }_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
  background: #9a6432;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
_x000D_
_x000D_

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Upgrade pip as follows:

curl https://bootstrap.pypa.io/get-pip.py | python

Note: You may need to use sudo python above if not in a virtual environment.

What's happening:

Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.

(Note that upgrading pip via pip install --upgrade pip will also not upgrade it correctly. It is a chicken-and-egg issue)

This thread explains it (thanks to this Twitter post):

Mac users who use pip and PyPI:

If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:

curl https://bootstrap.pypa.io/get-pip.py | python

and we recommend you do that by April 8th.

Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/

Also, the Python status page:

Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC

Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC

Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:

pip install --upgrade setuptools

Python Pandas - Missing required dependencies ['numpy'] 1

you are running python 3.7

create environment for python 3.6

python3.6 filename.py

How to use data-binding with Fragment

Try this in Android DataBinding

FragmentMainBinding binding;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false);
        View rootView = binding.getRoot();
        initInstances(savedInstanceState);
        return rootView;
}

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow

Trigger change() event when setting <select>'s value with val() function

As jQuery won't trigger native change event but only triggers its own change event. If you bind event without jQuery and then use jQuery to trigger it the callbacks you bound won't run !

The solution is then like below (100% working) :

var sortBySelect = document.querySelector("select.your-class"); 
sortBySelect.value = "new value"; 
sortBySelect.dispatchEvent(new Event("change"));

go to character in vim

:goto 21490 will take you to the 21490th byte in the buffer.

cleanup php session files

To handle session properly, take a look at http://php.net/manual/en/session.configuration.php.

There you'll find these variables:

  • session.gc_probability
  • session.gc_divisor
  • session.gc_maxlifetime

These control the garbage collector (GC) probability of running with each page request.

You could set those with ini_set() at the beginning of your script or .htaccess file so you get certainty to some extent they will get deleted sometime.

can't multiply sequence by non-int of type 'float'

In this line:

fund = fund * (1 + 0.01 * growthRates) + depositPerYear

I think you mean this:

fund = fund * (1 + 0.01 * i) + depositPerYear

When you try to multiply a float by growthRates (which is a list), you get that error.

How do I run a single test using Jest?

There is now a nice Jest plugin for this called jest-watch-typeahead it makes this process much simpler.

$_POST not working. "Notice: Undefined index: username..."

first of all,

be sure that there is a post

if(isset($_POST['username'])) { 
    // check if the username has been set
}

second, and most importantly, sanitize the data, meaning that

$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";

is deadly dangerous, instead use

$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";

and please research the subject sql injection

Angular 5 ngHide ngShow [hidden] not working

There is two way for hide a element

  1. Use the "hidden" html attribute But in angular you can bind it with one or more fields like this :

    <input class="txt" type="password" [(ngModel)]="input_pw" [hidden]="isHidden">

2.Better way of doing this is to use " *ngIf " directive like this :

<input class="txt" type="password" [(ngModel)]="input_pw" *ngIf="!isHidden">

Now why this is a better way because it doesn't just hide the element, it will removes it from the html code so this will help your page to render.

Force browser to clear cache

In addition to setting Cache-control: no-cache, you should also set the Expires header to -1 if you would like the local copy to be refreshed each time (some versions of IE seem to require this).

See HTTP Cache - check with the server, always sending If-Modified-Since

Formatting MM/DD/YYYY dates in textbox in VBA

Private Sub txtBoxBDayHim_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii >= 48 And KeyAscii <= 57 Or KeyAscii = 8 Then 'only numbers and backspace
    If KeyAscii = 8 Then 'if backspace, ignores + "/"
    Else
        If txtBoxBDayHim.TextLength = 10 Then 'limit textbox to 10 characters
        KeyAscii = 0
        Else
            If txtBoxBDayHim.TextLength = 2 Or txtBoxBDayHim.TextLength = 5 Then 'adds / automatically
            txtBoxBDayHim.Text = txtBoxBDayHim.Text + "/"
            End If
        End If
    End If
Else
KeyAscii = 0
End If
End Sub

This works for me. :)

Your code helped me a lot. Thanks!

I'm brazilian and my english is poor, sorry for any mistake.

iOS Remote Debugging

Note: I have no affiliation with Ghostlab creators Vanamco whatsoever.

It was important to me to be able to debug Chrome-specific problems, so I set out to find something that could help me with that. I ended up happily throwing my money at Ghostlab 3. I can test Chrome and Safari mobile browsers as if I was viewing them on my desktop. It just gives me a LAN address to use for any device I’d like to debug. Each application using that address will appear in the list in Ghostlab.

enter image description here

enter image description here

Highly recommended.

Check if any ancestor has a class using jQuery

There are many ways to filter for element ancestors.

if ($elem.closest('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents().hasClass('parentClass')) {/*...*/}
if ($('.parentClass').has($elem).length /* > 0*/) {/*...*/}
if ($elem.is('.parentClass *')) {/*...*/} 

Beware, closest() method includes element itself while checking for selector.

Alternatively, if you have a unique selector matching the $elem, e.g #myElem, you can use:

if ($('.parentClass:has(#myElem)').length /* > 0*/) {/*...*/}
if(document.querySelector('.parentClass #myElem')) {/*...*/}

If you want to match an element depending any of its ancestor class for styling purpose only, just use a CSS rule:

.parentClass #myElem { /* CSS property set */ }

Is mongodb running?

To check current running status of mongodb use: sudo service mongodb status

Concat all strings inside a List<string> using LINQ

By using LINQ, this should work;

string delimiter = ",";
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(items.Aggregate((i, j) => i + delimiter + j));

class description:

public class Foo
{
    public string Boo { get; set; }
}

Usage:

class Program
{
    static void Main(string[] args)
    {
        string delimiter = ",";
        List<Foo> items = new List<Foo>() { new Foo { Boo = "ABC" }, new Foo { Boo = "DEF" },
            new Foo { Boo = "GHI" }, new Foo { Boo = "JKL" } };

        Console.WriteLine(items.Aggregate((i, j) => new Foo{Boo = (i.Boo + delimiter + j.Boo)}).Boo);
        Console.ReadKey();

    }
}

And here is my best :)

items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j)

docker run <IMAGE> <MULTIPLE COMMANDS>

bash -c works well if the commands you are running are relatively simple. However, if you're trying to run a long series of commands full of control characters, it can get complex.

I successfully got around this by piping my commands into the process from the outside, i.e.

cat script.sh | docker run -i <image> /bin/bash

Is it possible to play music during calls so that the partner can hear it ? Android

Two answers, both valid, depending on how sloppy you like to be:

1) No, it's not currently possible to inject audio into a phone conversation.

2) Yes, it's possible. It's also an ugly, ugly kludge. Turn on the hands free function of your phone. Create a media player, set the media source, set the volume to 1.0f (highest) and call player.start(). If the microphone and speakers on the phone are of reasonable quality, the other party to the call will hear the music. He or she will also continue to hear anything you say, as well as ambient and other sounds in your immediate vicinity.

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

In testng.xml file, remove "." from tag "" class name if you are not using packages.

Add event handler for body.onload by javascript within <body> part

As @epascarello mentioned for W3C standard browsers, you should use:

body.addEventListener("load", init, false);

However, if you want it to work on IE<9 as well you can use:

var prefix = window.addEventListener ? "" : "on";
var eventName = window.addEventListener ? "addEventListener" : "attachEvent";
document.body[eventName](prefix + "load", init, false);

Or if you want it in a single line:

document.body[window.addEventListener ? 'addEventListener' : 'attachEvent'](
    window.addEventListener ? "load" : "onload", init, false);

Note: here I get a straight reference to the body element via the document, saving the need for the first line.

Also, if you're using jQuery, and you want to use the DOM ready event rather than when the body loads, the answer can be even shorter...

$(init);

What is the purpose of Looper and how to use it?

Life span of java Thread is over after completion of run() method. Same thread can't be started again.

Looper transforms normal Thread into a message loop. Key methods of Looper are :

void prepare ()

Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop() after calling this method, and end it by calling quit().

void loop ()

Run the message queue in this thread. Be sure to call quit() to end the loop.

void quit()

Quits the looper.

Causes the loop() method to terminate without processing any more messages in the message queue.

This mindorks article by Janishar explains the core concepts in nice way.

enter image description here

Looper is associated with a Thread. If you need Looper on UI thread, Looper.getMainLooper() will return associated thread.

You need Looper to be associated with a Handler.

Looper, Handler, and HandlerThread are the Android’s way of solving the problems of asynchronous programming.

Once you have Handler, you can call below APIs.

post (Runnable r)

Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.

boolean sendMessage (Message msg)

Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(Message), in the thread attached to this handler.

HandlerThread is handy class for starting a new thread that has a looper. The looper can then be used to create handler classes

In some scenarios, you can't run Runnable tasks on UI Thread. e.g. Network operations : Send message on a socket, open an URL and get content by reading InputStream

In these cases, HandlerThread is useful. You can get Looper object from HandlerThread and create a Handler on HandlerThread instead of main thread.

The HandlerThread code will be like this:

@Override
public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    Looper.loop();
    mTid = -1;
}

Refer to below post for example code:

Android: Toast in a thread

What is the problem with shadowing names defined in outer scopes?

The currently most up-voted and accepted answer and most answers here miss the point.

It doesn't matter how long your function is, or how you name your variable descriptively (to hopefully minimize the chance of potential name collision).

The fact that your function's local variable or its parameter happens to share a name in the global scope is completely irrelevant. And in fact, no matter how carefully you choose you local variable name, your function can never foresee "whether my cool name yadda will also be used as a global variable in future?". The solution? Simply don't worry about that! The correct mindset is to design your function to consume input from and only from its parameters in signature. That way you don't need to care what is (or will be) in global scope, and then shadowing becomes not an issue at all.

In other words, the shadowing problem only matters when your function need to use the same name local variable and the global variable. But you should avoid such design in the first place. The OP's code does not really have such design problem. It is just that PyCharm is not smart enough and it gives out a warning just in case. So, just to make PyCharm happy, and also make our code clean, see this solution quoting from silyevsk's answer to remove the global variable completely.

def print_data(data):
    print data

def main():
    data = [4, 5, 6]
    print_data(data)

main()

This is the proper way to "solve" this problem, by fixing/removing your global thing, not adjusting your current local function.

Find if variable is divisible by 2

You can do it in a better way (up to 50 % faster than modulo operator):

odd: x & 1 even: !(x & 1)

Reference: High Performance JavaScript, 8. ->Bitwise Operators

Finalize vs Dispose

Others have already covered the difference between Dispose and Finalize (btw the Finalize method is still called a destructor in the language specification), so I'll just add a little about the scenarios where the Finalize method comes in handy.

Some types encapsulate disposable resources in a manner where it is easy to use and dispose of them in a single action. The general usage is often like this: open, read or write, close (Dispose). It fits very well with the using construct.

Others are a bit more difficult. WaitEventHandles for instances are not used like this as they are used to signal from one thread to another. The question then becomes who should call Dispose on these? As a safeguard types like these implement a Finalize method, which makes sure resources are disposed when the instance is no longer referenced by the application.

Windows equivalent of $export

To translate your *nix style command script to windows/command batch style it would go like this:

SET PROJ_HOME=%USERPROFILE%/proj/111
SET PROJECT_BASEDIR=%PROJ_HOME%/exercises/ex1
mkdir "%PROJ_HOME%"

mkdir on windows doens't have a -p parameter : from the MKDIR /? help:

MKDIR creates any intermediate directories in the path, if needed.

which basically is what mkdir -p (or --parents for purists) on *nix does, as taken from the man guide

Media Queries - In between two widths

You need to switch your values:

/* No greater than 900px, no less than 400px */
@media (max-width:900px) and (min-width:400px) {
    .foo {
        display:none;
    }
}?

Demo: http://jsfiddle.net/xf6gA/ (using background color, so it's easier to confirm)

Set ANDROID_HOME environment variable in mac

solved my problem on mac 10.14 brew install android-sdk

Multiple separate IF conditions in SQL Server

Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.

As a beginner in SQL I find that when using a BEGIN and END SSMS usually adds a squiggly line with incorrect syntax near 'END' to END, simply because there's no content in between yet. If you're just setting up BEGIN and END to get started and add the actual query later, then simply add a bogus PRINT statement so SSMS stops bothering you.

For example:

IF (1=1)
BEGIN
  PRINT 'BOGUS'
END

The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:

IF (1=1)
BEGIN
END

How does one target IE7 and IE8 with valid CSS?

For a more complete list as of 2015:

IE 6

* html .ie6 {property:value;}

or

.ie6 { _property:value;}

IE 7

*+html .ie7 {property:value;}

or

*:first-child+html .ie7 {property:value;}

IE 6 and 7

@media screen\9 {
    .ie67 {property:value;}
}

or

.ie67 { *property:value;}

or

.ie67 { #property:value;}

IE 6, 7 and 8

@media \0screen\,screen\9 {
    .ie678 {property:value;}
}

IE 8

html>/**/body .ie8 {property:value;}

or

@media \0screen {
    .ie8 {property:value;}
}

IE 8 Standards Mode Only

.ie8 { property /*\**/: value\9 }

IE 8,9 and 10

@media screen\0 {
    .ie8910 {property:value;}
}

IE 9 only

@media screen and (min-width:0) and (min-resolution: .001dpcm) { 
 // IE9 CSS
 .ie9{property:value;}
}

IE 9 and above

@media screen and (min-width:0) and (min-resolution: +72dpi) {
  // IE9+ CSS
  .ie9up{property:value;}
}

IE 9 and 10

@media screen and (min-width:0) {
    .ie910{property:value;}
}

IE 10 only

_:-ms-lang(x), .ie10 { property:value\9; }

IE 10 and above

_:-ms-lang(x), .ie10up { property:value; }

or

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
   .ie10up{property:value;}
}

IE 11 (and above..)

_:-ms-fullscreen, :root .ie11up { property:value; }

Javascript alternatives

Modernizr

Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element

User agent selection

The Javascript:

var b = document.documentElement;
        b.setAttribute('data-useragent',  navigator.userAgent);
        b.setAttribute('data-platform', navigator.platform );
        b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

Adds (e.g) the below to the html element:

data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'

Allowing very targetted CSS selectors, e.g.:

html[data-useragent*='Chrome/13.0'] .nav{
    background:url(img/radial_grad.png) center bottom no-repeat;
}

Footnote

If possible, avoid browser targeting. Identify and fix any issue(s) you identify. Support progressive enhancement and graceful degradation. With that in mind, this is an 'ideal world' scenario not always obtainable in a production environment, as such- the above should help provide some good options.


Attribution / Essential Reading

how to make password textbox value visible when hover an icon

Complete example below. I just love the copy/paste :)

HTML

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
           <div class="panel panel-default">
              <div class="panel-body">
                  <form class="form-horizontal" method="" action="">

                     <div class="form-group">
                        <label class="col-md-4 control-label">Email</label>
                           <div class="col-md-6">
                               <input type="email" class="form-control" name="email" value="">
                           </div>
                     </div>
                     <div class="form-group">
                       <label class="col-md-4 control-label">Password</label>
                          <div class="col-md-6">
                              <input id="password-field" type="password" class="form-control" name="password" value="secret">
                              <span toggle="#password-field" class="fa fa-lg fa-eye field-icon toggle-password"></span>
                          </div>
                     </div>
                 </form>
              </div>
           </div>
      </div>
  </div>

CSS

.field-icon {
  float: right;
  margin-right: 8px;
  margin-top: -23px;
  position: relative;
  z-index: 2;
  cursor:pointer;
}

.container{
  padding-top:50px;
  margin: auto;
}

JS

$(".toggle-password").click(function() {
   $(this).toggleClass("fa-eye fa-eye-slash");
   var input = $($(this).attr("toggle"));
   if (input.attr("type") == "password") {
     input.attr("type", "text");
   } else {
     input.attr("type", "password");
   }
});

Try it here: https://codepen.io/anon/pen/ZoMQZP

What to gitignore from the .idea folder?

For a couple of years I was a supporter of using a specific .gitignore for IntelliJ with this suggested configuration.

Not anymore.

IntelliJ is updated quite frequently, internal config file specs change more often than I would like and JetBrains flagship excels at auto-configuring itself based on maven/gradle/etc build files.

So my suggestion would be to leave all editor config files out of project and have users configure editor to their liking. Things like code styling can and should be configured at build level; say using Google Code Style or CheckStyle directly on Maven/Gradle/sbt/etc.

This ensures consistency and leaves editor files out of source code that, in my personal opinion, is where they should be.

How to write connection string in web.config file and read from it?

Are you sure that your configuration file (web.config) is at the right place and the connection string is really in the (generated) file? If you publish your file, the content of web.release.config might be copied.

The configuration and the access to the Connection string looks all right to me. I would always add a providername

<connectionStrings>
  <add name="Dbconnection" 
       connectionString="Server=localhost; Database=OnlineShopping; 
       Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

SQL Server: Multiple table joins with a WHERE clause

When using LEFT JOIN or RIGHT JOIN, it makes a difference whether you put the filter in the WHERE or into the JOIN.

See this answer to a similar question I wrote some time ago:
What is the difference in these two queries as getting two different result set?

In short:

  • if you put it into the WHERE clause (like you did, the results that aren't associated with that computer are completely filtered out
  • if you put it into the JOIN instead, the results that aren't associated with that computer appear in the query result, only with NULL values
    --> this is what you want

Array or List in Java. Which is faster?

You should prefer generic types over arrays. As mentioned by others, arrays are inflexible and do not have the expressive power of generic types. (They do however support runtime typechecking, but that mixes badly with generic types.)

But, as always, when optimizing you should always follow these steps:

  • Don't optimize until you have a nice, clean, and working version of your code. Changing to generic types could very well be motivated at this step already.
  • When you have a version that is nice and clean, decide if it is fast enough.
  • If it isn't fast enough, measure its performance. This step is important for two reasons. If you don't measure you won't (1) know the impact of any optimizations you make and (2) know where to optimize.
  • Optimize the hottest part of your code.
  • Measure again. This is just as important as measuring before. If the optimization didn't improve things, revert it. Remember, the code without the optimization was clean, nice, and working.

How do I kill all the processes in Mysql "show processlist"?

If you are using laravel then this is for you:

$query = "SHOW FULL PROCESSLIST";
    $results = DB::select(DB::raw($query));

    foreach($results as $result){
        if($result->Command == "Sleep"){
            $sql="KILL ". $result->Id;
            DB::select(DB::raw($sql));
        }
    }

Of-course, you should use this use Illuminate\Support\Facades\DB; after your namespace.

How to reset radiobuttons in jQuery so that none is checked

In versions of jQuery before 1.6 use:

$('input[name="correctAnswer"]').attr('checked', false);

In versions of jQuery after 1.6 you should use:

$('input[name="correctAnswer"]').prop('checked', false);

but if you are using 1.6.1+ you can use the first form (see note 2 below).

Note 1: it is important that the second argument be false and not "false" since "false" is not a falsy value. i.e.

if ("false") {
    alert("Truthy value. You will see an alert");
}

Note 2: As of jQuery 1.6.0, there are now two similar methods, .attr and .prop that do two related but slightly different things. If in this particular case, the advice provide above works if you use 1.6.1+. The above will not work with 1.6.0, if you are using 1.6.0, you should upgrade. If you want the details, keep reading.

Details: When working with straight HTML DOM elements, there are properties attached to the DOM element (checked, type, value, etc) which provide an interface to the running state of the HTML page. There is also the .getAttribute/.setAttribute interface which provides access to the HTML Attribute values as provided in the HTML. Before 1.6 jQuery blurred the distinction by providing one method, .attr, to access both types of values. jQuery 1.6+ provides two methods, .attr and .prop to get distinguish between these situations.

.prop allows you to set a property on a DOM element, while .attr allows you to set an HTML attribute value. If you are working with plain DOM and set the checked property, elem.checked, to true or false you change the running value (what the user sees) and the value returned tracks the on page state. elem.getAttribute('checked') however only returns the initial state (and returns 'checked' or undefined depending on the initial state from the HTML). In 1.6.1+ using .attr('checked', false) does both elem.removeAttribute('checked') and elem.checked = false since the change caused a lot of backwards compatibility issues and it can't really tell if you wanted to set the HTML attribute or the DOM property. See more information in the documentation for .prop.

JS how to cache a variable

check out my js lib for caching: https://github.com/hoangnd25/cacheJS

My blog post: New way to cache your data with Javascript

Features:

  • Conveniently use array as key for saving cache
  • Support array and localStorage
  • Clear cache by context (clear all blog posts with authorId="abc")
  • No dependency

Basic usage:

Saving cache:

cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', null, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd',categoryId:2});

Retrieving cache:

cacheJS.get({blogId: 1,type: 'view'});

Flushing cache

cacheJS.removeByKey({blogId: 1,type: 'view'});
cacheJS.removeByKey({blogId: 2,type: 'view'});

cacheJS.removeByContext({author:'hoangnd'});

Switching provider

cacheJS.use('array');
cacheJS.use('array').set({blogId:1},'<h1>Blog 1</h1>')};

JavaScript variable number of arguments to function

Use the arguments object when inside the function to have access to all arguments passed in.

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

Javascript negative number

How about something as simple as:

function negative(number){
    return number < 0;
}

The * 1 part is to convert strings to numbers.

ngModel cannot be used to register form controls with a parent formGroup directive

I just got this error because I did not enclose all my form controls within a div with a formGroup attribute.

For example, this will throw an error

<div [formGroup]='formGroup'>
</div>
<input formControlName='userName' />

This can be quite easy to miss if its a particularly long form.

How do I disable a jquery-ui draggable?

Seems like no one looked at the original documentation. May be there was no it at that time))

Initialize a draggable with the disabled option specified.

$( ".selector" ).draggable({ disabled: true });

Get or set the disabled option, after init.

//getter
var disabled = $( ".selector" ).draggable( "option", "disabled" );
//setter
$( ".selector" ).draggable( "option", "disabled", true );

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

The jar file may be corrupt. Try removing the content of the following folder:

 C:\Users\[username]\.m2\repository

Then right click your project, select Maven, Update Project, check on Force Update of Snapshots/Releases.

What is the Regular Expression For "Not Whitespace and Not a hyphen"

It can be done much easier:

\S which equals [^ \t\r\n\v\f]

What is exactly the base pointer and stack pointer? To what do they point?

EDIT: For a better description, see x86 Disassembly/Functions and Stack Frames in a WikiBook about x86 assembly. I try to add some info you might be interested in using Visual Studio.

Storing the caller EBP as the first local variable is called a standard stack frame, and this may be used for nearly all calling conventions on Windows. Differences exist whether the caller or callee deallocates the passed parameters, and which parameters are passed in registers, but these are orthogonal to the standard stack frame problem.

Speaking about Windows programs, you might probably use Visual Studio to compile your C++ code. Be aware that Microsoft uses an optimization called Frame Pointer Omission, that makes it nearly impossible to do walk the stack without using the dbghlp library and the PDB file for the executable.

This Frame Pointer Omission means that the compiler does not store the old EBP on a standard place and uses the EBP register for something else, therefore you have hard time finding the caller EIP without knowing how much space the local variables need for a given function. Of course Microsoft provides an API that allows you to do stack-walks even in this case, but looking up the symbol table database in PDB files takes too long for some use cases.

To avoid FPO in your compilation units, you need to avoid using /O2 or need to explicitly add /Oy- to the C++ compilation flags in your projects. You probably link against the C or C++ runtime, which uses FPO in the Release configuration, so you will have hard time to do stack walks without the dbghlp.dll.

Get the item doubleclick event of listview

i see this subject is high on google, there is my simple and working sample :)

XAML:

    <ListView Name="MainTCList" HorizontalAlignment="Stretch" MinHeight="440" Height="Auto" Margin="10,10,5.115,4" VerticalAlignment="Stretch" MinWidth="500" Width="Auto" Grid.Column="0" MouseDoubleClick="MainTCList_MouseDoubleClick" IsSynchronizedWithCurrentItem="True">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="UserTID" DisplayMemberBinding="{Binding UserTID}" Width="80"/>
                <GridViewColumn Header="Title" DisplayMemberBinding="{Binding Title}" Width="410" />
            </GridView>
        </ListView.View>
    </ListView>

C#

    private void MainTCList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
            TC item = (TC)MainTCList.Items.CurrentItem;
            Wyswietlacz.Content = item.UserTID;  
    }

Wyswietlacz is a test Label to see item content :) I add here in this last line a method to Load Page with data from item.

Closing pyplot windows

Please use

plt.show(block=False)
plt.close('all')

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

One more sample

declare @objectId int,  @objectName varchar(500), @schemaName varchar(500), @type nvarchar(30), @parentObjId int, @parentObjName nvarchar(500)
declare cur cursor 
for 

select obj.object_id, s.name as schema_name, obj.name, obj.type, parent_object_id
from sys.schemas s
    inner join sys.sysusers u
        on u.uid = s.principal_id
        JOIN
        sys.objects obj on obj.schema_id = s.schema_id
WHERE s.name = 'schema_name' and (type = 'p' or obj.type = 'v' or obj.type = 'u' or obj.type = 'f' or obj.type = 'fn')

order by obj.type

open cur
fetch next from cur into @objectId, @schemaName, @objectName,  @type, @parentObjId
while @@fetch_status = 0
begin
    if @type = 'p'
    begin
        exec('drop procedure ['+@schemaName +'].[' + @objectName + ']')
    end

    if @type = 'fn'
    begin
        exec('drop FUNCTION ['+@schemaName +'].[' + @objectName + ']')
    end

    if @type = 'f'
    begin
        set @parentObjName = (SELECT name from sys.objects WHERE object_id = @parentObjId)
        exec('ALTER TABLE ['+@schemaName +'].[' + @parentObjName + ']' + 'DROP CONSTRAINT ' +  @objectName)
    end

    if @type = 'u'
    begin
        exec('drop table ['+@schemaName +'].[' + @objectName + ']')
    end

    if @type = 'v'
    begin
        exec('drop view ['+@schemaName +'].[' + @objectName + ']')
    end
    fetch next from cur into  @objectId, @schemaName, @objectName,  @type, @parentObjId
end
close cur
deallocate cur

get jquery `$(this)` id

Do you mean that for a select element with an id of "next" you need to perform some specific script?

$("#next").change(function(){
    //enter code here
});

Adding elements to object

This is an old question, anyway today the best practice is by using Object.defineProperty

const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false
});

object1.property1 = 77;
// throws an error in strict mode

console.log(object1.property1);
// expected output: 42

Correct way of getting Client's IP Addresses from http.Request

Looking at http.Request you can find the following member variables:

// HTTP defines that header names are case-insensitive.
// The request parser implements this by canonicalizing the
// name, making the first character and any characters
// following a hyphen uppercase and the rest lowercase.
//
// For client requests certain headers are automatically
// added and may override values in Header.
//
// See the documentation for the Request.Write method.
Header Header

// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request, usually for
// logging. This field is not filled in by ReadRequest and
// has no defined format. The HTTP server in this package
// sets RemoteAddr to an "IP:port" address before invoking a
// handler.
// This field is ignored by the HTTP client.
RemoteAddr string

You can use RemoteAddr to get the remote client's IP address and port (the format is "IP:port"), which is the address of the original requestor or the last proxy (for example a load balancer which lives in front of your server).

This is all you have for sure.

Then you can investigate the headers, which are case-insensitive (per documentation above), meaning all of your examples will work and yield the same result:

req.Header.Get("X-Forwarded-For") // capitalisation
req.Header.Get("x-forwarded-for") // doesn't
req.Header.Get("X-FORWARDED-FOR") // matter

This is because internally http.Header.Get will normalise the key for you. (If you want to access header map directly, and not through Get, you would need to use http.CanonicalHeaderKey first.)

Finally, "X-Forwarded-For" is probably the field you want to take a look at in order to grab more information about client's IP. This greatly depends on the HTTP software used on the remote side though, as client can put anything in there if it wishes to. Also, note the expected format of this field is the comma+space separated list of IP addresses. You will need to parse it a little bit to get a single IP of your choice (probably the first one in the list), for example:

// Assuming format is as expected
ips := strings.Split("10.0.0.1, 10.0.0.2, 10.0.0.3", ", ")
for _, ip := range ips {
    fmt.Println(ip)
}

will produce:

10.0.0.1
10.0.0.2
10.0.0.3

Css height in percent not working

This is what you need in the CSS:

html, body {
    height: 100%; 
    width: 100%; 
    margin: 0; 
}

Returning a C string from a function

If you really can't use pointers, do something like this:

char get_string_char(int index)
{
    static char array[] = "my string";
    return array[index];
}

int main()
{
    for (int i = 0; i < 9; ++i)
        printf("%c", get_string_char(i));
    printf("\n");
    return 0;
}

The magic number 9 is awful, and this is not an example of good programming. But you get the point. Note that pointers and arrays are the same thing (kind of), so this is a bit cheating.

Fill remaining vertical space - only CSS

you need javascript and some client side calculations: http://jsfiddle.net/omegaiori/NERE8/2/

you will need jquery to effectively achieve what you want. this function is very simple but very effective:

(function () {


    var heights = $("#wrapper").outerHeight(true);
    var outerHeights = $("#first").outerHeight(true);
    jQuery('#second').css('height', (heights - outerHeights) + "px");

})();

first it detects the wrapper height, as it is set to 100% it's different everytime (it depends on what screen you are landing). in the second step it gives the #second div the appropriate height subtracting from the wrapper height the #first div height. the result is the available height left in the wrapper div

How to get host name with port from a http or https request

If you want the original URL just use the method as described by jthalborn. If you want to rebuild the url do like David Levesque explained, here is a code snippet for it:

final javax.servlet.http.HttpServletRequest req = (javax.servlet.http.HttpServletRequest) ...;
final int serverPort = req.getServerPort();
if ((serverPort == 80) || (serverPort == 443)) {
  // No need to add the server port for standard HTTP and HTTPS ports, the scheme will help determine it.
  url = String.format("%s://%s/...", req.getScheme(), req.getServerName(), ...);
} else {
  url = String.format("%s://%s:%s...", req.getScheme(), req.getServerName(), serverPort, ...);
}

You still need to consider the case of a reverse-proxy:

Could use constants for the ports but not sure if there is a reliable source for them, default ports:

Most developers will know about port 80 and 443 anyways, so constants are not that helpful.

Also see this similar post.

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

Following a Google...

Taking the code from the website:

CREATE TABLE CRLF
    (
        col1 VARCHAR(1000)
    )

INSERT CRLF SELECT 'The quick brown@'
INSERT CRLF SELECT 'fox @jumped'
INSERT CRLF SELECT '@over the '
INSERT CRLF SELECT 'log@'

SELECT col1 FROM CRLF

Returns:

col1
-----------------
The quick brown@
fox @jumped
@over the
log@

(4 row(s) affected)


UPDATE CRLF
SET col1 = REPLACE(col1, '@', CHAR(13))

Looks like it can be done by replacing a placeholder with CHAR(13)

Good question, never done it myself :)

How to make blinking/flashing text with CSS 3

I don't know why but animating only the visibility property is not working on any browser.

What you can do is animate the opacity property in such a way that the browser doesn't have enough frames to fade in or out the text.

Example:

_x000D_
_x000D_
span {_x000D_
  opacity: 0;_x000D_
  animation: blinking 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes blinking {_x000D_
  from,_x000D_
  49.9% {_x000D_
    opacity: 0;_x000D_
  }_x000D_
  50%,_x000D_
  to {_x000D_
    opacity: 1;_x000D_
  }_x000D_
}
_x000D_
<span>I'm blinking text</span>
_x000D_
_x000D_
_x000D_

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

Anyone who is looking to do this in Ubuntu/linux using php -

Ubuntu comes with libre office installed default. Anyone can use the shell command to use the headless libre office for this.

shell_exec('/usr/bin/libreoffice --headless --convert-to pdf:writer_pdf_Export --outdir /var/www/html/demo/public_html/src/var/output /var/www/html/demo/public_html/src/var/source/sample.doc');

Hope it helps others like me.

how to File.listFiles in alphabetical order?

This is my code:

_x000D_
_x000D_
        try {_x000D_
            String folderPath = "../" + filePath.trim() + "/";_x000D_
            logger.info("Path: " + folderPath);_x000D_
            File folder = new File(folderPath);_x000D_
            File[] listOfFiles = folder.listFiles();_x000D_
            int length = listOfFiles.length;_x000D_
            logger.info("So luong files: " + length);_x000D_
            ArrayList<CdrFileBO> lstFile = new ArrayList< CdrFileBO>();_x000D_
_x000D_
            if (listOfFiles != null && length > 0) {_x000D_
                int count = 0;_x000D_
                for (int i = 0; i < length; i++) {_x000D_
                    if (listOfFiles[i].isFile()) {_x000D_
                        lstFile.add(new CdrFileBO(listOfFiles[i]));_x000D_
                    }_x000D_
                }_x000D_
                Collections.sort(lstFile);_x000D_
                for (CdrFileBO bo : lstFile) {_x000D_
                    //String newName = START_NAME + "_" + getSeq(SEQ_START) + "_" + DateSTR + ".s";_x000D_
                    String newName = START_NAME + DateSTR + getSeq(SEQ_START) + ".DAT";_x000D_
                    SEQ_START = SEQ_START + 1;_x000D_
                    bo.getFile().renameTo(new File(folderPath + newName));_x000D_
                    logger.info("newName: " + newName);_x000D_
                    logger.info("Next file: " + getSeq(SEQ_START));_x000D_
                }_x000D_
_x000D_
            }_x000D_
        } catch (Exception ex) {_x000D_
            logger.error(ex);_x000D_
            ex.printStackTrace();_x000D_
        }
_x000D_
_x000D_
_x000D_

How to add a ScrollBar to a Stackpanel

It works like this:

<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" Width="340" HorizontalAlignment="Left" Margin="12,0,0,0">
        <StackPanel Name="stackPanel1" Width="311">

        </StackPanel>
</ScrollViewer>

TextBox tb = new TextBox();
tb.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
stackPanel1.Children.Add(tb);

What is the largest Safe UDP Packet Size on the Internet

Given that IPV6 has a size of 1500, I would assert that carriers would not provide separate paths for IPV4 and IPV6 (they are both IP with different types), forcing them to equipment for ipv4 that would be old, redundant, more costly to maintain and less reliable. It wouldn't make any sense. Besides, doing so might easily be considered providing preferential treatment for some traffic -- a no no under rules they probably don't care much about (unless they get caught).

So 1472 should be safe for external use (though that doesn't mean an app like DNS that doesn't know about EDNS will accept it), and if you are talking internal nets, you can more likely know your network layout in which case jumbo packet sizes apply for for non-fragmented packets so for 4096 - 4068 bytes, and for intel's cards with 9014 byte buffers, a package size of ... wait...8086 bytes, would be the max...coincidence? snicker

****UPDATE****

Various answers give maximum values allowed by 1 SW vendor or various answers assuming encapsulation. The user didn't ask for the lowest value possible (like "0" for a safe UDP size), but the largest safe packet size.

Encapsulation values for various layers can be included multiple times. Since once you've encapsulated a stream -- there is nothing prohibiting, say, a VPN layer below that and a complete duplication of encapsulation layers above that.

Since the question was about maximum safe values, I'm assuming that they are talking about the maximum safe value for a UDP packet that can be received. Since no UDP packet is guaranteed, if you receive a UDP packet, the largest safe size would be 1 packet over IPv4 or 1472 bytes.

Note -- if you are using IPv6, the maximum size would be 1452 bytes, as IPv6's header size is 40 bytes vs. IPv4's 20 byte size (and either way, one must still allow 8 bytes for the UDP header).

C# Listbox Item Double Click Event

I know this question is quite old, but I was looking for a solution to this problem too. The accepted solution is for WinForms not WPF which I think many who come here are looking for.

For anyone looking for a WPF solution, here is a great approach (via Oskar's answer here):

private void myListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DependencyObject obj = (DependencyObject)e.OriginalSource;

    while (obj != null && obj != myListBox)
    {
        if (obj.GetType() == typeof(ListBoxItem))
        {
             // Do something
             break;
         }
         obj = VisualTreeHelper.GetParent(obj);
    }
}

Basically, you walk up the VisualTree until you've either found a parent item that is a ListBoxItem, or you ascend up to the actual ListBox (and therefore did not click a ListBoxItem).

How to list imported modules?

I like using a list comprehension in this case:

>>> [w for w in dir() if w == 'datetime' or w == 'sqlite3']
['datetime', 'sqlite3']

# To count modules of interest...
>>> count = [w for w in dir() if w == 'datetime' or w == 'sqlite3']
>>> len(count)
2

# To count all installed modules...
>>> count = dir()
>>> len(count)

Create a rounded button / button with border-radius in Flutter

You can use this code for a transparent rounded button by passing a transparent color to the color property inside BoxDecoration. eg. color: Colors.transparent. Also, take note that this button makes use of only the Container and GestureDetector widgets.

Container(
    height: 50.0,
    child: GestureDetector(
        onTap: () {},
        child: Container(
            decoration: BoxDecoration(
                border: Border.all(
                    color: Color(0xFFF05A22),
                    style: BorderStyle.solid,
                    width: 1.0,
                ),
                color: Colors.transparent,
                borderRadius: BorderRadius.circular(30.0),
            ),
            child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                    Center(
                        child: Text(
                           "BUTTON",
                            style: TextStyle(
                                color: Color(0xFFF05A22),
                                fontFamily: 'Montserrat',
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                                letterSpacing: 1,
                            ),
                        ),
                    )
                ],
            ),
        ),
    ),
)

Transaparent Background Button

Set default value of an integer column SQLite

A column with default value:

CREATE TABLE <TableName>(
...
<ColumnName> <Type> DEFAULT <DefaultValue>
...
)

<DefaultValue> is a placeholder for a:

  • value literal
  • ( expression )

Examples:

Count INTEGER DEFAULT 0,
LastSeen TEXT DEFAULT (datetime('now'))

How To Make Circle Custom Progress Bar in Android

I have solved this cool custom progress bar by creating the custom view. I have overriden the onDraw() method to draw the circles, filled arc and text on the canvas.

following is the custom progress bar

import android.annotation.TargetApi;

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Paint;

import android.graphics.Path;

import android.graphics.Rect;

import android.graphics.RectF;

import android.os.Build;

import android.util.AttributeSet;

import android.view.View;

import com.investorfinder.utils.UiUtils;


public class CustomProgressBar extends View {


private int max = 100;

private int progress;

private Path path = new Path();

int color = 0xff44C8E5;

private Paint paint;

private Paint mPaintProgress;

private RectF mRectF;

private Paint textPaint;

private String text = "0%";

private final Rect textBounds = new Rect();

private int centerY;

private int centerX;

private int swipeAndgle = 0;


public CustomProgressBar(Context context) {
    super(context);
    initUI();
}

public CustomProgressBar(Context context, AttributeSet attrs) {
    super(context, attrs);
    initUI();
}

public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initUI();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    initUI();
}

private void initUI() {
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setStrokeWidth(UiUtils.dpToPx(getContext(), 1));
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(color);


    mPaintProgress = new Paint();
    mPaintProgress.setAntiAlias(true);
    mPaintProgress.setStyle(Paint.Style.STROKE);
    mPaintProgress.setStrokeWidth(UiUtils.dpToPx(getContext(), 9));
    mPaintProgress.setColor(color);

    textPaint = new Paint();
    textPaint.setAntiAlias(true);
    textPaint.setStyle(Paint.Style.FILL);
    textPaint.setColor(color);
    textPaint.setStrokeWidth(2);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int viewWidth = MeasureSpec.getSize(widthMeasureSpec);
    int viewHeight = MeasureSpec.getSize(heightMeasureSpec);

    int radius = (Math.min(viewWidth, viewHeight) - UiUtils.dpToPx(getContext(), 2)) / 2;

    path.reset();

    centerX = viewWidth / 2;
    centerY = viewHeight / 2;
    path.addCircle(centerX, centerY, radius, Path.Direction.CW);

    int smallCirclRadius = radius - UiUtils.dpToPx(getContext(), 7);
    path.addCircle(centerX, centerY, smallCirclRadius, Path.Direction.CW);
    smallCirclRadius += UiUtils.dpToPx(getContext(), 4);

    mRectF = new RectF(centerX - smallCirclRadius, centerY - smallCirclRadius, centerX + smallCirclRadius, centerY + smallCirclRadius);

    textPaint.setTextSize(radius * 0.5f);
}


@Override
protected void onDraw(Canvas canvas) {


    super.onDraw(canvas);

    canvas.drawPath(path, paint);

    canvas.drawArc(mRectF, 270, swipeAndgle, false, mPaintProgress);

    drawTextCentred(canvas);

}

public void drawTextCentred(Canvas canvas) {

    textPaint.getTextBounds(text, 0, text.length(), textBounds);

    canvas.drawText(text, centerX - textBounds.exactCenterX(), centerY - textBounds.exactCenterY(), textPaint);
}

public void setMax(int max) {
    this.max = max;
}

public void setProgress(int progress) {
    this.progress = progress;

    int percentage = progress * 100 / max;

    swipeAndgle = percentage * 360 / 100;

    text = percentage + "%";

    invalidate();
}

public void setColor(int color) {
    this.color = color;
}
}

In layout XML

<com.your.package.name.CustomProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/txt_title"
            android:layout_marginRight="15dp" />

in activity

CustomProgressBar progressBar = (CustomProgressBar)findViewById(R.id.progress_bar);

    progressBar.setMax(9);

    progressBar.setProgress(5);

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I ran into this a couple times a quarter. This time I had a minimal change summary in my git diff and tracked the problem to a reset classpath (missing my WEB-INF/lib dependency) in eclipse. This seems to occur any time I pull in or pull out parent/sibling maven projects.

There are mentions of adding your spring jars to the tomcat web container lib - this is ok and is the way most EE servers run. However be aware that by placing spring higher in the classloader tree on tomcat you will be running higher than the classloader level of your war context. I recommend you leave the libs in a per/war lower level classloader.

We see the following after a truncated .classpath after a structural project change in eclipse.

Dec 18, 2016 11:13:39 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.web.context.request.RequestContextListener
java.lang.ClassNotFoundException: org.springframework.web.context.request.RequestContextListener

My classpath was reset and the WEB-INF/lib dependency was removed.

<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
    <attributes>
        <attribute name="maven.pomderived" value="true"/>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>

put back

<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>

and you will be OK.

thank you /michael

Difference between InvariantCulture and Ordinal string comparison

Always try to use InvariantCulture in those string methods that accept it as overload. By using InvariantCulture you are on a safe side. Many .NET programmers may not use this functionality but if your software will be used by different cultures, InvariantCulture is an extremely handy feature.

How to block until an event is fired in c#

A very easy kind of event you can wait for is the ManualResetEvent, and even better, the ManualResetEventSlim.

They have a WaitOne() method that does exactly that. You can wait forever, or set a timeout, or a "cancellation token" which is a way for you to decide to stop waiting for the event (if you want to cancel your work, or your app is asked to exit).

You fire them calling Set().

Here is the doc.

Model summary in pytorch

Yes, you can get exact Keras representation, using pytorch-summary package.

Example for VGG16

from torchvision import models
from torchsummary import summary

vgg = models.vgg16()
summary(vgg, (3, 224, 224))

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1         [-1, 64, 224, 224]           1,792
              ReLU-2         [-1, 64, 224, 224]               0
            Conv2d-3         [-1, 64, 224, 224]          36,928
              ReLU-4         [-1, 64, 224, 224]               0
         MaxPool2d-5         [-1, 64, 112, 112]               0
            Conv2d-6        [-1, 128, 112, 112]          73,856
              ReLU-7        [-1, 128, 112, 112]               0
            Conv2d-8        [-1, 128, 112, 112]         147,584
              ReLU-9        [-1, 128, 112, 112]               0
        MaxPool2d-10          [-1, 128, 56, 56]               0
           Conv2d-11          [-1, 256, 56, 56]         295,168
             ReLU-12          [-1, 256, 56, 56]               0
           Conv2d-13          [-1, 256, 56, 56]         590,080
             ReLU-14          [-1, 256, 56, 56]               0
           Conv2d-15          [-1, 256, 56, 56]         590,080
             ReLU-16          [-1, 256, 56, 56]               0
        MaxPool2d-17          [-1, 256, 28, 28]               0
           Conv2d-18          [-1, 512, 28, 28]       1,180,160
             ReLU-19          [-1, 512, 28, 28]               0
           Conv2d-20          [-1, 512, 28, 28]       2,359,808
             ReLU-21          [-1, 512, 28, 28]               0
           Conv2d-22          [-1, 512, 28, 28]       2,359,808
             ReLU-23          [-1, 512, 28, 28]               0
        MaxPool2d-24          [-1, 512, 14, 14]               0
           Conv2d-25          [-1, 512, 14, 14]       2,359,808
             ReLU-26          [-1, 512, 14, 14]               0
           Conv2d-27          [-1, 512, 14, 14]       2,359,808
             ReLU-28          [-1, 512, 14, 14]               0
           Conv2d-29          [-1, 512, 14, 14]       2,359,808
             ReLU-30          [-1, 512, 14, 14]               0
        MaxPool2d-31            [-1, 512, 7, 7]               0
           Linear-32                 [-1, 4096]     102,764,544
             ReLU-33                 [-1, 4096]               0
          Dropout-34                 [-1, 4096]               0
           Linear-35                 [-1, 4096]      16,781,312
             ReLU-36                 [-1, 4096]               0
          Dropout-37                 [-1, 4096]               0
           Linear-38                 [-1, 1000]       4,097,000
================================================================
Total params: 138,357,544
Trainable params: 138,357,544
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.57
Forward/backward pass size (MB): 218.59
Params size (MB): 527.79
Estimated Total Size (MB): 746.96
----------------------------------------------------------------

How to have a default option in Angular.js select box

try this in your angular controller...

$somethingHere = {name: 'Something Cool'};

You can set a value, but you are using a complex type and the angular will search key/value to set in your view.

And, if does not work, try this : ng-options="option.value as option.name for option in options track by option.name"

pandas: multiple conditions while indexing data frame - unexpected behavior

A little mathematical logic theory here:

"NOT a AND NOT b" is the same as "NOT (a OR b)", so:

"a NOT -1 AND b NOT -1" is equivalent of "NOT (a is -1 OR b is -1)", which is opposite (Complement) of "(a is -1 OR b is -1)".

So if you want exact opposite result, df1 and df2 should be as below:

df1 = df[(df.a != -1) & (df.b != -1)]
df2 = df[(df.a == -1) | (df.b == -1)]

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

phpmyadmin.pma_table_uiprefs doesn't exist

I came across this same problem on Ubuntu 13.10. I didn't want to hack PHP files, because normally phpMyAdmin works out of the box after installing the package from Ubuntu repositories. Instead I ran:

sudo dpkg-reconfigure phpmyadmin

During reconfigure, I said "yes" to reinstalling the phpMyAdmin database. Afterwards, the problem was gone. I have a vague memory of answering "No" to that question at some earlier time, during an install or upgrade. That is probably why the problem occurred in the first place.

Best way to store a key=>value array in JavaScript?

Objects inside an array:

var cars = [
        { "id": 1, brand: "Ferrari" }
        , { "id": 2, brand: "Lotus" }
        , { "id": 3, brand: "Lamborghini" }
    ];

How to print a linebreak in a python function?

All three way you can use for newline character :

'\n'

"\n"

"""\n"""

how to pass data in an hidden field from one jsp page to another?

To pass the value you must included the hidden value value="hiddenValue" in the <input> statement like so:

<input type="hidden" id="thisField" name="inputName" value="hiddenValue">

Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:

This code goes on the page where you want to hide the value.

<form action="anotherPage.jsp" method="GET">
    <input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">   
</form>

Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name) method of the implicit request object, as so:

<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>

The output of the above script will be:

The Hidden Value is hiddenValue 

WPF: Grid with column/row margin/padding?

As was stated before create a GridWithMargins class. Here is my working code example

public class GridWithMargins : Grid
{
    public Thickness RowMargin { get; set; } = new Thickness(10, 10, 10, 10);
    protected override Size ArrangeOverride(Size arrangeSize)
    {
        var basesize = base.ArrangeOverride(arrangeSize);

        foreach (UIElement child in InternalChildren)
        {
            var pos = GetPosition(child);
            pos.X += RowMargin.Left;
            pos.Y += RowMargin.Top;

            var actual = child.RenderSize;
            actual.Width -= (RowMargin.Left + RowMargin.Right);
            actual.Height -= (RowMargin.Top + RowMargin.Bottom);
            var rec = new Rect(pos, actual);
            child.Arrange(rec);
        }
        return arrangeSize;
    }

    private Point GetPosition(Visual element)
    {
        var posTransForm = element.TransformToAncestor(this);
        var areaTransForm = posTransForm.Transform(new Point(0, 0));
        return areaTransForm;
    }
}

Usage:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:GridWithMargins ShowGridLines="True">
            <Grid.RowDefinitions>
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Rectangle Fill="Red" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
            <Rectangle Fill="Green" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
            <Rectangle Fill="Blue" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
        </local:GridWithMargins>
    </Grid>
</Window>

SQL to LINQ Tool

Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.

[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.

Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.

round up to 2 decimal places in java?

Go back to your code, and replace 100 by 100.00 and let me know if it works. However, if you want to be formal, try this:

import java.text.DecimalFormat;
DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value); 
double finalValue = (Double)df.parse(formate) ;

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

You don't need both hibernate.cfg.xml and persistence.xml in this case. Have you tried removing hibernate.cfg.xml and mapping everything in persistence.xml only?

But as the other answer also pointed out, this is not okay like this:

@Id
@JoinColumn(name = "categoria") 
private String id;

Didn't you want to use @Column instead?

How do I get client IP address in ASP.NET CORE?

In ASP.NET 2.1, In StartUp.cs Add This Services:

services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();

and then do 3 step:

  1. Define a variable in your MVC controller

    private IHttpContextAccessor _accessor;
    
  2. DI into the controller's constructor

    public SomeController(IHttpContextAccessor accessor)
    {
        _accessor = accessor;
    }
    
  3. Retrieve the IP Address

    _accessor.HttpContext.Connection.RemoteIpAddress.ToString()
    

This is how it is done.

Can we call the function written in one JavaScript in another JS file?

You can call the function created in another js file from the file you are working in. So for this firstly you need to add the external js file into the html document as-

<html>
<head>
    <script type="text/javascript" src='path/to/external/js'></script>
</head>
<body>
........

The function defined in the external javascript file -

$.fn.yourFunctionName = function(){
    alert('function called succesfully for - ' + $(this).html() );
}

To call this function in your current file, just call the function as -

......
<script type="text/javascript">
    $(function(){
        $('#element').yourFunctionName();
    });
</script>

If you want to pass the parameters to the function, then define the function as-

$.fn.functionWithParameters = function(parameter1, parameter2){
        alert('Parameters passed are - ' + parameter1 + ' , ' + parameter2);
}

And call this function in your current file as -

$('#element').functionWithParameters('some parameter', 'another parameter');

CMake not able to find OpenSSL library

Just for fun ill post an alternative working answer for the OP's question:

cmake -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl/ -DOPENSSL_CRYPTO_LIBRARY=/usr/local/opt/openssl/lib/

typedef struct vs struct definitions

If you use struct without typedef, you'll always have to write

struct mystruct myvar;

It's illegal to write

mystruct myvar;

If you use the typedef you don't need the struct prefix anymore.

Adding to an ArrayList Java

If you're using Java 9, there's an easy way with less number of lines without needing to initialize or add method.

List<String> list = List.of("first", "second", "third");

Why extend the Android Application class?

Not an answer but an observation: keep in mind that the data in the extended application object should not be tied to an instance of an activity, as it is possible that you have two instances of the same activity running at the same time (one in the foreground and one not being visible).

For example, you start your activity normally through the launcher, then "minimize" it. You then start another app (ie Tasker) which starts another instance of your activitiy, for example in order to create a shortcut, because your app supports android.intent.action.CREATE_SHORTCUT. If the shortcut is then created and this shortcut-creating invocation of the activity modified the data the application object, then the activity running in the background will start to use this modified application object once it is brought back to the foreground.

Setting Action Bar title and subtitle

Nope! You have to do it at runtime.

If you want to make your app backwards compatible, then simply check the device API level. If it is higher than 11, then you can fiddle with the ActionBar and set the subtitle.

if(Integer.valueOf(android.os.Build.VERSION.SDK) >= 11){
    //set actionbar title
}

Validating a Textbox field for only numeric input.

        if (int.TryParse(txtDepartmentNo.Text, out checkNumber) == false)
        {
            lblMessage.Text = string.Empty;
            lblMessage.Visible = true;
            lblMessage.ForeColor = Color.Maroon;
            lblMessage.Text = "You have not entered a number";
            return;
        }

Rolling or sliding window iterator?

I use the following code as a simple sliding window that uses generators to drastically increase readability. Its speed has so far been sufficient for use in bioinformatics sequence analysis in my experience.

I include it here because I didn't see this method used yet. Again, I make no claims about its compared performance.

def slidingWindow(sequence,winSize,step=1):
"""Returns a generator that will iterate through
the defined chunks of input sequence. Input sequence
must be sliceable."""

    # Verify the inputs
    if not ((type(winSize) == type(0)) and (type(step) == type(0))):
        raise Exception("**ERROR** type(winSize) and type(step) must be int.")
    if step > winSize:
        raise Exception("**ERROR** step must not be larger than winSize.")
    if winSize > len(sequence):
        raise Exception("**ERROR** winSize must not be larger than sequence length.")

    # Pre-compute number of chunks to emit
    numOfChunks = ((len(sequence)-winSize)/step)+1

    # Do the work
    for i in range(0,numOfChunks*step,step):
        yield sequence[i:i+winSize]

If Browser is Internet Explorer: run an alternative script instead

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

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

Is it possible to pass parameters programmatically in a Microsoft Access update query?

You can also use TempVars - note '!' syntax is essential You can also use TempVars - note '!' syntax is essential

What is the best way to ensure only one instance of a Bash script is running?

Advisory locking has been used for ages and it can be used in bash scripts. I prefer simple flock (from util-linux[-ng]) over lockfile (from procmail). And always remember about a trap on exit (sigspec == EXIT or 0, trapping specific signals is superfluous) in those scripts.

In 2009 I released my lockable script boilerplate (originally available at my wiki page, nowadays available as gist). Transforming that into one-instance-per-user is trivial. Using it you can also easily write scripts for other scenarios requiring some locking or synchronization.

Here is the mentioned boilerplate for your convenience.

#!/bin/bash
# SPDX-License-Identifier: MIT

## Copyright (C) 2009 Przemyslaw Pawelczyk <[email protected]>
##
## This script is licensed under the terms of the MIT license.
## https://opensource.org/licenses/MIT
#
# Lockable script boilerplate

### HEADER ###

LOCKFILE="/var/lock/`basename $0`"
LOCKFD=99

# PRIVATE
_lock()             { flock -$1 $LOCKFD; }
_no_more_locking()  { _lock u; _lock xn && rm -f $LOCKFILE; }
_prepare_locking()  { eval "exec $LOCKFD>\"$LOCKFILE\""; trap _no_more_locking EXIT; }

# ON START
_prepare_locking

# PUBLIC
exlock_now()        { _lock xn; }  # obtain an exclusive lock immediately or fail
exlock()            { _lock x; }   # obtain an exclusive lock
shlock()            { _lock s; }   # obtain a shared lock
unlock()            { _lock u; }   # drop a lock

### BEGIN OF SCRIPT ###

# Simplest example is avoiding running multiple instances of script.
exlock_now || exit 1

# Remember! Lock file is removed when one of the scripts exits and it is
#           the only script holding the lock or lock is not acquired at all.

How to increase maximum execution time in php

Use the PHP function

void set_time_limit ( int $seconds )

The maximum execution time, in seconds. If set to zero, no time limit is imposed.

This function has no effect when PHP is running in safe mode. There is no workaround other than turning off safe mode or changing the time limit in the php.ini.

Map a 2D array onto a 1D array

As other have said C maps in row order

   #include <stdio.h>

   int main(int argc, char **argv) {
   int i, j, k;
   int arr[5][3];
   int *arr2 = (int*)arr;

       for (k=0; k<15; k++) {
          arr2[k] = k;
          printf("arr[%d] = %2d\n", k, arr2[k]);
       }

       for (i=0; i<5; i++) {
         for (j=0; j< 3; j++) {
            printf("arr2[%d][%d] = %2d\n", i, j ,arr[i][j]);
         }
       } 
    } 

Output:

arr[0] =  0
arr[1] =  1
arr[2] =  2
arr[3] =  3
arr[4] =  4
arr[5] =  5
arr[6] =  6
arr[7] =  7
arr[8] =  8
arr[9] =  9
arr[10] = 10
arr[11] = 11
arr[12] = 12
arr[13] = 13
arr[14] = 14
arr2[0][0] =  0
arr2[0][1] =  1
arr2[0][2] =  2
arr2[1][0] =  3
arr2[1][1] =  4
arr2[1][2] =  5
arr2[2][0] =  6
arr2[2][1] =  7
arr2[2][2] =  8
arr2[3][0] =  9
arr2[3][1] = 10
arr2[3][2] = 11
arr2[4][0] = 12
arr2[4][1] = 13
arr2[4][2] = 14

pass array to method Java

Simply remove the brackets from your original code.

PrintA(arryw);

private void PassArray(){
    String[] arrayw = new String[4];
    //populate array
    PrintA(arrayw);
}
private void PrintA(String[] a){
    //do whatever with array here
}

That is all.

How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

Basically, yes. You write alert('<?php echo($phpvariable); ?>');

There are sure other ways to interoperate, but none of which i can think of being as simple (or better) as the above.

Find all paths between two graph nodes

I think what you want is some form of the Ford–Fulkerson algorithm which is based on BFS. Its used to calculate the max flow of a network, by finding all augmenting paths between two nodes.

http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm

ADB error: cannot connect to daemon

Go to windows task manager and end process tree of adb. It will make attempts to start adb.

Sometimes on Windows adb kill-server and adb start-server fail to start adb.

merge one local branch into another local branch

Just in case you arrived here because you copied a branch name from Github, note that a remote branch is not automatically also a local branch, so a merge will not work and give the "not something we can merge" error.

In that case, you have two options:

git checkout [branchYouWantToMergeInto]
git merge origin/[branchYouWantToMerge]

or

# this creates a local branch
git checkout [branchYouWantToMerge]

git checkout [branchYouWantToMergeInto]
git merge [branchYouWantToMerge]

Kotlin - How to correctly concatenate a String

Yes, you can concatenate using a + sign. Kotlin has string templates, so it's better to use them like:

var fn = "Hello"
var ln = "World"

"$fn $ln" for concatenation.

You can even use String.plus() method.

Removing double quotes from a string in Java

Use replace method of string like the following way:

String x="\"abcd";
String z=x.replace("\"", "");
System.out.println(z);

Output:

abcd

How to get and set the current web page scroll position?

I went with the HTML5 local storage solution... All my links call a function which sets this before changing window.location:

localStorage.topper = document.body.scrollTop;

and each page has this in the body's onLoad:

  if(localStorage.topper > 0){ 
    window.scrollTo(0,localStorage.topper);
  }

Can I run javascript before the whole page is loaded?

Not only can you, but you have to make a special effort not to if you don't want to. :-)

When the browser encounters a classic script tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write calls to output markup that the parser should handle).

That's the default behavior, but you have a few options for delaying script execution:

  1. Use JavaScript modules. A type="module" script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:

    <script type="module" src="./my-code.js"></script>
    <!-- Or -->
    <script type="module">
    // Your code here
    </script>
    

    The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)

    This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.

  2. Use the defer attribute on a classic script tag:

    <script defer src="./my-code.js"></script>
    

    As with the module, the code in my-code.js will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer doesn't work with inline script content, only with external files referenced via src.

  3. I don't think it's what you want, but you can use the async attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module" tag, or use it instead of defer on a classic script tag.

  4. Put the script tag at the end of the document, just prior to the closing </body> tag:

    <!doctype html>
    <html>
    <!-- ... -->
    <body>
    <!-- The document's HTML goes here -->
    <script type="module" src="./my-code.js"></script><!-- Or inline script -->
    </body>
    </html>
    

    That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.

    It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer are better options.

The spec has a useful diagram showing a raw script tag, defer, async, type="module", and type="module" async and the timing of when the JavaScript code is fetched and run:

enter image description here

Here's an example of the default behavior, a raw script tag:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
    if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
        NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
    }_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

(See my answer here for details around that NodeList code.)

When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.

In contrast, here's a type="module" script:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer script with external content (but not inline content).

(There was no need for the NodeList check there because any modern browser supporting modules already has forEach on NodeList.)

In this modern world, there's no real value to the DOMContentLoaded event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script was in the head instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body, again back in the day.

Vertical dividers on horizontal UL menu

This works fine for me:

NB I'm using BEM/OCSS SCSS Syntax

#navigation{
  li{
     &:after{
        content: '|'; // use content for box-sizing
        text-indent: -999999px; // Hide the content
        display: block;
        float: right; // Position
        width: 1px;
        height: 100%; // The 100% of parent (li)
        background: black; // The color
        margin: {
          left: 5px;
          right: 5px;
        }
      }

      &:last-child{

        &:after{
          content: none;
        }

      }
  }
}

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

I find I rarely have need to use getCanonicalPath() but, if given a File with a filename that is in DOS 8.3 format on Windows, such as the java.io.tmpdir System property returns, then this method will return the "full" filename.

Run jQuery function onclick

You can bind the mouseenter and mouseleave events and jQuery will emulate those where they are not native.

$("div.system_box").on('mouseenter', function(){
    //enter
})
.on('mouseleave', function(){
    //leave
});

fiddle

note: do not use hover as that is deprecated

Removing index column in pandas when reading a csv

DataFrames and Series always have an index. Although it displays alongside the column(s), it is not a column, which is why del df['index'] did not work.

If you want to replace the index with simple sequential numbers, use df.reset_index().

To get a sense for why the index is there and how it is used, see e.g. 10 minutes to Pandas.

How to view the list of compile errors in IntelliJ?

A more up to date answer for anyone else who comes across this:

(from https://www.jetbrains.com/help/idea/eclipse.html, §Auto-compilation; click for screenshots)

Compile automatically:

To enable automatic compilation, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler and select the Build project automatically option

Show all errors in one place:

The Problems tool window appears if the Make project automatically option is enabled in the Compiler settings. It shows a list of problems that were detected on project compilation.

Use the Eclipse compiler: This is actually bundled in IntelliJ. It gives much more useful error messages, in my opinion, and, according to this blog, it's much faster since it was designed to run in the background of an IDE and uses incremental compilation.

While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you must use the Eclipse compiler, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler and select it... The biggest difference between the Eclipse and javac compilers is that the Eclipse compiler is more tolerant to errors, and sometimes lets you run code that doesn't compile.

What does the 'b' character do in front of a string literal?

The b denotes a byte string.

Bytes are the actual data. Strings are an abstraction.

If you had multi-character string object and you took a single character, it would be a string, and it might be more than 1 byte in size depending on encoding.

If took 1 byte with a byte string, you'd get a single 8-bit value from 0-255 and it might not represent a complete character if those characters due to encoding were > 1 byte.

TBH I'd use strings unless I had some specific low level reason to use bytes.

For homebrew mysql installs, where's my.cnf?

There is no my.cnf by default. As such, MySQL starts with all of the default settings. If you want to create your own my.cnf to override any defaults, place it at /etc/my.cnf.

Also, you can run mysql --help and look through it for the conf locations listed.

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf 
The following groups are read: mysql client
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit.
--no-defaults           Don't read default options from any option file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.

As you can see, there are also some options for bypassing the conf files, or specifying other files to read when you invoke mysql on the command line.

DataGridView - how to set column width?

Most of the above solutions assume that the parent DateGridView has .AutoSizeMode not equal to Fill. If you set the .AutoSizeMode for the grid to be Fill, you need to set the AutoSizeMode for each column to be None if you want to fix a particular column width (and let the other columns Fill). I found a weird MS exception regarding a null object if you change a Column Width and the .AutoSizeMode is not None first.

This works

chart.AutoSizeMode  = DataGridViewAutoSizeColumnMode.Fill;
... add some columns here
chart.Column[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
chart.Column[i].Width = 60;

This throws a null exception regarding some internal object regarding setting border thickness.

chart.AutoSizeMode  = DataGridViewAutoSizeColumnMode.Fill;
... add some columns here
 // chart.Column[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
chart.Column[i].Width = 60;

HashMap - getting First Key value

You can try this:

 Map<String,String> map = new HashMap<>();
 Map.Entry<String,String> entry = map.entrySet().iterator().next();
 String key = entry.getKey();
 String value = entry.getValue();

Keep in mind, HashMap does not guarantee the insertion order. Use a LinkedHashMap to keep the order intact.

Eg:

 Map<String,String> map = new LinkedHashMap<>();
 map.put("Active","33");
 map.put("Renewals Completed","3");
 map.put("Application","15");
 Map.Entry<String,String> entry = map.entrySet().iterator().next();
 String key= entry.getKey();
 String value=entry.getValue();
 System.out.println(key);
 System.out.println(value);

Output:

 Active
 33

Is there a way to get the XPath in Google Chrome?

No extension needed in chrome now. Right click on any element you want xpath for and click on "Inspect Element" and then again inside the Inspector, right click on element and click on "Copy Xpath".

What is the purpose of the var keyword and when should I use it (or omit it)?

Here's quite a good example of how you can get caught out from not declaring local variables with var:

<script>
one();

function one()
{
    for (i = 0;i < 10;i++)
    {
        two();
        alert(i);
    }
}

function two()
{
    i = 1;
}
</script>

(i is reset at every iteration of the loop, as it's not declared locally in the for loop but globally) eventually resulting in infinite loop

How to create a remote Git repository from a local one?

You need to create a directory on a remote server. Then use "git init" command to set it as a repository. This should be done for each new project you have (each new folder)

Assuming you have already setup and used git using ssh keys, I wrote a small Python script, which when executed from a working directory will set up a remote and initialize the directory as a git repo. Of course, you will have to edit script (only once) to tell it server and Root path for all repositories.

Check here - https://github.com/skbobade/ocgi

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

Read a variable in bash with a default value

Code:

IN_PATH_DEFAULT="/tmp/input.txt"
read -p "Please enter IN_PATH [$IN_PATH_DEFAULT]: " IN_PATH
IN_PATH="${IN_PATH:-$IN_PATH_DEFAULT}"

OUT_PATH_DEFAULT="/tmp/output.txt"
read -p "Please enter OUT_PATH [$OUT_PATH_DEFAULT]: " OUT_PATH
OUT_PATH="${OUT_PATH:-$OUT_PATH_DEFAULT}"

echo "Input: $IN_PATH Output: $OUT_PATH"

Sample run:

Please enter IN_PATH [/tmp/input.txt]: 
Please enter OUT_PATH [/tmp/output.txt]: ~/out.txt
Input: /tmp/input.txt Output: ~/out.txt

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

Center image horizontally within a div

CSS flexbox can do it with justify-content: center on the image parent element. To preserve the aspect ratio of the image, add align-self: flex-start; to it.

HTML

<div class="image-container">
  <img src="http://placehold.it/100x100" />
</div>

CSS

.image-container {
  display: flex;
  justify-content: center;
}

Output:

_x000D_
_x000D_
body {_x000D_
  background: lightgray;_x000D_
}_x000D_
.image-container {_x000D_
  width: 200px;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  margin: 10px;_x000D_
  padding: 10px;_x000D_
  /* Material design properties */_x000D_
  background: #fff;_x000D_
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12);_x000D_
}_x000D_
.image-2 {_x000D_
  width: 500px;_x000D_
  align-self: flex-start;  /* to preserve image aspect ratio */_x000D_
}_x000D_
.image-3 {_x000D_
  width: 300px;_x000D_
  align-self: flex-start;  /* to preserve image aspect ratio */_x000D_
}
_x000D_
<div class="image-container">_x000D_
  <img src="http://placehold.it/100x100" />_x000D_
</div>_x000D_
_x000D_
<div class="image-container image-2">_x000D_
  <img src="http://placehold.it/100x100/333" />_x000D_
</div>_x000D_
_x000D_
<div class="image-container image-3">_x000D_
  <img src="http://placehold.it/100x100/666" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery/JavaScript: accessing contents of an iframe

You need to attach an event to an iframe's onload handler, and execute the js in there, so that you make sure the iframe has finished loading before accessing it.

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

The above will solve the 'not-yet-loaded' problem, but as regards the permissions, if you are loading a page in the iframe that is from a different domain, you won't be able to access it due to security restrictions.

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}