Programs & Examples On #Hobbitmon

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

Convert hex color value ( #ffffff ) to integer value

I was facing the same problem. This way I was able to solved it. As CQM said, using Color.parseColor() is a good solution to this issue.

Here is the code I used:

this.Button_C.setTextColor(Color.parseColor(prefs.getString("color_prefs", String.valueOf(R.color.green))));

In this case my target was to change the Button's text color (Button_C) when I change the color selection from my Preferences (color_prefs).

Recursively list files in Java

Kotlin has FileTreeWalk for this purpose. For example:

dataDir.walkTopDown().filter { !it.isDirectory }.joinToString("\n") {
   "${it.toRelativeString(dataDir)}: ${it.length()}"
}

Will produce a text list of all the non-directory files under a given root, one file per line with the path relative to the root and length.

SQL Greater than, Equal to AND Less Than

Somthing like this should workL

SELECT BookingId, StartTime
FROM Booking
WHERE StartTime between dateadd(hour, -1, getdate()) and getdate()

Is there such a thing as min-font-size and max-font-size?

CSS min() and max() have fairly good usage rates in 2020.

The code below uses max() to get the largest of the [variablevalue] and [minimumvalue] and then passes that through to min() against the [maximumvalue] to get the smaller of the two. This creates an allowable font range (3.5rem is minimum, 6.5rem is maximum, 6vw is used only when in between).

font-size: min(max([variablevalue], [minimumvalue]), [maximumvalue]);
font-size: min(max(6vw, 3.5rem), 6.5rem);

I'm using this specifically with font-awesome as a video-play icon over an image within a bootstrap container element where max-width is set.

How do I install a module globally using npm?

If you want to install a npm module globally, make sure to use the new -g flag, for example:

npm install forever -g

The general recommendations concerning npm module installation since 1.0rc (taken from blog.nodejs.org):

  • If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your project.
  • If you’re installing something that you want to use in your shell, on the command line or something, install it globally, so that its binaries end up in your PATH environment variable.

I just recently used this recommendations and it went down pretty smoothly. I installed forever globally (since it is a command line tool) and all my application modules locally.

However, if you want to use some modules globally (i.e. express or mongodb), take this advice (also taken from blog.nodejs.org):

Of course, there are some cases where you want to do both. Coffee-script and Express both are good examples of apps that have a command line interface, as well as a library. In those cases, you can do one of the following:

  • Install it in both places. Seriously, are you that short on disk space? It’s fine, really. They’re tiny JavaScript programs.
  • Install it globally, and then npm link coffee-script or npm link express (if you’re on a platform that supports symbolic links.) Then you only need to update the global copy to update all the symlinks as well.

The first option is the best in my opinion. Simple, clear, explicit. The second is really handy if you are going to re-use the same library in a bunch of different projects. (More on npm link in a future installment.)

I did not test one of those variations, but they seem to be pretty straightforward.

When to use Comparable and Comparator

Use Comparable:

  • if the object is in your control.
  • if the comparing behaviour is the main comparing behaviour.

Use Comparator :

  • if the object is outside your control and you cannot make them implement Comparable.
  • when you want comparing behaviour different from the default (which is specified by Comparable) behaviour.

Checking if a field contains a string

Simplest way to accomplish this task

If you want the query to be case-sensitive

db.getCollection("users").find({'username':/Son/})

If you want the query to be case-insensitive

db.getCollection("users").find({'username':/Son/i})

How can I add shadow to the widget in flutter?

class ShadowContainer extends StatelessWidget {
  ShadowContainer({
    Key key,
    this.margin = const EdgeInsets.fromLTRB(0, 10, 0, 8),
    this.padding = const EdgeInsets.symmetric(horizontal: 8),
    this.circular = 4,
    this.shadowColor = const Color.fromARGB(
        128, 158, 158, 158), //Colors.grey.withOpacity(0.5),
    this.backgroundColor = Colors.white,
    this.spreadRadius = 1,
    this.blurRadius = 3,
    this.offset = const Offset(0, 1),
    @required this.child,
  }) : super(key: key);

  final Widget child;
  final EdgeInsetsGeometry margin;
  final EdgeInsetsGeometry padding;
  final double circular;
  final Color shadowColor;
  final double spreadRadius;
  final double blurRadius;
  final Offset offset;
  final Color backgroundColor;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: margin,
      padding: padding,
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(circular),
        boxShadow: [
          BoxShadow(
            color: shadowColor,
            spreadRadius: spreadRadius,
            blurRadius: blurRadius,
            offset: offset,
          ),
        ],
      ),
      child: child,
    );
  }
}

How do I get the domain originating the request in express.js?

Recently faced a problem with fetching 'Origin' request header, then I found this question. But pretty confused with the results, req.get('host') is deprecated, that's why giving Undefined. Use,

    req.header('Origin');
    req.header('Host');
    // this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.

Abstract Class vs Interface in C++

An abstract class would be used when some common implementation was required. An interface would be if you just want to specify a contract that parts of the program have to conform too. By implementing an interface you are guaranteeing that you will implement certain methods. By extending an abstract class you are inheriting some of it's implementation. Therefore an interface is just an abstract class with no methods implemented (all are pure virtual).

SQL Server format decimal places with commas

If you are using SQL Azure Reporting Services, the "format" function is unsupported. This is really the only way to format a tooltip in a chart in SSRS. So the workaround is to return a column that has a string representation of the formatted number to use for the tooltip. So, I do agree that SQL is not the place for formatting. Except in cases like this where the tool does not have proper functions to handle display formatting.

In my case I needed to show a number formatted with commas and no decimals (type decimal 2) and ended up with this gem of a calculated column in my dataset query:

,Fmt_DDS=reverse(stuff(reverse(CONVERT(varchar(25),cast(SUM(kv.DeepDiveSavingsEst) as money),1)), 1, 3, ''))

It works, but is very ugly and non-obvious to whoever maintains the report down the road. Yay Cloud!

Get filename from input [type='file'] using jQuery

If selected more 1 file:

$("input[type="file"]").change(function() {
   var files = $("input[type="file"]").prop("files");
   var names = $.map(files, function(val) { return val.name; });
   $(".some_div").text(names);
});

files will be a FileList object. names is an array of strings (file names).

Run batch file from Java code

try following

try {
            String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"};
            Process p =  Runtime.getRuntime().exec(command);           
        } catch (IOException ex) {
        }

Android new Bottom Navigation bar or BottomNavigationView

You should use BottomNavigationView from v25 Android Support Library. It represents a standard bottom navigation bar for application.

Here is a post on Medium that has a step by step guide: https://medium.com/@hitherejoe/exploring-the-android-design-support-library-bottom-navigation-drawer-548de699e8e0#.9vmiekxze

Message 'src refspec master does not match any' when pushing commits in Git

Try this:

git add .

git commit -m "your commit message"

git remote add origin *remote repository URL*

git push origin *your-branch-name*

jQuery append() and remove() element

Since this is an open-ended question, I will just give you an idea of how I would go about implementing something like this myself.

<span class="inputname">
    Project Images:
    <a href="#" class="add_project_file">
        <img src="images/add_small.gif" border="0" />
    </a>
</span>

<ul class="project_images">
    <li><input name="upload_project_images[]" type="file" /></li>
</ul>

Wrapping the file inputs inside li elements allows to easily remove the parent of our 'remove' links when clicked. The jQuery to do so is close to what you have already:

// Add new input with associated 'remove' link when 'add' button is clicked.
$('.add_project_file').click(function(e) {
    e.preventDefault();

    $(".project_images").append(
        '<li>'
      + '<input name="upload_project_images[]" type="file" class="new_project_image" /> '
      + '<a href="#" class="remove_project_file" border="2"><img src="images/delete.gif" /></a>'
      + '</li>');
});

// Remove parent of 'remove' link when link is clicked.
$('.project_images').on('click', '.remove_project_file', function(e) {
    e.preventDefault();

    $(this).parent().remove();
});

What is ":-!!" in C code?

Some people seem to be confusing these macros with assert().

These macros implement a compile-time test, while assert() is a runtime test.

Accessing dict keys like an attribute?

Here's a short example of immutable records using built-in collections.namedtuple:

def record(name, d):
    return namedtuple(name, d.keys())(**d)

and a usage example:

rec = record('Model', {
    'train_op': train_op,
    'loss': loss,
})

print rec.loss(..)

Checking length of dictionary object

This question is confusing. A regular object, {} doesn't have a length property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).

Meaning, you have to get the "length" by a for..in statement on the object, since length is not set, and increment a counter.

I'm confused as to why you need the length. Are you manually setting 0 on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';. If the latter, again, why the need for length?

Edit #1: Why can't you just do this?

list = [ {name:'john'}, {name:'bob'} ];

Then iterate over list? The length is already set.

What is the simplest way to get indented XML with line breaks from XmlDocument?

A more simplified approach based on the accepted answer:

static public string Beautify(this XmlDocument doc) {
    StringBuilder sb = new StringBuilder();
    XmlWriterSettings settings = new XmlWriterSettings
    {
        Indent = true
    };

    using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
        doc.Save(writer);
    }

    return sb.ToString(); 
}

Setting the new line is not necessary. Indent characters also has the default two spaces so I preferred not to set it as well.

Difference between Git and GitHub

Simply put, Git is a version control system that lets you manage and keep track of your source code history. GitHub is a cloud-based hosting service that lets you manage Git repositories. If you have open-source projects that use Git, then GitHub is designed to help you better manage them.

Add padding on view programmatically

You can set padding to your view by pro grammatically throughout below code -

view.setPadding(0,1,20,3);

And, also there are different type of padding available -

Padding

PaddingBottom

PaddingLeft

PaddingRight

PaddingTop

These, links will refer Android Developers site. Hope this helps you lot.

Pandas read in table without headers

Make sure you specify pass header=None and add usecols=[3,6] for the 4th and 7th columns.

How to create a inner border for a box in html?

IE doesn't support outline-offset so another solution would be to create 2 div tags, one nested into the other one. The inner one would have a border and be slightly smaller than the container.

_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  width: 400px;_x000D_
  height: 100px;_x000D_
  background: #000000;_x000D_
  padding: 10px;_x000D_
}_x000D_
.inner {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background: #000000;_x000D_
  border: 1px dashed #ffffff;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="inner"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the proper way to comment functions in Python?

I would go a step further than just saying "use a docstring". Pick a documentation generation tool, such as pydoc or epydoc (I use epydoc in pyparsing), and use the markup syntax recognized by that tool. Run that tool often while you are doing your development, to identify holes in your documentation. In fact, you might even benefit from writing the docstrings for the members of a class before implementing the class.

Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

After following the steps from @Johnride, I still got the same error.

This fixed the problem:

Tools-> Options-> Select no proxy

source: https://www.youtube.com/watch?v=uI1j-8F8eN4

Can I change the scroll speed using css or jQuery?

No. Scroll speed is determined by the browser (and usually directly by the settings on the computer/device). CSS and Javascript don't (or shouldn't) have any way to affect system settings.

That being said, there are likely a number of ways you could try to fake a different scroll speed by moving your own content around in such a way as to counteract scrolling. However, I think doing so is a HORRIBLE idea in terms of usability, accessibility, and respect for your users, but I would start by finding events that your target browsers fire that indicate scrolling.

Once you can capture the scroll event (assuming you can), then you would be able to adjust your content dynamically so that the portion you want is visible.

Another approach would be to deal with this in Flash, which does give you at least some level of control over scrolling events.

Use '=' or LIKE to compare strings in SQL?

For pattern matching use LIKE. For exact match =.

Where are my postgres *.conf files?

Run

sudo updatedb

followed by

locate postgresql.conf

PHP: maximum execution time when importing .SQL data file

you must change php_admin_value max_execution_time in your Alias config (\XAMPP\alias\phpmyadmin.conf)

answer is here: WAMPServer phpMyadmin Maximum execution time of 360 seconds exceeded

How to hide only the Close (x) button?

We can hide close button on form by setting this.ControlBox=false;

Note that this hides all of those sizing buttons. Not just the X. In some cases that may be fine.

How to click on hidden element in Selenium WebDriver?

Here is the script in Python.

You cannot click on elements in selenium that are hidden. However, you can execute JavaScript to click on the hidden element for you.

element = driver.find_element_by_id(buttonID)
driver.execute_script("$(arguments[0]).click();", element)

MySQL - DATE_ADD month interval

Do I understand right that you assume that DATE_ADD("2011-01-01", INTERVAL 6 MONTH) should give you '2011-06-30' instead of '2011-07-01'? Of course, 2011-01-01 + 6 months is 2011-07-01. You want something like DATE_SUB(DATE_ADD("2011-01-01", INTERVAL 6 MONTH), INTERVAL 1 DAY).

Calling async method synchronously

I prefer a non blocking approach:

            Dim aw1=GenerateCodeAsync().GetAwaiter()
            While Not aw1.IsCompleted
                Application.DoEvents()
            End While

Android Layout Right Align

If you want to use LinearLayout, you can do alignment with layout_weight with Space element.

E.g. following layout places textView and textView2 next to each other and textView3 will be right-aligned

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView2" />

    <Space
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="20dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView3" />
</LinearLayout>

you can achieve the same effect without Space if you would set layout_weight to textView2. It's just that I like things more separated, plus to demonstrate Space element.

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView2" />

Note that you should (not must though) set layout_width explicitly as it will be recalculated according to it's weight anyway (same way you should set height in elements of vertical LinearLayout). For other layout performance tips see Android Layout Tricks series.

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

better way to drop nan rows in pandas

To remove rows based on Nan value of particular column:

d= pd.DataFrame([[2,3],[4,None]])   #creating data frame
d
Output:
    0   1
0   2   3.0
1   4   NaN
d = d[np.isfinite(d[1])]  #Select rows where value of 1st column is not nan
d

Output:
    0   1
0   2   3.0

How to filter a data frame

Another method utilizing the dplyr package:

library(dplyr)
df <- mtcars %>%
        filter(mpg > 25)

Without the chain (%>%) operator:

library(dplyr)
df <- filter(mtcars, mpg > 25)

Using GPU from a docker container?

Use x11docker by mviereck:

https://github.com/mviereck/x11docker#hardware-acceleration says

Hardware acceleration

Hardware acceleration for OpenGL is possible with option -g, --gpu.

This will work out of the box in most cases with open source drivers on host. Otherwise have a look at wiki: feature dependencies. Closed source NVIDIA drivers need some setup and support less x11docker X server options.

This script is really convenient as it handles all the configuration and setup. Running a docker image on X with gpu is as simple as

x11docker --gpu imagename

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

I would suggest using System.Runtime.Serialization.Json that is part of .NET 4.5.

[DataContract]
public class Foo
{
   [DataMember(Name = "data")]
   public Dictionary<string,string> Data { get; set; }
}

Then use it like this:

var serializer = new DataContractJsonSerializer(typeof(List<Foo>));
var jsonParams = @"{""data"": [{""Key"":""foo"",""Value"":""bar""}] }";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonParams));

var obj = serializer.ReadObject(stream);
Console.WriteLine(obj);

Storing money in a decimal column - what precision and scale?

The money datatype on SQL Server has four digits after the decimal.

From SQL Server 2000 Books Online:

Monetary data represents positive or negative amounts of money. In Microsoft® SQL Server™ 2000, monetary data is stored using the money and smallmoney data types. Monetary data can be stored to an accuracy of four decimal places. Use the money data type to store values in the range from -922,337,203,685,477.5808 through +922,337,203,685,477.5807 (requires 8 bytes to store a value). Use the smallmoney data type to store values in the range from -214,748.3648 through 214,748.3647 (requires 4 bytes to store a value). If a greater number of decimal places are required, use the decimal data type instead.

How to prevent page scrolling when scrolling a DIV element?

Here is the plugin that is useful for preventing parent scroll while scrolling a specific div and has a bunch of options to play with.

Check it out here:

https://github.com/MohammadYounes/jquery-scrollLock

Usage

Trigger Scroll Lock via JavaScript:

$('#target').scrollLock();

Trigger Scroll Lock via Markup:

    <!-- HTML -->
<div data-scrollLock
     data-strict='true'
     data-selector='.child'
     data-animation='{"top":"top locked","bottom":"bottom locked"}'
     data-keyboard='{"tabindex":0}'
     data-unblock='.inner'>
     ...
</div>

<!-- JavaScript -->
<script type="text/javascript">
  $('[data-scrollLock]').scrollLock()
</script>

View Demo

Deploying my application at the root in Tomcat

on tomcat v.7 (vanilla installation)

in your conf/server.xml add the following bit towards the end of the file, just before the </Host> closing tag:

<Context path="" docBase="app_name">
    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

Note that docBase attribute. It's the important bit. You either make sure you've deployed app_name before you change your root web app, or just copy your unpacked webapp (app_name) into your tomcat's webapps folder. Startup, visit root, see your app_name there!

Instagram API - How can I retrieve the list of people a user is following on Instagram

I made my own way based on Caitlin Morris's answer for fetching all folowers and followings on Instagram. Just copy this code, paste in browser console and wait for a few seconds.

You need to use browser console from instagram.com tab to make it works.

let username = 'USERNAME'
let followers = [], followings = []
try {
  let res = await fetch(`https://www.instagram.com/${username}/?__a=1`)

  res = await res.json()
  let userId = res.graphql.user.id

  let after = null, has_next = true
  while (has_next) {
    await fetch(`https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=` + encodeURIComponent(JSON.stringify({
      id: userId,
      include_reel: true,
      fetch_mutual: true,
      first: 50,
      after: after
    }))).then(res => res.json()).then(res => {
      has_next = res.data.user.edge_followed_by.page_info.has_next_page
      after = res.data.user.edge_followed_by.page_info.end_cursor
      followers = followers.concat(res.data.user.edge_followed_by.edges.map(({node}) => {
        return {
          username: node.username,
          full_name: node.full_name
        }
      }))
    })
  }
  console.log('Followers', followers)

  has_next = true
  after = null
  while (has_next) {
    await fetch(`https://www.instagram.com/graphql/query/?query_hash=d04b0a864b4b54837c0d870b0e77e076&variables=` + encodeURIComponent(JSON.stringify({
      id: userId,
      include_reel: true,
      fetch_mutual: true,
      first: 50,
      after: after
    }))).then(res => res.json()).then(res => {
      has_next = res.data.user.edge_follow.page_info.has_next_page
      after = res.data.user.edge_follow.page_info.end_cursor
      followings = followings.concat(res.data.user.edge_follow.edges.map(({node}) => {
        return {
          username: node.username,
          full_name: node.full_name
        }
      }))
    })
  }
  console.log('Followings', followings)
} catch (err) {
  console.log('Invalid username')
}

How to correctly link php-fpm and Nginx Docker containers?

As pointed out before, the problem was that the files were not visible by the fpm container. However to share data among containers the recommended pattern is using data-only containers (as explained in this article).

Long story short: create a container that just holds your data, share it with a volume, and link this volume in your apps with volumes_from.

Using compose (1.6.2 in my machine), the docker-compose.yml file would read:

version: "2"
services:
  nginx:
    build:
      context: .
      dockerfile: nginx/Dockerfile
    ports:
      - "80:80"
    links:
      - fpm
    volumes_from:
      - data
  fpm:
    image: php:fpm
    volumes_from:
      - data
  data:
    build:
      context: .
      dockerfile: data/Dockerfile
    volumes:
      - /var/www/html

Note that data publishes a volume that is linked to the nginx and fpm services. Then the Dockerfile for the data service, that contains your source code:

FROM busybox

# content
ADD path/to/source /var/www/html

And the Dockerfile for nginx, that just replaces the default config:

FROM nginx

# config
ADD config/default.conf /etc/nginx/conf.d

For the sake of completion, here's the config file required for the example to work:

server {
    listen 0.0.0.0:80;

    root /var/www/html;

    location / {
        index index.php index.html;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass fpm:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
    }
}

which just tells nginx to use the shared volume as document root, and sets the right config for nginx to be able to communicate with the fpm container (i.e.: the right HOST:PORT, which is fpm:9000 thanks to the hostnames defined by compose, and the SCRIPT_FILENAME).

java.io.FileNotFoundException: (Access is denied)

  1. check the rsp's reply
  2. check that you have permissions to read the file
  3. check whether the file is not locked by other application. It is relevant mostly if you are on windows. for example I think that you can get the exception if you are trying to read the file while it is opened in notepad

How to access a dictionary element in a Django template?

Could find nothing simpler and better than this solution. Also see the doc.

@register.filter
def dictitem(dictionary, key):
    return dictionary.get(key)

But there's a problem (also discussed here) that the returned item is an object and I need to reference a field of this object. Expressions like {{ (schema_dict|dictitem:schema_code).name }} are not supported, so the only solution I found was:

{% with schema=schema_dict|dictitem:schema_code %}
    <p>Selected schema: {{ schema.name }}</p>
{% endwith %}

UPDATE:

@register.filter
def member(obj, name):
    return getattr(obj, name, None)

So no need for a with tag:

{{ schema_dict|dictitem:schema_code|member:'name' }}

How to close a web page on a button click, a hyperlink or a link button click?

double click the button and add write // this.close();

  private void buttonClick(object sender, EventArgs e)
{
    this.Close();
}

Eclipse - debugger doesn't stop at breakpoint

This is what works for me:

I had to put my local server address in the PHP Server configuration like this:

enter image description here

Note: that address, is the one I configure in my Apache .conf file.

Note: the only breakpoint that was working was the 'Break at first line', after that, the breakpoints didn't work.

Note: check your xdebug properties in your php.ini file, and remove any you think is not required.

Is there a way to perform "if" in python's lambda

Probably the worst python line I've written so far:

f = lambda x: sys.stdout.write(["2\n",][2*(x==2)-2])

If x == 2 you print,

if x != 2 you raise.

How to use a client certificate to authenticate and authorize in a Web API

Tracing helped me find what the problem was (Thank you Fabian for that suggestion). I found with further testing that I could get the client certificate to work on another server (Windows Server 2012). I was testing this on my development machine (Window 7) so I could debug this process. So by comparing the trace to an IIS Server that worked and one that did not I was able to pinpoint the relevant lines in the trace log. Here is a portion of a log where the client certificate worked. This is the setup right before the send

System.Net Information: 0 : [17444] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [17444] SecureChannel#54718731 - We have user-provided certificates. The server has not specified any issuers, so try all the certificates.
System.Net Information: 0 : [17444] SecureChannel#54718731 - Selected certificate:

Here is what the trace log looked like on the machine where the client certificate failed.

System.Net Information: 0 : [19616] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [19616] SecureChannel#54718731 - We have user-provided certificates. The server has specified 137 issuer(s). Looking for certificates that match any of the issuers.
System.Net Information: 0 : [19616] SecureChannel#54718731 - Left with 0 client certificates to choose from.
System.Net Information: 0 : [19616] Using the cached credential handle.

Focusing on the line that indicated the server specified 137 issuers I found this Q&A that seemed similar to my issue. The solution for me was not the one marked as an answer since my certificate was in the trusted root. The answer is the one under it where you update the registry. I just added the value to the registry key.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL

Value name: SendTrustedIssuerList Value type: REG_DWORD Value data: 0 (False)

After adding this value to the registry it started to work on my Windows 7 machine. This appears to be a Windows 7 issue.

Android Studio how to run gradle sync manually?

gradle --recompile-scripts

seems to do a sync without building anything. you can enable automatic building by

gradle --recompile-scripts --continuous

Please refer the docs for more info:

https://docs.gradle.org/current/userguide/gradle_command_line.html

TypeError: Cannot read property "0" from undefined

For me, the problem was I was using a package that isn't included in package.json nor installed.

import { ToastrService } from 'ngx-toastr';

So when the compiler tried to compile this, it threw an error.

(I installed it locally, and when running a build on an external server the error was thrown)

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Get Absolute Position of element within the window in wpf

Hm. You have to specify window you clicked in Mouse.GetPosition(IInputElement relativeTo) Following code works well for me

protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        base.OnMouseDown(e);
        Point p = e.GetPosition(this);
    }

I suspect that you need to refer to the window not from it own class but from other point of the application. In this case Application.Current.MainWindow will help you.

How to sort an array based on the length of each element?

<script>
         arr = []
         arr[0] = "ab"
         arr[1] = "abcdefgh"
         arr[2] = "sdfds"
         arr.sort(function(a,b){
            return a.length<b.length
         })
         document.write(arr)

</script>

The anonymous function that you pass to sort tells it how to sort the given array.hope this helps.I know this is confusing but you can tell the sort function how to sort the elements of the array by passing it a function as a parameter telling it what to do

Disable password authentication for SSH

In file /etc/ssh/sshd_config

# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication no

Uncomment the second line, and, if needed, change yes to no.

Then run

service ssh restart

Getting the client's time zone (and offset) in JavaScript

you can simply try this. it will return you current machine time

var _d = new Date(), t = 0, d = new Date(t*1000 + _d.getTime())

Why ModelState.IsValid always return false in mvc

As Brad Wilson states in his answer here:

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

Try using :-

if (!ModelState.IsValid)
{
    var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));

    // Breakpoint, Log or examine the list with Exceptions.
}

If it helps catching you the error. Courtesy this and this

Excel VBA Password via Hex Editor

I have your answer, as I just had the same problem today:

Someone made a working vba code that changes the vba protection password to "macro", for all excel files, including .xlsm (2007+ versions). You can see how it works by browsing his code.

This is the guy's blog: http://lbeliarl.blogspot.com/2014/03/excel-removing-password-from-vba.html Here's the file that does the work: https://docs.google.com/file/d/0B6sFi5sSqEKbLUIwUTVhY3lWZE0/edit

Pasted from a previous post from his blog:

For Excel 2007/2010 (.xlsm) files do following steps:

  1. Create a new .xlsm file.
  2. In the VBA part, set a simple password (for instance 'macro').
  3. Save the file and exit.
  4. Change file extention to '.zip', open it by any archiver program.
  5. Find the file: 'vbaProject.bin' (in 'xl' folder).
  6. Extract it from archive.
  7. Open the file you just extracted with a hex editor.
  8. Find and copy the value from parameter DPB (value in quotation mark), example: DPB="282A84CBA1CBA1345FCCB154E20721DE77F7D2378D0EAC90427A22021A46E9CE6F17188A". (This value generated for 'macro' password. You can use this DPB value to skip steps 1-8)

  9. Do steps 4-7 for file with unknown password (file you want to unlock).

  10. Change DBP value in this file on value that you have copied in step 8.

    If copied value is shorter than in encrypted file you should populate missing characters with 0 (zero). If value is longer - that is not a problem (paste it as is).

  11. Save the 'vbaProject.bin' file and exit from hex editor.

  12. Replace existing 'vbaProject.bin' file with modified one.
  13. Change extention from '.zip' back to '.xlsm'
  14. Now, open the excel file you need to see the VBA code in. The password for the VBA code will simply be macro (as in the example I'm showing here).

Best practices for Storyboard login screen, handling clearing of data upon logout

I didn't like bhavya's answer because of using AppDelegate inside View Controllers and setting rootViewController has no animation. And Trevor's answer has issue with flashing view controller on iOS8.

UPD 07/18/2015

AppDelegate inside View Controllers:

Changing AppDelegate state (properties) inside view controller breaks encapsulation.

Very simple hierarchy of objects in every iOS project:

AppDelegate (owns window and rootViewController)

ViewController (owns view)

It's ok that objects from the top change objects at the bottom, because they are creating them. But it's not ok if objects on the bottom change objects on top of them (I described some basic programming/OOP principle : DIP (Dependency Inversion Principle : high level module must not depend on the low level module, but they should depend on abstractions)).

If any object will change any object in this hierarchy, sooner or later there will be a mess in the code. It might be ok on the small projects but it's no fun to dig through this mess on the bit projects =]

UPD 07/18/2015

I replicate modal controller animations using UINavigationController (tl;dr: check the project).

I'm using UINavigationController to present all controllers in my app. Initially I displayed login view controller in navigation stack with plain push/pop animation. Than I decided to change it to modal with minimal changes.

How it works:

  1. Initial view controller (or self.window.rootViewController) is UINavigationController with ProgressViewController as a rootViewController. I'm showing ProgressViewController because DataModel can take some time to initialize because it inits core data stack like in this article (I really like this approach).

  2. AppDelegate is responsible for getting login status updates.

  3. DataModel handles user login/logout and AppDelegate is observing it's userLoggedIn property via KVO. Arguably not the best method to do this but it works for me. (Why KVO is bad, you can check in this or this article (Why Not Use Notifications? part).

  4. ModalDismissAnimator and ModalPresentAnimator are used to customize default push animation.

How animators logic works:

  1. AppDelegate sets itself as a delegate of self.window.rootViewController (which is UINavigationController).

  2. AppDelegate returns one of animators in -[AppDelegate navigationController:animationControllerForOperation:fromViewController:toViewController:] if necessary.

  3. Animators implement -transitionDuration: and -animateTransition: methods. -[ModalPresentAnimator animateTransition:]:

    - (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
    {
        UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        [[transitionContext containerView] addSubview:toViewController.view];
        CGRect frame = toViewController.view.frame;
        CGRect toFrame = frame;
        frame.origin.y = CGRectGetHeight(frame);
        toViewController.view.frame = frame;
        [UIView animateWithDuration:[self transitionDuration:transitionContext]
                         animations:^
         {
             toViewController.view.frame = toFrame;
         } completion:^(BOOL finished)
         {
             [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
         }];
    }
    

Test project is here.

Should Gemfile.lock be included in .gitignore?

No Gemfile.lock means:

  • new contributors cannot run tests because weird things fail, so they won't contribute or get failing PRs ... bad first experience.
  • you cannot go back to a x year old project and fix a bug without having to update/rewrite the project if you lost your local Gemfile.lock

-> Always check in Gemfile.lock, make travis delete it if you want to be extra thorough https://grosser.it/2015/08/14/check-in-your-gemfile-lock/

Export Postgresql table data using pgAdmin

  1. Right-click on your table and pick option Backup..
  2. On File Options, set Filepath/Filename and pick PLAIN for Format
  3. Ignore Dump Options #1 tab
  4. In Dump Options #2 tab, check USE INSERT COMMANDS
  5. In Dump Options #2 tab, check Use Column Inserts if you want column names in your inserts.
  6. Hit Backup button

mysql delete under safe mode

I have a far more simple solution, it is working for me; it is also a workaround but might be usable and you dont have to change your settings. I assume you can use value that will never be there, then you use it on your WHERE clause

DELETE FROM MyTable WHERE MyField IS_NOT_EQUAL AnyValueNoItemOnMyFieldWillEverHave

I don't like that solution either too much, that's why I am here, but it works and it seems better than what it has been answered

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

From my experience the default location is /var/lib/mongodb after I do

sudo apt-get install -y mongodb-org

How to concatenate properties from multiple JavaScript objects

Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

Spread syntax for object literals was introduced in ECMAScript 2018):

const a = { "one": 1, "two": 2 };
const b = { "three": 3 };
const c = { "four": 4, "five": 5 };

const result = {...a, ...b, ...c};
// Object { "one": 1, "two": 2 , "three": 3, "four": 4, "five": 5 }

Spread (...) operator is supported in many modern browsers but not all of them.

So, it is recommend to use a transpiler like Babel to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.

This is the equivalent code Babel will generate for you:

"use strict";

var _extends = Object.assign || function(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};

var a = { "one": 1, "two": 2 };
var b = { "three": 3 };
var c = { "four": 4, "five": 5 };

var result = _extends({}, a, b, c);
// Object { "one": 1, "two": 2 , "three": 3, "four": 4, "five": 5 }

How to add many functions in ONE ng-click?

ng-click "$watch(edit($index), open())"

Set background color in PHP?

You must use CSS. Can't be done with PHP.

Android ImageButton with a selected state?

ToggleImageButton which implements Checkable interface and supports OnCheckedChangeListener and android:checked xml attribute:

public class ToggleImageButton extends ImageButton implements Checkable {
    private OnCheckedChangeListener onCheckedChangeListener;

    public ToggleImageButton(Context context) {
        super(context);
    }

    public ToggleImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        setChecked(attrs);
    }

    public ToggleImageButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setChecked(attrs);
    }

    private void setChecked(AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
        setChecked(a.getBoolean(R.styleable.ToggleImageButton_android_checked, false));
        a.recycle();
    }

    @Override
    public boolean isChecked() {
        return isSelected();
    }

    @Override
    public void setChecked(boolean checked) {
        setSelected(checked);

        if (onCheckedChangeListener != null) {
            onCheckedChangeListener.onCheckedChanged(this, checked);
        }
    }

    @Override
    public void toggle() {
        setChecked(!isChecked());
    }

    @Override
    public boolean performClick() {
        toggle();
        return super.performClick();
    }

    public OnCheckedChangeListener getOnCheckedChangeListener() {
        return onCheckedChangeListener;
    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        this.onCheckedChangeListener = onCheckedChangeListener;
    }

    public static interface OnCheckedChangeListener {
        public void onCheckedChanged(ToggleImageButton buttonView, boolean isChecked);
    }
}

res/values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ToggleImageButton">
        <attr name="android:checked" />
    </declare-styleable>
</resources>

Is it possible to open developer tools console in Chrome on Android phone?

Please do yourself a favor and just hit the easy button:

download Web Inspector (Open Source) from the Play store.

A CAVEAT: ATTOW, console output does not accept rest params! I.e. if you have something like this:

console.log('one', 'two', 'three');

you will only see

one

logged to the console. You'll need to manually wrap the params in an Array and join, like so:

console.log([ 'one', 'two', 'three' ].join(' '));

to see the expected output.

But the app is open source! A patch may be imminent! The patcher could even be you!

Very simple log4j2 XML configuration file using Console and File appender

Here is my simplistic log4j2.xml that prints to console and writes to a daily rolling file:

// java
private static final Logger LOGGER = LogManager.getLogger(MyClass.class);


// log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="logPath">target/cucumber-logs</Property>
        <Property name="rollingFileName">cucumber</Property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
        </Console>
        <RollingFile name="rollingFile" fileName="${logPath}/${rollingFileName}.log" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
            <Policies>
                <!-- Causes a rollover if the log file is older than the current JVM's start time -->
                <OnStartupTriggeringPolicy />
                <!-- Causes a rollover once the date/time pattern no longer applies to the active file -->
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="DEBUG" additivity="false">
            <AppenderRef ref="console" />
            <AppenderRef ref="rollingFile" />
        </Root>
    </Loggers>
</Configuration>

TimeBasedTriggeringPolicy

interval (integer) - How often a rollover should occur based on the most specific time unit in the date pattern. For example, with a date pattern with hours as the most specific item and and increment of 4 rollovers would occur every 4 hours. The default value is 1.

modulate (boolean) - Indicates whether the interval should be adjusted to cause the next rollover to occur on the interval boundary. For example, if the item is hours, the current hour is 3 am and the interval is 4 then the first rollover will occur at 4 am and then next ones will occur at 8 am, noon, 4pm, etc.

Source: https://logging.apache.org/log4j/2.x/manual/appenders.html

Output:

[INFO ] 2018-07-21 12:03:47,412 ScenarioHook.beforeScenario() - Browser=CHROME32_NOHEAD
[INFO ] 2018-07-21 12:03:48,623 ScenarioHook.beforeScenario() - Screen Resolution (WxH)=1366x768
[DEBUG] 2018-07-21 12:03:52,125 HomePageNavigationSteps.I_Am_At_The_Home_Page() - Base URL=http://simplydo.com/projector/
[DEBUG] 2018-07-21 12:03:52,700 NetIncomeProjectorSteps.I_Enter_My_Start_Balance() - Start Balance=348000

A new log file will be created daily with previous day automatically renamed to:

cucumber_yyyy-MM-dd.log

In a Maven project, you would put the log4j2.xml in src/main/resources or src/test/resources.

angular.service vs angular.factory

Here are the primary differences:

Services

Syntax: module.service( 'serviceName', function );

Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to module.service.

Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending ( ) to the injected function reference. Could also be run with injectedArg.call( this ) or similar.

Factories

Syntax: module.factory( 'factoryName', function );

Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.

Here is example using services and factory. Read more about AngularJS Service vs Factory.

You can also check the AngularJS documentation and similar question on stackoverflow confused about service vs factory.

How to Git stash pop specific stash in 1.8.3?

On Windows Powershell I run this:

git stash apply "stash@{1}"

How to make circular background using css?

Maybe you should use a display inline-block too:

.circle {
    display: inline-block;
    height: 25px;
    width: 25px;
    background-color: #bbb;
    border-radius: 50%;
    z-index: -1;
}

How to Set Opacity (Alpha) for View in Android

For a view you can set opacity by the following.

view_name.setAlpha(float_value);

The property view.setAlpha(int) is deprecated for the API version greater than 11. Henceforth, property like .setAlpha(0.5f) is used.

jQuery Ajax error handling, show custom exception messages

I believe the Ajax response handler uses the HTTP status code to check if there was an error.

So if you just throw a Java exception on your server side code but then the HTTP response doesn't have a 500 status code jQuery (or in this case probably the XMLHttpRequest object) will just assume that everything was fine.

I'm saying this because I had a similar problem in ASP.NET where I was throwing something like a ArgumentException("Don't know what to do...") but the error handler wasn't firing.

I then set the Response.StatusCode to either 500 or 200 whether I had an error or not.

Eclipse DDMS error "Can't bind to local 8600 for debugger"

Based on an Aptana Studio support response, it was confirmed that the Aptana plugin and Android Development Tools collide on this port (i.e. Aptana's Comet server overlapped on this port). Aptana opened a ticket back in 2010.

Unfortunately, it does not appear that Aptana has fixed it yet or made their Comet server port configurable. Changing the port number in eclipse and restarting adb did NOT fix it for me. I finally was forced to uninstall the Aptana plugin.

C - function inside struct

It can't be done directly, but you can emulate the same thing using function pointers and explicitly passing the "this" parameter:

typedef struct client_t client_t, *pno;
struct client_t
{
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;

        pno (*AddClient)(client_t *);    
};

pno client_t_AddClient(client_t *self) { /* code */ }

int main()
{

    client_t client;
    client.AddClient = client_t_AddClient; // probably really done in some init fn

    //code ..

    client.AddClient(&client);

}

It turns out that doing this, however, doesn't really buy you an awful lot. As such, you won't see many C APIs implemented in this style, since you may as well just call your external function and pass the instance.

AppStore - App status is ready for sale, but not in app store

You may also need to provide your contact info, bank info, and tax info in this page so it will allow your last release on App Store:

https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/wo/6.0

How to set Grid row and column positions programmatically

For attached properties you can either call SetValue on the object for which you want to assign the value:

tblock.SetValue(Grid.RowProperty, 4);

Or call the static Set method (not as an instance method like you tried) for the property on the owner type, in this case SetRow:

Grid.SetRow(tblock, 4);

TypeError: 'builtin_function_or_method' object is not subscriptable

instead of writing listb.pop[0] write

listb.pop()[0]
         ^
         |

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

To make it just show up in your JSP pages, you can use the Spring Security Tag Lib:

http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html

To use any of the tags, you must have the security taglib declared in your JSP:

<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>

Then in a jsp page do something like this:

<security:authorize access="isAuthenticated()">
    logged in as <security:authentication property="principal.username" /> 
</security:authorize>

<security:authorize access="! isAuthenticated()">
    not logged in
</security:authorize>

NOTE: As mentioned in the comments by @SBerg413, you'll need to add

use-expressions="true"

to the "http" tag in the security.xml config for this to work.

VBA vlookup reference in different sheet

Your code work fine, provided the value in Sheet2!D2 exists in Sheet1!A:A. If it does not then error 1004 is raised.

To handle this case, try

Sub Demo()
    Dim MyStringVar1 As Variant
    On Error Resume Next
    MyStringVar1 = Application.WorksheetFunction.VLookup(Range("D2"), _
      Worksheets("Sheet1").Range("A:C"), 1, False)
    On Error GoTo 0
    If IsEmpty(MyStringVar1) Then
        MsgBox "Value not found!"
    End If

    Range("E2") = MyStringVar1

End Sub

Leap year calculation

You really should try to google first.

Wikipedia has a explanation of leap years. The algorithm your describing is for the Proleptic Gregorian calendar.

More about the math around it can be found in the article Calendar Algorithms.

PHP: How to send HTTP response code?

since PHP 5.4 you can use http_response_code() for get and set header status code.

here an example:

<?php

// Get the current response code and set a new one
var_dump(http_response_code(404));

// Get the new response code
var_dump(http_response_code());
?>

here is the document of this function in php.net:

http_response_code

Error in setting JAVA_HOME

JAVA_HOME = C:\Program Files\Java\jdk(JDK version number)

Example: C:\Program Files\Java\jdk-10

And then restart you command prompt it works.

Empty or Null value display in SSRS text boxes

I had a similar situation but the following worked best for me..

=Iif(Fields!Sales_Diff.Value)>1,Fields!Sales_Diff.Value),"")

Is it possible to use an input value attribute as a CSS selector?

As mentioned before, you need more than a css selector because it doesn't access the stored value of the node, so javascript is definitely needed. Heres another possible solution:

<style>
input:not([value=""]){
border:2px solid red;
}
</style>

<input type="text" onkeyup="this.setAttribute('value', this.value);"/>

Filter Java Stream to 1 and only 1 element

I am using those two collectors:

public static <T> Collector<T, ?, Optional<T>> zeroOrOne() {
    return Collectors.reducing((a, b) -> {
        throw new IllegalStateException("More than one value was returned");
    });
}

public static <T> Collector<T, ?, T> onlyOne() {
    return Collectors.collectingAndThen(zeroOrOne(), Optional::get);
}

What is the correct way to read from NetworkStream in .NET

Setting the underlying socket ReceiveTimeout property did the trick. You can access it like this: yourTcpClient.Client.ReceiveTimeout. You can read the docs for more information.

Now the code will only "sleep" as long as needed for some data to arrive in the socket, or it will raise an exception if no data arrives, at the beginning of a read operation, for more than 20ms. I can tweak this timeout if needed. Now I'm not paying the 20ms price in every iteration, I'm only paying it at the last read operation. Since I have the content-length of the message in the first bytes read from the server I can use it to tweak it even more and not try to read if all expected data has been already received.

I find using ReceiveTimeout much easier than implementing asynchronous read... Here is the working code:

string SendCmd(string cmd, string ip, int port)
{
  var client = new TcpClient(ip, port);
  var data = Encoding.GetEncoding(1252).GetBytes(cmd);
  var stm = client.GetStream();
  stm.Write(data, 0, data.Length);
  byte[] resp = new byte[2048];
  var memStream = new MemoryStream();
  var bytes = 0;
  client.Client.ReceiveTimeout = 20;
  do
  {
      try
      {
          bytes = stm.Read(resp, 0, resp.Length);
          memStream.Write(resp, 0, bytes);
      }
      catch (IOException ex)
      {
          // if the ReceiveTimeout is reached an IOException will be raised...
          // with an InnerException of type SocketException and ErrorCode 10060
          var socketExept = ex.InnerException as SocketException;
          if (socketExept == null || socketExept.ErrorCode != 10060)
              // if it's not the "expected" exception, let's not hide the error
              throw ex;
          // if it is the receive timeout, then reading ended
          bytes = 0;
      }
  } while (bytes > 0);
  return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}

Finding the indices of matching elements in list in Python

if you're doing a lot of this kind of thing you should consider using numpy.

In [56]: import random, numpy

In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list

In [58]: a, b = 1, 3

In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])

In response to Seanny123's question, I used this timing code:

import numpy, timeit, random

a, b = 1, 3

lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])

def numpy_way():
    numpy.flatnonzero((lst > 1) & (lst < 3))[:10]

def list_comprehension():
    [e for e in lst if 1 < e < 3][:10]

print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)

The numpy version is over 60 times faster.

Simple logical operators in Bash

Here is the code for the short version of if-then-else statement:

( [ $a -eq 1 ] || [ $b -eq 2 ] ) && echo "ok" || echo "nok"

Pay attention to the following:

  1. || and && operands inside if condition (i.e. between round parentheses) are logical operands (or/and)

  2. || and && operands outside if condition mean then/else

Practically the statement says:

if (a=1 or b=2) then "ok" else "nok"

Execute a SQL Stored Procedure and process the results

From MSDN

To execute a stored procedure returning rows programmatically using a command object

Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader

cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1

sqlConnection1.Open()

reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
' Use Read method (true/false) to see if reader has records and advance to next record
' You can use a While loop for multiple records (While reader.Read() ... End While)
If reader.Read() Then
  someVar = reader(0)
  someVar2 = reader(1)
  someVar3 = reader("NamedField")
End If    

sqlConnection1.Close()

How do I empty an array in JavaScript?

If you are using

a = []; 

Then you are assigning new array reference to a, if reference in a is already assigned to any other variable, then it will not empty that array too and hence garbage collector will not collect that memory.

For ex.

var a=[1,2,3];
var b=a;
a=[];
console.log(b);// It will print [1,2,3];

or

a.length = 0;

When we specify a.length, we are just resetting boundaries of the array and memory for rest array elements will be connected by garbage collector.

Instead of these two solutions are better.

a.splice(0,a.length)

and

while(a.length > 0) {
    a.pop();
}

As per previous answer by kenshou.html, second method is faster.

Root password inside a Docker container

You can SSH in to docker container as root by using

docker exec -it --user root <container_id> /bin/bash

Then change root password using this

passwd root

Make sure sudo is installed check by entering

sudo

if it is not installed install it

apt-get install sudo

If you want to give sudo permissions for user dev you can add user dev to sudo group

usermod -aG sudo dev

Now you'll be able to run sudo level commands from your dev user while inside the container or else you can switch to root inside the container by using the password you set earlier.

To test it login as user dev and list the contents of root directory which is normally only accessible to the root user.

sudo ls -la /root

Enter password for dev

If your user is in the proper group and you entered the password correctly, the command that you issued with sudo should run with root privileges.

Inserting values to SQLite table in Android

I see it is an old thread but I had the same error.

I found the explanation here: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

void execSQL(String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.

void execSQL(String sql, Object[] bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.

jQuery checkbox event handling

Acknowledging the fact that the asker specifically requested jQuery and that the answer selected is correct, it should be noted that this problem doesn't actually need jQuery per say. If one desires to solve this problem without it, one can simply set the onClick attribute of the checkboxes that he or she wants to add additional functionality to, like so:

HTML:

<form id="myform">
  <input type="checkbox" name="check1" value="check1" onClick="cbChanged(this);">
  <input type="checkbox" name="check2" value="check2" onClick="cbChanged(this);">
</form>

javascript:

function cbChanged(checkboxElem) {
  if (checkboxElem.checked) {
    // Do something special
  } else {
    // Do something else
  }
}

Fiddle: http://jsfiddle.net/Y9f66/1/

How to write an ArrayList of Strings into a text file?

If you need to create each ArrayList item in a single line then you can use this code

private void createFile(String file, ArrayList<String> arrData)
            throws IOException {
        FileWriter writer = new FileWriter(file + ".txt");
        int size = arrData.size();
        for (int i=0;i<size;i++) {
            String str = arrData.get(i).toString();
            writer.write(str);
            if(i < size-1)**//This prevent creating a blank like at the end of the file**
                writer.write("\n");
        }
        writer.close();
    }

Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document

I agree with @pkozlowski.opensource answer, but ng-clock class did't work for me for using with ng-repeat. so I would like to recommend you to use class for simple delimiter expression like {{name}} and ngCloak directive for ng-repeat.

<div class="ng-cloak">{{name}}<div>

and

<li ng-repeat="item in items" ng-cloak>{{item.name}}<li>

How to attach a process in gdb

The first argument should be the path to the executable program. So

gdb progname 12271

Get first and last day of month using threeten, LocalDate

The API was designed to support a solution that matches closely to business requirements

import static java.time.temporal.TemporalAdjusters.*;

LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.with(firstDayOfMonth());
LocalDate end = initial.with(lastDayOfMonth());

However, Jon's solutions are also fine.

How can I clear an HTML file input with JavaScript?

I changed to type text and back to type to file using setAttribute

'<input file-model="thefilePic" style="width:95%;" type="file" name="file" id="filepicture" accept="image/jpeg" />'

'var input=document.querySelector('#filepicture');'

if(input != null)
{
    input.setAttribute("type", "text");
    input.setAttribute("type", "file");
}

How to list running screen sessions?

So you're using screen to keep the experiments running in the background, or what? If so, why not just start it in the background?

./experiment &

And if you're asking how to get notification the job i done, how about stringing the experiment together with a mail command?

./experiment && echo "the deed is done" | mail youruser@yourlocalworkstation -s "job on server $HOSTNAME is done"

Use ffmpeg to add text subtitles

ffmpeg supports the mov_text subtitle encoder which is about the only one supported in an MP4 container and playable by iTunes, Quicktime, iOS etc.

Your line would read:

ffmpeg -i input.mp4 -i input.srt -map 0:0 -map 0:1 -map 1:0 -c:s mov_text output.mp4

Get the Year/Month/Day from a datetime in php?

Try below code if you want to use php loop to display

<span>
  <select name="birth_month">
    <?php for( $m=1; $m<=12; ++$m ) { 
      $month_label = date('F', mktime(0, 0, 0, $m, 1));
    ?>
      <option value="<?php echo $month_label; ?>"><?php echo $month_label; ?></option>
    <?php } ?>
  </select> 
</span>
<span>
  <select name="birth_day">
    <?php 
      $start_date = 1;
      $end_date   = 31;
      for( $j=$start_date; $j<=$end_date; $j++ ) {
        echo '<option value='.$j.'>'.$j.'</option>';
      }
    ?>
  </select>
</span>
<span>
  <select name="birth_year">
    <?php 
      $year = date('Y');
      $min = $year - 60;
      $max = $year;
      for( $i=$max; $i>=$min; $i-- ) {
        echo '<option value='.$i.'>'.$i.'</option>';
      }
    ?>
  </select>
</span>

How can I build a recursive function in python?

Recursive function example:

def recursive(string, num):
    print "#%s - %s" % (string, num)
    recursive(string, num+1)

Run it with:

recursive("Hello world", 0)

How to invoke function from external .c file in C?

use #include "ClasseAusiliaria.c" [Dont use angle brackets (< >) ]

and I prefer save file with .h extension in the same Directory/folder.

#include "ClasseAusiliaria.h"

The source was not found, but some or all event logs could not be searched

Had the same exception. In my case, I had to run Command Prompt with Administrator Rights.

From the Start Menu, right click on Command Prompt, select "Run as administrator".

Extract year from date

When you convert your variable to Date:

date <-  as.Date('10/30/2018','%m/%d/%Y')

you can then cut out the elements you want and make new variables, like year:

year <- as.numeric(format(date,'%Y'))

or month:

month <- as.numeric(format(date,'%m'))

How to SELECT WHERE NOT EXIST using LINQ?

from s in context.shift
where !context.employeeshift.Any(es=>(es.shiftid==s.shiftid)&&(es.empid==57))
select s;

Hope this helps

What do *args and **kwargs mean?

Putting *args and/or **kwargs as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.

For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:

def my_sum(*args):
    return sum(args)

It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.

You don’t actually have to call them args and kwargs, that’s just a convention. It’s the * and ** that do the magic.

The official Python documentation has a more in-depth look.

Simple Pivot Table to Count Unique Values

Siddharth's answer is terrific.

However, this technique can hit trouble when working with a large set of data (my computer froze up on 50,000 rows). Some less processor-intensive methods:

Single uniqueness check

  1. Sort by the two columns (A, B in this example)
  2. Use a formula that looks at less data

    =IF(SUMPRODUCT(($A2:$A3=A2)*($B2:$B3=B2))>1,0,1) 
    

Multiple uniqueness checks

If you need to check uniqueness in different columns, you can't rely on two sorts.

Instead,

  1. Sort single column (A)
  2. Add formula covering the maximum number of records for each grouping. If ABC might have 50 rows, the formula will be

    =IF(SUMPRODUCT(($A2:$A49=A2)*($B2:$B49=B2))>1,0,1)
    

jQuery vs. javascript?

It's all about performance and development speed. Of course, if you are a good programmer and design something that is really tailored to your needs, you might achieve better performance than if you had used a Javascript framework. But do you have the time to do it all by yourself?

My personal opinion is that Javascript is incredibly useful and overused, but that if you really need it, a framework is the way to go.

Now comes the choice of the framework. For what benchmarks are worth, you can find one at http://ejohn.org/files/142/ . It also depends on which plugins are available and what you intend to do with them. I started using jQuery because it seemed to be maintained and well featured, even though it wasn't the fastest at that moment. I do not regret it but I didn't test anything else since then.

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

you can also use Recursion

Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called recursive method.

Mean per group in a data.frame

Here are a variety of ways to do this in base R including an alternative aggregate approach. The examples below return means per month, which I think is what you requested. Although, the same approach could be used to return means per person:

Using ave:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

Rate1.mean <- with(my.data, ave(Rate1, Month, FUN = function(x) mean(x, na.rm = TRUE)))
Rate2.mean <- with(my.data, ave(Rate2, Month, FUN = function(x) mean(x, na.rm = TRUE)))

my.data <- data.frame(my.data, Rate1.mean, Rate2.mean)
my.data

Using by:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

by.month <- as.data.frame(do.call("rbind", by(my.data, my.data$Month, FUN = function(x) colMeans(x[,3:4]))))
colnames(by.month) <- c('Rate1.mean', 'Rate2.mean')
by.month <- cbind(Month = rownames(by.month), by.month)

my.data <- merge(my.data, by.month, by = 'Month')
my.data

Using lapply and split:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

ly.mean <- lapply(split(my.data, my.data$Month), function(x) c(Mean = colMeans(x[,3:4])))
ly.mean <- as.data.frame(do.call("rbind", ly.mean))
ly.mean <- cbind(Month = rownames(ly.mean), ly.mean)

my.data <- merge(my.data, ly.mean, by = 'Month')
my.data

Using sapply and split:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.data

sy.mean <- t(sapply(split(my.data, my.data$Month), function(x) colMeans(x[,3:4])))
colnames(sy.mean) <- c('Rate1.mean', 'Rate2.mean')
sy.mean <- data.frame(Month = rownames(sy.mean), sy.mean, stringsAsFactors = FALSE)
my.data <- merge(my.data, sy.mean, by = 'Month')
my.data

Using aggregate:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

my.summary <- with(my.data, aggregate(list(Rate1, Rate2), by = list(Month), 
                   FUN = function(x) { mon.mean = mean(x, na.rm = TRUE) } ))

my.summary <- do.call(data.frame, my.summary)
colnames(my.summary) <- c('Month', 'Rate1.mean', 'Rate2.mean')
my.summary

my.data <- merge(my.data, my.summary, by = 'Month')
my.data

EDIT: June 28, 2020

Here I use aggregate to obtain the column means of an entire matrix by group where group is defined in an external vector:

my.group <- c(1,2,1,2,2,3,1,2,3,3)

my.data <- matrix(c(   1,    2,    3,    4,    5,
                      10,   20,   30,   40,   50,
                       2,    4,    6,    8,   10,
                      20,   30,   40,   50,   60,
                      20,   18,   16,   14,   12,
                    1000, 1100, 1200, 1300, 1400,
                       2,    3,    4,    3,    2,
                      50,   40,   30,   20,   10,
                    1001, 2001, 3001, 4001, 5001,
                    1000, 2000, 3000, 4000, 5000), nrow = 10, ncol = 5, byrow = TRUE)
my.data

my.summary <- aggregate(list(my.data), by = list(my.group), FUN = function(x) { my.mean = mean(x, na.rm = TRUE) } )
my.summary
#  Group.1          X1       X2          X3       X4          X5
#1       1    1.666667    3.000    4.333333    5.000    5.666667
#2       2   25.000000   27.000   29.000000   31.000   33.000000
#3       3 1000.333333 1700.333 2400.333333 3100.333 3800.333333

No assembly found containing an OwinStartupAttribute Error

if you want to use signalr you haveto add startup.cs Class in your project

Right Click In You Project Then Add New Item And Select OWIN Startup Class

then inside Configuration Method Add Code Below

app.MapSignalR();

I Hope it will be useful for you

adb is not recognized as internal or external command on windows

If you go to your android-sdk/tools folder I think you'll find a message :

The adb tool has moved to platform-tools/

If you don't see this directory in your SDK, launch the SDK and AVD Manager (execute the android tool) and install "Android SDK Platform-tools"

Please also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

So you should also add C:/android-sdk/platform-tools to you environment path. Also after you modify the PATH variable make sure that you start a new CommandPrompt window.

How to check Spark Version

Addition to @Binary Nerd

If you are using Spark, use the following to get the Spark version:

spark-submit --version

or

Login to the Cloudera Manager and goto Hosts page then run inspect hosts in cluster

writing a batch file that opens a chrome URL

It's very simple. Just try:

start chrome https://www.google.co.in/

it will open the Google page in the Chrome browser.

If you wish to open the page in Firefox, try:

start firefox https://www.google.co.in/

Have Fun!

Setting Environment Variables for Node to retrieve

If you are using a mac/linux and you want to retrieve local parameters to the machine you're using, this is what you'll do:

  1. In terminal run nano ~/.bash_profile
  2. add a line like: export MY_VAR=var
  3. save & run source ~/.bash_profile
  4. in node use like: console.log(process.env.MY_VAR);

Tree implementation in Java (root, parents and children)

In the accepted answer

public Node(T data, Node<T> parent) {
    this.data = data;
    this.parent = parent;
}

should be

public Node(T data, Node<T> parent) {
    this.data = data;
    this.setParent(parent);
}

otherwise the parent does not have the child in its children list

CentOS 7 and Puppet unable to install nc

You can use a case in this case, to separate versions one example is using FACT os (which returns the version etc of your system... the command facter will return the details:

root@sytem# facter -p os
{"name"=>"CentOS", "family"=>"RedHat", "release"=>{"major"=>"7", "minor"=>"0", "full"=>"7.0.1406"}}

#we capture release hash
$curr_os = $os['release']

case $curr_os['major'] {
  '7': { .... something }
  *: {something}
}

That is an fast example, Might have typos, or not exactly working. But using system facts you can see what happens.

The OS fact provides you 3 main variables: name, family, release... Under release you have a small dictionary with more information about your os! combining these you can create cases to meet your targets.

Using .text() to retrieve only text not nested in child tags

I presume this would be a fine solution also - if you want to get contents of all text nodes that are direct children of selected element.

$(selector).contents().filter(function(){ return this.nodeType == 3; }).text();

Note: jQuery documentation uses similar code to explain contents function: https://api.jquery.com/contents/

P.S. There's also a bit uglier way to do that, but this shows more in depth how things work, and allows for custom separator between text nodes (maybe you want a line break there)

$(selector).contents().filter(function(){ return this.nodeType == 3; }).map(function() { return this.nodeValue; }).toArray().join("");

Add to integers in a list

You can append to the end of a list:

foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])    
print(foo)            # [1, 2, 3, 4, 5, 4, [8, 7]]

You can edit items in the list like this:

foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4     
print(foo)            # [1, 2, 3, 8, 5]

Insert integers into the middle of a list:

x = [2, 5, 10]
x.insert(2, 77)
print(x)              # [2, 5, 77, 10]

What does .shape[] do in "for i in range(Y.shape[0])"?

shape() consists of array having two arguments rows and columns.

if you search shape[0] then it will gave you the number of rows. shape[1] will gave you number of columns.

App can't be opened because it is from an unidentified developer

Right-click (or control-click) the application in question and choose "Open"

How can I use getSystemService in a non-activity class (LocationManager)?

You can go for this :

getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

jQuery hide and show toggle div with plus and minus icon

I would say the most elegant way is this:

<div class="toggle"></div>
<div class="content">...</div>

then css:

.toggle{
 display:inline-block;
height:48px;
width:48px;  background:url("http://icons.iconarchive.com/icons/pixelmixer/basic/48/plus-icon.png");
}
.toggle.expanded{
  background:url("http://cdn2.iconfinder.com/data/icons/onebit/PNG/onebit_32.png");
}

and js:

$(document).ready(function(){
  var $content = $(".content").hide();
  $(".toggle").on("click", function(e){
    $(this).toggleClass("expanded");
    $content.slideToggle();
  });
});

FIDDLE

html div onclick event

The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".

In fact, there are multiple solutions:

  • Checking in the DIV click event handler whether the actual target element was the anchor
    → jsFiddle

    $('.expandable-panel-heading').click(function (evt) {
        if (evt.target.tagName != "A") {
            alert('123');
        }
    
        // Also possible if conditions:
        // - evt.target.id != "ancherComplaint"
        // - !$(evt.target).is("#ancherComplaint")
    });
    
    $("#ancherComplaint").click(function () {
        alert($(this).attr("id"));
    });
    
  • Stopping the event propagation from the anchor click listener
    → jsFiddle

    $("#ancherComplaint").click(function (evt) {
        evt.stopPropagation();
        alert($(this).attr("id"));
    });
    


As you may have noticed, I have removed the following selector part from my examples:

:not(#ancherComplaint)

This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.

I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.

How to remove "Server name" items from history of SQL Server Management Studio

In SSMS 2012 there is a documented way to delete the server name from the "Connect to Server" dialog. Now, we can remove the server name by selecting it in the dialog and pressing DELETE.

What is the difference between T(n) and O(n)?

one is Big "O"

one is Big Theta

http://en.wikipedia.org/wiki/Big_O_notation

Big O means your algorithm will execute in no more steps than in given expression(n^2)

Big Omega means your algorithm will execute in no fewer steps than in the given expression(n^2)

When both condition are true for the same expression, you can use the big theta notation....

Is there a command for formatting HTML in the Atom editor?

You can add atom beauty package for formatting text in atom..

file --> setting --> Install

then you type atom-beautify in search area.

then click Package button.. select atom beuty and install it.

next you can format your text using (Alt + ctrl + b) or right click and select beautify editor contents

How to remove all white spaces in java

You can use a regular expression to delete white spaces , try that snippet:

Scanner scan = new Scanner(System.in);
    System.out.println(scan.nextLine().replaceAll(" ", ""));

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

I don't exactly know what causes that, but I solve it this way.
Reinstall whole project but remember that webpack-dev-server must be globally installed.
I walk through some server errors like webpack cant be found, so I linked Webpack using link command.
In output Resolving some absolute path issues.

In devServer object: inline: false

webpack.config.js

module.exports = {
    entry: "./src/js/main.js",
    output: {
        path:__dirname+ '/dist/',
        filename: "bundle.js",
        publicPath: '/'
    },
    devServer: {
        inline: false,
        contentBase: "./dist",
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude:/(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    }

};

package.json

{
  "name": "react-flux-architecture-es6",
  "version": "1.0.0",
  "description": "egghead",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cichy/react-flux-architecture-es6.git"
  },
  "keywords": [
    "React",
    "flux"
  ],
  "author": "Jaroslaw Cichon",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cichy/react-flux-architecture-es6/issues"
  },
  "homepage": "https://github.com/cichy/react-flux-architecture-es6#readme",
  "dependencies": {
    "flux": "^3.1.2",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-router": "^3.0.2"
  },
  "devDependencies": {
    "babel-core": "^6.22.1",
    "babel-loader": "^6.2.10",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.22.0"
  }
}

Set initial value in datepicker with jquery?

You can set the value in the HTML and then init datepicker to start/highlight the actual date

<input name="datefrom" type="text" class="datepicker" value="20-1-2011">
<input name="dateto" type="text" class="datepicker" value="01-01-2012">
<input name="dateto2" type="text" class="datepicker" >


$(".datepicker").each(function() {    
    $(this).datepicker('setDate', $(this).val());
});

The above even works with danish date formats

http://jsfiddle.net/DDsBP/2/

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

var fileName = @"C:\ExcelFile.xlsx";
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ;
using (var conn = new OleDbConnection(connectionString))
{
    conn.Open();

    var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";

        var adapter = new OleDbDataAdapter(cmd);
        var ds = new DataSet();
        adapter.Fill(ds);
    }
}

What is this: [Ljava.lang.Object;?

[Ljava.lang.Object; is the name for Object[].class, the java.lang.Class representing the class of array of Object.

The naming scheme is documented in Class.getName():

If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).

If this class object represents a primitive type or void, then the name returned is the Java language keyword corresponding to the primitive type or void.

If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:

Element Type        Encoding
boolean             Z
byte                B
char                C
double              D
float               F
int                 I
long                J
short               S 
class or interface  Lclassname;

Yours is the last on that list. Here are some examples:

// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx

The reason why the toString() method on arrays returns String in this format is because arrays do not @Override the method inherited from Object, which is specified as follows:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Note: you can not rely on the toString() of any arbitrary object to follow the above specification, since they can (and usually do) @Override it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass() on it (a final method inherited from Object) and then reflecting on the returned Class object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).


On a more "useful" toString for arrays

java.util.Arrays provides toString overloads for primitive arrays and Object[]. There is also deepToString that you may want to use for nested arrays.

Here are some examples:

int[] nums = { 1, 2, 3 };

System.out.println(nums);
// [I@xxxxx

System.out.println(Arrays.toString(nums));
// [1, 2, 3]

int[][] table = {
        { 1, },
        { 2, 3, },
        { 4, 5, 6, },
};

System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]

System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]

There are also Arrays.equals and Arrays.deepEquals that perform array equality comparison by their elements, among many other array-related utility methods.

Related questions

How to use mouseover and mouseout in Angular 6

You can use (mouseover) and (mouseout) events.

component.ts

changeText:boolean=true;

component.html

<div (mouseover)="changeText=true" (mouseout)="changeText=false">
  <span [hidden]="changeText">Hide</span>
  <span [hidden]="!changeText">Show</span>
</div>

error C2220: warning treated as error - no 'object' file generated

This warning is about unsafe use of strcpy. Try IOBname[ii]='\0'; instead.

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

The first <img /> is invalid - src is a required attribute. data-src is an attribute than can be leveraged by, say, JavaScript, but has no presentational meaning.

SVN how to resolve new tree conflicts when file is added on two branches

I found a post suggesting a solution for that. It's about to run:

svn resolve --accept working <YourPath>

which will claim the local version files as OK.
You can run it for single file or entire project catalogues.

Determine Whether Integer Is Between Two Other Integers?

There are two ways to compare three integers and check whether b is between a and c:

if a < b < c:
    pass

and

if a < b and b < c:
    pass

The first one looks like more readable, but the second one runs faster.

Let's compare using dis.dis:

>>> dis.dis('a < b and b < c')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 COMPARE_OP               0 (<)
              6 JUMP_IF_FALSE_OR_POP    14
              8 LOAD_NAME                1 (b)
             10 LOAD_NAME                2 (c)
             12 COMPARE_OP               0 (<)
        >>   14 RETURN_VALUE
>>> dis.dis('a < b < c')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 DUP_TOP
              6 ROT_THREE
              8 COMPARE_OP               0 (<)
             10 JUMP_IF_FALSE_OR_POP    18
             12 LOAD_NAME                2 (c)
             14 COMPARE_OP               0 (<)
             16 RETURN_VALUE
        >>   18 ROT_TWO
             20 POP_TOP
             22 RETURN_VALUE
>>>

and using timeit:

~$ python3 -m timeit "1 < 2 and 2 < 3"
10000000 loops, best of 3: 0.0366 usec per loop

~$ python3 -m timeit "1 < 2 < 3"
10000000 loops, best of 3: 0.0396 usec per loop

also, you may use range, as suggested before, however it is much more slower.

Can I run a 64-bit VMware image on a 32-bit machine?

The easiest way to check your workstation is to download the VMware Processor Check for 64-Bit Compatibility tool from the VMware website.

You can't run a 64-bit VM session on a 32-bit processor. However, you can run a 64-bit VM session if you have a 64-bit processor but have installed a 32-bit host OS and your processor supports the right extensions. The tool linked above will tell you if yours does.

Why isn't Python very good for functional programming?

Another reason not mentioned above is that many built-in functions and methods of built-in types modify an object but do not return the modified object. If those modified objects were returned, that would make functional code cleaner and more concise. For example, if some_list.append(some_object) returned some_list with some_object appended.

PHPExcel Make first row bold

Use this:

$sheet->getStyle('A1:'.$sheet->getHighestColumn().'1')->getFont()->setBold(true);

How to change spinner text size and text color?

Another variation of Ashraf's solution would be to make sure you're taking into account screen sizes. You'll need to get the spinner in onCreate and set the listener after you set the adapter:

//set your adapter with default or custom spinner cell, then://
serverSpinner.setOnItemSelectedListener(spinnerSelector);
serverSpinner.setSelection(defaultServer);

Then you can start changing the text size of the view that's showing before the spinner is clicked:

private AdapterView.OnItemSelectedListener spinnerSelector = new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
        boolean largeTablet = getResources().getBoolean(R.bool.isLargeTablet);
        if (tabletSize) { ((TextView)parent.getChildAt(0)).setTextSize(16); }
        else if (largeTablet) { ((TextView)parent.getChildAt(0)).setTextSize(18); }
        else { ((TextView)parent.getChildAt(0)).setTextSize(12); }
    }
    public void onNothingSelected(AdapterView<?> parent) {

    }
};

All you need to do is create layout specific folders like this:

values-sw360dp

values-sw600dp

values-sw800dp

an then add an xml file named "bool.xml" into each of those folders:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="isTablet">false</bool>
    <bool name="isLargeTablet">false</bool>
</resources>

Insert the same fixed value into multiple rows

You're looking for UPDATE not insert.

UPDATE mytable
SET    table_column = 'test';

UPDATE will change the values of existing rows (and can include a WHERE to make it only affect specific rows), whereas INSERT is adding a new row (which makes it look like it changed only the last row, but in effect is adding a new row with that value).

How to remove the default link color of the html hyperlink 'a' tag?

If you don't want to see the underline and default color which is provided by the browser, you can keep the following code in the top of your main.css file. If you need different color and decoration styling you can easily override the defaults using the below code snippet.

 a, a:hover, a:focus, a:active {
      text-decoration: none;
      color: inherit;
 }

Eclipse HotKey: how to switch between tabs?

You can use ALT+Left to go to your previous tab, or ALT+Right to go to forward. This method is using tab-switching like history, though, so it will go to the previous tab you had open, and forward if you've gone "back" once or more. A bit weird, I know, but it works. You can always "reset" the history by clicking through every tab once.

What are good grep tools for Windows?

Update July 2013:

Another grep tool I now use all the time on Windows is AstroGrep:

AstroGrep awesomeness

Its ability to show me more than just the line search (i.e. the --context=NUM of a command-line grep) is invaluable.
And it is fast. Very fast, even on an old computer with non-SSD drive (I know, they used to do this hard drive with spinning disks, called platters, crazy right?)

It is free.
It is portable (simple zip archive to unzip).


Original answer October 2008

alt textGnu Grep is alright

You can download it for example here: (site ftp)

All the usual options are here.

That, combined with gawk and xargs (includes 'find', from GnuWin32), and you can really script like you were on Unix!

See also the options I am using to grep recursively:

grep --include "*.xxx" -nRHI "my Text to grep" *

How can I get a web site's favicon?

It's a good practice to minimize the number of requests each page needs. So if you need several icons, yandex can do a sprite of favicons in one query. Here is an example http://favicon.yandex.net/favicon/google.com/stackoverflow.com/yandex.net/

How to write UTF-8 in a CSV file

From your shell run:

pip2 install unicodecsv

And (unlike the original question) presuming you're using Python's built in csv module, turn
import csv into
import unicodecsv as csv in your code.

converting drawable resource image into bitmap

First Create Bitmap Image

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image);

now set bitmap in Notification Builder Icon....

Notification.Builder.setLargeIcon(bmp);

How do I remove the last comma from a string using PHP?

It is better to use implode for that purpose. Implode is easy and awesome:

    $array = ['name1', 'name2', 'name3'];
    $str = implode(', ', $array);

Output:

    name1, name2, name3

What is the difference between sscanf or atoi to convert a string to an integer?

*scanf() family of functions return the number of values converted. So you should check to make sure sscanf() returns 1 in your case. EOF is returned for "input failure", which means that ssacnf() will never return EOF.

For sscanf(), the function has to parse the format string, and then decode an integer. atoi() doesn't have that overhead. Both suffer from the problem that out-of-range values result in undefined behavior.

You should use strtol() or strtoul() functions, which provide much better error-detection and checking. They also let you know if the whole string was consumed.

If you want an int, you can always use strtol(), and then check the returned value to see if it lies between INT_MIN and INT_MAX.

How to add DOM element script to head section?

For modern browsers, the best solution is to use Promises.

Go to https://stackoverflow.com/a/63936671/13720928 to find out more!

How to format numbers?

On browsers that support the ECMAScript® 2016 Internationalization API Specification (ECMA-402), you can use an Intl.NumberFormat instance:

var nf = Intl.NumberFormat();
var x = 42000000;
console.log(nf.format(x)); // 42,000,000 in many locales
                           // 42.000.000 in many other locales

_x000D_
_x000D_
if (typeof Intl === "undefined" || !Intl.NumberFormat) {_x000D_
  console.log("This browser doesn't support Intl.NumberFormat");_x000D_
} else {_x000D_
  var nf = Intl.NumberFormat();_x000D_
  var x = 42000000;_x000D_
  console.log(nf.format(x)); // 42,000,000 in many locales_x000D_
                             // 42.000.000 in many other locales_x000D_
}
_x000D_
_x000D_
_x000D_

Sorting rows in a data table

I'm afraid you can't easily do an in-place sort of a DataTable like it sounds like you want to do.

What you can do is create a new DataTable from a DataView that you create from your original DataTable. Apply whatever sorts and/or filters you want on the DataView and then create a new DataTable from the DataView using the DataView.ToTable method:

   DataView dv = ft.DefaultView;
   dv.Sort = "occr desc";
   DataTable sortedDT = dv.ToTable();

How do you convert a JavaScript date to UTC?

Using moment.js UTC method;

const moment = require('moment');
const utc = moment.utc(new Date(string));

Java - Convert image to Base64

You can create a large array and then copy it to a new array using System.arrayCopy

        int contentLength = 100000000;
        byte[] byteArray = new byte[contentLength];

        BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
        while ((bytesRead = inputStream.read()) != -1)
        {
            byteArray[count++] = (byte)bytesRead;
        }

        byte[] destArray = new byte[count];
        System.arraycopy(byteArray, 0, destArray , 0, count);

destArray will contain the information you want

Angular2 @Input to a property with get/set

Updated accepted answer to angular 7.0.1 on stackblitz here: https://stackblitz.com/edit/angular-inputsetter?embed=1&file=src/app/app.component.ts

directives are no more in Component decorator options. So I have provided sub directive to app module.

thank you @thierry-templier!

Why are C++ inline functions in the header?

This is a limit of the C++ compiler. If you put the function in the header, all the cpp files where it can be inlined can see the "source" of your function and the inlining can be done by the compiler. Otherwhise the inlining would have to be done by the linker (each cpp file is compiled in an obj file separately). The problem is that it would be much more difficult to do it in the linker. A similar problem exists with "template" classes/functions. They need to be instantiated by the compiler, because the linker would have problem instantiating (creating a specialized version of) them. Some newer compiler/linker can do a "two pass" compilation/linking where the compiler does a first pass, then the linker does its work and call the compiler to resolve unresolved things (inline/templates...)

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Same issue occurred for me, but before getting this error, my app was running. So I just did undo 2/3 times. And did changes again. And build app.app ran successfully.

Creating a singleton in Python

Using a function attribute is also very simple

def f():
    if not hasattr(f, 'value'):
        setattr(f, 'value', singletonvalue)
    return f.value

Python Anaconda - How to Safely Uninstall

Package "anaconda clean", available from Anaconda platform, should uninstall safely.

conda install anaconda-clean   # install the package anaconda clean
anaconda-clean --yes           # clean all anaconda related files and directories 
rm -rf ~/anaconda3             # removes the entire anaconda directory

rm -rf ~/.anaconda_backup       # anaconda clean creates a back_up of files/dirs, remove it 
                                # (conda list; cmd shouldn't respond after the clean up)

Refer: https://docs.anaconda.com/anaconda/install/uninstall for more details.

hardcoded string "row three", should use @string resource

It is not good practice to hard code strings into your layout files. You should add them to a string resource file and then reference them from your layout.

This allows you to update every occurrence of the word "Yellow" in all layouts at the same time by just editing your strings.xml file.

It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language.

example: XML file saved at res/values/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="yellow">Yellow</string>
</resources>

This layout XML applies a string to a View:

<TextView android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="@string/yellow" />

Similarly colors should be stored in colors.xml and then referenced by using @color/color_name

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="Black">#000000</color>
</resources>

Change the name of a key in dictionary

if you want to change all the keys:

d = {'x':1, 'y':2, 'z':3}
d1 = {'x':'a', 'y':'b', 'z':'c'}

In [10]: dict((d1[key], value) for (key, value) in d.items())
Out[10]: {'a': 1, 'b': 2, 'c': 3}

if you want to change single key: You can go with any of the above suggestion.

open link in iframe

Well, there's an alternate way! You can use a button instead of hyperlink. Hence, when the button is clicked the web page specified in "name_of_webpage" is opened in the target frame named "name_of_iframe". It works for me!

<form method="post" action="name_of_webpage" target="name_of_iframe">
<input type="submit" value="any_name_you_want" />
</form>
<iframe name="name_of_iframe"></iframe>

With ng-bind-html-unsafe removed, how do I inject HTML?

  1. You need to make sure that sanitize.js is loaded. For example, load it from https://ajax.googleapis.com/ajax/libs/angularjs/[LAST_VERSION]/angular-sanitize.min.js
  2. you need to include ngSanitize module on your app eg: var app = angular.module('myApp', ['ngSanitize']);
  3. you just need to bind with ng-bind-html the original html content. No need to do anything else in your controller. The parsing and conversion is automatically done by the ngBindHtml directive. (Read the How does it work section on this: $sce). So, in your case <div ng-bind-html="preview_data.preview.embed.html"></div> would do the work.

How to vertically align text inside a flexbox?

The best move is to just nest a flexbox inside of a flexbox. All you have to do is give the child align-items: center. This will vertically align the text inside of its parent.

// Assuming a horizontally centered row of items for the parent but it doesn't have to be
.parent {
  align-items: center;
  display: flex;
  justify-content: center;
}

.child {
  display: flex;
  align-items: center;
}

Bootstrap 4 navbar color

You can just use "!important" to get your custom color

.navbar {
 background-color: yourcolor !important;
 }

SQLAlchemy: print the actual query

This works in python 2 and 3 and is a bit cleaner than before, but requires SA>=1.0.

from sqlalchemy.engine.default import DefaultDialect
from sqlalchemy.sql.sqltypes import String, DateTime, NullType

# python2/3 compatible.
PY3 = str is not bytes
text = str if PY3 else unicode
int_type = int if PY3 else (int, long)
str_type = str if PY3 else (str, unicode)


class StringLiteral(String):
    """Teach SA how to literalize various things."""
    def literal_processor(self, dialect):
        super_processor = super(StringLiteral, self).literal_processor(dialect)

        def process(value):
            if isinstance(value, int_type):
                return text(value)
            if not isinstance(value, str_type):
                value = text(value)
            result = super_processor(value)
            if isinstance(result, bytes):
                result = result.decode(dialect.encoding)
            return result
        return process


class LiteralDialect(DefaultDialect):
    colspecs = {
        # prevent various encoding explosions
        String: StringLiteral,
        # teach SA about how to literalize a datetime
        DateTime: StringLiteral,
        # don't format py2 long integers to NULL
        NullType: StringLiteral,
    }


def literalquery(statement):
    """NOTE: This is entirely insecure. DO NOT execute the resulting strings."""
    import sqlalchemy.orm
    if isinstance(statement, sqlalchemy.orm.Query):
        statement = statement.statement
    return statement.compile(
        dialect=LiteralDialect(),
        compile_kwargs={'literal_binds': True},
    ).string

Demo:

# coding: UTF-8
from datetime import datetime
from decimal import Decimal

from literalquery import literalquery


def test():
    from sqlalchemy.sql import table, column, select

    mytable = table('mytable', column('mycol'))
    values = (
        5,
        u'snowman: ?',
        b'UTF-8 snowman: \xe2\x98\x83',
        datetime.now(),
        Decimal('3.14159'),
        10 ** 20,  # a long integer
    )

    statement = select([mytable]).where(mytable.c.mycol.in_(values)).limit(1)
    print(literalquery(statement))


if __name__ == '__main__':
    test()

Gives this output: (tested in python 2.7 and 3.4)

SELECT mytable.mycol
FROM mytable
WHERE mytable.mycol IN (5, 'snowman: ?', 'UTF-8 snowman: ?',
      '2015-06-24 18:09:29.042517', 3.14159, 100000000000000000000)
 LIMIT 1

CSS: center element within a <div> element

I believe the modern way to go is place-items: center in the parent container

An example can be found here: https://1linelayouts.glitch.me

How to know elastic search installed version from kibana?

I would like to add which isn't mentioned in above answers.

From your kibana's dev console, hit following command:

GET /

This is similar to accessing localhost:9200 from browser.

Hope this will help someone.

How to insert a large block of HTML in JavaScript?

The easiest way to insert html blocks is to use template strings (backticks). It will also allow you to insert dynamic content via ${...}:

document.getElementById("log-menu").innerHTML = `
            <a href="#"> 
               ${data.user.email}
            </a>
            <div class="dropdown-menu p-3 dropdown-menu-right">
                <div class="form-group">
                    <label for="email1">Logged in as:</label>
                    <p>${data.user.email}</p>
                </div>
                <button onClick="getLogout()" ">Sign out</button>
            </div>
    `

jQuery Button.click() event is triggered twice

Your current code works, you can try it here: http://jsfiddle.net/s4UyH/

You have something outside the example triggering another .click(), check for other handlers that are also triggering a click event on that element.

Cross-Origin Read Blocking (CORB)

It's not clear from the question, but assuming this is something happening on a development or test client, and given that you are already using Fiddler you can have Fiddler respond with an allow response:

  • Select the problem request in Fiddler
  • Open the AutoResponder tab
  • Click Add Rule and edit the rule to:
    • Method:OPTIONS server url here, e.g. Method:OPTIONS http://localhost
    • *CORSPreflightAllow
  • Check Unmatched requests passthrough
  • Check Enable Rules

A couple notes:

  1. Obviously this is only a solution for development/testing where it isn't possible/practical to modify the API service
  2. Check that any agreements you have with the third-party API provider allow you to do this
  3. As others have noted, this is part of how CORS works, and eventually the header will need to be set on the API server. If you control that server, you can set the headers yourself. In this case since it is a third party service, I can only assume they have some mechanism via which you are able to provide them with the URL of the originating site and they will update their service accordingly to respond with the correct headers.

Sorting by date & time in descending order?

If you want the last 5 rows, ordered in ascending order, you need a subquery:

SELECT *
FROM
    ( SELECT id, name, form_id, DATE(updated_at) AS updated_date, updated_at
      FROM wp_frm_items
      WHERE user_id = 11 
        AND form_id=9
      ORDER BY updated_at DESC
      LIMIT 5
    ) AS tmp
ORDER BY updated_at

After reading the question for 10th time, this may be (just maybe) what you want. Order by Date descending and then order by time (on same date) ascending:

SELECT id, name, form_id, DATE(updated_at) AS updated_date
FROM wp_frm_items
WHERE user_id = 11 
  AND form_id=9
ORDER BY DATE(updated_at) DESC
       , updated_at ASC

Url.Action parameters?

This works for MVC 5:

<a href="@Url.Action("ActionName", "ControllerName", new { paramName1 = item.paramValue1, paramName2 = item.paramValue2 })" >
    Link text
</a>

Excel: last character/string match in a string

A simple way to do that in VBA is:

YourText = "c:\excel\text.txt"
xString = Mid(YourText, 2 + Len(YourText) - InStr(StrReverse(YourText), "\" ))

Formatting floats in a numpy array

In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:

In [1]: float_formatter = "{:.2f}".format

The f here means fixed-point format (not 'scientific'), and the .2 means two decimal places (you can read more about string formatting here).

Let's test it out with a float value:

In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'

To make numpy print all float arrays this way, you can pass the formatter= argument to np.set_printoptions:

In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})

Now numpy will print all float arrays this way:

In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]

Note that this only affects numpy arrays, not scalars:

In [5]: np.pi
Out[5]: 3.141592653589793

It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.

You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.

For example:

In [6]: a = np.array([1E-9])

In [7]: a
Out[7]: array([0.00])

In [8]: a == 0
Out[8]: array([False], dtype=bool)

numpy prints a as if it were equal to 0, but it is not - it still equals 1E-9.

If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round, as others have already pointed out.

jQuery get content between <div> tags

I suggest that you give an if to the div than:

$("#my_div_id").html();

CodeIgniter - accessing $config variable in view

Also, the Common function config_item() works pretty much everywhere throughout the CodeIgniter instance. Controllers, models, views, libraries, helpers, hooks, whatever.

What's the difference between JPA and Hibernate?

From the Wiki.

Motivation for creating the Java Persistence API

Many enterprise Java developers use lightweight persistent objects provided by open-source frameworks or Data Access Objects instead of entity beans: entity beans and enterprise beans had a reputation of being too heavyweight and complicated, and one could only use them in Java EE application servers. Many of the features of the third-party persistence frameworks were incorporated into the Java Persistence API, and as of 2006 projects like Hibernate (version 3.2) and Open-Source Version TopLink Essentials have become implementations of the Java Persistence API.

As told in the JCP page the Eclipse link is the Reference Implementation for JPA. Have look at this answer for bit more on this.

JPA itself has features that will make up for a standard ORM framework. Since JPA is a part of Java EE spec, you can use JPA alone in a project and it should work with any Java EE compatible Servers. Yes, these servers will have the implementations for the JPA spec.

Hibernate is the most popular ORM framework, once the JPA got introduced hibernate conforms to the JPA specifications. Apart from the basic set of specification that it should follow hibernate provides whole lot of additional stuff.

SQL Server: Best way to concatenate multiple columns?

Try using below:

SELECT 
    (RTRIM(LTRIM(col_1))) + (RTRIM(LTRIM(col_2))) AS Col_newname,
    col_1,
    col_2 
FROM 
    s_cols 
WHERE
    col_any_condition = ''
;

PHP and MySQL Select a Single Value

mysql_* extension has been deprecated in 2013 and removed completely from PHP in 2018. You have two alternatives PDO or MySQLi.

PDO

The simpler option is PDO which has a neat helper function fetchColumn():

$stmt = $pdo->prepare("SELECT id FROM Users WHERE username=?");
$stmt->execute([ $_GET["username"] ]);
$value = $stmt->fetchColumn();

Proper PDO tutorial

MySQLi

You can do the same with MySQLi, but it is more complicated:

$stmt = $mysqliConn->prepare('SELECT id FROM Users WHERE username=?');
$stmt->bind_param("s", $_GET["username"]);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
$value = $data ? $data['id'] : null;

fetch_assoc() could return NULL if there are no rows returned from the DB, which is why I check with ternary if there was any data returned.

What is the best way to seed a database in Rails?

The best way is to use fixtures.

Note: Keep in mind that fixtures do direct inserts and don't use your model so if you have callbacks that populate data you will need to find a workaround.

How can I store the result of a system command in a Perl variable?

Use backticks for system commands, which helps to store their results into Perl variables.

my $pid = 5892;
my $not = ``top -H -p $pid -n 1 | grep myprocess | wc -l`; 
print "not = $not\n";

Detecting request type in PHP (GET, POST, PUT or DELETE)

You can get any query string data i.e www.example.com?id=2&name=r

You must get data using $_GET['id'] or $_REQUEST['id'].

Post data means like form <form action='' method='POST'> you must use $_POST or $_REQUEST.

"python" not recognized as a command

You can do it in python installer: enter image description here

How do format a phone number as a String in Java?

Pattern phoneNumber = Pattern.compile("(\\d{3})(\\d{3})(\\d{4})");
// ...
Matcher matcher = phoneNumber(numberAsLineOf10Symbols);
if (matcher.matches) {
    return "(" + matcher.group(1) + ")-" +matcher.group(2) + "-" + matcher.group(3);
}

Count specific character occurrences in a string

var charCount = "string with periods...".Count(x => '.' == x);

How to use the unsigned Integer in Java 8 and Java 9?

There is no way how to declare an unsigned long or int in Java 8 or Java 9. But some methods treat them as if they were unsigned, for example:

static long values = Long.parseUnsignedLong("123456789012345678");

but this is not declaration of the variable.

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Convert String to Calendar Object in Java

SimpleDateFormat is great, just note that HH is different from hh when working with hours. HH will return 24 hour based hours and hh will return 12 hour based hours.

For example, the following will return 12 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

While this will return 24 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

How to insert values in two dimensional array programmatically?

String[][] shades = new String[intSize][intSize];
 // print array in rectangular form
 for (int r=0; r<shades.length; r++) {
     for (int c=0; c<shades[r].length; c++) {
         shades[r][c]="hello";//your value
     }
 }