Programs & Examples On #Class helpers

Extends existing classes/records in Delphi without using inheritance. Class helpers also introduces a wider scope for the compiler when resolving identifiers. The syntax was introduced in Delphi 2005.

Maven: The packaging for this project did not assign a file to the build artifact

While @A_Di-Matteo answer does work for non multimodule I have a solution for multimodules.

The solution is to override every plugin configuration so that it binds to the phase of none with the exception of the jar/war/ear plugin and of course the deploy plugin. Even if you do have a single module my rudimentary tests show this to be a little faster (for reasons I don't know) performance wise.

Thus the trick is to make a profile that does the above that is activated when you only want to deploy.

Below is an example from one of my projects which uses the shade plugin and thus I had to re-override the jar plugin not to overwrite:

    <profile>
      <id>deploy</id>
      <activation>
        <property>
          <name>buildStep</name>
          <value>deploy</value>
        </property>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <executions>
              <execution>
                <id>default-compile</id>
                <phase>none</phase>
              </execution>
              <execution>
                <id>default-testCompile</id>
                <phase>none</phase>
              </execution>
              <execution>
                <id>test-compile</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <executions>
              <execution>
                <id>default-test</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <executions>
              <execution>
                <id>default-install</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <executions>
              <execution>
                <id>default-resources</id>
                <phase>none</phase>
              </execution>
              <execution>
                <id>default-testResources</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <executions>
              <execution>
                <id>default</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <executions>
              <execution>
                <id>default-jar</id>
                <configuration>
                  <forceCreation>false</forceCreation>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>

Now if I run mvn deploy -Pdeploy it will only run the jar and deploy plugins.

How you can figure out which plugins you need to override is to run deploy and look at the log to see which plugins are running. Make sure to keep track of the id of the plugin configuration which is parens after the name of the plugin.

How can I reverse a NSArray in Objective-C?

There is a much easier solution, if you take advantage of the built-in reverseObjectEnumerator method on NSArray, and the allObjects method of NSEnumerator:

NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];

allObjects is documented as returning an array with the objects that have not yet been traversed with nextObject, in order:

This array contains all the remaining objects of the enumerator in enumerated order.

Convert integer to string Jinja

The OP needed to cast as string outside the {% set ... %}. But if that not your case you can do:

{% set curYear = 2013 | string() %}

Note that you need the parenthesis on that jinja filter.

If you're concatenating 2 variables, you can also use the ~ custom operator.

How to draw an overlay on a SurfaceView used by Camera on Android?

SurfaceView probably does not work like a regular View in this regard.

Instead, do the following:

  1. Put your SurfaceView inside of a FrameLayout or RelativeLayout in your layout XML file, since both of those allow stacking of widgets on the Z-axis
  2. Move your drawing logic into a separate custom View class
  3. Add an instance of the custom View class to the layout XML file as a child of the FrameLayout or RelativeLayout, but have it appear after the SurfaceView

This will cause your custom View class to appear to float above the SurfaceView.

See here for a sample project that layers popup panels above a SurfaceView used for video playback.

Copy multiple files with Ansible

copy module is a wrong tool for copying many files and/or directory structure, use synchronize module instead which uses rsync as backend. Mind you, it requires rsync installed on both controller and target host. It's really powerful, check ansible documentation.

Example - copy files from build directory (with subdirectories) of controller to /var/www/html directory on target host:

synchronize:
  src: ./my-static-web-page/build/
  dest: /var/www/html
  rsync_opts:
    - "--chmod=D2755,F644" # copy from windows - force permissions

How to install gem from GitHub source?

Also you can do gem install username-projectname -s http://gems.github.com

Updating address bar with new URL without hash or reloading the page

You can now do this in most "modern" browsers!

Here is the original article I read (posted July 10, 2010): HTML5: Changing the browser-URL without refreshing page.

For a more in-depth look into pushState/replaceState/popstate (aka the HTML5 History API) see the MDN docs.

TL;DR, you can do this:

window.history.pushState("object or string", "Title", "/new-url");

See my answer to Modify the URL without reloading the page for a basic how-to.

Git SSH error: "Connect to host: Bad file number"

This is the simple solution for saving some typing you can use the following steps in git bash easily..

(1) create the remote repository

git remote add origin https://{your_username}:{your_password}@github.com/{your_username}/repo.git

Note: If your password contains '@' sign use '%40' instead of that

(2) Then do anything you want with the remote repository

ex:- git push origin master

What do numbers using 0x notation mean?

In C and languages based on the C syntax, the prefix 0x means hexadecimal (base 16).

Thus, 0x400 = 4×(162) + 0×(161) + 0×(160) = 4×((24)2) = 22 × 28 = 210 = 1024, or one binary K.

And so 0x6400 = 0x4000 + 0x2400 = 0x19×0x400 = 25K

In jQuery, what's the best way of formatting a number to 2 decimal places?

Maybe something like this, where you could select more than one element if you'd like?

$("#number").each(function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});

Updating version numbers of modules in a multi-module Maven project

If you want to fully automate the process (i.e. you want to increment the version number without having to know what the current version number is), you can do this:

mvn build-helper:parse-version versions:set -DnewVersion=\${parsedVersion.majorVersion}.\${parsedVersion.minorVersion}.\${parsedVersion.nextIncrementalVersion} versions:commit

React - Preventing Form Submission

There's another, more accessible solution: Don't put the action on your buttons. There's a lot of functionality built into forms already. Instead of handling button presses, handle form submissions and resets. Simply add onSubmit={handleSubmit} and onReset={handleReset} to your form elements.

To stop the actual submission just include event in your function and an event.preventDefault(); to stop the default submission behavior. Now your form behaves correctly from an accessibility standpoint and you're handling any form of submission the user might take.

How to set encoding in .getJSON jQuery

You need to analyze the JSON calls using Wireshark, so you will see if you include the charset in the formation of the JSON page or not, for example:

  • If the page is simple if text / html
0000  48 54 54 50 2f 31 2e 31  20 32 30 30 20 4f 4b 0d   HTTP/1.1  200 OK.
0010  0a 43 6f 6e 74 65 6e 74  2d 54 79 70 65 3a 20 74   .Content -Type: t
0020  65 78 74 2f 68 74 6d 6c  0d 0a 43 61 63 68 65 2d   ext/html ..Cache-
0030  43 6f 6e 74 72 6f 6c 3a  20 6e 6f 2d 63 61 63 68   Control:  no-cach
  • If the page is of the type including custom JSON with MIME "charset = ISO-8859-1"
0000  48 54 54 50 2f 31 2e 31  20 32 30 30 20 4f 4b 0d   HTTP/1.1  200 OK.
0010  0a 43 61 63 68 65 2d 43  6f 6e 74 72 6f 6c 3a 20   .Cache-C ontrol: 
0020  6e 6f 2d 63 61 63 68 65  0d 0a 43 6f 6e 74 65 6e   no-cache ..Conten
0030  74 2d 54 79 70 65 3a 20  74 65 78 74 2f 68 74 6d   t-Type:  text/htm
0040  6c 3b 20 63 68 61 72 73  65 74 3d 49 53 4f 2d 38   l; chars et=ISO-8
0050  38 35 39 2d 31 0d 0a 43  6f 6e 6e 65 63 74 69 6f   859-1..C onnectio

Why is that? because we can not put on the page of JSON a goal like this:

In my case I use the manufacturer Connect Me 9210 Digi:

  • I had to use a flag to indicate that one would use non-standard MIME: p-> theCgiPtr-> = fDataType eRpDataTypeOther;
  • It added the new MIME in the variable: strcpy (p-> theCgiPtr-> fOtherMimeType, "text / html; charset = ISO-8859-1 ");

It worked for me without having to convert the data passed by JSON for UTF-8 and then redo the conversion on the page ...

What's the most elegant way to cap a number to a segment?

The way you do it is pretty standard. You can define a utility clamp function:

/**
 * Returns a number whose value is limited to the given range.
 *
 * Example: limit the output of this computation to between 0 and 255
 * (x * 255).clamp(0, 255)
 *
 * @param {Number} min The lower boundary of the output range
 * @param {Number} max The upper boundary of the output range
 * @returns A number in the range [min, max]
 * @type Number
 */
Number.prototype.clamp = function(min, max) {
  return Math.min(Math.max(this, min), max);
};

(Although extending language built-ins is generally frowned upon)

Increasing the JVM maximum heap size for memory intensive applications

When you are using JVM in 32-bit mode, the maximum heap size that can be allocated is 1280 MB. So, if you want to go beyond that, you need to invoke JVM in 64-mode.

You can use following:

$ java -d64 -Xms512m -Xmx4g HelloWorld

where,

  • -d64: Will enable 64-bit JVM
  • -Xms512m: Will set initial heap size as 512 MB
  • -Xmx4g: Will set maximum heap size as 4 GB

You can tune in -Xms and -Xmx as per you requirements (YMMV)

A very good resource on JVM performance tuning, which might want to look into: http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html

how to redirect to home page

window.location = '/';

Should usually do the trick, but it depends on your sites directories. This will work for your example

Is it better to use std::memcpy() or std::copy() in terms to performance?

Always use std::copy because memcpy is limited to only C-style POD structures, and the compiler will likely replace calls to std::copy with memcpy if the targets are in fact POD.

Plus, std::copy can be used with many iterator types, not just pointers. std::copy is more flexible for no performance loss and is the clear winner.

What's the difference between primitive and reference types?

Primitives vs. References

First :-

Primitive types are the basic types of data: byte, short, int, long, float, double, boolean, char. Primitive variables store primitive values. Reference types are any instantiable class as well as arrays: String, Scanner, Random, Die, int[], String[], etc. Reference variables store addresses to locations in memory for where the data is stored.

Second:-

Primitive types store values but Reference type store handles to objects in heap space. Remember, reference variables are not pointers like you might have seen in C and C++, they are just handles to objects, so that you can access them and make some change on object's state.

Read more: http://javarevisited.blogspot.com/2015/09/difference-between-primitive-and-reference-variable-java.html#ixzz3xVBhi2cr

What does '<?=' mean in PHP?

As of PHP 5.4.0, <?= ?> are always available even without the short_open_tag set in php.ini.

Furthermore, as of PHP 7.0, The ASP tags: <%, %> and the script tag <script language="php"> are removed from PHP.

Count distinct values

SELECT CUSTOMER, COUNT(*) as PETS 
FROM table_name 
GROUP BY CUSTOMER;

Linux cmd to search for a class file among jars irrespective of jar path

Use deepgrep and deepfind. On debian-based systems you can install them by:

sudo apt-get install strigi-utils

Both commands search for nested archives as well. In your case the command would look like:

find . -name "*.jar" | xargs -I {} deepfind {} | grep Hello.class

Converting .NET DateTime to JSON

If you pass a DateTime from a .Net code to a javascript code, C#:

DateTime net_datetime = DateTime.Now;

javascript treats it as a string, like "/Date(1245398693390)/":

You can convert it as fllowing:

// convert the string to date correctly
var d = eval(net_datetime.slice(1, -1))

or:

// convert the string to date correctly
var d = eval("/Date(1245398693390)/".slice(1, -1))

How to select a specific node with LINQ-to-XML

I'd use something like:

dim customer = (from c in xmldoc...<Customer> 
                where c.<ID>.Value=22 
                select c).SingleOrDefault 

Edit:

missed the c# tag, sorry......the example is in VB.NET

How can prevent a PowerShell window from closing so I can see the error?

The simplest and easiest way is to execute your particular script with -NoExit param.

1.Open run box by pressing:

Win + R

2.Then type into input prompt:

PowerShell -NoExit "C:\folder\script.ps1"

and execute.

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

You can also find create_tables.sql file it phpMyAdmin's repo. Just import it from phpMyAdmin panel. It should work.

Create a temporary table in a SELECT statement without a separate CREATE TABLE

Engine must be before select:

CREATE TEMPORARY TABLE temp1 ENGINE=MEMORY 
as (select * from table1)

bootstrap 3 tabs not working properly

In my case we were setting the div id as a number and setting the href="#123", this did not work.. adding a prefix to the id helped.

Example: This did not work-

<li> <a data-toggle="tab" href="#@i"> <li/>
...
<div class="tab-pane" id="#@i">

This worked:

<li><a data-toggle="tab" href="#prefix@i"><li/>
...
<div class="tab-pane" id="#prefix@i">

How to check if MySQL returns null/empty?

Also, don't forget the === operator when you're working with numbers that could mean null or 0 or return some form of false or null that isn't what you're looking for.

Convert hex color value ( #ffffff ) to integer value

Get Shared Preferences Color Code in String then Convert to integer and add layout-background color:

    sharedPreferences = getSharedPreferences(mypref, Context.MODE_PRIVATE);
    String sw=sharedPreferences.getString(name, "");
    relativeLayout.setBackgroundColor(Color.parseColor(sw));

How do I download code using SVN/Tortoise from Google Code?

If you are behind a firewall you will have to configure the Tortoise client to connect to it. Right click somewhere in your window, select "TortoiseSVN", select "settings", and then select "network" on the left side of the panel. Fill out all the required fields. Good luck.

How to fix warning from date() in PHP"

You could also use this:

ini_alter('date.timezone','Asia/Calcutta');

You should call this before calling any date function. It accepts the key as the first parameter to alter PHP settings during runtime and the second parameter is the value.

I had done these things before I figured out this:

  1. Changed the PHP.timezone to "Asia/Calcutta" - but did not work
  2. Changed the lat and long parameters in the ini - did not work
  3. Used date_default_timezone_set("Asia/Calcutta"); - did not work
  4. Used ini_alter() - IT WORKED
  5. Commented date_default_timezone_set("Asia/Calcutta"); - IT WORKED
  6. Reverted the changes made to the PHP.ini - IT WORKED

For me the init_alter() method got it all working.

I am running Apache 2 (pre-installed), PHP 5.3 on OSX mountain lion

How many socket connections possible?

A limit on the number of open sockets is configurable in the /proc file system

cat /proc/sys/fs/file-max

Max for incoming connections in the OS defined by integer limits.

Linux itself allows billions of open sockets.

To use the sockets you need an application listening, e.g. a web server, and that will use a certain amount of RAM per socket.

RAM and CPU will introduce the real limits. (modern 2017, think millions not billions)

1 millions is possible, not easy. Expect to use X Gigabytes of RAM to manage 1 million sockets.

Outgoing TCP connections are limited by port numbers ~65000 per IP. You can have multiple IP addresses, but not unlimited IP addresses. This is a limit in TCP not Linux.

Am I trying to connect to a TLS-enabled daemon without TLS?

It is possible that you do not have the permission to the file yet. It happened to me after I add myself to dockergroup using

sudo gpasswd -a user docker

but not yet logout.

To resolve this, you can either re-login, or use sg docker "docker <subcommand> ..." before you logout.

If you are in group docker in /etc/group, you should be able to run it without typing password.

https://dingyichen.wordpress.com/2015/02/05/docker-dial-unix-varrundocker-sock-no-such-file-or-directory-are-you-trying-to-connect-to-a-tls-enabled-daemon-without-tls/

How do I compile C++ with Clang?

I've had a similar problem when building Clang from source (but not with sudo apt-get install. This might depend on the version of Ubuntu which you're running).

It might be worth checking if clang++ can find the correct locations of your C++ libraries:

Compare the results of g++ -v <filename.cpp> and clang++ -v <filename.cpp>, under "#include < ... > search starts here:".

Base64 Encoding Image

Check the following example:

// First get your image
$imgPath = 'path-to-your-picture/image.jpg';
$img = base64_encode(file_get_contents($imgPath));
echo '<img width="100" height="100" src="data:image/jpg;base64,'. $img .'" />'

How to replace blank (null ) values with 0 for all records?

UPDATE table SET column=0 WHERE column IS NULL

Adding a color background and border radius to a Layout

You don't need the separate fill item. In fact, it's invalid. You just have to add a solid block to the shape. The subsequent stroke draws on top of the solid:

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">

    <corners android:radius="5dp" />
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dip"
        android:color="@color/bggrey" />
</shape>

You also don't need the layer-list if you only have one shape.

javascript pushing element at the beginning of an array

For an uglier version of unshift use splice:

TheArray.splice(0, 0, TheNewObject);

Save text file UTF-8 encoded with VBA

Here is another way to do this - using the API function WideCharToMultiByte:

Option Explicit

Private Declare Function WideCharToMultiByte Lib "kernel32.dll" ( _
  ByVal CodePage As Long, _
  ByVal dwFlags As Long, _
  ByVal lpWideCharStr As Long, _
  ByVal cchWideChar As Long, _
  ByVal lpMultiByteStr As Long, _
  ByVal cbMultiByte As Long, _
  ByVal lpDefaultChar As Long, _
  ByVal lpUsedDefaultChar As Long) As Long

Private Sub getUtf8(ByRef s As String, ByRef b() As Byte)
Const CP_UTF8 As Long = 65001
Dim len_s As Long
Dim ptr_s As Long
Dim size As Long
  Erase b
  len_s = Len(s)
  If len_s = 0 Then _
    Err.Raise 30030, , "Len(WideChars) = 0"
  ptr_s = StrPtr(s)
  size = WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, 0, 0, 0, 0)
  If size = 0 Then _
    Err.Raise 30030, , "WideCharToMultiByte() = 0"
  ReDim b(0 To size - 1)
  If WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, VarPtr(b(0)), size, 0, 0) = 0 Then _
    Err.Raise 30030, , "WideCharToMultiByte(" & Format$(size) & ") = 0"
End Sub

Public Sub writeUtf()
Dim file As Integer
Dim s As String
Dim b() As Byte
  s = "äöüßµ@€|~{}[]²³\ .." & _
    " OMEGA" & ChrW$(937) & ", SIGMA" & ChrW$(931) & _
    ", alpha" & ChrW$(945) & ", beta" & ChrW$(946) & ", pi" & ChrW$(960) & vbCrLf
  file = FreeFile
  Open "C:\Temp\TestUtf8.txt" For Binary Access Write Lock Read Write As #file
  getUtf8 s, b
  Put #file, , b
  Close #file
End Sub

MySQL: Cloning a MySQL database on the same MySql instance

Using MySQL Utilities

The MySQL Utilities contain the nice tool mysqldbcopy which by default copies a DB including all related objects (“tables, views, triggers, events, procedures, functions, and database-level grants”) and data from one DB server to the same or to another DB server. There are lots of options available to customize what is actually copied.

So, to answer the OP’s question:

mysqldbcopy \
    --source=root:your_password@localhost \
    --destination=root:your_password@localhost \
    sitedb1:sitedb2

requestFeature() must be called before adding content

For SDK version 23 and above, the same RuntimeException is thrown if you are using AppCompatActivity to extend your activity. It will not happen if your activity derives directly from Activity.

This is a known issue on google as mentioned in https://code.google.com/p/android/issues/detail?id=186440

The work around provided for this is to use supportRequestWindowFeature() method instead of using requestFeature().

Please upvote if it solves your problem.

Which Python memory profiler is recommended?

Try also the pytracemalloc project which provides the memory usage per Python line number.

EDIT (2014/04): It now has a Qt GUI to analyze snapshots.

Is there any boolean type in Oracle databases?

DECLARE
error_flag  BOOLEAN := false;
BEGIN

error_flag := true;
--error_flag := 13;--expression is of wrong type

  IF error_flag THEN 

UPDATE table_a SET id= 8 WHERE id = 1;

END IF;
END;

how to wait for first command to finish?

Make sure that st_new.sh does something at the end what you can recognize (like touch /tmp/st_new.tmp when you remove the file first and always start one instance of st_new.sh).
Then make a polling loop. First sleep the normal time you think you should wait, and wait short time in every loop. This will result in something like

max_retry=20
retry=0
sleep 10 # Minimum time for st_new.sh to finish
while [ ${retry} -lt ${max_retry} ]; do
   if [ -f /tmp/st_new.tmp ]; then
      break # call results.sh outside loop
   else
      (( retry = retry + 1 ))
      sleep 1
   fi
done
if [ -f /tmp/st_new.tmp ]; then
   source ../../results.sh 
   rm -f /tmp/st_new.tmp
else
   echo Something wrong with st_new.sh
fi

How do you check what version of SQL Server for a database using TSQL?

Try this:

SELECT @@VERSION[server], SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

SQL using sp_HelpText to view a stored procedure on a linked server

Little addition in answer if you have different user rather then dbo then do like this.

EXEC  [ServerName].[DatabaseName].dbo.sp_HelpText '[user].[storedProcName]'

phonegap open link in browser

I'm using PhoneGap Build (v3.4.0), with focus on iOS, and I needed to have this entry in my config.xml for PhoneGap to recognize the InAppBrowser plug-in.

<gap:plugin name="org.apache.cordova.inappbrowser" />

After that, using window.open(url, target) should work as expected, as documented here.

X-Frame-Options Allow-From multiple domains

X-Frame-Options is deprecated. From MDN:

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

The modern alternative is the Content-Security-Policy header, which along many other policies can white-list what URLs are allowed to host your page in a frame, using the frame-ancestors directive.
frame-ancestors supports multiple domains and even wildcards, for example:

Content-Security-Policy: frame-ancestors 'self' example.com *.example.net ;

Unfortunately, for now, Internet Explorer does not fully support Content-Security-Policy.

UPDATE: MDN has removed their deprecation comment. Here's a similar comment from W3C's Content Security Policy Level

The frame-ancestors directive obsoletes the X-Frame-Options header. If a resource has both policies, the frame-ancestors policy SHOULD be enforced and the X-Frame-Options policy SHOULD be ignored.

Boxplot in R showing the mean

With ggplot2:

p<-qplot(spray,count,data=InsectSprays,geom='boxplot')
p<-p+stat_summary(fun.y=mean,shape=1,col='red',geom='point')
print(p)

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

Usage of __slots__?

In Python, what is the purpose of __slots__ and what are the cases one should avoid this?

TLDR:

The special attribute __slots__ allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results:

  1. faster attribute access.
  2. space savings in memory.

The space savings is from

  1. Storing value references in slots instead of __dict__.
  2. Denying __dict__ and __weakref__ creation if parent classes deny them and you declare __slots__.

Quick Caveats

Small caveat, you should only declare a particular slot one time in an inheritance tree. For example:

class Base:
    __slots__ = 'foo', 'bar'

class Right(Base):
    __slots__ = 'baz', 

class Wrong(Base):
    __slots__ = 'foo', 'bar', 'baz'        # redundant foo and bar

Python doesn't object when you get this wrong (it probably should), problems might not otherwise manifest, but your objects will take up more space than they otherwise should. Python 3.8:

>>> from sys import getsizeof
>>> getsizeof(Right()), getsizeof(Wrong())
(56, 72)

This is because the Base's slot descriptor has a slot separate from the Wrong's. This shouldn't usually come up, but it could:

>>> w = Wrong()
>>> w.foo = 'foo'
>>> Base.foo.__get__(w)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: foo
>>> Wrong.foo.__get__(w)
'foo'

The biggest caveat is for multiple inheritance - multiple "parent classes with nonempty slots" cannot be combined.

To accommodate this restriction, follow best practices: Factor out all but one or all parents' abstraction which their concrete class respectively and your new concrete class collectively will inherit from - giving the abstraction(s) empty slots (just like abstract base classes in the standard library).

See section on multiple inheritance below for an example.

Requirements:

  • To have attributes named in __slots__ to actually be stored in slots instead of a __dict__, a class must inherit from object.

  • To prevent the creation of a __dict__, you must inherit from object and all classes in the inheritance must declare __slots__ and none of them can have a '__dict__' entry.

There are a lot of details if you wish to keep reading.

Why use __slots__: Faster attribute access.

The creator of Python, Guido van Rossum, states that he actually created __slots__ for faster attribute access.

It is trivial to demonstrate measurably significant faster access:

import timeit

class Foo(object): __slots__ = 'foo',

class Bar(object): pass

slotted = Foo()
not_slotted = Bar()

def get_set_delete_fn(obj):
    def get_set_delete():
        obj.foo = 'foo'
        obj.foo
        del obj.foo
    return get_set_delete

and

>>> min(timeit.repeat(get_set_delete_fn(slotted)))
0.2846834529991611
>>> min(timeit.repeat(get_set_delete_fn(not_slotted)))
0.3664822799983085

The slotted access is almost 30% faster in Python 3.5 on Ubuntu.

>>> 0.3664822799983085 / 0.2846834529991611
1.2873325658284342

In Python 2 on Windows I have measured it about 15% faster.

Why use __slots__: Memory Savings

Another purpose of __slots__ is to reduce the space in memory that each object instance takes up.

My own contribution to the documentation clearly states the reasons behind this:

The space saved over using __dict__ can be significant.

SQLAlchemy attributes a lot of memory savings to __slots__.

To verify this, using the Anaconda distribution of Python 2.7 on Ubuntu Linux, with guppy.hpy (aka heapy) and sys.getsizeof, the size of a class instance without __slots__ declared, and nothing else, is 64 bytes. That does not include the __dict__. Thank you Python for lazy evaluation again, the __dict__ is apparently not called into existence until it is referenced, but classes without data are usually useless. When called into existence, the __dict__ attribute is a minimum of 280 bytes additionally.

In contrast, a class instance with __slots__ declared to be () (no data) is only 16 bytes, and 56 total bytes with one item in slots, 64 with two.

For 64 bit Python, I illustrate the memory consumption in bytes in Python 2.7 and 3.6, for __slots__ and __dict__ (no slots defined) for each point where the dict grows in 3.6 (except for 0, 1, and 2 attributes):

       Python 2.7             Python 3.6
attrs  __slots__  __dict__*   __slots__  __dict__* | *(no slots defined)
none   16         56 + 272†   16         56 + 112† | †if __dict__ referenced
one    48         56 + 272    48         56 + 112
two    56         56 + 272    56         56 + 112
six    88         56 + 1040   88         56 + 152
11     128        56 + 1040   128        56 + 240
22     216        56 + 3344   216        56 + 408     
43     384        56 + 3344   384        56 + 752

So, in spite of smaller dicts in Python 3, we see how nicely __slots__ scale for instances to save us memory, and that is a major reason you would want to use __slots__.

Just for completeness of my notes, note that there is a one-time cost per slot in the class's namespace of 64 bytes in Python 2, and 72 bytes in Python 3, because slots use data descriptors like properties, called "members".

>>> Foo.foo
<member 'foo' of 'Foo' objects>
>>> type(Foo.foo)
<class 'member_descriptor'>
>>> getsizeof(Foo.foo)
72

Demonstration of __slots__:

To deny the creation of a __dict__, you must subclass object:

class Base(object): 
    __slots__ = ()

now:

>>> b = Base()
>>> b.a = 'a'
Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    b.a = 'a'
AttributeError: 'Base' object has no attribute 'a'

Or subclass another class that defines __slots__

class Child(Base):
    __slots__ = ('a',)

and now:

c = Child()
c.a = 'a'

but:

>>> c.b = 'b'
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    c.b = 'b'
AttributeError: 'Child' object has no attribute 'b'

To allow __dict__ creation while subclassing slotted objects, just add '__dict__' to the __slots__ (note that slots are ordered, and you shouldn't repeat slots that are already in parent classes):

class SlottedWithDict(Child): 
    __slots__ = ('__dict__', 'b')

swd = SlottedWithDict()
swd.a = 'a'
swd.b = 'b'
swd.c = 'c'

and

>>> swd.__dict__
{'c': 'c'}

Or you don't even need to declare __slots__ in your subclass, and you will still use slots from the parents, but not restrict the creation of a __dict__:

class NoSlots(Child): pass
ns = NoSlots()
ns.a = 'a'
ns.b = 'b'

And:

>>> ns.__dict__
{'b': 'b'}

However, __slots__ may cause problems for multiple inheritance:

class BaseA(object): 
    __slots__ = ('a',)

class BaseB(object): 
    __slots__ = ('b',)

Because creating a child class from parents with both non-empty slots fails:

>>> class Child(BaseA, BaseB): __slots__ = ()
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    class Child(BaseA, BaseB): __slots__ = ()
TypeError: Error when calling the metaclass bases
    multiple bases have instance lay-out conflict

If you run into this problem, You could just remove __slots__ from the parents, or if you have control of the parents, give them empty slots, or refactor to abstractions:

from abc import ABC

class AbstractA(ABC):
    __slots__ = ()

class BaseA(AbstractA): 
    __slots__ = ('a',)

class AbstractB(ABC):
    __slots__ = ()

class BaseB(AbstractB): 
    __slots__ = ('b',)

class Child(AbstractA, AbstractB): 
    __slots__ = ('a', 'b')

c = Child() # no problem!

Add '__dict__' to __slots__ to get dynamic assignment:

class Foo(object):
    __slots__ = 'bar', 'baz', '__dict__'

and now:

>>> foo = Foo()
>>> foo.boink = 'boink'

So with '__dict__' in slots we lose some of the size benefits with the upside of having dynamic assignment and still having slots for the names we do expect.

When you inherit from an object that isn't slotted, you get the same sort of semantics when you use __slots__ - names that are in __slots__ point to slotted values, while any other values are put in the instance's __dict__.

Avoiding __slots__ because you want to be able to add attributes on the fly is actually not a good reason - just add "__dict__" to your __slots__ if this is required.

You can similarly add __weakref__ to __slots__ explicitly if you need that feature.

Set to empty tuple when subclassing a namedtuple:

The namedtuple builtin make immutable instances that are very lightweight (essentially, the size of tuples) but to get the benefits, you need to do it yourself if you subclass them:

from collections import namedtuple
class MyNT(namedtuple('MyNT', 'bar baz')):
    """MyNT is an immutable and lightweight object"""
    __slots__ = ()

usage:

>>> nt = MyNT('bar', 'baz')
>>> nt.bar
'bar'
>>> nt.baz
'baz'

And trying to assign an unexpected attribute raises an AttributeError because we have prevented the creation of __dict__:

>>> nt.quux = 'quux'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyNT' object has no attribute 'quux'

You can allow __dict__ creation by leaving off __slots__ = (), but you can't use non-empty __slots__ with subtypes of tuple.

Biggest Caveat: Multiple inheritance

Even when non-empty slots are the same for multiple parents, they cannot be used together:

class Foo(object): 
    __slots__ = 'foo', 'bar'
class Bar(object):
    __slots__ = 'foo', 'bar' # alas, would work if empty, i.e. ()

>>> class Baz(Foo, Bar): pass
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
    multiple bases have instance lay-out conflict

Using an empty __slots__ in the parent seems to provide the most flexibility, allowing the child to choose to prevent or allow (by adding '__dict__' to get dynamic assignment, see section above) the creation of a __dict__:

class Foo(object): __slots__ = ()
class Bar(object): __slots__ = ()
class Baz(Foo, Bar): __slots__ = ('foo', 'bar')
b = Baz()
b.foo, b.bar = 'foo', 'bar'

You don't have to have slots - so if you add them, and remove them later, it shouldn't cause any problems.

Going out on a limb here: If you're composing mixins or using abstract base classes, which aren't intended to be instantiated, an empty __slots__ in those parents seems to be the best way to go in terms of flexibility for subclassers.

To demonstrate, first, let's create a class with code we'd like to use under multiple inheritance

class AbstractBase:
    __slots__ = ()
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def __repr__(self):
        return f'{type(self).__name__}({repr(self.a)}, {repr(self.b)})'

We could use the above directly by inheriting and declaring the expected slots:

class Foo(AbstractBase):
    __slots__ = 'a', 'b'

But we don't care about that, that's trivial single inheritance, we need another class we might also inherit from, maybe with a noisy attribute:

class AbstractBaseC:
    __slots__ = ()
    @property
    def c(self):
        print('getting c!')
        return self._c
    @c.setter
    def c(self, arg):
        print('setting c!')
        self._c = arg

Now if both bases had nonempty slots, we couldn't do the below. (In fact, if we wanted, we could have given AbstractBase nonempty slots a and b, and left them out of the below declaration - leaving them in would be wrong):

class Concretion(AbstractBase, AbstractBaseC):
    __slots__ = 'a b _c'.split()

And now we have functionality from both via multiple inheritance, and can still deny __dict__ and __weakref__ instantiation:

>>> c = Concretion('a', 'b')
>>> c.c = c
setting c!
>>> c.c
getting c!
Concretion('a', 'b')
>>> c.d = 'd'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Concretion' object has no attribute 'd'

Other cases to avoid slots:

  • Avoid them when you want to perform __class__ assignment with another class that doesn't have them (and you can't add them) unless the slot layouts are identical. (I am very interested in learning who is doing this and why.)
  • Avoid them if you want to subclass variable length builtins like long, tuple, or str, and you want to add attributes to them.
  • Avoid them if you insist on providing default values via class attributes for instance variables.

You may be able to tease out further caveats from the rest of the __slots__ documentation (the 3.7 dev docs are the most current), which I have made significant recent contributions to.

Critiques of other answers

The current top answers cite outdated information and are quite hand-wavy and miss the mark in some important ways.

Do not "only use __slots__ when instantiating lots of objects"

I quote:

"You would want to use __slots__ if you are going to instantiate a lot (hundreds, thousands) of objects of the same class."

Abstract Base Classes, for example, from the collections module, are not instantiated, yet __slots__ are declared for them.

Why?

If a user wishes to deny __dict__ or __weakref__ creation, those things must not be available in the parent classes.

__slots__ contributes to reusability when creating interfaces or mixins.

It is true that many Python users aren't writing for reusability, but when you are, having the option to deny unnecessary space usage is valuable.

__slots__ doesn't break pickling

When pickling a slotted object, you may find it complains with a misleading TypeError:

>>> pickle.loads(pickle.dumps(f))
TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled

This is actually incorrect. This message comes from the oldest protocol, which is the default. You can select the latest protocol with the -1 argument. In Python 2.7 this would be 2 (which was introduced in 2.3), and in 3.6 it is 4.

>>> pickle.loads(pickle.dumps(f, -1))
<__main__.Foo object at 0x1129C770>

in Python 2.7:

>>> pickle.loads(pickle.dumps(f, 2))
<__main__.Foo object at 0x1129C770>

in Python 3.6

>>> pickle.loads(pickle.dumps(f, 4))
<__main__.Foo object at 0x1129C770>

So I would keep this in mind, as it is a solved problem.

Critique of the (until Oct 2, 2016) accepted answer

The first paragraph is half short explanation, half predictive. Here's the only part that actually answers the question

The proper use of __slots__ is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. This saves the overhead of one dict for every object that uses slots

The second half is wishful thinking, and off the mark:

While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.

Python actually does something similar to this, only creating the __dict__ when it is accessed, but creating lots of objects with no data is fairly ridiculous.

The second paragraph oversimplifies and misses actual reasons to avoid __slots__. The below is not a real reason to avoid slots (for actual reasons, see the rest of my answer above.):

They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies.

It then goes on to discuss other ways of accomplishing that perverse goal with Python, not discussing anything to do with __slots__.

The third paragraph is more wishful thinking. Together it is mostly off-the-mark content that the answerer didn't even author and contributes to ammunition for critics of the site.

Memory usage evidence

Create some normal objects and slotted objects:

>>> class Foo(object): pass
>>> class Bar(object): __slots__ = ()

Instantiate a million of them:

>>> foos = [Foo() for f in xrange(1000000)]
>>> bars = [Bar() for b in xrange(1000000)]

Inspect with guppy.hpy().heap():

>>> guppy.hpy().heap()
Partition of a set of 2028259 objects. Total size = 99763360 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0 1000000  49 64000000  64  64000000  64 __main__.Foo
     1     169   0 16281480  16  80281480  80 list
     2 1000000  49 16000000  16  96281480  97 __main__.Bar
     3   12284   1   987472   1  97268952  97 str
...

Access the regular objects and their __dict__ and inspect again:

>>> for f in foos:
...     f.__dict__
>>> guppy.hpy().heap()
Partition of a set of 3028258 objects. Total size = 379763480 bytes.
 Index  Count   %      Size    % Cumulative  % Kind (class / dict of class)
     0 1000000  33 280000000  74 280000000  74 dict of __main__.Foo
     1 1000000  33  64000000  17 344000000  91 __main__.Foo
     2     169   0  16281480   4 360281480  95 list
     3 1000000  33  16000000   4 376281480  99 __main__.Bar
     4   12284   0    987472   0 377268952  99 str
...

This is consistent with the history of Python, from Unifying types and classes in Python 2.2

If you subclass a built-in type, extra space is automatically added to the instances to accomodate __dict__ and __weakrefs__. (The __dict__ is not initialized until you use it though, so you shouldn't worry about the space occupied by an empty dictionary for each instance you create.) If you don't need this extra space, you can add the phrase "__slots__ = []" to your class.

How to use CSS to surround a number with a circle?

You work like with a standard block, that is a square

.circle {
    width: 10em; height: 10em; 
    -webkit-border-radius: 5em; -moz-border-radius: 5em;
  }

This is feature of CSS 3 and it is not very well suporrted, you can count on firefox and safari for sure.

<div class="circle"><span>1234</span></div>

Set position / size of UI element as percentage of screen size

I think what you want is to set the android:layout_weight,

http://developer.android.com/resources/tutorials/views/hello-linearlayout.html

something like this (I'm just putting text views above and below as placeholders):

  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="68"/>
    <Gallery 
        android:id="@+id/gallery"
        android:layout_width="fill_parent"
        android:layout_height="0dp"

        android:layout_weight="16"
    />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="16"/>

  </LinearLayout>

How to make a DIV not wrap?

This worked for me:

_x000D_
_x000D_
.container {_x000D_
  display: inline-flex;_x000D_
}_x000D_
_x000D_
.slide {_x000D_
  float: left;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="slide">something1</div>_x000D_
  <div class="slide">something2</div>_x000D_
  <div class="slide">something3</div>_x000D_
  <div class="slide">something4</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

How to create relationships in MySQL

If the tables are innodb you can create it like this:

CREATE TABLE accounts(
    account_id INT NOT NULL AUTO_INCREMENT,
    customer_id INT( 4 ) NOT NULL ,
    account_type ENUM( 'savings', 'credit' ) NOT NULL,
    balance FLOAT( 9 ) NOT NULL,
    PRIMARY KEY ( account_id ), 
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id) 
) ENGINE=INNODB;

You have to specify that the tables are innodb because myisam engine doesn't support foreign key. Look here for more info.

What is the use of the %n format specifier in C?

Most of these answers explain what %n does (which is to print nothing and to write the number of characters printed thus far to an int variable), but so far no one has really given an example of what use it has. Here is one:

int n;
printf("%s: %nFoo\n", "hello", &n);
printf("%*sBar\n", n, "");

will print:

hello: Foo
       Bar

with Foo and Bar aligned. (It's trivial to do that without using %n for this particular example, and in general one always could break up that first printf call:

int n = printf("%s: ", "hello");
printf("Foo\n");
printf("%*sBar\n", n, "");

Whether the slightly added convenience is worth using something esoteric like %n (and possibly introducing errors) is open to debate.)

Delete all files of specific type (extension) recursively down a directory using a batch file

I don't have enough reputation to add comment, so I posted this as an answer. But for original issue with this command:

@echo off
FOR %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

The first For is lacking recursive syntax, it should be:

@echo off
FOR /R %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

You can just do:

FOR %%p IN (C:\Users\0300092544\Downloads\Ces_Sce_600) DO @ECHO %%p

to show the actual output.

Check if file exists and whether it contains a specific string

Instead of storing the output of grep in a variable and then checking whether the variable is empty, you can do this:

if grep -q "poet" $file_name
then
    echo "poet was found in $file_name"
fi

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

Here are some commonly used tests:

   -d FILE
          FILE exists and is a directory
   -e FILE
          FILE exists
   -f FILE
          FILE exists and is a regular file
   -h FILE
          FILE exists and is a symbolic link (same as -L)
   -r FILE
          FILE exists and is readable
   -s FILE
          FILE exists and has a size greater than zero
   -w FILE
          FILE exists and is writable
   -x FILE
          FILE exists and is executable
   -z STRING
          the length of STRING is zero

Example:

if [ -e "$file_name" ] && [ ! -z "$used_var" ]
then
    echo "$file_name exists and $used_var is not empty"
fi

Bootstrap modal in React.js

The quickest fix would be to explicitly use the jQuery $ from the global context (which has been extended with your $.modal() because you referenced that in your script tag when you did ):

  window.$('#scheduleentry-modal').modal('show') // to show 
  window.$('#scheduleentry-modal').modal('hide') // to hide

so this is how you can about it on react

import React, { Component } from 'react';

export default Modal extends Component {
    componentDidMount() {
        window.$('#Modal').modal('show');
    }

    handleClose() {
        window.$('#Modal').modal('hide');
    }

    render() {
        <
        div className = 'modal fade'
        id = 'ModalCenter'
        tabIndex = '-1'
        role = 'dialog'
        aria - labelledby = 'ModalCenterTitle'
        data - backdrop = 'static'
        aria - hidden = 'true' >
            <
            div className = 'modal-dialog modal-dialog-centered'
        role = 'document' >
            <
            div className = 'modal-content' >
            // ...your modal body
            <
            button
        type = 'button'
        className = 'btn btn-secondary'
        onClick = {
                this.handleClose
            } >
            Close <
            /button> < /
        div > <
            /div> < /
        div >
    }
}

How to remove all white spaces from a given text file

Much simpler to my opinion:

sed -r 's/\s+//g' filename

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

To fix this specific error, CSP should include this:

font-src 'self' data:;

So, index.html meta should read:

<meta http-equiv="Content-Security-Policy" content="font-src 'self' data:; img-src 'self' data:; default-src 'self' http://121.0.0:3000/">

Constant pointer vs Pointer to constant

const int* ptr; here think like *ptr is constant and *ptr can't be change again

int * const ptr; while here think like ptr as a constant and that can't be change again

m2eclipse error

My issue was that eclipse could not find the mvn.bat file within the installation directory. The solution is to create a mvn.bat file with the following code:

"%~dp0\mvn.cmd" %*

Save that file. Place it inside the [Maven Installation Folder]\bin directory.

How to run function of parent window when child window closes?

I know this post is old, but I found that this really works well:

window.onunload = function() {
    window.opener.location.href = window.opener.location.href;
};

The window.onunload part was the hint I found googling this page. Thanks, @jerjer!

How to add 10 minutes to my (String) time?

I used the code below to add a certain time interval to the current time.

    int interval = 30;  
    SimpleDateFormat df = new SimpleDateFormat("HH:mm");
    Calendar time = Calendar.getInstance();

    Log.i("Time ", String.valueOf(df.format(time.getTime())));

    time.add(Calendar.MINUTE, interval);

    Log.i("New Time ", String.valueOf(df.format(time.getTime())));

How to get the path of the batch script in Windows?

%~dp0 - return the path from where script executed

But, important to know also below one:

%CD% - return the current path in runtime, for example if you get into other folders using "cd folder1", and then "cd folder2", it will return the full path until folder2 and not the original path where script located

Best way to update data with a RecyclerView adapter

RecyclerView's Adapter doesn't come with many methods otherwise available in ListView's adapter. But your swap can be implemented quite simply as:

class MyRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
   List<Data> data;
   ...

    public void swap(ArrayList<Data> datas)
    {
        data.clear();
        data.addAll(datas);
        notifyDataSetChanged();     
    }
}

Also there is a difference between

list.clear();
list.add(data);

and

list = newList;

The first is reusing the same list object. The other is dereferencing and referencing the list. The old list object which can no longer be reached will be garbage collected but not without first piling up heap memory. This would be the same as initializing new adapter everytime you want to swap data.

Changing image sizes proportionally using CSS?

Put it as a background on your holder e.g.

<div style="background:url(path/to/image/myimage.jpg) center center; width:120px; height:120px;">
&nbsp;
</div>

This will center your image inside a 120x120 div chopping off any excess of the image

Sample database for exercise

Check out CodePlex for Microsoft SQL Server Community Projects & Samples

3rd party edit

On top of the link above you might look at

Matrix Multiplication in pure Python?

The shape of your matrix C is wrong; it's the transpose of what you actually want it to be. (But I agree with ulmangt: the Right Thing is almost certainly to use numpy, really.)

How to add url parameter to the current url?

Maybe you can write a function as follows:

var addParams = function(key, val, url) {
  var arr = url.split('?');
  if(arr.length == 1) {
    return url + '?' + key + '=' + val;
  }
  else if(arr.length == 2) {
    var params = arr[1].split('&');
    var p = {};
    var a = [];
    var strarr = [];
    $.each(params, function(index, element) {
      a = element.split('=');
      p[a[0]] = a[1];
      })
    p[key] = val;
    for(var o in p) {
      strarr.push(o + '=' + p[o]);
    }
    var str = strarr.join('&');
    return(arr[0] + '?' + str);
  }
}

Get raw POST body in Python Flask regardless of Content-Type header

request.stream is the stream of raw data passed to the application by the WSGI server. No parsing is done when reading it, although you usually want request.get_data() instead.

data = request.stream.read()

The stream will be empty if it was previously read by request.data or another attribute.

How to convert a datetime to string in T-SQL

In addition to the CAST and CONVERT functions in the previous answers, if you are using SQL Server 2012 and above you use the FORMAT function to convert a DATETIME based type to a string.

To convert back, use the opposite PARSE or TRYPARSE functions.

The formatting styles are based on .NET (similar to the string formatting options of the ToString() method) and has the advantage of being culture aware. eg.

DECLARE @DateTime DATETIME2 = SYSDATETIME();
DECLARE @StringResult1 NVARCHAR(100) = FORMAT(@DateTime, 'g') --without culture
DECLARE @StringResult2 NVARCHAR(100) = FORMAT(@DateTime, 'g', 'en-gb') 
SELECT @DateTime
SELECT @StringResult1, @StringResult2
SELECT PARSE(@StringResult1 AS DATETIME2)
SELECT PARSE(@StringResult2 AS DATETIME2 USING 'en-gb')

Results:

2015-06-17 06:20:09.1320951
6/17/2015 6:20 AM
17/06/2015 06:20
2015-06-17 06:20:00.0000000
2015-06-17 06:20:00.0000000

Distinct by property of class with LINQ

I think the best option in Terms of performance (or in any terms) is to Distinct using the The IEqualityComparer interface.

Although implementing each time a new comparer for each class is cumbersome and produces boilerplate code.

So here is an extension method which produces a new IEqualityComparer on the fly for any class using reflection.

Usage:

var filtered = taskList.DistinctBy(t => t.TaskExternalId).ToArray();

Extension Method Code

public static class LinqExtensions
{
    public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
    {
        GeneralPropertyComparer<T, TKey> comparer = new GeneralPropertyComparer<T,TKey>(property);
        return items.Distinct(comparer);
    }   
}
public class GeneralPropertyComparer<T,TKey> : IEqualityComparer<T>
{
    private Func<T, TKey> expr { get; set; }
    public GeneralPropertyComparer (Func<T, TKey> expr)
    {
        this.expr = expr;
    }
    public bool Equals(T left, T right)
    {
        var leftProp = expr.Invoke(left);
        var rightProp = expr.Invoke(right);
        if (leftProp == null && rightProp == null)
            return true;
        else if (leftProp == null ^ rightProp == null)
            return false;
        else
            return leftProp.Equals(rightProp);
    }
    public int GetHashCode(T obj)
    {
        var prop = expr.Invoke(obj);
        return (prop==null)? 0:prop.GetHashCode();
    }
}

How to reverse a 'rails generate'

rails destroy controller Controller_name was returning a bunch of errors. To be able to destroy controller I had to remove related routes in routes.rb. P.S. I'm using rails 3.1

How can I transform string to UTF-8 in C#?

@anothershrubery answer worked for me. I've made an enhancement using StringEntensions Class so I can easily convert any string at all in my program.

Method:

public static class StringExtensions
{
    public static string ToUTF8(this string text)
    {
        return Encoding.UTF8.GetString(Encoding.Default.GetBytes(text));
    }
}

Usage:

string myString = "Acción";
string strConverted = myString.ToUTF8();

Or simply:

string strConverted = "Acción".ToUTF8();

Get list of all tables in Oracle?

SELECT owner, table_name
  FROM dba_tables

This is assuming that you have access to the DBA_TABLES data dictionary view. If you do not have those privileges but need them, you can request that the DBA explicitly grants you privileges on that table, or, that the DBA grants you the SELECT ANY DICTIONARY privilege or the SELECT_CATALOG_ROLE role (either of which would allow you to query any data dictionary table). Of course, you may want to exclude certain schemas like SYS and SYSTEM which have large numbers of Oracle tables that you probably don't care about.

Alternatively, if you do not have access to DBA_TABLES, you can see all the tables that your account has access to through the ALL_TABLES view:

SELECT owner, table_name
  FROM all_tables

Although, that may be a subset of the tables available in the database (ALL_TABLES shows you the information for all the tables that your user has been granted access to).

If you are only concerned with the tables that you own, not those that you have access to, you could use USER_TABLES:

SELECT table_name
  FROM user_tables

Since USER_TABLES only has information about the tables that you own, it does not have an OWNER column – the owner, by definition, is you.

Oracle also has a number of legacy data dictionary views-- TAB, DICT, TABS, and CAT for example-- that could be used. In general, I would not suggest using these legacy views unless you absolutely need to backport your scripts to Oracle 6. Oracle has not changed these views in a long time so they often have problems with newer types of objects. For example, the TAB and CAT views both show information about tables that are in the user's recycle bin while the [DBA|ALL|USER]_TABLES views all filter those out. CAT also shows information about materialized view logs with a TABLE_TYPE of "TABLE" which is unlikely to be what you really want. DICT combines tables and synonyms and doesn't tell you who owns the object.

Deleting a local branch with Git

In my case there were uncommitted changes from the previous branch lingering around. I used following commands and then delete worked.

git checkout *

git checkout master

git branch -D

How can I remove the first line of a text file using bash/sed script?

Since it sounds like I can't speed up the deletion, I think a good approach might be to process the file in batches like this:

While file1 not empty
  file2 = head -n1000 file1
  process file2
  sed -i -e "1000d" file1
end

The drawback of this is that if the program gets killed in the middle (or if there's some bad sql in there - causing the "process" part to die or lock-up), there will be lines that are either skipped, or processed twice.

(file1 contains lines of sql code)

Can CSS force a line break after each word in an element?

Use

.one-word-per-line {
    word-spacing: <parent-width>; 
}

.your-classname{
    width: min-intrinsic;
    width: -webkit-min-content;
    width: -moz-min-content;
    width: min-content;
    display: table-caption;
    display: -ms-grid;
    -ms-grid-columns: min-content;
}

where <parent-width> is the width of the parent element (or an arbitrary high value that doesn't fit into one line). That way you can be sure that there is even a line-break after a single letter. Works with Chrome/FF/Opera/IE7+ (and probably even IE6 since it's supporting word-spacing as well).

GCD to perform task in main thread

No, you do not need to check whether you’re already on the main thread. By dispatching the block to the main queue, you’re just scheduling the block to be executed serially on the main thread, which happens when the corresponding run loop is run.

If you already are on the main thread, the behaviour is the same: the block is scheduled, and executed when the run loop of the main thread is run.

Python matplotlib multiple bars

The trouble with using dates as x-values, is that if you want a bar chart like in your second picture, they are going to be wrong. You should either use a stacked bar chart (colours on top of each other) or group by date (a "fake" date on the x-axis, basically just grouping the data points).

import numpy as np
import matplotlib.pyplot as plt

N = 3
ind = np.arange(N)  # the x locations for the groups
width = 0.27       # the width of the bars

fig = plt.figure()
ax = fig.add_subplot(111)

yvals = [4, 9, 2]
rects1 = ax.bar(ind, yvals, width, color='r')
zvals = [1,2,3]
rects2 = ax.bar(ind+width, zvals, width, color='g')
kvals = [11,12,13]
rects3 = ax.bar(ind+width*2, kvals, width, color='b')

ax.set_ylabel('Scores')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('2011-Jan-4', '2011-Jan-5', '2011-Jan-6') )
ax.legend( (rects1[0], rects2[0], rects3[0]), ('y', 'z', 'k') )

def autolabel(rects):
    for rect in rects:
        h = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)
autolabel(rects3)

plt.show()

enter image description here

jsonify a SQLAlchemy result set in Flask

I was working with a sql query defaultdict of lists of RowProxy objects named jobDict It took me a while to figure out what Type the objects were.

This was a really simple quick way to resolve to some clean jsonEncoding just by typecasting the row to a list and by initially defining the dict with a value of list.

    jobDict = defaultdict(list)
    def set_default(obj):
        # trickyness needed here via import to know type
        if isinstance(obj, RowProxy):
            return list(obj)
        raise TypeError


    jsonEncoded = json.dumps(jobDict, default=set_default)

How to enter quotes in a Java string?

In Java, you can use char value with ":

char quotes ='"';

String strVar=quotes+"ROM"+quotes;

Graphical HTTP client for windows

Honestly, for simplistic stuff like that I typically whip up a quick HTML form in a local file and load that up in a browser.

How to reset the bootstrap modal when it gets closed and open it fresh again?

The below statements show how to open/reopen Modal without using bootstrap.

Add two classes in css

And then use the below jQuery to reopen the modal if it is closed.

.hide_block
 {
   display:none  !important;
 }

 .display_block
 {
    display:block !important;
 } 

 $("#Modal").removeClass('hide_block');
 $("#Modal").addClass('display_block');
 $("Modal").show("slow");

It worked fine for me :)

IntelliJ: Never use wildcard imports

The solution above was not working for me. I had to set 'class count to use import with '*'' to a high value, e.g. 999.

Using C++ base class constructors?

Here is a good discussion about superclass constructor calling rules. You always want the base class constructor to be called before the derived class constructor in order to form an object properly. Which is why this form is used

  B( int v) : A( v )
  {
  }

How to auto-indent code in the Atom editor?

I was working on some groovy code, which doesn't auto-format on save. What I did was right-click on the code pane, then chose ESLint Fix. That fixed my indents.

enter image description here

Clear form after submission with jQuery

You can add this to the callback from $.post

$( '#newsletterform' ).each(function(){
    this.reset();
});

You can't just call $( '#newsletterform' ).reset() because .reset() is a form object and not a jquery object, or something to that effect. You can read more about it here about half way down the page.

How to reload current page in ReactJS?

You can use window.location.reload(); in your componentDidMount() lifecycle method. If you are using react-router, it has a refresh method to do that.

Edit: If you want to do that after a data update, you might be looking to a re-render not a reload and you can do that by using this.setState(). Here is a basic example of it to fire a re-render after data is fetched.

import React from 'react'

const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;

class MyComponent extends React.Component {
    state = {
        users: null
    }
    componentDidMount() {
        fetch(url)
            .then(response => response.json())
            .then(users => this.setState({users: users}));
    }
    render() {
        const {users} = this.state;
        if (users) {
            return (
                <ul>
                    {users.map(user => <li>{user.name}</li>)}
                </ul>
            )
        } else {
            return (<h1>Loading ...</h1>)
        }
    }
}

export default MyComponent;

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

How to hide the border for specified rows of a table?

Use the CSS property border on the <td>s following the <tr>s you do not want to have the border.

In my example I made a class noBorder that I gave to one <tr>. Then I use a simple selector tr.noBorder td to make the border go away for all the <td>s that are inside of <tr>s with the noBorder class by assigning border: 0.

Note that you do not need to provide the unit (i.e. px) if you set something to 0 as it does not matter anyway. Zero is just zero.

_x000D_
_x000D_
table, tr, td {_x000D_
  border: 3px solid red;_x000D_
}_x000D_
tr.noBorder td {_x000D_
  border: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>A1</td>_x000D_
    <td>B1</td>_x000D_
    <td>C1</td>_x000D_
  </tr>_x000D_
  <tr class="noBorder">_x000D_
    <td>A2</td>_x000D_
    <td>B2</td>_x000D_
    <td>C2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>A3</td>_x000D_
    <td>A3</td>_x000D_
    <td>A3</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Here's the output as an image:

Output from HTML

How to create an array for JSON using PHP?

<?php 

    $username=urldecode($_POST['log_user']);

    $user="select * from tbl_registration where member_id= '".$username."' ";
    $rsuser = $obj->select($user);
    if(count($rsuser)>0)
    {
        //   (Status if 2 then its expire)    (1= use) ( 0 = not use)

        $cheknew="select name,ldate,offer_photo  from tbl_offer where status=1 ";
        $rscheknew = $obj->selectjson($cheknew);

        if(count($rscheknew)>0)
        {

             $nik=json_encode($rscheknew);
            echo "{\"status\" : \"200\" ,\"responce\" : \"201\", \"message\" : \"Get Record\",\"feed\":".str_replace("<p>","",$nik). "}";
        }
        else
        {
            $row2="No Record Found";
            $nik1=json_encode($row2);
            echo "{\"status\" : \"202\",  \"responce\" : \"604\",\"message\" : \"No Record Found \",\"feed\":".str_replace("<p>","",$nik1). "}";
        }
    }
    else
    {
        $row2="Invlid User";
        $nik1=json_encode($row2);
        echo "{\"status\" : \"404\", \"responce\" : \"602\",\"message\" : \"Invlid User \",\"feed\":".str_replace("<p>","",$nik1). "}";
    }

 ?>

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

I am late, hope it will help someone ....This is a known issue with IIS 8.0

The solution is to delete the 3.x module and handler from IIS manager. You could delete them at the application or site level if you want to keep them in applicationHost.config. But I wanted to delete them from applicationHost.config. do the following steps:

In IIS manager, click the machine name node. In “Features View”, double-click “Modules”. Find “ServiceModel” and remove it. Image 1 for Solve IIS 8 Error: Could not load type ‘System.ServiceModel.Activation.HttpModule’

Go back to the machine name node’s “Features View”, double-click “Handler Mappings”. Find “svc-Integrated” and remove it. Image 2 for Solve IIS 8 Error: Could not load type ‘System.ServiceModel.Activation.HttpModule’

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

Simplest way is definitely to enter the following command in the terminal:

sudo gem update --system

You can add the flag --no-document if you do not want to download the documentation. Here is sample output after running the command:

sudo gem update --system
Password:
Updating rubygems-update
Fetching: rubygems-update-2.6.8.gem (100%)
Successfully installed rubygems-update-2.6.8
Parsing documentation for rubygems-update-2.6.8
Installing ri documentation for rubygems-update-2.6.8
Installing darkfish documentation for rubygems-update-2.6.8
Installing RubyGems 2.6.8
RubyGems 2.6.8 installed
Parsing documentation for rubygems-2.6.8
Installing ri documentation for rubygems-2.6.8

------------------------------------------------------------------------------

RubyGems installed the following executables:
    /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/gem

Ruby Interactive (ri) documentation was installed. ri is kind of like man 
pages for ruby libraries. You may access it like this:
  ri Classname
  ri Classname.class_method
  ri Classname#instance_method

Group query results by month and year in postgresql

There is another way to achieve the result using the date_part() function in postgres.

 SELECT date_part('month', txn_date) AS txn_month, date_part('year', txn_date) AS txn_year, sum(amount) as monthly_sum
     FROM yourtable
 GROUP BY date_part('month', txn_date)

Thanks

Where does R store packages?

You do not want the '='

Use .libPaths("C:/R/library") in you Rprofile.site file

And make sure you have correct " symbol (Shift-2)

DIV table colspan: how?

I've achieved this by separating them in different , e.g.:

<div class="table">
  <div class="row">
    <div class="col">TD</div>
    <div class="col">TD</div>
    <div class="col">TD</div>
    <div class="col">TD</div>
    <div class="col">TD</div>
  </div>
</div>
<div class="table">
  <div class="row">
    <div class="col">TD</div>
  </div>
</div>

or you can define different classes for each tables

<div class="table2">
  <div class="row2">
    <div class="col2">TD</div>
  </div>
</div>

From the user point of view they behave identically.

Granted it doesn't solve all colspan/rowspan problems but it does answer my need of the time.

Using a Python subprocess call to invoke a Python script

Check out this.

from subprocess import call 
with open('directory_of_logfile/logfile.txt', 'w') as f:
   call(['python', 'directory_of_called_python_file/called_python_file.py'], stdout=f)

How to nicely format floating numbers to string without unnecessary decimal 0's

My two cents:

if(n % 1 == 0) {
    return String.format(Locale.US, "%.0f", n));
} else {
    return String.format(Locale.US, "%.1f", n));
}

how to load url into div tag

$(document).ready(function() {
 $('#content').load('your_url_here');
});

C# LINQ select from list

Execute the GetEventIdsByEventDate() method and save the results in a variable, and then you can use the .Contains() method

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

Only to supplement. If you need to pass a variable and iterate it, you can do just like so:

function start(counter){
  if(counter < 10){
    setTimeout(function(){
      counter++;
      console.log(counter);
      start(counter);
    }, 1000);
  }
}
start(0);

Output:

1
2
3
...
9
10

One line per second.

How to create an empty file with Ansible?

Building on the accepted answer, if you want the file to be checked for permissions on every run, and these changed accordingly if the file exists, or just create the file if it doesn't exist, you can use the following:

- stat: path=/etc/nologin
  register: p

- name: create fake 'nologin' shell
  file: path=/etc/nologin 
        owner=root
        group=sys
        mode=0555
        state={{ "file" if  p.stat.exists else "touch"}}

What's the difference between .bashrc, .bash_profile, and .environment?

That's simple. It's explained in man bash:

/bin/bash
       The bash executable
/etc/profile
       The systemwide initialization file, executed for login shells
~/.bash_profile
       The personal initialization file, executed for login shells
~/.bashrc
       The individual per-interactive-shell startup file
~/.bash_logout
       The individual login shell cleanup file, executed when a login shell exits
~/.inputrc
       Individual readline initialization file

Login shells are the ones that are read one you login (so, they are not executed when merely starting up xterm, for example). There are other ways to login. For example using an X display manager. Those have other ways to read and export environment variables at login time.

Also read the INVOCATION chapter in the manual. It says "The following paragraphs describe how bash executes its startup files.", i think that's a spot-on :) It explains what an "interactive" shell is too.

Bash does not know about .environment. I suspect that's a file of your distribution, to set environment variables independent of the shell that you drive.

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

Uninstall your application from the emulator or device. Run the app again. (OnCreate() is not executed when the database already exists)

How to find sum of multiple columns in a table in SQL Server 2005?

Try this:

select sum(num_tax_amount+num_total_amount) from table_name;

Add to Array jQuery

For JavaScript arrays, you use Both push() and concat() function.

var array = [1, 2, 3];
array.push(4, 5);         //use push for appending a single array.




var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

var array3 = array1.concat(array2);   //It is better use concat for appending more then one array.

How to check if field is null or empty in MySQL?

Try using nullif:

SELECT ifnull(nullif(field1,''),'empty') AS field1
  FROM tablename;

Why does Python code use len() function instead of a length method?

Jim's answer to this question may help; I copy it here. Quoting Guido van Rossum:

First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much later). There are two intertwined reasons actually, both HCI:

(a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into xa + xb to the clumsiness of doing the same thing using a raw OO notation.

(b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method.

Saying the same thing in another way, I see ‘len‘ as a built-in operation. I’d hate to lose that. /…/

Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

For certain html fragments like <td>test</td>, div.innerHTML, DOMParser.parseFromString and range.createContextualFragment (without the right context) solutions mentioned in other answers here, won't create the <td> element.

jQuery.parseHTML() handles them properly (I extracted jQuery 2's parseHTML function into an independent function that can be used in non-jquery codebases).

If you are only supporting Edge 13+, it is simpler to just use the HTML5 template tag:

function parseHTML(html) {
    var t = document.createElement('template');
    t.innerHTML = html;
    return t.content.cloneNode(true);
}

var documentFragment = parseHTML('<td>Test</td>');

Key Listeners in python?

Here's how can do it on Windows:

"""

    Display series of numbers in infinite loop
    Listen to key "s" to stop
    Only works on Windows because listening to keys
    is platform dependent

"""

# msvcrt is a windows specific native module
import msvcrt
import time

# asks whether a key has been acquired
def kbfunc():
    #this is boolean for whether the keyboard has bene hit
    x = msvcrt.kbhit()
    if x:
        #getch acquires the character encoded in binary ASCII
        ret = msvcrt.getch()
    else:
        ret = False
    return ret

#begin the counter
number = 1

#infinite loop
while True:

    #acquire the keyboard hit if exists
    x = kbfunc() 

    #if we got a keyboard hit
    if x != False and x.decode() == 's':
        #we got the key!
        #because x is a binary, we need to decode to string
        #use the decode() which is part of the binary object
        #by default, decodes via utf8
        #concatenation auto adds a space in between
        print ("STOPPING, KEY:", x.decode())
        #break loop
        break
    else:
        #prints the number
        print (number)
        #increment, there's no ++ in python
        number += 1
        #wait half a second
        time.sleep(0.5)

How do you read from stdin?

Building on all the anwers using sys.stdin, you can also do something like the following to read from an argument file if at least one argument exists, and fall back to stdin otherwise:

import sys
f = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin    
for line in f:
#     Do your stuff

and use it as either

$ python do-my-stuff.py infile.txt

or

$ cat infile.txt | python do-my-stuff.py

or even

$ python do-my-stuff.py < infile.txt

That would make your Python script behave like many GNU/Unix programs such as cat, grep and sed.

How to convert C# nullable int to int

GetValueOrDefault()

retrieves the value of the object. If it is null, it returns the default value of int , which is 0.

Example:

v2= v1.GetValueOrDefault();

How to convert JSON string to array

Use json_decode($json_string, TRUE) function to convert the JSON object to an array.

Example:

$json_string   = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

$my_array_data = json_decode($json_string, TRUE);

NOTE: The second parameter will convert decoded JSON string into an associative array.

===========

Output:

var_dump($my_array_data);

array(5) {

    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

What is the best java image processing library/approach?

imo the best approach is using GraphicsMagick Image Processing System with im4java as a comand-line interface for Java.

There are a lot of advantages of GraphicsMagick, but one for all:

  • GM is used to process billions of files at the world's largest photo sites (e.g. Flickr and Etsy).

What is a superfast way to read large files line-by-line in VBA?

'you can modify above and read full file in one go and then display each line as shown below

Option Explicit

Public Function QuickRead(FName As String) As Variant
    Dim i As Integer
    Dim res As String
    Dim l As Long
    Dim v As Variant

    i = FreeFile
    l = FileLen(FName)
    res = Space(l)
    Open FName For Binary Access Read As #i
    Get #i, , res
    Close i
    'split the file with vbcrlf
    QuickRead = Split(res, vbCrLf)
End Function

Sub Test()
    ' you can replace file for "c:\writename.txt to any file name you desire
    Dim strFilePathName As String: strFilePathName = "C:\writename.txt"
    Dim strFileLine As String
    Dim v As Variant
    Dim i As Long
    v = QuickRead(strFilePathName)
    For i = 0 To UBound(v)
        MsgBox v(i)
    Next
End Sub

Create space at the beginning of a UITextField

Such margin can be achieved by setting leftView / rightView to UITextField.

Updated For Swift 4

// Create a padding view for padding on left
textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: textField.frame.height))
textField.leftViewMode = .always

// Create a padding view for padding on right
textField.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: textField.frame.height))
textField.rightViewMode = .always

I just added/placed an UIView to left and right side of the textfield. So now the typing will start after the view.

Thanks

Hope this helped...

Getting GET "?" variable in laravel

I haven't tested on other Laravel versions but on 5.3-5.8 you reference the query parameter as if it were a member of the Request class.

1. Url

http://example.com/path?page=2

2. In a route callback or controller action using magic method Request::__get()

Route::get('/path', function(Request $request){
 dd($request->page);
}); 

//or in your controller
public function foo(Request $request){
 dd($request->page);
}

//NOTE: If you are wondering where the request instance is coming from, Laravel automatically injects the request instance from the IOC container
//output
"2"

3. Default values

We can also pass in a default value which is returned if a parameter doesn't exist. It's much cleaner than a ternary expression that you'd normally use with the request globals

   //wrong way to do it in Laravel
   $page = isset($_POST['page']) ? $_POST['page'] : 1; 

   //do this instead
   $request->get('page', 1);

   //returns page 1 if there is no page
   //NOTE: This behaves like $_REQUEST array. It looks in both the
   //request body and the query string
   $request->input('page', 1);

4. Using request function

$page = request('page', 1);
//returns page 1 if there is no page parameter in the query  string
//it is the equivalent of
$page = 1; 
if(!empty($_GET['page'])
   $page = $_GET['page'];

The default parameter is optional therefore one can omit it

5. Using Request::query()

While the input method retrieves values from entire request payload (including the query string), the query method will only retrieve values from the query string

//this is the equivalent of retrieving the parameter
//from the $_GET global array
$page = $request->query('page');

//with a default
$page = $request->query('page', 1);

6. Using the Request facade

$page = Request::get('page');

//with a default value
$page = Request::get('page', 1);

You can read more in the official documentation https://laravel.com/docs/5.8/requests

Is there a way to avoid null check before the for-each loop iteration starts?

How much shorter do you want it to be? It is only an extra 2 lines AND it is clear and concise logic.

I think the more important thing you need to decide is if null is a valid value or not. If they are not valid, you should write you code to prevent it from happening. Then you would not need this kind of check. If you go get an exception while doing a foreach loop, that is a sign that there is a bug somewhere else in your code.

Django DB Settings 'Improperly Configured' Error

On Django 1.9, I tried django-admin runserver and got the same error, but when I used python manage.py runserver I got the intended result. This may solve this error for a lot of people!

Android: java.lang.SecurityException: Permission Denial: start Intent

I solved this exception by changing the target sdk version from 19 onwards kitkat version AndroidManifest.xml.

<uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

MongoDB distinct aggregation

Distinct and the aggregation framework are not inter-operable.

Instead you just want:

db.zips.aggregate([ 
    {$group:{_id:{city:'$city', state:'$state'}, numberOfzipcodes:{$sum:1}}}, 
    {$sort:{numberOfzipcodes:-1}},
    {$group:{_id:'$_id.state', city:{$first:'$_id.city'}, 
              numberOfzipcode:{$first:'$numberOfzipcodes'}}}
]);

How do you run CMD.exe under the Local System Account?

Using task scheduler, schedule a run of CMDKEY running under SYSTEM with the appropriate arguments of /add: /user: and /pass:

No need to install anything.

What are .a and .so files?

.a are static libraries. If you use code stored inside them, it's taken from them and embedded into your own binary. In Visual Studio, these would be .lib files.

.so are dynamic libraries. If you use code stored inside them, it's not taken and embedded into your own binary. Instead it's just referenced, so the binary will depend on them and the code from the so file is added/loaded at runtime. In Visual Studio/Windows these would be .dll files (with small .lib files containing linking information).

How do I import a .bak file into Microsoft SQL Server 2012?

You can use the following script if you don't wish to use Wizard;

RESTORE DATABASE myDB
FROM  DISK = N'C:\BackupDB.bak' 
WITH  REPLACE,RECOVERY,  
MOVE N'HRNET' TO N'C:\MSSQL\Data\myDB.mdf',  
MOVE N'HRNET_LOG' TO N'C:\MSSQL\Data\myDB.ldf'

How to append rows in a pandas dataframe in a for loop?

A more compact and efficient way would be perhaps:

cols = ['frame', 'count']
N = 4
dat = pd.DataFrame(columns = cols)
for i in range(N):

    dat = dat.append({'frame': str(i), 'count':i},ignore_index=True)

output would be:

>>> dat
   frame count
0     0     0
1     1     1
2     2     2
3     3     3

How can I clear event subscriptions in C#?

class c1
{
    event EventHandler someEvent;
    ResetSubscriptions() => someEvent = delegate { };
}

It is better to use delegate { } than null to avoid the null ref exception.

Difference between HashMap and Map in Java..?

Map<K,V> is an interface, HashMap<K,V> is a class that implements Map.

you can do

Map<Key,Value> map = new HashMap<Key,Value>();

Here you have a link to the documentation of each one: Map, HashMap.

Could not autowire field:RestTemplate in Spring boot application

The simplest way I was able to achieve a similar feat to use the code below (reference), but I would suggest not to make API calls in controllers(SOLID principles). Also autowiring this way is better optimsed than the traditional way of doing it.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class TestController {

    private final RestTemplate restTemplate;


    @Autowired
    public TestController(RestTemplateBuilder builder) {
        this.restTemplate = builder.build();
    }

    @RequestMapping(value="/micro/order/{id}", method= RequestMethod.GET, produces= MediaType.ALL_VALUE)
    public String placeOrder(@PathVariable("id") int customerId){

        System.out.println("Hit ===> PlaceOrder");

        Object[] customerJson = restTemplate.getForObject("http://localhost:8080/micro/customers", Object[].class);

        System.out.println(customerJson.toString());

        return "false";
    }
}

What is a "static" function in C?

Minimal runnable multi-file scope example

Here I illustrate how static affects the scope of function definitions across multiple files.

a.c

#include <stdio.h>

/* Undefined behavior: already defined in main.
 * Binutils 2.24 gives an error and refuses to link.
 * https://stackoverflow.com/questions/27667277/why-does-borland-compile-with-multiple-definitions-of-same-object-in-different-c
 */
/*void f() { puts("a f"); }*/

/* OK: only declared, not defined. Will use the one in main. */
void f(void);

/* OK: only visible to this file. */
static void sf() { puts("a sf"); }

void a() {
    f();
    sf();
}

main.c

#include <stdio.h>

void a(void);        

void f() { puts("main f"); }

static void sf() { puts("main sf"); }

void m() {
    f();
    sf();
}

int main() {
    m();
    a();
    return 0;
}

GitHub upstream.

Compile and run:

gcc -c a.c -o a.o
gcc -c main.c -o main.o
gcc -o main main.o a.o
./main

Output:

main f
main sf
main f
a sf

Interpretation

  • there are two separate functions sf, one for each file
  • there is a single shared function f

As usual, the smaller the scope, the better, so always declare functions static if you can.

In C programming, files are often used to represent "classes", and static functions represent "private" methods of the class.

A common C pattern is to pass a this struct around as the first "method" argument, which is basically what C++ does under the hood.

What standards say about it

C99 N1256 draft 6.7.1 "Storage-class specifiers" says that static is a "storage-class specifier".

6.2.2/3 "Linkages of identifiers" says static implies internal linkage:

If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.

and 6.2.2/2 says that internal linkage behaves like in our example:

In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function.

where "translation unit" is a source file after preprocessing.

How GCC implements it for ELF (Linux)?

With the STB_LOCAL binding.

If we compile:

int f() { return 0; }
static int sf() { return 0; }

and disassemble the symbol table with:

readelf -s main.o

the output contains:

Num:    Value          Size Type    Bind   Vis      Ndx Name
  5: 000000000000000b    11 FUNC    LOCAL  DEFAULT    1 sf
  9: 0000000000000000    11 FUNC    GLOBAL DEFAULT    1 f

so the binding is the only significant difference between them. Value is just their offset into the .bss section, so we expect it to differ.

STB_LOCAL is documented on the ELF spec at http://www.sco.com/developers/gabi/2003-12-17/ch4.symtab.html:

STB_LOCAL Local symbols are not visible outside the object file containing their definition. Local symbols of the same name may exist in multiple files without interfering with each other

which makes it a perfect choice to represent static.

Functions without static are STB_GLOBAL, and the spec says:

When the link editor combines several relocatable object files, it does not allow multiple definitions of STB_GLOBAL symbols with the same name.

which is coherent with the link errors on multiple non static definitions.

If we crank up the optimization with -O3, the sf symbol is removed entirely from the symbol table: it cannot be used from outside anyways. TODO why keep static functions on the symbol table at all when there is no optimization? Can they be used for anything?

See also

C++ anonymous namespaces

In C++, you might want to use anonymous namespaces instead of static, which achieves a similar effect, but further hides type definitions: Unnamed/anonymous namespaces vs. static functions

Set ImageView width and height programmatically?

The best and easiest way to set a button dynamically is

 Button index=new Button(this);
 int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, getResources().getDisplayMetrics());             
 int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 42, getResources().getDisplayMetrics());

The above height and width are in pixels px. 45 being the height in dp and 42 being the width in dp.

 index.setLayoutParams(new <Parent>.LayoutParams(width, height));

So, for example, if you've placed your button within a TableRow within a TableLayout, you should have it as TableRow.LayoutParams

 index.setLayoutParams(new TableRow.LayoutParams(width, height));

POST data in JSON format

Here is an example using jQuery...

 <head>
   <title>Test</title>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
   <script type="text/javascript" src="http://www.json.org/json2.js"></script>
   <script type="text/javascript">
     $(function() {
       var frm = $(document.myform);
       var dat = JSON.stringify(frm.serializeArray());

       alert("I am about to POST this:\n\n" + dat);

       $.post(
         frm.attr("action"),
         dat,
         function(data) {
           alert("Response: " + data);
         }
       );
     });
   </script>
</head>

The jQuery serializeArray function creates a Javascript object with the form values. Then you can use JSON.stringify to convert that into a string, if needed. And you can remove your body onload, too.

Do HTTP POST methods send data as a QueryString?

If your post try to reach the following URL

mypage.php?id=1

you will have the POST data but also GET data.

How to quickly and conveniently disable all console.log statements in my code?

I think that the easiest and most understandable method in 2020 is to just create a global function like log() and you can pick one of the following methods:

const debugging = true;

function log(toLog) {
  if (debugging) {
    console.log(toLog);
  }
}
function log(toLog) {
  if (true) { // You could manually change it (Annoying, though)
    console.log(toLog);
  }
}

You could say that the downside of these features is that:

  1. You are still calling the functions on runtime
  2. You have to remember to change the debugging variable or the if statement in the second option
  3. You need to make sure you have the function loaded before all of your other files

And my retorts to these statements is that this is the only method that won't completely remove the console or console.log function which I think is bad programming because other developers who are working on the website would have to realize that you ignorantly removed them. Also, you can't edit JavaScript source code in JavaScript, so if you really want something to just wipe all of those from the code you could use a minifier that minifies your code and removes all console.logs. Now, the choice is yours, what will you do?

Get all photos from Instagram which have a specific hashtag with PHP

Since Nov 17, 2015 you have to authenticate users to make any (even such as "get some pictures who have specific hashtag") requests. See the Instagram Platform Changelog:

Apps created on or after Nov 17, 2015: All API endpoints require a valid access_token. Apps created before Nov 17, 2015: Unaffected by new API behavior until June 1, 2016.

this makes now all answers given here before June 1, 2016 no longer useful.

Why should I use a container div in HTML?

Most of the browser are taking web page size by default. So, sometime page will not display same in different browser. So, by using user can change for specific HTML element. For example, user can add margin, size, width, height etc of specific HTML tag.

How to access host port from docker container

For docker-compose using bridge networking to create a private network between containers, the accepted solution using docker0 doesn't work because the egress interface from the containers is not docker0, but instead, it's a randomly generated interface id, such as:

$ ifconfig

br-02d7f5ba5a51: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.32.1  netmask 255.255.240.0  broadcast 192.168.47.255

Unfortunately that random id is not predictable and will change each time compose has to recreate the network (e.g. on a host reboot). My solution to this is to create the private network in a known subnet and configure iptables to accept that range:

Compose file snippet:

version: "3.7"

services:
  mongodb:
    image: mongo:4.2.2
    networks:
    - mynet
    # rest of service config and other services removed for clarity

networks:
  mynet:
    name: mynet
    ipam:
      driver: default
      config:
      - subnet: "192.168.32.0/20"

You can change the subnet if your environment requires it. I arbitrarily selected 192.168.32.0/20 by using docker network inspect to see what was being created by default.

Configure iptables on the host to permit the private subnet as a source:

$ iptables -I INPUT 1 -s 192.168.32.0/20 -j ACCEPT

This is the simplest possible iptables rule. You may wish to add other restrictions, for example by destination port. Don't forget to persist your iptables rules when you're happy they're working.

This approach has the advantage of being repeatable and therefore automatable. I use ansible's template module to deploy my compose file with variable substitution and then use the iptables and shell modules to configure and persist the firewall rules, respectively.

how to get current datetime in SQL?

I always just use NOW():

INSERT INTO table (lastModifiedTime) VALUES (NOW())

http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_now

Error message Strict standards: Non-static method should not be called statically in php

Your methods are missing the static keyword. Change

function getInstanceByName($name=''){

to

public static function getInstanceByName($name=''){

if you want to call them statically.

Note that static methods (and Singletons) are death to testability.

Also note that you are doing way too much work in the constructor, especially all that querying shouldn't be in there. All your constructor is supposed to do is set the object into a valid state. If you have to have data from outside the class to do that consider injecting it instead of pulling it. Also note that constructors cannot return anything. They will always return void so all these return false statements do nothing but end the construction.

Using the Underscore module with Node.js

Or :

    var _ = require('underscore')._;

Maintaining href "open in new tab" with an onClick handler in React

Most Secure Solution, JS only

As mentioned by alko989, there is a major security flaw with _blank (details here).

To avoid it from pure JS code:

const openInNewTab = (url) => {
  const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
  if (newWindow) newWindow.opener = null
}

Then add to your onClick

onClick={() => openInNewTab('https://stackoverflow.com')}

The third param can also take these optional values, based on your needs.

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

A primary key is a column (or columns) in a table that uniquely identifies the rows in that table.

CUSTOMERS


CustomerNo  FirstName   LastName
1   Sally   Thompson
2   Sally   Henderson
3   Harry   Henderson
4   Sandra  Wellington

For example, in the table above, CustomerNo is the primary key.

The values placed in primary key columns must be unique for each row: no duplicates can be tolerated. In addition, nulls are not allowed in primary key columns.

So, having told you that it is possible to use one or more columns as a primary key, how do you decide which columns (and how many) to choose?

Well there are times when it is advisable or essential to use multiple columns. However, if you cannot see an immediate reason to use multiple columns, then use one. This isn't an absolute rule, it is simply advice. However, primary keys made up of single columns are generally easier to maintain and faster in operation. This means that if you query the database, you will usually get the answer back faster if the tables have single column primary keys.

Next question — which column should you pick? The easiest way to choose a column as a primary key (and a method that is reasonably commonly employed) is to get the database itself to automatically allocate a unique number to each row.

In a table of employees, clearly any column like FirstName is a poor choice since you cannot control employee's first names. Often there is only one choice for the primary key, as in the case above. However, if there is more than one, these can be described as 'candidate keys' — the name reflects that they are candidates for the responsible job of primary key.

How to install Intellij IDEA on Ubuntu?

You can also try my ubuntu repository: https://launchpad.net/~mmk2410/+archive/ubuntu/intellij-idea

To use it just run the following commands:

sudo apt-add-repository ppa:mmk2410/intellij-idea
sudo apt-get update

The community edition can then installed with

sudo apt-get install intellij-idea-community

and the ultimate edition with

sudo apt-get install intellij-idea-ultimate

HTML5 Canvas Rotate Image

Quickest 2D context image rotation method

A general purpose image rotation, position, and scale.

// no need to use save and restore between calls as it sets the transform rather 
// than multiply it like ctx.rotate ctx.translate ctx.scale and ctx.transform
// Also combining the scale and origin into the one call makes it quicker
// x,y position of image center
// scale scale of image
// rotation in radians.
function drawImage(image, x, y, scale, rotation){
    ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin
    ctx.rotate(rotation);
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
} 

If you wish to control the rotation point use the next function

// same as above but cx and cy are the location of the point of rotation
// in image pixel coordinates
function drawImageCenter(image, x, y, cx, cy, scale, rotation){
    ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin
    ctx.rotate(rotation);
    ctx.drawImage(image, -cx, -cy);
} 

To reset the 2D context transform

ctx.setTransform(1,0,0,1,0,0); // which is much quicker than save and restore

Thus to rotate image to the left (anti clockwise) 90 deg

drawImage(image, canvas.width / 2, canvas.height / 2, 1, - Math.PI / 2);

Thus to rotate image to the right (clockwise) 90 deg

drawImage(image, canvas.width / 2, canvas.height / 2, 1, Math.PI / 2);

Example draw 500 images translated rotated scaled

_x000D_
_x000D_
var image = new Image;_x000D_
image.src = "https://i.stack.imgur.com/C7qq2.png?s=328&g=1";_x000D_
var canvas = document.createElement("canvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
canvas.style.position = "absolute";_x000D_
canvas.style.top = "0px";_x000D_
canvas.style.left = "0px";_x000D_
document.body.appendChild(canvas);_x000D_
var w,h;_x000D_
function resize(){ w = canvas.width = innerWidth; h = canvas.height = innerHeight;}_x000D_
resize();_x000D_
window.addEventListener("resize",resize);_x000D_
function rand(min,max){return Math.random() * (max ?(max-min) : min) + (max ? min : 0) }_x000D_
function DO(count,callback){ while (count--) { callback(count) } }_x000D_
const sprites = [];_x000D_
DO(500,()=>{_x000D_
    sprites.push({_x000D_
       x : rand(w), y : rand(h),_x000D_
       xr : 0, yr : 0, // actual position of sprite_x000D_
       r : rand(Math.PI * 2),_x000D_
       scale : rand(0.1,0.25),_x000D_
       dx : rand(-2,2), dy : rand(-2,2),_x000D_
       dr : rand(-0.2,0.2),_x000D_
    });_x000D_
});_x000D_
function drawImage(image, spr){_x000D_
    ctx.setTransform(spr.scale, 0, 0, spr.scale, spr.xr, spr.yr); // sets scales and origin_x000D_
    ctx.rotate(spr.r);_x000D_
    ctx.drawImage(image, -image.width / 2, -image.height / 2);_x000D_
}_x000D_
function update(){_x000D_
    var ihM,iwM;_x000D_
    ctx.setTransform(1,0,0,1,0,0);_x000D_
    ctx.clearRect(0,0,w,h);_x000D_
    if(image.complete){_x000D_
      var iw = image.width;_x000D_
      var ih = image.height;_x000D_
      for(var i = 0; i < sprites.length; i ++){_x000D_
          var spr = sprites[i];_x000D_
          spr.x += spr.dx;_x000D_
          spr.y += spr.dy;_x000D_
          spr.r += spr.dr;_x000D_
          iwM = iw * spr.scale * 2 + w;_x000D_
          ihM = ih * spr.scale * 2 + h;_x000D_
          spr.xr = ((spr.x % iwM) + iwM) % iwM - iw * spr.scale;_x000D_
          spr.yr = ((spr.y % ihM) + ihM) % ihM - ih * spr.scale;_x000D_
          drawImage(image,spr);_x000D_
      }_x000D_
    }    _x000D_
    requestAnimationFrame(update);_x000D_
}_x000D_
requestAnimationFrame(update);
_x000D_
_x000D_
_x000D_

How to create a css rule for all elements except one class?

Wouldn't setting a css rule for all tables, and then a subsequent one for tables where class="dojoxGrid" work? Or am I missing something?

What does "./" (dot slash) refer to in terms of an HTML file path location?

You are correct that you can omit it. It's useful only for clarity. There is no functional difference between it being there and not being there.

How to style the parent element when hovering a child element?

there is no CSS selector for selecting a parent of a selected child.

you could do it with JavaScript

How to set a variable inside a loop for /F

set list = a1-2019 a3-2018 a4-2017
setlocal enabledelayedexpansion
set backup=
set bb1=

for /d %%d in (%list%) do (
   set td=%%d
   set x=!td!
   set y=!td!
   set y=!y:~-4!
   if !y! gtr !bb1! (
     set bb1=!y!
     set backup=!x!
   )
)

rem: backup will be 2019
echo %backup% 

Matplotlib scatter plot with different text at each data point

For limited set of values matplotlib is fine. But when you have lots of values the tooltip starts to overlap over other data points. But with limited space you can't ignore the values. Hence it's better to zoom out or zoom in.

Using plotly

import plotly.express as px
df = px.data.tips()

df = px.data.gapminder().query("year==2007 and continent=='Americas'")


fig = px.scatter(df, x="gdpPercap", y="lifeExp", text="country", log_x=True, size_max=100, color="lifeExp")
fig.update_traces(textposition='top center')
fig.update_layout(title_text='Life Expectency', title_x=0.5)
fig.show()

enter image description here

What key shortcuts are to comment and uncomment code?

Keyboard accelerators are configurable. You can find out which keyboard accelerators are bound to a command in Tools -> Options on the Environment -> Keyboard page.

These commands are named Edit.CommentSelection and Edit.UncommentSelection.

(With my settings, these are bound to Ctrl+K, Ctrl+C and Ctrl+K, Ctrl+U. I would guess that these are the defaults, at least in the C++ defaults, but I don't know for sure. The best way to find out is to check your settings.)

Linq Select Group By

    from p in PriceLog
    group p by p.LogDateTime.ToString("MMM") into g
    select new 
    { 
        LogDate = g.Key.ToString("MMM yyyy"),
        GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), 
        SilverPrice = (int)dateGroup.Average(p => p.SilverPrice) 
    }

How to get text in QlineEdit when QpushButton is pressed in a string?

The object name is not very important. what you should be focusing at is the variable that stores the lineedit object (le) and your pushbutton object(pb)

QObject(self.pb, SIGNAL("clicked()"), self.button_clicked)

def button_clicked(self):
  self.le.setText("shost")

I think this is what you want. I hope i got your question correctly :)

What is the difference between MOV and LEA?

None of the previous answers quite got to the bottom of my own confusion, so I'd like to add my own.

What I was missing is that lea operations treat the use of parentheses different than how mov does.

Think of C. Let's say I have an array of long that I call array. Now the expression array[i] performs a dereference, loading the value from memory at the address array + i * sizeof(long) [1].

On the other hand, consider the expression &array[i]. This still contains the sub-expression array[i], but no dereferencing is performed! The meaning of array[i] has changed. It no longer means to perform a deference but instead acts as a kind of a specification, telling & what memory address we're looking for. If you like, you could alternatively think of the & as "cancelling out" the dereference.

Because the two use-cases are similar in many ways, they share the syntax array[i], but the existence or absence of a & changes how that syntax is interpreted. Without &, it's a dereference and actually reads from the array. With &, it's not. The value array + i * sizeof(long) is still calculated, but it is not dereferenced.

The situation is very similar with mov and lea. With mov, a dereference occurs that does not happen with lea. This is despite the use of parentheses that occurs in both. For instance, movq (%r8), %r9 and leaq (%r8), %r9. With mov, these parentheses mean "dereference"; with lea, they don't. This is similar to how array[i] only means "dereference" when there is no &.

An example is in order.

Consider the code

movq (%rdi, %rsi, 8), %rbp

This loads the value at the memory location %rdi + %rsi * 8 into the register %rbp. That is: get the value in the register %rdi and the value in the register %rsi. Multiply the latter by 8, and then add it to the former. Find the value at this location and place it into the register %rbp.

This code corresponds to the C line x = array[i];, where array becomes %rdi and i becomes %rsi and x becomes %rbp. The 8 is the length of the data type contained in the array.

Now consider similar code that uses lea:

leaq (%rdi, %rsi, 8), %rbp

Just as the use of movq corresponded to dereferencing, the use of leaq here corresponds to not dereferencing. This line of assembly corresponds to the C line x = &array[i];. Recall that & changes the meaning of array[i] from dereferencing to simply specifying a location. Likewise, the use of leaq changes the meaning of (%rdi, %rsi, 8) from dereferencing to specifying a location.

The semantics of this line of code are as follows: get the value in the register %rdi and the value in the register %rsi. Multiply the latter by 8, and then add it to the former. Place this value into the register %rbp. No load from memory is involved, just arithmetic operations [2].

Note that the only difference between my descriptions of leaq and movq is that movq does a dereference, and leaq doesn't. In fact, to write the leaq description, I basically copy+pasted the description of movq, and then removed "Find the value at this location".

To summarize: movq vs. leaq is tricky because they treat the use of parentheses, as in (%rsi) and (%rdi, %rsi, 8), differently. In movq (and all other instruction except lea), these parentheses denote a genuine dereference, whereas in leaq they do not and are purely convenient syntax.


[1] I've said that when array is an array of long, the expression array[i] loads the value from the address array + i * sizeof(long). This is true, but there's a subtlety that should be addressed. If I write the C code

long x = array[5];

this is not the same as typing

long x = *(array + 5 * sizeof(long));

It seems that it should be based on my previous statements, but it's not.

What's going on is that C pointer addition has a trick to it. Say I have a pointer p pointing to values of type T. The expression p + i does not mean "the position at p plus i bytes". Instead, the expression p + i actually means "the position at p plus i * sizeof(T) bytes".

The convenience of this is that to get "the next value" we just have to write p + 1 instead of p + 1 * sizeof(T).

This means that the C code long x = array[5]; is actually equivalent to

long x = *(array + 5)

because C will automatically multiply the 5 by sizeof(long).

So in the context of this StackOverflow question, how is this all relevant? It means that when I say "the address array + i * sizeof(long)", I do not mean for "array + i * sizeof(long)" to be interpreted as a C expression. I am doing the multiplication by sizeof(long) myself in order to make my answer more explicit, but understand that due to that, this expression should not be read as C. Just as normal math that uses C syntax.

[2] Side note: because all lea does is arithmetic operations, its arguments don't actually have to refer to valid addresses. For this reason, it's often used to perform pure arithmetic on values that may not be intended to be dereferenced. For instance, cc with -O2 optimization translates

long f(long x) {
  return x * 5;
}

into the following (irrelevant lines removed):

f:
  leaq (%rdi, %rdi, 4), %rax  # set %rax to %rdi + %rdi * 4
  ret

Simple file write function in C++

The function declaration int writeFile () ; seems to be missing in the code. Add int writeFile () ; before the function main()

How to change the Title of the window in Qt?

I know this is years later but I ran into the same problem. The solution I found was to change the window title in main.cpp. I guess once the w.show(); is called the window title can no longer be changed. In my case I just wanted the title to reflect the current directory and it works.

int main(int argc, char *argv[]) 
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle(QDir::currentPath());
w.show();

return a.exec();
}

Redirect pages in JSP?

This answer also contains a standard solution using only the jstl redirect tag:

<c:redirect url="/home.html"/>

What is the best way to add a value to an array in state

For functional components with hooks

const [searches, setSearches] = useState([]);

// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query));

// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query));

// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query]);

// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query]);

source: https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

To Enable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);

To Disable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);

Note: To access with WiFi state, we have to add following permissions inside the AndroidManifest.xml file:

android.permission.ACCESS_WIFI_STATE
android.permission.UPDATE_DEVICE_STATS 
android.permission.CHANGE_WIFI_STATE

Git copy file preserving history

All you have to do is:

  1. move the file to two different locations,
  2. merge the two commits that do the above, and
  3. move one copy back to the original location.

You will be able to see historical attributions (using git blame) and full history of changes (using git log) for both files.

Suppose you want to create a copy of file foo called bar. In that case the workflow you'd use would look like this:

git mv foo bar
git commit

SAVED=`git rev-parse HEAD`
git reset --hard HEAD^
git mv foo copy
git commit

git merge $SAVED     # This will generate conflicts
git commit -a        # Trivially resolved like this

git mv copy foo
git commit

Why this works

After you execute the above commands, you end up with a revision history that looks like this:

( revision history )            ( files )

    ORIG_HEAD                      foo
     /     \                      /   \
SAVED       ALTERNATE          bar     copy
     \     /                      \   /
      MERGED                     bar,copy
        |                           |
     RESTORED                    bar,foo

When you ask Git about the history of foo, it will:

  1. detect the rename from copy between MERGED and RESTORED,
  2. detect that copy came from the ALTERNATE parent of MERGED, and
  3. detect the rename from foo between ORIG_HEAD and ALTERNATE.

From there it will dig into the history of foo.

When you ask Git about the history of bar, it will:

  1. notice no change between MERGED and RESTORED,
  2. detect that bar came from the SAVED parent of MERGED, and
  3. detect the rename from foo between ORIG_HEAD and SAVED.

From there it will dig into the history of foo.

It's that simple. :)

You just need to force Git into a merge situation where you can accept two traceable copies of the file(s), and we do this with a parallel move of the original (which we soon revert).

C++ Loop through Map

You can achieve this like following :

map<string, int>::iterator it;

for (it = symbolTable.begin(); it != symbolTable.end(); it++)
{
    std::cout << it->first    // string (key)
              << ':'
              << it->second   // string's value 
              << std::endl;
}

With C++11 ( and onwards ),

for (auto const& x : symbolTable)
{
    std::cout << x.first  // string (key)
              << ':' 
              << x.second // string's value 
              << std::endl;
}

With C++17 ( and onwards ),

for (auto const& [key, val] : symbolTable)
{
    std::cout << key        // string (key)
              << ':'  
              << val        // string's value
              << std::endl;
}

How to test if a DataSet is empty?

It is not a valid answer as it gives following error

Cannot find table 0.

Use the following statement instead

if (ds.Tables.Count == 0)
{
     //DataSet is empty
}

Fitting a density curve to a histogram in R

Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:

> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35, 
    times = 10), rep(45, times = 4)))

$cp
    mean     s.d. skewness 
41.46228 12.47892  0.99527 

Skew-normal distributed data plot

This probably works better on data that is more skew-normal:

Another skew-normal plot

Any free WPF themes?

Here's another one for Silverlight. And a list of nice gradients to use.

Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

Update: This will create a second context same as in applicationContext.xml

or you can add this code snippet to your web.xml

<servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

instead of

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

Display PDF within web browser

I use Google Docs embeddable PDF viewer. The docs don't have to be uploaded to Google Docs, but they do have to be available online.

<iframe src="http://docs.google.com/gview?url=http://path.com/to/your/pdf.pdf&embedded=true" 
style="width:600px; height:500px;" frameborder="0"></iframe>

How can I get name of element with jQuery?

You should use attr('name') like this

 $('#yourid').attr('name')

you should use an id selector, if you use a class selector you encounter problems because a collection is returned

Bootstrap how to get text to vertical align in a div container

h2.text-left{
  position:relative;
  top:50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
}

Explanation:

The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.

Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.

A possible fix for multiple lines would be to use a percentage slightly less than 50%.

Hidden TextArea

but is the css style tag the correct way to get cross browser compatibility?

 <textarea style="display:none;" ></textarea>

or what I learned long ago....

     <textarea hidden ></textarea>

or
the global hidden element method:

    <textarea hidden="hidden" ></textarea>       

C# Remove object from list of objects

Originally I used a foreach but then realised you can't use this while modifying a collection

You can create a copy of the collection and iterate over that using ToList() to create to copy:

 foreach(Chunk chunk in ChunkList.ToList())
 {
     if (chunk.UniqueID == ChunkID)
     {
         ChunkList.Remove(chunk);
     }
 }

Escaping quotes and double quotes

Using the backtick (`) works fine for me if I put them in the following places:

$cmd="\\server\toto.exe -batch=B -param=`"sort1;parmtxt='Security ID=1234'`""

$cmd returns as:

\\server\toto.exe -batch=B -param="sort1;parmtxt='Security ID=1234'"

Is that what you were looking for?

The error PowerShell gave me referred to an unexpected token 'sort1', and that's how I determined where to put the backticks.

The @' ... '@ syntax is called a "here string" and will return exactly what is entered. You can also use them to populate variables in the following fashion:

$cmd=@'
"\\server\toto.exe -batch=B -param="sort1;parmtxt='Security ID=1234'""
'@

The opening and closing symbols must be on their own line as shown above.

Put text at bottom of div

<div id="container">
    <div><span>Two Words</span></div>
    <div><span>Two Words</span></div>
    <div><span>Two Words</span></div>
    <div><span>Two Words</span></div>
</div>

#container{
    width:450px;
    height:200px;
    margin:0px auto;
    border:1px solid red;
}

#container div{
    position:relative;
    width:100px;
    height:100px;
    border:1px solid #ccc;
    float:left;
    margin-right:5px;
}
#container div span{
    position:absolute;
    bottom:0;
    right:0;
}

Check working example at http://jsfiddle.net/7YTYu/2/

How can I use an array of function pointers?

This should be a short & simple copy & paste piece of code example of the above responses. Hopefully this helps.

#include <iostream>
using namespace std;

#define DBG_PRINT(x) do { std::printf("Line:%-4d" "  %15s = %-10d\n", __LINE__, #x, x); } while(0);

void F0(){ printf("Print F%d\n", 0); }
void F1(){ printf("Print F%d\n", 1); }
void F2(){ printf("Print F%d\n", 2); }
void F3(){ printf("Print F%d\n", 3); }
void F4(){ printf("Print F%d\n", 4); }
void (*fArrVoid[N_FUNC])() = {F0, F1, F2, F3, F4};

int Sum(int a, int b){ return(a+b); }
int Sub(int a, int b){ return(a-b); }
int Mul(int a, int b){ return(a*b); }
int Div(int a, int b){ return(a/b); }
int (*fArrArgs[4])(int a, int b) = {Sum, Sub, Mul, Div};

int main(){
    for(int i = 0; i < 5; i++)  (*fArrVoid[i])();
    printf("\n");

    DBG_PRINT((*fArrArgs[0])(3,2))
    DBG_PRINT((*fArrArgs[1])(3,2))
    DBG_PRINT((*fArrArgs[2])(3,2))
    DBG_PRINT((*fArrArgs[3])(3,2))

    return(0);
}

How do I find the MySQL my.cnf location

If you are using MAMP, access Templates > MySQL (my.cnf) > [version]

If you are running MAMP windowless you may need to customize the toolbar using the Customize button.

MAMP PRO Templates Menu

Unique constraint violation during insert: why? (Oracle)

Your error looks like you are duplicating an already existing Primary Key in your DB. You should modify your sql code to implement its own primary key by using something like the IDENTITY keyword.

CREATE TABLE [DB] (
    [DBId] bigint NOT NULL IDENTITY,
    ...

    CONSTRAINT [DB_PK] PRIMARY KEY ([DB] ASC),

); 

Chart.js canvas resize

What's happening is Chart.js multiplies the size of the canvas when it is called then attempts to scale it back down using CSS, the purpose being to provide higher resolution graphs for high-dpi devices.

The problem is it doesn't realize it has already done this, so when called successive times, it multiplies the already (doubled or whatever) size AGAIN until things start to break. (What's actually happening is it is checking whether it should add more pixels to the canvas by changing the DOM attribute for width and height, if it should, multiplying it by some factor, usually 2, then changing that, and then changing the css style attribute to maintain the same size on the page.)

For example, when you run it once and your canvas width and height are set to 300, it sets them to 600, then changes the style attribute to 300... but if you run it again, it sees that the DOM width and height are 600 (check the other answer to this question to see why) and then sets it to 1200 and the css width and height to 600.

Not the most elegant solution, but I solved this problem while maintaining the enhanced resolution for retina devices by simply setting the width and height of the canvas manually before each successive call to Chart.js

var ctx = document.getElementById("canvas").getContext("2d");
ctx.canvas.width = 300;
ctx.canvas.height = 300;
var myDoughnut = new Chart(ctx).Doughnut(doughnutData);

How to search for file names in Visual Studio?

You can press ctrl+t to get a editor Get to all , in which you can type the file name to navigate to that specific file.

What are enums and why are they useful?

Java lets you restrict variable to having one of only a few predefined values - in other words, one value from an enumerated list. Using enums can help to reduce bug's in your code. Here is an example of enums outside a class:

enums coffeesize{BIG , HUGE , OVERWHELMING }; 
//This semicolon is optional.

This restricts coffeesize to having either: BIG , HUGE , or OVERWHELMING as a variable.

How to redirect 'print' output to a file using python?

If you are using Linux I suggest you to use the tee command. The implementation goes like this:

python python_file.py | tee any_file_name.txt

If you don't want to change anything in the code, I think this might be the best possible solution. You can also implement logger but you need do some changes in the code.

Json.net serialize/deserialize derived types?

You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.

Base object1 = new Base() { Name = "Object1" };
Derived object2 = new Derived() { Something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);

This will result in correct deserialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.

Running PHP script from the command line

I was looking for a resolution to this issue in Windows, and it seems to be that if you don't have the environments vars ok, you need to put the complete directory. For eg. with a file in the same directory than PHP:

F:\myfolder\php\php.exe -f F:\myfolder\php\script.php

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

After trial and error comparing the using statements of my controller and the Asp.Net Template controller

using System.Web;

Solved the problem for me. You are also going to need to add:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

To use GetUserManager method.

Microsoft couldn't find a way to resolve this automatically with right click and resolve like other missing using statements?

get the value of input type file , and alert if empty

HTML Code

<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload"  class="send_upload" value="upload" />

jQuery Code using bind method

$(document).ready(function() {
    $('#upload').bind("click",function() 
    { if(!$('#uploadImage').val()){
                alert("empty");
                return false;} });  });

Convert textbox text to integer

int num = int.Parse(textBox.Text);

try this. It worked for me

Get the element with the highest occurrence in an array

I came up with a shorter solution, but it's using lodash. Works with any data, not just strings. For objects can be used:

const mostFrequent = _.maxBy(Object.values(_.groupBy(inputArr, el => el.someUniqueProp)), arr => arr.length)[0];

This is for strings:

const mostFrequent = _.maxBy(Object.values(_.groupBy(inputArr, el => el)), arr => arr.length)[0];

Just grouping data under a certain criteria, then finding the largest group.

How do you install an APK file in the Android emulator?

you write the command on terminal/cmd adb install FileName.apk.

How to revert a "git rm -r ."?

undo git rm

git rm file             # delete file & update index
git checkout HEAD file  # restore file & index from HEAD

undo git rm -r

git rm -r dir          # delete tracked files in dir & update index
git checkout HEAD dir  # restore file & index from HEAD

undo git rm -rf

git rm -r dir          # delete tracked files & delete uncommitted changes
not possible           # `uncommitted changes` can not be restored.

Uncommitted changes includes not staged changes, staged changes but not committed.

Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js

This error means that file was not found. Either path is wrong or file is not present where you want it to be. Try to access it by entering source address in your browser to check if it really is there. Browse the directories on server to ensure the path is correct. You may even copy and paste the relative path to be certain it is alright.

How to make Bootstrap Panel body with fixed height

HTML :

<div class="span4">
  <div class="panel panel-primary">
    <div class="panel-heading">jhdsahfjhdfhs</div>
    <div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
  </div>
</div>

CSS :

.panel-height {
  height: 100px; / change according to your requirement/
}

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

In your case, the first value to insert must be NULL, because it's AUTO_INCREMENT.

Join/Where with LINQ and Lambda

Daniel has a good explanation of the syntax relationships, but I put this document together for my team in order to make it a little simpler for them to understand. Hope this helps someoneenter image description here

How to convert Varchar to Int in sql server 2008?

Spaces will not be a problem for cast, however characters like TAB, CR or LF will appear as spaces, will not be trimmed by LTRIM or RTRIM, and will be a problem.

For example try the following:

declare @v1 varchar(21) = '66',
        @v2 varchar(21) = '   66   ',
        @v3 varchar(21) = '66' + char(13) + char(10),
        @v4 varchar(21) = char(9) + '66'

select cast(@v1 as int)   -- ok
select cast(@v2 as int)   -- ok
select cast(@v3 as int)   -- error
select cast(@v4 as int)   -- error

Check your input for these characters and if you find them, use REPLACE to clean up your data.


Per your comment, you can use REPLACE as part of your cast:

select cast(replace(replace(@v3, char(13), ''), char(10), '') as int)

If this is something that will be happening often, it would be better to clean up the data and modify the way the table is populated to remove the CR and LF before it is entered.

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

I encountered the same ImportError. Somehow the setuptools package had been deleted in my Python environment.

To fix the issue, run the setup script for setuptools:

curl https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py | python

If you have any version of distribute, or any setuptools below 0.6, you will have to uninstall it first.*

See Installation Instructions for further details.


* If you already have a working distribute, upgrading it to the "compatibility wrapper" that switches you over to setuptools is easier. But if things are already broken, don't try that.

How do I pass along variables with XMLHTTPRequest

How about?

function callHttpService(url, params){
  // Assume params contains key/value request params
  let queryStrings = '';

  for(let key in params){
      queryStrings += `${key}=${params[key]}&`
    } 
 const fullUrl = `${url}?queryStrings`

  //make http request with fullUrl
}

What are Runtime.getRuntime().totalMemory() and freeMemory()?

According to the API

totalMemory()

Returns the total amount of memory in the Java virtual machine. The value returned by this method may vary over time, depending on the host environment. Note that the amount of memory required to hold an object of any given type may be implementation-dependent.

maxMemory()

Returns the maximum amount of memory that the Java virtual machine will attempt to use. If there is no inherent limit then the value Long.MAX_VALUE will be returned.

freeMemory()

Returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by freeMemory.

In reference to your question, maxMemory() returns the -Xmx value.

You may be wondering why there is a totalMemory() AND a maxMemory(). The answer is that the JVM allocates memory lazily. Lets say you start your Java process as such:

java -Xms64m -Xmx1024m Foo

Your process starts with 64mb of memory, and if and when it needs more (up to 1024m), it will allocate memory. totalMemory() corresponds to the amount of memory currently available to the JVM for Foo. If the JVM needs more memory, it will lazily allocate it up to the maximum memory. If you run with -Xms1024m -Xmx1024m, the value you get from totalMemory() and maxMemory() will be equal.

Also, if you want to accurately calculate the amount of used memory, you do so with the following calculation :

final long usedMem = totalMemory() - freeMemory();

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

//Use following to check if the id is a valid ObjectId?

var valid = mongoose.Types.ObjectId.isValid(req.params.id);
if(valid)
{
  //process your code here
} else {
  //the id is not a valid ObjectId
}

Install Qt on Ubuntu

In Ubuntu 18.04 the QtCreator examples and API docs missing, This is my way to solve this problem, should apply to almost every Ubuntu release.

For QtCreator and Examples and API Docs:

sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `

sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`

sudo apt-get install build-essential qtcreator qt5-default

If something is also missing, then:

sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `

Hope to be helpful.

Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing