Programs & Examples On #Uitextfielddelegate

UITextField text change event

  1. KVO solutions do not work

KVO does NOT work in iOS for controls: http://stackoverflow.com/a/6352525/1402846 https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/KVO.html

  1. In the observing class, you do this:

Given that you know the text view you want to watch:

var watchedTextView: UITextView!

Do this:

NotificationCenter.default.addObserver(
    self,
    selector: #selector(changed),
    name: UITextView.textDidChangeNotification,
    object: watchedTextView)

However, be careful with that:

  • it's likely you only want to call that once, so do not call it in, for example, layoutSubviews

  • it's quite difficult to know when to best call it during your bring-up process. It will depend on your situation. Unfortunately there is no standard, locked-in solution

  • for example you usually certainly can not call it at init time, since of course watchedTextView may not exist yet

.

  1. the next problem is that ...

None of the notifications are called when text is changed programmatically.

This is a huge, age-old, and stupid, nuisance in iOS engineering.

Controls simply do not - end of story - call the notifcations when the .text property is changed programmatically.

This is insanely annoying because of course - obviously - every app ever made sets the text programmatically, such as clearing the field after the user posts, etc.

You have to subclass the text view (or similar control) like this:

class NonIdioticTextView: UIITextView {

    override var text: String! {
        // boilerplate code needed to make watchers work properly:
        get {
            return super.text
        }
        set {
            super.text = newValue
            NotificationCenter.default.post(
                name: UITextView.textDidChangeNotification,
                object: self)
        }

    }

}

(Tip - don't forget the super call has to come before ! the post call.)

There is no solution available, unless, you fix the control by subclassing as shown just above. That is the only solution.

Note that the notification

UITextView.textDidChangeNotification

results in

func textViewDidChangeSelection(_ textView: UITextView) 

being called.

(Not textViewDidChange .)

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

Proper way to handle multiple forms on one page in Django

view:

class AddProductView(generic.TemplateView):
template_name = 'manager/add_product.html'

    def get(self, request, *args, **kwargs):
    form = ProductForm(self.request.GET or None, prefix="sch")
    sub_form = ImageForm(self.request.GET or None, prefix="loc")
    context = super(AddProductView, self).get_context_data(**kwargs)
    context['form'] = form
    context['sub_form'] = sub_form
    return self.render_to_response(context)

def post(self, request, *args, **kwargs):
    form = ProductForm(request.POST,  prefix="sch")
    sub_form = ImageForm(request.POST, prefix="loc")
    ...

template:

{% block container %}
<div class="container">
    <br/>
    <form action="{% url 'manager:add_product' %}" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        {{ sub_form.as_p }}
        <p>
            <button type="submit">Submit</button>
        </p>
    </form>
</div>
{% endblock %}

Spring - applicationContext.xml cannot be opened because it does not exist

I got the same error. I solved it moving the file applicationContext.xmlin a

sub-folder of the srcfolder. e.g:

context = new ClassPathXmlApplicationContext("/com/ejemplo/dao/applicationContext.xml");

Has anyone ever got a remote JMX JConsole to work?

After putting my Google-fu to the test for the last couple of days, I was finally able to get this to work after compiling answers from Stack Overflow and this page http://help.boomi.com/atomsphere/GUID-F787998C-53C8-4662-AA06-8B1D32F9D55B.html.

Reposting from the Dell Boomi page:

To Enable Remote JMX on an Atom

If you want to monitor the status of an Atom, you need to turn on Remote JMX (Java Management Extensions) for the Atom.

Use a text editor to open the <atom_installation_directory>\bin\atom.vmoptions file.

Add the following lines to the file:

-Dcom.sun.management.jmxremote.port=5002
-Dcom.sun.management.jmxremote.rmi.port=5002
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

The one line that I haven't seen any Stack Overflow answer cover is

-Dcom.sun.management.jmxremote.rmi.port=5002

In my case, I was attempting to retrieve Kakfa metrics, so I simply changed the above option to match the -Dcom.sun.management.jmxremote.port value. So, without authentication of any kind, the bare minimum config should look like this:

-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.port=(jmx remote port)

-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.rmi.port=(jmx remote port)
-Djava.rmi.server.hostname=(CNAME|IP Address)

How to handle a single quote in Oracle SQL

I found the above answer giving an error with Oracle SQL, you also must use square brackets, below;

SQL> SELECT Q'[Paddy O'Reilly]' FROM DUAL;


Result: Paddy O'Reilly

How can I get an HTTP response body as a string?

The Answer by McDowell is correct one. However if you try other suggestion in few of the posts above.

HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
   response = EntityUtils.toString(responseEntity);
   S.O.P (response);
}

Then it will give you illegalStateException stating that content is already consumed.

Checking character length in ruby

I think you could just use the String#length method...

http://ruby-doc.org/core-1.9.3/String.html#method-i-length

Example:

text = 'The quick brown fox jumps over the lazy dog.'
puts text.length > 25 ? 'Too many characters' : 'Accepted'

Extreme wait-time when taking a SQL Server database offline

In my case, after waiting so much for it to finish I had no patience and simply closed management studio. Before exiting, it showed the success message, db is offline. The files were available to rename.

How to force table cell <td> content to wrap?

This worked for me when I needed to display "pretty" JSON in a cell:

td { white-space:pre }

More about the white-space property:

  • normal : This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.

  • pre : This value prevents user agents from collapsing sequences of white space.
    Lines are only broken at preserved newline characters.

  • nowrap : This value collapses white space as for normal, but suppresses line breaks within text.

  • pre-wrap : This value prevents user agents from collapsing sequences of white space.
    Lines are broken at preserved newline characters, and as necessary to fill line boxes.

  • pre-line : This value directs user agents to collapse sequences of white space.
    Lines are broken at preserved newline characters, and as necessary to fill line boxes.

(Also, see more at the source.)

How to use registerReceiver method?

Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.

First, your IntentFilter must contain an event.

static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

Second, when you send a broadcast, use this same action:

Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);

Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.

Fourth, is your service declared in the AndroidManifest.xml?

Unable to use Intellij with a generated sources folder

I wanted to update at the comment earlier made by DaShaun, but as it is my first time commenting, application didn't allow me.

Nonetheless, I am using eclipse and after I added the below mention code snippet to my pom.xml as suggested by Dashun and I ran the mvn clean package to generate the avro source files, but I was still getting compilation error in the workspace.

I right clicked on project_name -> maven -> update project and updated the project, which added the target/generated-sources as a source folder to my eclipse project.

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>1.4</version>
    <executions>
        <execution>
            <id>test</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>${basedir}/target/generated-sources</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>

How to terminate process from Python using pid?

So, not directly related but this is the first question that appears when you try to find how to terminate a process running from a specific folder using Python.

It also answers the question in a way(even though it is an old one with lots of answers).

While creating a faster way to scrape some government sites for data I had an issue where if any of the processes in the pool got stuck they would be skipped but still take up memory from my computer. This is the solution I reached for killing them, if anyone knows a better way to do it please let me know!

import pandas as pd
import wmi
from re import escape
import os

def kill_process(kill_path, execs):
    f = wmi.WMI()
    esc = escape(kill_path)
    temp = {'id':[], 'path':[], 'name':[]}
    for process in f.Win32_Process():
        temp['id'].append(process.ProcessId)
        temp['path'].append(process.ExecutablePath)
        temp['name'].append(process.Name)
    temp = pd.DataFrame(temp)
    temp = temp.dropna(subset=['path']).reset_index().drop(columns=['index'])
    temp = temp.loc[temp['path'].str.contains(esc)].loc[temp.name.isin(execs)].reset_index().drop(columns=['index'])
    [os.system('taskkill /PID {} /f'.format(t)) for t in temp['id']]

Difference between "managed" and "unmanaged"

Managed code is a differentiation coined by Microsoft to identify computer program code that requires and will only execute under the "management" of a Common Language Runtime virtual machine (resulting in Bytecode).

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

http://www.developer.com/net/cplus/article.php/2197621/Managed-Unmanaged-Native-What-Kind-of-Code-Is-This.htm

pandas get rows which are NOT in other dataframe

Suppose you have two dataframes, df_1 and df_2 having multiple fields(column_names) and you want to find the only those entries in df_1 that are not in df_2 on the basis of some fields(e.g. fields_x, fields_y), follow the following steps.

Step1.Add a column key1 and key2 to df_1 and df_2 respectively.

Step2.Merge the dataframes as shown below. field_x and field_y are our desired columns.

Step3.Select only those rows from df_1 where key1 is not equal to key2.

Step4.Drop key1 and key2.

This method will solve your problem and works fast even with big data sets. I have tried it for dataframes with more than 1,000,000 rows.

df_1['key1'] = 1
df_2['key2'] = 1
df_1 = pd.merge(df_1, df_2, on=['field_x', 'field_y'], how = 'left')
df_1 = df_1[~(df_1.key2 == df_1.key1)]
df_1 = df_1.drop(['key1','key2'], axis=1)

JDBC connection failed, error: TCP/IP connection to host failed

The error is self explanatory:

  • Check if your SQL server is actually up and running
  • Check SQL server hostname, username and password is correct
  • Check there's no firewall rule blocking TCP connection to port 1433
  • Check the host is actually reachable

A good check I often use is to use telnet, eg on a windows command prompt run:

telnet 127.0.0.1 1433

If you get a blank screen it indicates network connection established successfully, and it's not a network problem. If you get 'Could not open connection to the host' then this is network problem

You need to use a Theme.AppCompat theme (or descendant) with this activity

This solution worked for me.

Design library depends on the Support v4 and AppCompat Support Libraries, so don't use different version for appcompat and design library in gradle.

use

 compile 'com.android.support:appcompat-v7:23.0.0'
 compile 'com.android.support:design:23.0.0'

instead of

 compile 'com.android.support:appcompat-v7:23.0.0'
 compile 'com.android.support:design:23.1.0'

Delete worksheet in Excel using VBA

Consider:

Sub SheetKiller()
    Dim s As Worksheet, t As String
    Dim i As Long, K As Long
    K = Sheets.Count

    For i = K To 1 Step -1
        t = Sheets(i).Name
        If t = "ID Sheet" Or t = "Summary" Then
            Application.DisplayAlerts = False
                Sheets(i).Delete
            Application.DisplayAlerts = True
        End If
    Next i
End Sub

NOTE:

Because we are deleting, we run the loop backwards.

What's the algorithm to calculate aspect ratio?

I guess you want to decide which of 4:3 and 16:9 is the best fit.

function getAspectRatio(width, height) {
    var ratio = width / height;
    return ( Math.abs( ratio - 4 / 3 ) < Math.abs( ratio - 16 / 9 ) ) ? '4:3' : '16:9';
}

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

Your main problem is thinking that the variable you declared outside of the template is the same variable being "set" inside the choose statement. This is not how XSLT works, the variable cannot be reassigned. This is something more like what you want:

<xsl:template match="class">
  <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
  <xsl:variable name="subexists">
    <xsl:choose>
      <xsl:when test="joined-subclass">true</xsl:when>
      <xsl:otherwise>false</xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

And if you need the variable to have "global" scope then declare it outside of the template:

<xsl:variable name="subexists">
  <xsl:choose>
     <xsl:when test="/path/to/node/joined-subclass">true</xsl:when>
     <xsl:otherwise>false</xsl:otherwise>
  </xsl:choose>
</xsl:variable>

<xsl:template match="class">
   subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

SQLite: How do I save the result of a query as a CSV file?

From here and d5e5's comment:

You'll have to switch the output to csv-mode and switch to file output.

sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

remove objects from array by object property

With lodash/underscore:

If you want to modify the existing array itself, then we have to use splice. Here is the little better/readable way using findWhere of underscore/lodash:

var items= [{id:'abc',name:'oh'}, // delete me
                  {id:'efg',name:'em'},
                  {id:'hij',name:'ge'}];

items.splice(_.indexOf(items, _.findWhere(items, { id : "abc"})), 1);

With ES5 or higher

(without lodash/underscore)

With ES5 onwards we have findIndex method on array, so its easier without lodash/underscore

items.splice(items.findIndex(function(i){
    return i.id === "abc";
}), 1);

(ES5 is supported in almost all morden browsers)

About findIndex, and its Browser compatibility

cmake error 'the source does not appear to contain CMakeLists.txt'

This reply may be late but it may help users having similar problem. The opencv-contrib (available at https://github.com/opencv/opencv_contrib/releases) contains extra modules but the build procedure has to be done from core opencv (available at from https://github.com/opencv/opencv/releases) modules.

Follow below steps (assuming you are building it using CMake GUI)

  1. Download openCV (from https://github.com/opencv/opencv/releases) and unzip it somewhere on your computer. Create build folder inside it

  2. Download exra modules from OpenCV. (from https://github.com/opencv/opencv_contrib/releases). Ensure you download the same version.

  3. Unzip the folder.

  4. Open CMake

  5. Click Browse Source and navigate to your openCV folder.

  6. Click Browse Build and navigate to your build Folder.

  7. Click the configure button. You will be asked how you would like to generate the files. Choose Unix-Makefile from the drop down menu and Click OK. CMake will perform some tests and return a set of red boxes appear in the CMake Window.

  8. Search for "OPENCV_EXTRA_MODULES_PATH" and provide the path to modules folder (e.g. /Users/purushottam_d/Programs/OpenCV3_4_5_contrib/modules)

  9. Click Configure again, then Click Generate.

  10. Go to build folder

# cd build
# make
# sudo make install
  1. This will install the opencv libraries on your computer.

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

The justify-self and justify-items properties are not implemented in flexbox. This is due to the one-dimensional nature of flexbox, and that there may be multiple items along the axis, making it impossible to justify a single item. To align items along the main, inline axis in flexbox you use the justify-content property.

Reference: Box alignment in CSS Grid Layout

Can an int be null in Java?

Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so

public int getHeight(String name){
    if(map.containsKey(name)){
        return map.get(name);
    }else{
        return -1;
    }
}

How do I connect to mongodb with node.js (and authenticate)?

My version:

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://user:pass@dhost:port/baseName', function(err, db) {
    if (err) {
        console.error(err);
    }
    var collection = db.collection('collectionName');
    collection.find().toArray(function(err, docs) {
        console.log(docs);
    });
});

How to display an IFRAME inside a jQuery UI dialog

Although this is a old post, I have spent 3 hours to fix my issue and I think this might help someone in future.

Here is my jquery-dialog hack to show html content inside an <iframe> :

let modalProperties = {autoOpen: true, width: 900, height: 600, modal: true, title: 'Modal Title'};
let modalHtmlContent = '<div>My Content First div</div><div>My Content Second div</div>';

// create wrapper iframe
let wrapperIframe = $('<iframe src="" frameborder="0" style="width:100%; height:100%;"></iframe>');

// create jquery dialog by a 'div' with 'iframe' appended
$("<div></div>").append(wrapperIframe).dialog(modalProperties);

// insert html content to iframe 'body'
let wrapperIframeDocument = wrapperIframe[0].contentDocument;
let wrapperIframeBody = $('body', wrapperIframeDocument);
wrapperIframeBody.html(modalHtmlContent);

jsfiddle demo

Question mark characters displaying within text, why is this?

Edit your Apache configuration file on the "mirror" server (the server with the problem), and comment-out the following line:

AddDefaultCharset UTF-8

Then restart Apache:

service httpd restart

The problem is that the "AddDefaultCharset UTF-8" line overrides the Content-Type specified in the .html files; e.g.:

<meta http-equiv=Content-Type content="text/html; charset=windows-1252">

The most common symptom is that character codes above 127 display as black diamonds with question marks on them (in Chrome, Safari or Firefox), or as little boxes (in IE and Opera). HTML files generated by Microsoft Word usually have many such characters, the most common one being character code 160 = 0xA0, which is equivalent to "&nbsp;" in the Windows-1252 encoding, and is often found between span tags, like this:

<span style="mso-spacerun: yes">ááá </span>

Add line break within tooltips

AngularJS with Bootstrap UI Tolltip (uib-tooltip), has three versions of tool-tip:

uib-tooltip, uib-tooltip-template and uib-tooltip-html

- uib-tooltip takes only text and will escape any HTML provided
- uib-tooltip-html takes an expression that evaluates to an HTML string
- uib-tooltip-template takes a text that specifies the location of the template

In my case, I opted for uib-tooltip-html and there are three parts to it:

  1. configuration
  2. controller
  3. HTML

Example:

(function(angular) {

//Step 1: configure $sceProvider - this allows the configuration of $sce service.

angular.module('myApp', ['uib.bootstrap'])
       .config(function($sceProvider) {
           $sceProvider.enabled(false);
       });

//Step 2: Set the tooltip content in the controller

angular.module('myApp')
       .controller('myController', myController);

myController.$inject = ['$sce'];

function myController($sce) {
    var vm = this;
    vm.tooltipContent = $sce.trustAsHtml('I am the first line <br /><br />' +
                                         'I am the second line-break');

    return vm;
}

 })(window.angular);

//Step 3: Use the tooltip in HTML (UI)

<div ng-controller="myController as get">
     <span uib-tooltip-html="get.tooltipContent">other Contents</span>
</div>

For more information, please check here

WHERE clause on SQL Server "Text" data type

Another option would be:

SELECT * FROM [Village] WHERE PATINDEX('foo', [CastleType]) <> 0

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

Try to run xcrun simctl delete unavailable in your terminal.

Original answer: Xcode - free to clear devices folder?

selecting an entire row based on a variable excel vba

You need to add quotes. VBA is translating

Rows(copyToRow & ":" & copyToRow).Select`

into

 Rows(52:52).Select

Try changing

Rows(""" & copyToRow & ":" & copyToRow & """).Select

convert UIImage to NSData

Create the reference of image....

UIImage *rainyImage = [UIImage imageNamed:@"rainy.jpg"];

displaying image in image view... imagedisplay is reference of imageview:

imagedisplay.image = rainyImage;

convert it into NSData by passing UIImage reference and provide compression quality in float values:

NSData *imgData = UIImageJPEGRepresentation(rainyImage, 0.9);

Get Mouse Position

In SWT you need not be in a listener to get at the mouse location. The Display object has the method getCursorLocation().

In vanilla SWT/JFace, call Display.getCurrent().getCursorLocation().

In an RCP application, call PlatformUI.getWorkbench().getDisplay().getCursorLocation().

For SWT applications, it is preferable to use getCursorLocation() over the MouseInfo.getPointerInfo() that others have mentioned, as the latter is implemented in the AWT toolkit that SWT was designed to replace.

How to make sure docker's time syncs with that of the host?

Enabling Hyper-V in Windows Features solved the problem: Windows Features

Android Studio Google JAR file causing GC overhead limit exceeded error

At some point a duplicate copy of apply plugin: 'com.android.application' got added to my build gradle. Removing the duplicate copy and making sure all my apply plugins were at the top fixed the issue for me.

Find all zero-byte files in directory and subdirectories

To print the names of all files in and below $dir of size 0:

find "$dir" -size 0

Note that not all implementations of find will produce output by default, so you may need to do:

find "$dir" -size 0 -print

Two comments on the final loop in the question:

Rather than iterating over every other word in a string and seeing if the alternate values are zero, you can partially eliminate the issue you're having with whitespace by iterating over lines. eg:

printf '1 f1\n0 f 2\n10 f3\n' | while read size path; do
    test "$size" -eq 0 && echo "$path"; done

Note that this will fail in your case if any of the paths output by ls contain newlines, and this reinforces 2 points: don't parse ls, and have a sane naming policy that doesn't allow whitespace in paths.

Secondly, to output the data from the loop, there is no need to store the output in a variable just to echo it. If you simply let the loop write its output to stdout, you accomplish the same thing but avoid storing it.

JQuery - Call the jquery button click event based on name property

$('element[name="element_name"]').click(function(){
    //do stuff
});

in your case:

$('input[name="btnName"]').click(function(){
    //do stuff
});

Overlay normal curve to histogram in R

This is an implementation of aforementioned StanLe's anwer, also fixing the case where his answer would produce no curve when using densities.

This replaces the existing but hidden hist.default() function, to only add the normalcurve parameter (which defaults to TRUE).

The first three lines are to support roxygen2 for package building.

#' @noRd
#' @exportMethod hist.default
#' @export
hist.default <- function(x,
                         breaks = "Sturges",
                         freq = NULL,
                         include.lowest = TRUE,
                         normalcurve = TRUE,
                         right = TRUE,
                         density = NULL,
                         angle = 45,
                         col = NULL,
                         border = NULL,
                         main = paste("Histogram of", xname),
                         ylim = NULL,
                         xlab = xname,
                         ylab = NULL,
                         axes = TRUE,
                         plot = TRUE,
                         labels = FALSE,
                         warn.unused = TRUE,
                         ...)  {

  # https://stackoverflow.com/a/20078645/4575331
  xname <- paste(deparse(substitute(x), 500), collapse = "\n")

  suppressWarnings(
    h <- graphics::hist.default(
      x = x,
      breaks = breaks,
      freq = freq,
      include.lowest = include.lowest,
      right = right,
      density = density,
      angle = angle,
      col = col,
      border = border,
      main = main,
      ylim = ylim,
      xlab = xlab,
      ylab = ylab,
      axes = axes,
      plot = plot,
      labels = labels,
      warn.unused = warn.unused,
      ...
    )
  )

  if (normalcurve == TRUE & plot == TRUE) {
    x <- x[!is.na(x)]
    xfit <- seq(min(x), max(x), length = 40)
    yfit <- dnorm(xfit, mean = mean(x), sd = sd(x))
    if (isTRUE(freq) | (is.null(freq) & is.null(density))) {
      yfit <- yfit * diff(h$mids[1:2]) * length(x)
    }
    lines(xfit, yfit, col = "black", lwd = 2)
  }

  if (plot == TRUE) {
    invisible(h)
  } else {
    h
  }
}

Quick example:

hist(g)

enter image description here

For dates it's bit different. For reference:

#' @noRd
#' @exportMethod hist.Date
#' @export
hist.Date <- function(x,
                      breaks = "months",
                      format = "%b",
                      normalcurve = TRUE,
                      xlab = xname,
                      plot = TRUE,
                      freq = NULL,
                      density = NULL,
                      start.on.monday = TRUE,
                      right = TRUE,
                      ...)  {

  # https://stackoverflow.com/a/20078645/4575331
  xname <- paste(deparse(substitute(x), 500), collapse = "\n")

  suppressWarnings(
    h <- graphics:::hist.Date(
      x = x,
      breaks = breaks,
      format = format,
      freq = freq,
      density = density,
      start.on.monday = start.on.monday,
      right = right,
      xlab = xlab,
      plot = plot,
      ...
    )
  )

  if (normalcurve == TRUE & plot == TRUE) {
    x <- x[!is.na(x)]
    xfit <- seq(min(x), max(x), length = 40)
    yfit <- dnorm(xfit, mean = mean(x), sd = sd(x))
    if (isTRUE(freq) | (is.null(freq) & is.null(density))) {
      yfit <- as.double(yfit) * diff(h$mids[1:2]) * length(x)
    }
    lines(xfit, yfit, col = "black", lwd = 2)
  }

  if (plot == TRUE) {
    invisible(h)
  } else {
    h
  }
}

How to show soft-keyboard when edittext is focused

After trying every individual answer here the keyboard doesn't show up.. I got hours to get this solved, so hope someone doesn't waste it in the future..

For my case, the issue was not a programming issue at at, I was testing on an emulator with a phone that has a hardware keyboard, so it doesn't show up the software keyboard by default, to solve this, you need to make sure that the show soft input enabled in your emulator by turning off the hardware keyboard or enable the soft keyboard.

In faced this only on API-15 & 16. Here are screen shots how to do that

On Geny Motion emulator:

enter image description here enter image description here

On Android Studio emulator:

enter image description here

Maven is not working in Java 8 when Javadoc tags are incomplete

I don't think just turning off DocLint is a good solution, at least not long term. It is good that Javadoc has become a bit more strict so the right way to fix the build problem is to fix the underlying problem. Yes, you'll ultimately need to fix those source code files.

Here are the things to look out for that you could previously get away with:

  • Malformed HTML (for example a missing end-tag, un-escaped brackets, etc)
  • Invalid {@link }s. (same goes for similar tags such as @see)
  • Invalid @author values. This used to be accepted : @author John <[email protected]> but not so anymore because of the un-escaped brackets.
  • HTML tables in Javadoc now require a summary or caption. See this question for explanation.

You'll simply have to fix your source code files and keep building your Javadoc until it can build without a failure. Cumbersome yes, but personally I like when I have brought my projects up to DocLint level because it means I can be more confident that the Javadoc I produce is actually what I intend.

There's of course the problem if you are generating Javadoc on some source code you've not produced yourself, for example because it comes from some code generator, e.g. wsimport. Strange that Oracle didn't prepare their own tools for JDK8 compliance before actually releasing JDK8. It seems it won't be fixed until Java 9. Only in this particular case I suggest to turn off DocLint as documented elsewhere on this page.

Check if a string is a palindrome

public Boolean IsPalindrome(string value)
{
   var one = value.ToList<char>();
   var two = one.Reverse<char>().ToList();
   return one.Equals(two);
}

Java FileOutputStream Create File if not exists

It will throw a FileNotFoundException if the file doesn't exist and cannot be created (doc), but it will create it if it can. To be sure you probably should first test that the file exists before you create the FileOutputStream (and create with createNewFile() if it doesn't):

File yourFile = new File("score.txt");
yourFile.createNewFile(); // if file already exists will do nothing 
FileOutputStream oFile = new FileOutputStream(yourFile, false); 

Notify ObservableCollection when Item changes

The ObservableCollection and its derivatives raises its property changes internally. The code in your setter should only be triggered if you assign a new TrulyObservableCollection<MyType> to the MyItemsSource property. That is, it should only happen once, from the constructor.

From that point forward, you'll get property change notifications from the collection, not from the setter in your viewmodel.

Android M Permissions: onRequestPermissionsResult() not being called

This issue was actually being caused by NestedFragments. Basically most fragments we have extend a HostedFragment which in turn extends a CompatFragment. Having these nested fragments caused issues which eventually were solved by another developer on the project.

He was doing some low level stuff like bit switching to get this working so I'm not too sure of the actual final solution

python dict to numpy structured array

I would prefer storing keys and values on separate arrays. This i often more practical. Structures of arrays are perfect replacement to array of structures. As most of the time you have to process only a subset of your data (in this cases keys or values, operation only with only one of the two arrays would be more efficient than operating with half of the two arrays together.

But in case this way is not possible, I would suggest to use arrays sorted by column instead of by row. In this way you would have the same benefit as having two arrays, but packed only in one.

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

names = 0
values = 1
array = np.empty(shape=(2, len(result)), dtype=float)
array[names] = result.keys()
array[values] = result.values()

But my favorite is this (simpler):

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

arrays = {'names': np.array(result.keys(), dtype=float),
          'values': np.array(result.values(), dtype=float)}

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Your example code is wrong. This works:

import datetime

datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")

The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.

[INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

If you got this error when working with your flutter project, you can add the following code in the module build.gradle and within Android block and then in the defaultConfig block. This error happened when I was trying to make a flutter apk build.

android{
    ...
    defaultConfig{
        ...
        //Add this ndk block of code to your build.gradle
        ndk {
            abiFilters 'armeabi-v7a', 'x86', 'armeabi'
        }
    }
}

Java associative-array

There is no such thing as associative array in Java. Its closest relative is a Map, which is strongly typed, however has less elegant syntax/API.

This is the closest you can get based on your example:

Map<Integer, Map<String, String>> arr = 
    org.apache.commons.collections.map.LazyMap.decorate(
         new HashMap(), new InstantiateFactory(HashMap.class));

//$arr[0]['name'] = 'demo';
arr.get(0).put("name", "demo");

System.out.println(arr.get(0).get("name"));
System.out.println(arr.get(1).get("name"));    //yields null

Can you install and run apps built on the .NET framework on a Mac?

  • .NET Core will install and run on macOS - and just about any other desktop OS.
    IDEs are available for the mac, including:

  • Mono is a good option that I've used in the past. But with Core 3.0 out now, I would go that route.

JavaScript get element by name

All Answers here seem to be outdated. Please use this now:

document.querySelector("[name='acc']");
document.querySelector("[name='pass']")

How to use Object.values with typescript?

Object.values() is part of ES2017, and the compile error you are getting is because you need to configure TS to use the ES2017 library. You are probably using ES6 or ES5 library in your current TS configuration.

Solution: use es2017 or es2017.object in your --lib compiler option.

For example, using tsconfig.json:

"compilerOptions": {
    "lib": ["es2017", "dom"]
}

Note that targeting ES2017 with TypeScript does not emit polyfills in the browser for ES2017 (meaning the above solves your compile error, but you can still encounter a runtime error because the browser doesn't implement ES2017 Object.values), it's up to you to polyfill your project code yourself if you want. And since Object.values is not yet well supported by all browsers (at the time of this writing) you definitely want a polyfill: core-js will do the job.

Getting json body in aws Lambda via API gateway

You may have forgotten to define the Content-Type header. For example:

  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ items }),
  }

Importing .py files in Google Colab

We can do so.

import sys
import os

py_file_location = "/content/drive/My Drive"
sys.path.append(os.path.abspath(py_file_location))

Now you can import it as module in notebook for that location.

import whatever

Invalid column count in CSV input on line 1 Error

If the table was already created, and you were lazy enough not to specify the columns in the fields names input, then all you have to do is to select the empty columns at right to the file content and delete them.

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

That's fine. To understand the above, you have to understand the nature of abstract classes first. They are similar to interfaces in that respect. This is what Oracle say about this here.

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation.

So you have to think about what happens when an interface extends another interface. For example ...

//Filename: Sports.java
public interface Sports
{
   public void setHomeTeam(String name);
   public void setVisitingTeam(String name);
}

//Filename: Football.java
public interface Football extends Sports
{
   public void homeTeamScored(int points);
   public void visitingTeamScored(int points);
   public void endOfQuarter(int quarter);
}

... as you can see, this also compiles perfectly fine. Simply because, just like an abstract class, an interface can NOT be instantiated. So, it is not required to explicitly mention the methods from its "parent". However, ALL the parent method signatures DO implicitly become a part of the extending interface or implementing abstract class. So, once a proper class (one that can be instantiated) extends the above, it WILL be required to ensure that every single abstract method is implemented.

Hope that helps... and Allahu 'alam !

How to remove an unpushed outgoing commit in Visual Studio?

I could not find a single good answer that helped me get rid of this issue.

Let's say the name of branch, you accidentally committed changes to, is master. Following four simple steps proved like a world to me:

  1. Go to Branches
  2. Choose or create any branch other than master
  3. Delete local/workspace version of master
  4. Switch to master from remotes/origin

Date constructor returns NaN in IE, but works in Firefox and Chrome

Here's my approach:

var parseDate = function(dateArg) {
    var dateValues = dateArg.split('-');
    var date = new Date(dateValues[0],dateValues[1],dateValues[2]);
    return date.format("m/d/Y");
}

replace ('-') with the delimeter you're using.

Safely turning a JSON string into an object

JSON.parse(jsonString);

json.parse will change into object.

What does "all" stand for in a makefile?

The manual for GNU Make gives a clear definition for all in its list of standard targets.

If the author of the Makefile is following that convention then the target all should:

  1. Compile the entire program, but not build documentation.
  2. Be the the default target. As in running just make should do the same as make all.

To achieve 1 all is typically defined as a .PHONY target that depends on the executable(s) that form the entire program:

.PHONY : all
all : executable

To achieve 2 all should either be the first target defined in the make file or be assigned as the default goal:

.DEFAULT_GOAL := all

What is the difference between required and ng-required?

The HTML attribute required="required" is a statement telling the browser that this field is required in order for the form to be valid. (required="required" is the XHTML form, just using required is equivalent)

The Angular attribute ng-required="yourCondition" means 'isRequired(yourCondition)' and sets the HTML attribute dynamically for you depending on your condition.

Also note that the HTML version is confusing, it is not possible to write something conditional like required="true" or required="false", only the presence of the attribute matters (present means true) ! This is where Angular helps you out with ng-required.

Convert to absolute value in Objective-C

Depending on the type of your variable, one of abs(int), labs(long), llabs(long long), imaxabs(intmax_t), fabsf(float), fabs(double), or fabsl(long double).

Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)

(Alas, there is no habs(short) function. Or scabs(signed char) for that matter...)


Apple's and GNU's Objective-C headers also include an ABS() macro which is type-agnostic. I don't recommend using ABS() however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++) will have an undefined result.


If you're using C++ or Objective-C++, you can bring in the <cmath> header and use std::abs(), which is templated for all the standard integer and floating-point types.

Installing cmake with home-brew

  1. Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)

  2. Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.

  3. Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"

  4. Reload your .bashrc file: source ~/.bashrc

  5. Verify the latest cmake version is installed: cmake --version

  6. You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

Add the following to the avd config.ini

disk.dataPartition.size=1024MB

Let me know if this works for you also.

I added in the line Add Data Partition Size Configuration
Screen Shot of AVD Storage Space being increased

Inline <style> tags vs. inline css properties

I agree with the majority view that external stylesheets are the prefered method.

However, here are some practical exceptions:

  • Dynamic background images. CSS stylesheets are static files so you need to use an inline style to add a dynamic (from a database, CMS etc...) background-image style.

  • If an element needs to be hidden when the page loads, using an external stylesheet for this is not practical, since there will always be some delay before the stylesheet is processed and the element will be visible until that happens. style="display: none;" is the best way to achieve this.

  • If an application is going to give the user fine control over a particular CSS value, e.g. text color, then it may be necessary to add this to inline style elements or in-page <style></style> blocks. E.g. style="color:#{{ page.color }}", or <style> p.themed { color: #{{ page.color }}; }</style>

How to execute a command in a remote computer?

Another solution is to use WMI.NET or Windows Management Instrumentation.

Using the .NET Framework namespace System.Management, you can automate administrative tasks using Windows Management Instrumentation (WMI).

Code Sample

using System.Management;
...
var processToRun = new[] { "notepad.exe" };
var connection = new ConnectionOptions();
connection.Username = "username";
connection.Password = "password";
var wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", REMOTE_COMPUTER_NAME), connection);
var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
wmiProcess.InvokeMethod("Create", processToRun);

If you have trouble with authentication, then check the DCOM configuration.

  1. On the target machine, run dcomcnfg from the command prompt.
  2. Expand Component Services\Computers\My Computer\DCOM Config
  3. Find Windows Management Instruction, identified with GUID 8BC3F05E-D86B-11D0-A075-00C04FB68820 (you can see this in the details view).
  4. Edit the properties and then add the username you are trying to login with under the permissions tab.
  5. You may need to reboot the service or the entire machine.

NOTE: All paths used for the remote process need to be local to the target machine.

How to delete parent element using jQuery

what about using unwrap()

<div class="parent">
<p class="child">
</p>
</div>

after using - $(".child").unwrap() - it will be;

<p class="child">
</p>

Generate a random point within a circle (uniformly)

Here is my Python code to generate num random points from a circle of radius rad:

import matplotlib.pyplot as plt
import numpy as np
rad = 10
num = 1000

t = np.random.uniform(0.0, 2.0*np.pi, num)
r = rad * np.sqrt(np.random.uniform(0.0, 1.0, num))
x = r * np.cos(t)
y = r * np.sin(t)

plt.plot(x, y, "ro", ms=1)
plt.axis([-15, 15, -15, 15])
plt.show()

Routing with Multiple Parameters using ASP.NET MVC

Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:

public ActionResult GetImages(string artistName, string apiKey)

MVC will auto-populate the parameters when given a URL like:

/Artist/GetImages/?artistName=cher&apiKey=XXX

One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:

public ActionResult GetImages(string id, string apiKey)

would be populated correctly with a URL like the following:

/Artist/GetImages/cher?apiKey=XXX

In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:

routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

If you wanted to support a url like

/Artist/GetImages/cher/api-key

you could add a route like:

routes.MapRoute(
            "ArtistImages",                                              // Route name
            "{controller}/{action}/{artistName}/{apikey}",                           // URL with parameters
            new { controller = "Home", action = "Index", artistName = "", apikey = "" }  // Parameter defaults
        );

and a method like the first example above.

How to align LinearLayout at the center of its parent?

Below is code to put your Linearlayout at bottom and put its content at center. You have to use RelativeLayout to set Layout at bottom.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#97611F"
    android:gravity="center_horizontal"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:text="View Saved Searches"
        android:textSize="15dp"
        android:textColor="#fff"
        android:gravity="center_vertical"
        android:visibility="visible" />
    <TextView
        android:layout_width="30dp"
        android:layout_height="24dp"
        android:text="12"
        android:textSize="12dp"
        android:textColor="#fff"
        android:gravity="center_horizontal"
        android:padding="1dp"
        android:visibility="visible" />
  </LinearLayout>  
</RelativeLayout>

Propagate all arguments in a bash shell script

I realize this has been well answered but here's a comparison between "$@" $@ "$*" and $*

Contents of test script:

# cat ./test.sh
#!/usr/bin/env bash
echo "================================="

echo "Quoted DOLLAR-AT"
for ARG in "$@"; do
    echo $ARG
done

echo "================================="

echo "NOT Quoted DOLLAR-AT"
for ARG in $@; do
    echo $ARG
done

echo "================================="

echo "Quoted DOLLAR-STAR"
for ARG in "$*"; do
    echo $ARG
done

echo "================================="

echo "NOT Quoted DOLLAR-STAR"
for ARG in $*; do
    echo $ARG
done

echo "================================="

Now, run the test script with various arguments:

# ./test.sh  "arg with space one" "arg2" arg3
=================================
Quoted DOLLAR-AT
arg with space one
arg2
arg3
=================================
NOT Quoted DOLLAR-AT
arg
with
space
one
arg2
arg3
=================================
Quoted DOLLAR-STAR
arg with space one arg2 arg3
=================================
NOT Quoted DOLLAR-STAR
arg
with
space
one
arg2
arg3
=================================

How do I convert a string to a double in Python?

The decimal operator might be more in line with what you are looking for:

>>> from decimal import Decimal
>>> x = "234243.434"
>>> print Decimal(x)
234243.434

How to make System.out.println() shorter

In Java 8 :

    List<String> players = new ArrayList<>();
     players.forEach(System.out::println);

From an array of objects, extract value of a property as array

Here is a shorter way of achieving it:

let result = objArray.map(a => a.foo);

OR

let result = objArray.map(({ foo }) => foo)

You can also check Array.prototype.map().

CSS3 equivalent to jQuery slideUp and slideDown?

So I've gone ahead and answered my own question :)

@True's answer regarded transforming an element to a specific height. The problem with this is I don't know the height of the element (it can fluctuate).

I found other solutions around which used max-height as the transition but this produced a very jerky animation for me.

My solution below works only in WebKit browsers.

Although not purely CSS, it involves transitioning the height, which is determined by some JS.

_x000D_
_x000D_
$('#click-me').click(function() {_x000D_
  var height = $("#this").height();_x000D_
  if (height > 0) {_x000D_
    $('#this').css('height', '0');_x000D_
  } else {_x000D_
    $("#this").css({_x000D_
      'position': 'absolute',_x000D_
      'visibility': 'hidden',_x000D_
      'height': 'auto'_x000D_
    });_x000D_
    var newHeight = $("#this").height();_x000D_
    $("#this").css({_x000D_
      'position': 'static',_x000D_
      'visibility': 'visible',_x000D_
      'height': '0'_x000D_
    });_x000D_
    $('#this').css('height', newHeight + 'px');_x000D_
  }_x000D_
});
_x000D_
#this {_x000D_
  width: 500px;_x000D_
  height: 0;_x000D_
  max-height: 9999px;_x000D_
  overflow: hidden;_x000D_
  background: #BBBBBB;_x000D_
  -webkit-transition: height 1s ease-in-out;_x000D_
}_x000D_
_x000D_
#click-me {_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>_x000D_
_x000D_
<p id="click-me">click me</p>_x000D_
<div id="this">here<br />is<br />a<br />bunch<br />of<br />content<br />sdf</div>_x000D_
<div>always shows</div>
_x000D_
_x000D_
_x000D_

View on JSFiddle

Copy all values in a column to a new column in a pandas dataframe

Here is your dataframe:

import pandas as pd
df = pd.DataFrame({
    'A': ['a.1', 'a.2', 'a.3'],
    'B': ['b.1', 'b.2', 'b.3'],
    'C': ['c.1', 'c.2', 'c.3']})

Your answer is in the paragraph "Setting with enlargement" in the section on "Indexing and selecting data" in the documentation on Pandas.

It says:

A DataFrame can be enlarged on either axis via .loc.

So what you need to do is simply one of these two:

df.loc[:, 'D'] = df.loc[:, 'B']
df.loc[:, 'D'] = df['B']

bash assign default value

Use a colon:

: ${A:=hello}

The colon is a null command that does nothing and ignores its arguments. It is built into bash so a new process is not created.

MySQL GROUP BY two columns

Using Concat on the group by will work

SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30

How to compare two JSON have the same properties without order?

lodash will work, tested even for angular 5, http://jsfiddle.net/L5qrfx3x/

var remoteJSON = {"allowExternalMembers": "false", "whoCanJoin": 
   "CAN_REQUEST_TO_JOIN"};
var localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN", 
  "allowExternalMembers": "false"};

 if(_.isEqual(remoteJSON, localJSON)){
     //TODO
    }

it works, for installation in angular, follow this

Getting an attribute value in xml element

How about:

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(new File("input.xml"));
        NodeList nodeList = document.getElementsByTagName("Item");
        for(int x=0,size= nodeList.getLength(); x<size; x++) {
            System.out.println(nodeList.item(x).getAttributes().getNamedItem("name").getNodeValue());
        }
    }
}

Run Command Prompt Commands

if you want to keep the cmd window open or want to use it in winform/wpf then use it like this

    string strCmdText;
//For Testing
    strCmdText= "/K ipconfig";

 System.Diagnostics.Process.Start("CMD.exe",strCmdText);

/K

Will keep the cmd window open

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

This is straightforward, readable solution using a simple regex.

// Get specific char in string
const char = string.charAt(index);

const isLowerCaseLetter = (/[a-z]/.test(char));
const isUpperCaseLetter = (/[A-Z]/.test(char));

ASP.NET MVC 3 - redirect to another action

Your method needs to return a ActionResult type:

public ActionResult Index()
{
    //All we want to do is redirect to the class selection page
    return RedirectToAction("SelectClasses", "Registration");
}

Trying to make bootstrap modal wider

You could try:

.modal.modal-wide .modal-dialog {
  width: 90%;
}

.modal-wide .modal-body {
  overflow-y: auto;
}

Just add .modal-wide to your classes

Save and load weights in keras

Since this question is quite old, but still comes up in google searches, I thought it would be good to point out the newer (and recommended) way to save Keras models. Instead of saving them using the older h5 format like has been shown before, it is now advised to use the SavedModel format, which is actually a dictionary that contains both the model configuration and the weights.

More information can be found here: https://www.tensorflow.org/guide/keras/save_and_serialize

The snippets to save & load can be found below:

model.fit(test_input, test_target)
# Calling save('my_model') creates a SavedModel folder 'my_model'.
model.save('my_model')

# It can be used to reconstruct the model identically.
reconstructed_model = keras.models.load_model('my_model')

A sample output of this :

enter image description here

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

Please add attribute useLegacyV2RuntimeActivationPolicy="true" in your applications app.config file.

Old Value

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
  </startup>

New Value

  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
  </startup>

It will solve your problem.

How can I get a uitableViewCell by indexPath?

For Swift 4

    let indexPath = IndexPath(row: 0, section: 0)
    let cell = tableView.cellForRow(at: indexPath)

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

If your h:commandLink is inside a h:dataTable there is another reason why the h:commandLink might not work:

The underlying data-source which is bound to the h:dataTable must also be available in the second JSF-Lifecycle that is triggered when the link is clicked.

So if the underlying data-source is request scoped, the h:commandLink does not work!

How to fire AJAX request Periodically?

I tried the below code,

    function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});

This didn't work as expected for the specified interval,the page didn't load completely and the function was been called continuously. Its better to call setTimeout(executeQuery, 5000); outside executeQuery() in a separate function as below,

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  updateCall();
}

function updateCall(){
setTimeout(function(){executeQuery()}, 5000);
}

$(document).ready(function() {
  executeQuery();
});

This worked exactly as intended.

How to size an Android view based on its parent's dimensions

Try this

int parentWidth = ((parentViewType)childView.getParent()).getWidth();
int parentHeight = ((parentViewType)childView.getParent()).getHeight();

then you can use LinearLayout.LayoutParams for setting the chileView's parameters

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(childWidth,childLength);
childView.setLayoutParams(params);

Add URL link in CSS Background Image?

Try wrapping the spans in an anchor tag and apply the background image to that.

HTML:

<div class="header">
    <a href="/">
        <span class="header-title">My gray sea design</span><br />
        <span class="header-title-two">A beautiful design</span>
    </a>
</div>

CSS:

.header {
    border-bottom:1px solid #eaeaea;
}

.header a {
    display: block;
    background-image: url("./images/embouchure.jpg");
    background-repeat: no-repeat;
    height:160px;
    padding-left:280px;
    padding-top:50px;
    width:470px;
    color: #eaeaea;
}

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

find . -type f -name "*.xls" -printf "xls2csv %p %p.csv\n" | bash

bash 4 (recursive)

shopt -s globstar
for xls in /path/**/*.xls
do
  xls2csv "$xls" "${xls%.xls}.csv"
done

get the titles of all open windows

Here’s some code you can use to get a list of all the open windows. Actually, you get a dictionary where each item is a KeyValuePair where the key is the handle (hWnd) of the window and the value is its title. It also finds pop-up windows, such as those created by MessageBox.Show.

using System.Runtime.InteropServices;
using HWND = System.IntPtr;

/// <summary>Contains functionality to get all the open windows.</summary>
public static class OpenWindowGetter
{
  /// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
  /// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
  public static IDictionary<HWND, string> GetOpenWindows()
  {
    HWND shellWindow = GetShellWindow();
    Dictionary<HWND, string> windows = new Dictionary<HWND, string>();

    EnumWindows(delegate(HWND hWnd, int lParam)
    {
      if (hWnd == shellWindow) return true;
      if (!IsWindowVisible(hWnd)) return true;

      int length = GetWindowTextLength(hWnd);
      if (length == 0) return true;

      StringBuilder builder = new StringBuilder(length);
      GetWindowText(hWnd, builder, length + 1);

      windows[hWnd] = builder.ToString();
      return true;

    }, 0);

    return windows;
  }

  private delegate bool EnumWindowsProc(HWND hWnd, int lParam);

  [DllImport("USER32.DLL")]
  private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

  [DllImport("USER32.DLL")]
  private static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);

  [DllImport("USER32.DLL")]
  private static extern int GetWindowTextLength(HWND hWnd);

  [DllImport("USER32.DLL")]
  private static extern bool IsWindowVisible(HWND hWnd);

  [DllImport("USER32.DLL")]
  private static extern IntPtr GetShellWindow();
}

And here’s some code that uses it:

foreach(KeyValuePair<IntPtr, string> window in OpenWindowGetter.GetOpenWindows())
{
  IntPtr handle = window.Key;
  string title = window.Value;

  Console.WriteLine("{0}: {1}", handle, title);
}

Credit: http://www.tcx.be/blog/2006/list-open-windows/

Regex doesn't work in String.matches()

Used

String[] words = {"{apf","hum_","dkoe","12f"};
    for(String s:words)
    {
        if(s.matches("[a-z]+"))
        {
            System.out.println(s);
        }
    }

How to make an embedded video not autoplay

A couple of wires are crossed here. The various autoplay settings that you're working with only affect whether the SWF's root timeline starts out paused or not. So if your SWF had a timeline animation, or if it had an embedded video on the root timeline, then these settings would do what you're after.

However, the SWF you're working with almost certainly has only one frame on its timeline, so these settings won't affect playback at all. That one frame contains some flavor of video playback component, which contains ActionScript that controls how the video behaves. To get that player component to start of paused, you'll have to change the settings of the component itself.

Without knowing more about where the content came from it's hard to say more, but when one publishes from Flash, video player components normally include a parameter for whether to autoplay. If your SWF is being published by an application other than Flash (Captivate, I suppose, but I'm not up on that) then your best bet would be to check the settings for that app. Anyway it's not something you can control from the level of the HTML page. (Unless you were talking to the SWF from JavaScript, and for that to work the video component would have to be designed to allow it.)

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

In XML there can be only one root element - you have two - heading and song.

If you restructure to something like:

<?xml version="1.0" encoding="UTF-8"?>
<song> 
 <heading>
 The Twelve Days of Christmas
 </heading>
 ....
</song>

The error about well-formed XML on the root level should disappear (though there may be other issues).

How to track down a "double free or corruption" error

Are you using smart pointers such as Boost shared_ptr? If so, check if you are directly using the raw pointer anywhere by calling get(). I've found this to be quite a common problem.

For example, imagine a scenario where a raw pointer is passed (maybe as a callback handler, say) to your code. You might decide to assign this to a smart pointer in order to cope with reference counting etc. Big mistake: your code doesn't own this pointer unless you take a deep copy. When your code is done with the smart pointer it will destroy it and attempt to destroy the memory it points to since it thinks that no-one else needs it, but the calling code will then try to delete it and you'll get a double free problem.

Of course, that might not be your problem here. At it's simplest here's an example which shows how it can happen. The first delete is fine but the compiler senses that it's already deleted that memory and causes a problem. That's why assigning 0 to a pointer immediately after deletion is a good idea.

int main(int argc, char* argv[])
{
    char* ptr = new char[20];

    delete[] ptr;
    ptr = 0;  // Comment me out and watch me crash and burn.
    delete[] ptr;
}

Edit: changed delete to delete[], as ptr is an array of char.

How can I pair socks from a pile efficiently?

Towards an efficient algorithm for pairing socks from a pile

Preconditions

  1. There must be at least one sock in the pile
  2. The table must be large enough to accommodate N/2 socks (worst case), where N is the total number of socks.

Algorithm

Try:

  1. Pick the first sock
  2. Put it down on the table
  3. Pick next sock, and look at it (may throw 'no more socks in the pile' exception)
  4. Now scan the socks on the table (throws exception if there are no socks left on the table)
  5. Is there any match? a) yes => remove the matching sock from the table b) no => put the sock on the table (may throw 'the table is not large enough' exception)

Except:

  • The table is not large enough:
       carefully mix all unpaired socks together, then resume operation
       // this operation will result in a new pile and an empty table

  • No socks left on the table:
       throw (the last unpairable sock)

  • No socks left in the pile:
       exit laundry room

Finally:

  • If there are still socks in the pile:
       goto 3

Known issues

The algorithm will enter an infinite loop if there is no table around or there is not enough place on the table to accommodate at least one sock.

Possible improvement

Depending on the number of socks to be sorted, throughput could be increased by sorting the socks on the table, provided there's enough space.

In order for this to work, an attribute is needed that has a unique value for each pair of socks. Such an attribute can be easily synthesized from the visual properties of the socks.

Sort the socks on the table by said attribute. Let's call that attribute ' colour'. Arrange the socks in a row, and put darker coloured socks to the right (i.e. .push_back()) and lighter coloured socks to the left (i.e. .push_front())

For huge piles and especially previously unseen socks, attribute synthesis might require significant time, so throughput will apparently decrease. However, these attributes can be persisted in memory and reused.

Some research is needed to evaluate the efficiency of this possible improvement. The following questions arise:

  • What is the optimal number of socks to be paired using above improvement?
  • For a given number of socks, how many iterations are needed before throughput increases?
    a) for the last iteration
    b) for all iterations overall

PoC in line with the MCVE guidelines:

#include <iostream>
#include <vector>
#include <string>
#include <time.h>

using namespace std;

struct pileOfsocks {
    pileOfsocks(int pairCount = 42) :
        elemCount(pairCount<<1) {
        srand(time(NULL));
        socks.resize(elemCount);

        vector<int> used_colors;
        vector<int> used_indices;

        auto getOne = [](vector<int>& v, int c) {
            int r;
            do {
                r = rand() % c;
            } while (find(v.begin(), v.end(), r) != v.end());
            v.push_back(r);
            return r;
        };

        for (auto i = 0; i < pairCount; i++) {
            auto sock_color = getOne(used_colors, INT_MAX);
            socks[getOne(used_indices, elemCount)] = sock_color;
            socks[getOne(used_indices, elemCount)] = sock_color;
        }
    }

    void show(const string& prompt) {
        cout << prompt << ":" << endl;
        for (auto i = 0; i < socks.size(); i++){
            cout << socks[i] << " ";
        }
        cout << endl;
    }

    void pair() {
        for (auto i = 0; i < socks.size(); i++) {
            std::vector<int>::iterator it = find(unpaired_socks.begin(), unpaired_socks.end(), socks[i]);
            if (it != unpaired_socks.end()) {
                unpaired_socks.erase(it);
                paired_socks.push_back(socks[i]);
                paired_socks.push_back(socks[i]);
            }
            else
                unpaired_socks.push_back(socks[i]);
        }

        socks = paired_socks;
        paired_socks.clear();
    }

private:
    int elemCount;
    vector<int> socks;
    vector<int> unpaired_socks;
    vector<int> paired_socks;
};

int main() {
    pileOfsocks socks;

    socks.show("unpaired socks");
    socks.pair();
    socks.show("paired socks");

    system("pause");
    return 0;
}

How do I bind to list of checkbox values with AngularJS?

Since you accepted an answer in which a list was not used, I'll assume the answer to my comment question is "No, it doesn't have to be a list". I also had the impression that maybe you were rending the HTML server side, since "checked" is present in your sample HTML (this would not be needed if ng-model were used to model your checkboxes).

Anyway, here's what I had in mind when I asked the question, also assuming you were generating the HTML server-side:

<div ng-controller="MyCtrl" 
 ng-init="checkboxes = {apple: true, orange: false, pear: true, naartjie: false}">
    <input type="checkbox" ng-model="checkboxes.apple">apple
    <input type="checkbox" ng-model="checkboxes.orange">orange
    <input type="checkbox" ng-model="checkboxes.pear">pear
    <input type="checkbox" ng-model="checkboxes.naartjie">naartjie
    <br>{{checkboxes}}
</div>

ng-init allows server-side generated HTML to initially set certain checkboxes.

Fiddle.

Create own colormap using matplotlib and plot color scale

There is an illustrative example of how to create custom colormaps here. The docstring is essential for understanding the meaning of cdict. Once you get that under your belt, you might use a cdict like this:

cdict = {'red':   ((0.0, 1.0, 1.0), 
                   (0.1, 1.0, 1.0),  # red 
                   (0.4, 1.0, 1.0),  # violet
                   (1.0, 0.0, 0.0)), # blue

         'green': ((0.0, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'blue':  ((0.0, 0.0, 0.0),
                   (0.1, 0.0, 0.0),  # red
                   (0.4, 1.0, 1.0),  # violet
                   (1.0, 1.0, 0.0))  # blue
          }

Although the cdict format gives you a lot of flexibility, I find for simple gradients its format is rather unintuitive. Here is a utility function to help generate simple LinearSegmentedColormaps:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors


def make_colormap(seq):
    """Return a LinearSegmentedColormap
    seq: a sequence of floats and RGB-tuples. The floats should be increasing
    and in the interval (0,1).
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)


c = mcolors.ColorConverter().to_rgb
rvb = make_colormap(
    [c('red'), c('violet'), 0.33, c('violet'), c('blue'), 0.66, c('blue')])
N = 1000
array_dg = np.random.uniform(0, 10, size=(N, 2))
colors = np.random.uniform(-2, 2, size=(N,))
plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=rvb)
plt.colorbar()
plt.show()

enter image description here


By the way, the for-loop

for i in range(0, len(array_dg)):
  plt.plot(array_dg[i], markers.next(),alpha=alpha[i], c=colors.next())

plots one point for every call to plt.plot. This will work for a small number of points, but will become extremely slow for many points. plt.plot can only draw in one color, but plt.scatter can assign a different color to each dot. Thus, plt.scatter is the way to go.

Missing MVC template in Visual Studio 2015

Other answer looks old.

For Visual Studio 2017, screen shots are below


New project


ASP.NET web Application


 MVC option


 MVC in solution explorer


How to get the hours difference between two date objects?

Try using getTime (mdn doc) :

var diff = Math.abs(date1.getTime() - date2.getTime()) / 3600000;
if (diff < 18) { /* do something */ }

Using Math.abs() we don't know which date is the smallest. This code is probably more relevant :

var diff = (date1 - date2) / 3600000;
if (diff < 18) { array.push(date1); }

How to fix Error: listen EADDRINUSE while using nodejs?

Try both commands and it will stop all node process.

killall 9 node
pkill node
npm start 

Insert new column into table in sqlite?

ALTER TABLE {tableName} ADD COLUMN COLNew {type};
UPDATE {tableName} SET COLNew = {base on {type} pass value here};

This update is required to handle the null value, inputting a default value as you require. As in your case, you need to call the SELECT query and you will get the order of columns, as paxdiablo already said:

SELECT name, colnew, qty, rate FROM{tablename}

and in my opinion, your column name to get the value from the cursor:

private static final String ColNew="ColNew";
String val=cursor.getString(cursor.getColumnIndex(ColNew));

so if the index changes your application will not face any problems.

This is the safe way in the sense that otherwise, if you are using CREATE temptable or RENAME table or CREATE, there would be a high chance of data loss if not handled carefully, for example in the case where your transactions occur while the battery is running out.

Npm install cannot find module 'semver'

On MS Windows, the solution is to remove %APPDATA%\npm and reinstall node

How do I upgrade PHP in Mac OS X?

Option #1

As recommended here, this site provides a convenient, up-to-date one liner.

This doesn't overwrite the base version of PHP on your system, but instead installs it cleanly in /usr/local/php5.

Option #2

My preferred method is to just install via Homebrew.

MySQL: How to set the Primary Key on phpMyAdmin?

MySQL can index the first x characters of a column,but a TEXT type is of variable length so mysql cant assure the uniqueness of the column.If you still want text column,use VARCHAR.

How can I solve "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."?

Both of the following work (as discussed here).

exec sp_rename 'ENG_TEst.[[ENG_Test_A/C_TYPE]]]' , 
                'ENG_Test_A/C_TYPE', 'COLUMN'


exec sp_rename 'ENG_TEst."[ENG_Test_A/C_TYPE]"' , 
                'ENG_Test_A/C_TYPE', 'COLUMN'

addClass and removeClass in jQuery - not removing class

The issue is caused because of event bubbling. The first part of your code to add .grown works fine.

The second part "removing grown class" on clicking the link doesn't work as expected as both the handler for .close_button and .clickable are executed. So it removes and readd the grown class to the div.

You can avoid this by using e.stopPropagation() inside .close_button click handler to avoid the event from bubbling.

DEMO: http://jsfiddle.net/vL8DP/

Full Code

$(document).on('click', '.clickable', function () {
   $(this).addClass('grown').removeClass('spot');
}).on('click', '.close_button', function (e) {
   e.stopPropagation();
   $(this).closest('.clickable').removeClass('grown').addClass('spot');
});

Multiple Python versions on the same machine?

I did this with anaconda navigator. I installed anaconda navigator and created two different development environments with different python versions

and switch between different python versions by switching or activating and deactivating environments.

first install anaconda navigator and then create environments.

see help here on how to manage environments

https://docs.anaconda.com/anaconda/navigator/tutorials/manage-environments/

Here is the video to do it with conda

https://youtu.be/EGaw6VXV3GI

Using IS NULL or IS NOT NULL on join conditions - Theory question

Example with tables A and B:

 A (parent)       B (child)    
============    =============
 id | name        pid | name 
------------    -------------
  1 | Alex         1  | Kate
  2 | Bill         1  | Lia
  3 | Cath         3  | Mary
  4 | Dale       NULL | Pan
  5 | Evan  

If you want to find parents and their kids, you do an INNER JOIN:

SELECT id,  parent.name AS parent
     , pid, child.name  AS child

FROM
        parent  INNER JOIN  child
  ON   parent.id     =    child.pid

Result is that every match of a parent's id from the left table and a child's pid from the second table will show as a row in the result:

+----+--------+------+-------+
| id | parent | pid  | child | 
+----+--------+------+-------+
|  1 | Alex   |   1  | Kate  |
|  1 | Alex   |   1  | Lia   |
|  3 | Cath   |   3  | Mary  |
+----+--------+------+-------+

Now, the above does not show parents without kids (because their ids do not have a match in child's ids, so what do you do? You do an outer join instead. There are three types of outer joins, the left, the right and the full outer join. We need the left one as we want the "extra" rows from the left table (parent):

SELECT id,  parent.name AS parent
     , pid, child.name  AS child

FROM
        parent  LEFT JOIN  child
  ON   parent.id    =    child.pid

Result is that besides previous matches, all parents that do not have a match (read: do not have a kid) are shown too:

+----+--------+------+-------+
| id | parent | pid  | child | 
+----+--------+------+-------+
|  1 | Alex   |   1  | Kate  |
|  1 | Alex   |   1  | Lia   |
|  3 | Cath   |   3  | Mary  |
|  2 | Bill   | NULL | NULL  |
|  4 | Dale   | NULL | NULL  |
|  5 | Evan   | NULL | NULL  |
+----+--------+------+-------+

Where did all those NULL come from? Well, MySQL (or any other RDBMS you may use) will not know what to put there as these parents have no match (kid), so there is no pid nor child.name to match with those parents. So, it puts this special non-value called NULL.

My point is that these NULLs are created (in the result set) during the LEFT OUTER JOIN.


So, if we want to show only the parents that do NOT have a kid, we can add a WHERE child.pid IS NULL to the LEFT JOIN above. The WHERE clause is evaluated (checked) after the JOIN is done. So, it's clear from the above result that only the last three rows where the pid is NULL will be shown:

SELECT id,  parent.name AS parent
     , pid, child.name  AS child

FROM
        parent  LEFT JOIN  child
  ON   parent.id    =    child.pid

WHERE child.pid IS NULL

Result:

+----+--------+------+-------+
| id | parent | pid  | child | 
+----+--------+------+-------+
|  2 | Bill   | NULL | NULL  |
|  4 | Dale   | NULL | NULL  |
|  5 | Evan   | NULL | NULL  |
+----+--------+------+-------+

Now, what happens if we move that IS NULL check from the WHERE to the joining ON clause?

SELECT id,  parent.name AS parent
     , pid, child.name  AS child

FROM
        parent  LEFT JOIN  child
  ON   parent.id    =    child.pid
  AND  child.pid IS NULL

In this case the database tries to find rows from the two tables that match these conditions. That is, rows where parent.id = child.pid AND child.pid IN NULL. But it can find no such match because no child.pid can be equal to something (1, 2, 3, 4 or 5) and be NULL at the same time!

So, the condition:

ON   parent.id    =    child.pid
AND  child.pid IS NULL

is equivalent to:

ON   1 = 0

which is always False.

So, why does it return ALL rows from the left table? Because it's a LEFT JOIN! And left joins return rows that match (none in this case) and also rows from the left table that do not match the check (all in this case):

+----+--------+------+-------+
| id | parent | pid  | child | 
+----+--------+------+-------+
|  1 | Alex   | NULL | NULL  |
|  2 | Bill   | NULL | NULL  |
|  3 | Cath   | NULL | NULL  |
|  4 | Dale   | NULL | NULL  |
|  5 | Evan   | NULL | NULL  |
+----+--------+------+-------+

I hope the above explanation is clear.



Sidenote (not directly related to your question): Why on earth doesn't Pan show up in none of our JOINs? Because his pid is NULL and NULL in the (not common) logic of SQL is not equal to anything so it can't match with any of the parent ids (which are 1,2,3,4 and 5). Even if there was a NULL there, it still wouldn't match because NULL does not equal anything, not even NULL itself (it's a very strange logic, indeed!). That's why we use the special check IS NULL and not a = NULL check.

So, will Pan show up if we do a RIGHT JOIN ? Yes, it will! Because a RIGHT JOIN will show all results that match (the first INNER JOIN we did) plus all rows from the RIGHT table that don't match (which in our case is one, the (NULL, 'Pan') row.

SELECT id,  parent.name AS parent
     , pid, child.name  AS child

FROM
        parent  RIGHT JOIN  child
  ON   parent.id     =    child.pid

Result:

+------+--------+------+-------+
| id   | parent | pid  | child | 
+---------------+------+-------+
|   1  | Alex   |   1  | Kate  |
|   1  | Alex   |   1  | Lia   |
|   3  | Cath   |   3  | Mary  |
| NULL | NULL   | NULL | Pan   |
+------+--------+------+-------+

Unfortunately, MySQL does not have FULL JOIN. You can try it in other RDBMSs, and it will show:

+------+--------+------+-------+
|  id  | parent | pid  | child | 
+------+--------+------+-------+
|   1  | Alex   |   1  | Kate  |
|   1  | Alex   |   1  | Lia   |
|   3  | Cath   |   3  | Mary  |
|   2  | Bill   | NULL | NULL  |
|   4  | Dale   | NULL | NULL  |
|   5  | Evan   | NULL | NULL  |
| NULL | NULL   | NULL | Pan   |
+------+--------+------+-------+

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

Make sure you have selected the correct version of Visual Studio. This is trickier than it seems because Visual Studio 2015 is actually Visual Studio 14, and similarly Visual Studio 2012 is Visual Studio 11. I had incorrectly selected Visual Studio 15 which is actually Visual Studio 2017, when I had 2015 installed.

Maven and adding JARs to system scope

Use a repository manager and install this kind of jars into it. That solves your problems at all and for all computers in your network.

PHP Configuration: It is not safe to rely on the system's timezone settings

Open your .htaccess file , add this line to the file, save, and try again :

php_value date.timezone "America/Sao_Paulo"

This works for me.

How to do a scatter plot with empty circles in Python?

So I assume you want to highlight some points that fit a certain criteria. You can use Prelude's command to do a second scatter plot of the hightlighted points with an empty circle and a first call to plot all the points. Make sure the s paramter is sufficiently small for the larger empty circles to enclose the smaller filled ones.

The other option is to not use scatter and draw the patches individually using the circle/ellipse command. These are in matplotlib.patches, here is some sample code on how to draw circles rectangles etc.

Perform an action in every sub-directory using Bash

Use find command.

In GNU find, you can use -execdir parameter:

find . -type d -execdir realpath "{}" ';'

or by using -exec parameter:

find . -type d -exec sh -c 'cd -P "$0" && pwd -P' {} \;

or with xargs command:

find . -type d -print0 | xargs -0 -L1 sh -c 'cd "$0" && pwd && echo Do stuff'

Or using for loop:

for d in */; { echo "$d"; }

For recursivity try extended globbing (**/) instead (enable by: shopt -s extglob).


For more examples, see: How to go to each directory and execute a command? at SO

java comparator, how to sort by integer?

From Java 8 you can use :

Comparator.comparingInt(Dog::getDogAge).reversed();

mySQL :: insert into table, data from another table?

Answered by zerkms is the correct method. But, if someone looking to insert more extra column in the table then you can get it from the following:

INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`)
SELECT `campaign_id`, `from_number`, '[email protected]', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8'

In the above query, there are 2 extra columns named email & current_time.

Should Gemfile.lock be included in .gitignore?

The real problem happens when you are working on an open-source Rails app that needs to have a configurable database adapter. I'm developing the Rails 3 branch of Fat Free CRM. My preference is postgres, but we want the default database to be mysql2.

In this case, Gemfile.lock still needs be checked in with the default set of gems, but I need to ignore changes that I have made to it on my machine. To accomplish this, I run:

git update-index --assume-unchanged Gemfile.lock

and to reverse:

git update-index --no-assume-unchanged Gemfile.lock

It is also useful to include something like the following code in your Gemfile. This loads the appropriate database adapter gem, based on your database.yml.

# Loads the database adapter gem based on config/database.yml (Default: mysql2)
# -----------------------------------------------------------------------------
db_gems = {"mysql2"     => ["mysql2", ">= 0.2.6"],
           "postgresql" => ["pg",     ">= 0.9.0"],
           "sqlite3"    => ["sqlite3"]}
adapter = if File.exists?(db_config = File.join(File.dirname(__FILE__),"config","database.yml"))
  db = YAML.load_file(db_config)
  # Fetch the first configured adapter from config/database.yml
  (db["production"] || db["development"] || db["test"])["adapter"]
else
  "mysql2"
end
gem *db_gems[adapter]
# -----------------------------------------------------------------------------

I can't say if this is an established best practice or not, but it works well for me.

How to scroll table's "tbody" independent of "thead"?

try this.

table 
{
    background-color: #aaa;
}

tbody 
{
    background-color: #ddd;
    height: 100px;
    overflow-y: scroll;
    position: absolute;
}

td 
{
    padding: 3px 10px;
    color: green;
    width: 100px;
}

Checking if a character is a special character in Java

You can use regular expressions.

String input = ...
if (input.matches("[^a-zA-Z0-9 ]"))

If your definition of a 'special character' is simply anything that doesn't apply to your other filters that you already have, then you can simply add an else. Also note that you have to use else if in this case:

if(c == ' ') {
    blankCount++;
} else if (Character.isDigit(c)) {
    digitCount++;
} else if (Character.isLetter(c)) {
    letterCount++;
} else { 
  specialcharCount++;
}

Get current clipboard content?

You can use

window.clipboardData.getData('Text')

to get the content of user's clipboard in IE. However, in other browser you may need to use flash to get the content, since there is no standard interface to access the clipboard. May be you can have try this plugin Zero Clipboard

Complexities of binary tree traversals

In-order, Pre-order, and Post-order traversals are Depth-First traversals.

For a Graph, the complexity of a Depth First Traversal is O(n + m), where n is the number of nodes, and m is the number of edges.

Since a Binary Tree is also a Graph, the same applies here. The complexity of each of these Depth-first traversals is O(n+m).

Since the number of edges that can originate from a node is limited to 2 in the case of a Binary Tree, the maximum number of total edges in a Binary Tree is n-1, where n is the total number of nodes.

The complexity then becomes O(n + n-1), which is O(n).

jQuery same click event for multiple elements

In addition to the excellent examples and answers above, you can also do a "find" for two different elements using their classes. For example:

<div class="parent">
<div class="child1">Hello</div>
<div class="child2">World</div>
</div>

<script>
var x = jQuery('.parent').find('.child1, .child2').text();
console.log(x);
</script>

This should output "HelloWorld".

How to uninstall with msiexec using product id guid without .msi file present

msiexec.exe /x "{588A9A11-1E20-4B91-8817-2D36ACBBBF9F}" /q 

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

You likely have Hyper-V enabled. The manual installer provides this detailed notice when it refuses to install on a Windows with it on.

This computer does not support Intel Virtualization Technology (VT-x) or it is being exclusively used by Hyper-V. HAXM cannot be installed. Please ensure Hyper-V is disabled in Windows Features, or refer to the Intel HAXM documentation for more information.

No function matches the given name and argument types

That error means that a function call is only matched by an existing function if all its arguments are of the same type and passed in same order. So if the next f() function

create function f() returns integer as $$ 
    select 1;
$$ language sql;

is called as

select f(1);

It will error out with

ERROR:  function f(integer) does not exist
LINE 1: select f(1);
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

because there is no f() function that takes an integer as argument.

So you need to carefully compare what you are passing to the function to what it is expecting. That long list of table columns looks like bad design.

How do I git rm a file without deleting it from disk?

git rm --cached file

should do what you want.

You can read more details at git help rm

Count distinct values

I think this link is pretty good.

Sample output from that link:

mysql> SELECT cate_id,COUNT(DISTINCT(pub_lang)), ROUND(AVG(no_page),2)
    -> FROM book_mast
    -> GROUP BY cate_id;
+---------+---------------------------+-----------------------+
| cate_id | COUNT(DISTINCT(pub_lang)) | ROUND(AVG(no_page),2) |
+---------+---------------------------+-----------------------+
| CA001   |                         2 |                264.33 | 
| CA002   |                         1 |                433.33 | 
| CA003   |                         2 |                256.67 | 
| CA004   |                         3 |                246.67 | 
| CA005   |                         3 |                245.75 | 
+---------+---------------------------+-----------------------+
5 rows in set (0.00 sec)

Query to count the number of tables I have in MySQL

SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'dbName';

Source

This is mine:

USE databasename; 
SHOW TABLES; 
SELECT FOUND_ROWS();

Determine if a cell (value) is used in any formula

On Excel 2010 try this:

  1. select the cell you want to check if is used somewhere in a formula;
  2. Formulas -> Trace Dependents (on Formula Auditing menu)

Checking if my Windows application is running

you can simply use varialbles and one file to check for running your program. when open the file contain a value and when program closes changes this value to another one.

Always pass weak reference of self into block in ARC?

I totally agree with @jemmons:

But this should not be the default pattern you follow when dealing with blocks that call self! This should only be used to break what would otherwise be a retain cycle between self and the block. If you were to adopt this pattern everywhere, you'd run the risk of passing a block to something that got executed after self was deallocated.

//SUSPICIOUS EXAMPLE:
__weak MyObject *weakSelf = self;
[[SomeOtherObject alloc] initWithCompletion:^{
  //By the time this gets called, "weakSelf" might be nil because it's not  retained!
  [weakSelf doSomething];
}];

To overcome this problem one can define a strong reference over the weakSelf inside the block:

__weak MyObject *weakSelf = self;
[[SomeOtherObject alloc] initWithCompletion:^{
  MyObject *strongSelf = weakSelf;
  [strongSelf doSomething];
}];

Runtime vs. Compile time

Imagine that you are a boss and you have an assistant and a maid, and you give them a list of tasks to do, the assistant (compile time) will grab this list and make a checkup to see if the tasks are understandable and that you didn't write in any awkward language or syntax, so he understands that you want to assign someone for a Job so he assign him for you and he understand that you want some coffee, so his role is over and the maid (run time)starts to run those tasks so she goes to make you some coffee but in sudden she doesn’t find any coffee to make so she stops making it or she acts differently and make you some tea (when the program acts differently because he found an error).

How to call function that takes an argument in a Django template?

By design, Django templates cannot call into arbitrary Python code. This is a security and safety feature for environments where designers write templates, and it also prevents business logic migrating into templates.

If you want to do this, you can switch to using Jinja2 templates (http://jinja.pocoo.org/docs/), or any other templating system you like that supports this. No other part of django will be affected by the templates you use, because it is intentionally a one-way process. You could even use many different template systems in the same project if you wanted.

Cannot open include file 'afxres.h' in VC2010 Express

Had the same problem . Fixed it by installing Microsoft Foundation Classes for C++.

  1. Start
  2. Change or remove program (type)
  3. Microsoft Visual Studio
  4. Modify
  5. Select 'Microsoft Foundation Classes for C++'
  6. Update

enter image description here

Select value from list of tuples where condition

Yes, you can use filter if you know at which position in the tuple the desired column resides. If the case is that the id is the first element of the tuple then you can filter the list like so:

filter(lambda t: t[0]==10, mylist)

This will return the list of corresponding tuples. If you want the age, just pick the element you want. Instead of filter you could also use list comprehension and pick the element in the first go. You could even unpack it right away (if there is only one result):

[age] = [t[1] for t in mylist if t[0]==10]

But I would strongly recommend to use dictionaries or named tuples for this purpose.

How to create an empty R vector to add new items

I pre-allocate a vector with

> (a <- rep(NA, 10))
 [1] NA NA NA NA NA NA NA NA NA NA

You can then use [] to insert values into it.

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

You can use ButtonTheme() also

enter image description here

Here is a example code -

ButtonTheme(
              minWidth: 200.0,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(18.0),
                  side: BorderSide(color: Colors.green)),
              child: RaisedButton(
                elevation: 5.0,
                hoverColor: Colors.green,
                color: Colors.amber,
                child: Text(
                  "Place Order",
                  style: TextStyle(
                      color: Colors.white, fontWeight: FontWeight.bold),
                ),
                onPressed: () {},
              ),
            ),

how can select from drop down menu and call javascript function

Greetings if i get you right you need a JavaScript function that doing it

function report(v) {
//To Do
  switch(v) {
    case "daily":
      //Do something
      break;
    case "monthly":
      //Do somthing
      break;
    }
  }

Regards

Android Button Onclick

Here is some sample code of how to add a button named Add. You should declare the variable as a member variable, and the naming convention for member variables is to start with the letter "m".

Hit Alt+Enter on the classes to add the missing references.

Add this to your activity_main.xml:

 <Button
        android:id="@+id/buttonAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ADD"
     />

Add this to your MainActivity.java:

public class MainActivity extends AppCompatActivity {

    Button mButtonAdd; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButtonAdd = findViewById(R.id.buttonAdd);

        mButtonAdd.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // do something here
            }
        });
    }
}

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

CSS3 scrollbar styling on a div

You're setting overflow: hidden. This will hide anything that's too large for the <div>, meaning scrollbars won't be shown. Give your <div> an explicit width and/or height, and change overflow to auto:

.scroll {
   width: 200px;
   height: 400px;
   overflow: scroll;
}

If you only want to show a scrollbar if the content is longer than the <div>, change overflow to overflow: auto. You can also only show one scrollbar by using overflow-y or overflow-x.

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

There a small difference when u use rgba(255,255,255,a),background color becomes more and more lighter as the value of 'a' increase from 0.0 to 1.0. Where as when use rgba(0,0,0,a), the background color becomes more and more darker as the value of 'a' increases from 0.0 to 1.0. Having said that, its clear that both (255,255,255,0) and (0,0,0,0) make background transparent. (255,255,255,1) would make the background completely white where as (0,0,0,1) would make background completely black.

How do you add an in-app purchase to an iOS application?

Swift Users

Swift users can check out My Swift Answer for this question.
Or, check out Yedidya Reiss's Answer, which translates this Objective-C code to Swift.

Objective-C Users

The rest of this answer is written in Objective-C

App Store Connect

  1. Go to appstoreconnect.apple.com and log in
  2. Click My Apps then click the app you want do add the purchase to
  3. Click the Features header, and then select In-App Purchases on the left
  4. Click the + icon in the middle
  5. For this tutorial, we are going to be adding an in-app purchase to remove ads, so choose non-consumable. If you were going to send a physical item to the user, or give them something that they can buy more than once, you would choose consumable.
  6. For the reference name, put whatever you want (but make sure you know what it is)
  7. For product id put tld.websitename.appname.referencename this will work the best, so for example, you could use com.jojodmo.blix.removeads
  8. Choose cleared for sale and then choose price tier as 1 (99¢). Tier 2 would be $1.99, and tier 3 would be $2.99. The full list is available if you click view pricing matrix I recommend you use tier 1, because that's usually the most anyone will ever pay to remove ads.
  9. Click the blue add language button, and input the information. This will ALL be shown to the customer, so don't put anything you don't want them seeing
  10. For hosting content with Apple choose no
  11. You can leave the review notes blank FOR NOW.
  12. Skip the screenshot for review FOR NOW, everything we skip we will come back to.
  13. Click 'save'

It could take a few hours for your product ID to register in App Store Connect, so be patient.

Setting up your project

Now that you've set up your in-app purchase information on App Store Connect, go into your Xcode project, and go to the application manager (blue page-like icon at the top of where your methods and header files are) click on your app under targets (should be the first one) then go to general. At the bottom, you should see linked frameworks and libraries click the little plus symbol and add the framework StoreKit.framework If you don't do this, the in-app purchase will NOT work!

If you are using Objective-C as the language for your app, you should skip these five steps. Otherwise, if you are using Swift, you can follow My Swift Answer for this question, here, or, if you prefer to use Objective-C for the In-App Purchase code but are using Swift in your app, you can do the following:

  1. Create a new .h (header) file by going to File > New > File... (Command ? + N). This file will be referred to as "Your .h file" in the rest of the tutorial

  2. When prompted, click Create Bridging Header. This will be our bridging header file. If you are not prompted, go to step 3. If you are prompted, skip step 3 and go directly to step 4.

  3. Create another .h file named Bridge.h in the main project folder, Then go to the Application Manager (the blue page-like icon), then select your app in the Targets section, and click Build Settings. Find the option that says Swift Compiler - Code Generation, and then set the Objective-C Bridging Header option to Bridge.h

  4. In your bridging header file, add the line #import "MyObjectiveCHeaderFile.h", where MyObjectiveCHeaderFile is the name of the header file that you created in step one. So, for example, if you named your header file InAppPurchase.h, you would add the line #import "InAppPurchase.h" to your bridge header file.

  5. Create a new Objective-C Methods (.m) file by going to File > New > File... (Command ? + N). Name it the same as the header file you created in step 1. For example, if you called the file in step 1 InAppPurchase.h, you would call this new file InAppPurchase.m. This file will be referred to as "Your .m file" in the rest of the tutorial.

Coding

Now we're going to get into the actual coding. Add the following code into your .h file:

BOOL areAdsRemoved;

- (IBAction)restore;
- (IBAction)tapsRemoveAds;

Next, you need to import the StoreKit framework into your .m file, as well as add SKProductsRequestDelegate and SKPaymentTransactionObserver after your @interface declaration:

#import <StoreKit/StoreKit.h>

//put the name of your view controller in place of MyViewController
@interface MyViewController() <SKProductsRequestDelegate, SKPaymentTransactionObserver>

@end

@implementation MyViewController //the name of your view controller (same as above)
  //the code below will be added here
@end

and now add the following into your .m file, this part gets complicated, so I suggest that you read the comments in the code:

//If you have more than one in-app purchase, you can define both of
//of them here. So, for example, you could define both kRemoveAdsProductIdentifier
//and kBuyCurrencyProductIdentifier with their respective product ids
//
//for this example, we will only use one product

#define kRemoveAdsProductIdentifier @"put your product id (the one that we just made in App Store Connect) in here"

- (IBAction)tapsRemoveAds{
    NSLog(@"User requests to remove ads");

    if([SKPaymentQueue canMakePayments]){
        NSLog(@"User can make payments");
    
        //If you have more than one in-app purchase, and would like
        //to have the user purchase a different product, simply define 
        //another function and replace kRemoveAdsProductIdentifier with 
        //the identifier for the other product

        SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:kRemoveAdsProductIdentifier]];
        productsRequest.delegate = self;
        [productsRequest start];
    
    }
    else{
        NSLog(@"User cannot make payments due to parental controls");
        //this is called the user cannot make payments, most likely due to parental controls
    }
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    SKProduct *validProduct = nil;
    int count = [response.products count];
    if(count > 0){
        validProduct = [response.products objectAtIndex:0];
        NSLog(@"Products Available!");
        [self purchase:validProduct];
    }
    else if(!validProduct){
        NSLog(@"No products available");
        //this is called if your product id is not valid, this shouldn't be called unless that happens.
    }
}

- (void)purchase:(SKProduct *)product{
    SKPayment *payment = [SKPayment paymentWithProduct:product];

    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

- (IBAction) restore{
    //this is called when the user restores purchases, you should hook this up to a button
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

- (void) paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue
{
    NSLog(@"received restored transactions: %i", queue.transactions.count);
    for(SKPaymentTransaction *transaction in queue.transactions){
        if(transaction.transactionState == SKPaymentTransactionStateRestored){
            //called when the user successfully restores a purchase
            NSLog(@"Transaction state -> Restored");

            //if you have more than one in-app purchase product,
            //you restore the correct product for the identifier.
            //For example, you could use
            //if(productID == kRemoveAdsProductIdentifier)
            //to get the product identifier for the
            //restored purchases, you can use
            //
            //NSString *productID = transaction.payment.productIdentifier;
            [self doRemoveAds];
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            break;
        }
    }   
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
    for(SKPaymentTransaction *transaction in transactions){
        //if you have multiple in app purchases in your app,
        //you can get the product identifier of this transaction
        //by using transaction.payment.productIdentifier
        //
        //then, check the identifier against the product IDs
        //that you have defined to check which product the user
        //just purchased            

        switch(transaction.transactionState){
            case SKPaymentTransactionStatePurchasing: NSLog(@"Transaction state -> Purchasing");
                //called when the user is in the process of purchasing, do not add any of your own code here.
                break;
            case SKPaymentTransactionStatePurchased:
            //this is called when the user has successfully purchased the package (Cha-Ching!)
                [self doRemoveAds]; //you can add your code for what you want to happen when the user buys the purchase here, for this tutorial we use removing ads
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                NSLog(@"Transaction state -> Purchased");
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"Transaction state -> Restored");
                //add the same code as you did from SKPaymentTransactionStatePurchased here
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                //called when the transaction does not finish
                if(transaction.error.code == SKErrorPaymentCancelled){
                    NSLog(@"Transaction state -> Cancelled");
                    //the user cancelled the payment ;(
                }
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;
        }
    }
}

Now you want to add your code for what will happen when the user finishes the transaction, for this tutorial, we use removing adds, you will have to add your own code for what happens when the banner view loads.

- (void)doRemoveAds{
    ADBannerView *banner;
    [banner setAlpha:0];
    areAdsRemoved = YES;
    removeAdsButton.hidden = YES;
    removeAdsButton.enabled = NO;
    [[NSUserDefaults standardUserDefaults] setBool:areAdsRemoved forKey:@"areAdsRemoved"];
    //use NSUserDefaults so that you can load whether or not they bought it
    //it would be better to use KeyChain access, or something more secure
    //to store the user data, because NSUserDefaults can be changed.
    //You're average downloader won't be able to change it very easily, but
    //it's still best to use something more secure than NSUserDefaults.
    //For the purpose of this tutorial, though, we're going to use NSUserDefaults
    [[NSUserDefaults standardUserDefaults] synchronize];
}

If you don't have ads in your application, you can use any other thing that you want. For example, we could make the color of the background blue. To do this we would want to use:

- (void)doRemoveAds{
    [self.view setBackgroundColor:[UIColor blueColor]];
    areAdsRemoved = YES
    //set the bool for whether or not they purchased it to YES, you could use your own boolean here, but you would have to declare it in your .h file

    [[NSUserDefaults standardUserDefaults] setBool:areAdsRemoved forKey:@"areAdsRemoved"];
    //use NSUserDefaults so that you can load wether or not they bought it
    [[NSUserDefaults standardUserDefaults] synchronize];
}

Now, somewhere in your viewDidLoad method, you're going to want to add the following code:

areAdsRemoved = [[NSUserDefaults standardUserDefaults] boolForKey:@"areAdsRemoved"];
[[NSUserDefaults standardUserDefaults] synchronize];
//this will load wether or not they bought the in-app purchase

if(areAdsRemoved){
    [self.view setBackgroundColor:[UIColor blueColor]];
    //if they did buy it, set the background to blue, if your using the code above to set the background to blue, if your removing ads, your going to have to make your own code here
}

Now that you have added all the code, go into your .xib or storyboard file, and add two buttons, one saying purchase, and the other saying restore. Hook up the tapsRemoveAds IBAction to the purchase button that you just made, and the restore IBAction to the restore button. The restore action will check if the user has previously purchased the in-app purchase, and give them the in-app purchase for free if they do not already have it.

Submitting for review

Next, go into App Store Connect, and click Users and Access then click the Sandbox Testers header, and then click the + symbol on the left where it says Testers. You can just put in random things for the first and last name, and the e-mail does not have to be real - you just have to be able to remember it. Put in a password (which you will have to remember) and fill in the rest of the info. I would recommend that you make the Date of Birth a date that would make the user 18 or older. App Store Territory HAS to be in the correct country. Next, log out of your existing iTunes account (you can log back in after this tutorial).

Now, run your application on your iOS device, if you try running it on the simulator, the purchase will always error, you HAVE TO run it on your iOS device. Once the app is running, tap the purchase button. When you are prompted to log into your iTunes account, log in as the test user that we just created. Next,when it asks you to confirm the purchase of 99¢ or whatever you set the price tier too, TAKE A SCREEN SNAPSHOT OF IT this is what your going to use for your screenshot for review on App Store Connect. Now cancel the payment.

Now, go to App Store Connect, then go to My Apps > the app you have the In-app purchase on > In-App Purchases. Then click your in-app purchase and click edit under the in-app purchase details. Once you've done that, import the photo that you just took on your iPhone into your computer, and upload that as the screenshot for review, then, in review notes, put your TEST USER e-mail and password. This will help apple in the review process.

After you have done this, go back onto the application on your iOS device, still logged in as the test user account, and click the purchase button. This time, confirm the payment Don't worry, this will NOT charge your account ANY money, test user accounts get all in-app purchases for free After you have confirmed the payment, make sure that what happens when the user buys your product actually happens. If it doesn't, then thats going to be an error with your doRemoveAds method. Again, I recommend using changing the background to blue for testing the in-app purchase, this should not be your actual in-app purchase though. If everything works and you're good to go! Just make sure to include the in-app purchase in your new binary when you upload it to App Store Connect!


Here are some common errors:

Logged: No Products Available

This could mean four things:

  • You didn't put the correct in-app purchase ID in your code (for the identifier kRemoveAdsProductIdentifier in the above code
  • You didn't clear your in-app purchase for sale on App Store Connect
  • You didn't wait for the in-app purchase ID to be registered in App Store Connect. Wait a couple hours from creating the ID, and your problem should be resolved.
  • You didn't complete filling your Agreements, Tax, and Banking info.

If it doesn't work the first time, don't get frustrated! Don't give up! It took me about 5 hours straight before I could get this working, and about 10 hours searching for the right code! If you use the code above exactly, it should work fine. Feel free to comment if you have any questions at all.

I hope this helps to all of those hoping to add an in-app purchase to their iOS application. Cheers!

How do I draw a circle in iOS Swift?

If you want to use a UIView to draw it, then you need to make the radius / of the height or width.

so just change:

block.layer.cornerRadius = 9

to:

block.layer.cornerRadius = block.frame.width / 2

You'll need to make the height and width the same however. If you'd like to use coregraphics, then you'll want to do something like this:

CGContextRef ctx= UIGraphicsGetCurrentContext();
CGRect bounds = [self bounds];

CGPoint center;
center.x = bounds.origin.x + bounds.size.width / 2.0;
center.y = bounds.origin.y + bounds.size.height / 2.0;
CGContextSaveGState(ctx);

CGContextSetLineWidth(ctx,5);
CGContextSetRGBStrokeColor(ctx,0.8,0.8,0.8,1.0);
CGContextAddArc(ctx,locationOfTouch.x,locationOfTouch.y,30,0.0,M_PI*2,YES);
CGContextStrokePath(ctx);

What is the difference between . (dot) and $ (dollar sign)?

The $ operator is for avoiding parentheses. Anything appearing after it will take precedence over anything that comes before.

For example, let's say you've got a line that reads:

putStrLn (show (1 + 1))

If you want to get rid of those parentheses, any of the following lines would also do the same thing:

putStrLn (show $ 1 + 1)
putStrLn $ show (1 + 1)
putStrLn $ show $ 1 + 1

The primary purpose of the . operator is not to avoid parentheses, but to chain functions. It lets you tie the output of whatever appears on the right to the input of whatever appears on the left. This usually also results in fewer parentheses, but works differently.

Going back to the same example:

putStrLn (show (1 + 1))
  1. (1 + 1) doesn't have an input, and therefore cannot be used with the . operator.
  2. show can take an Int and return a String.
  3. putStrLn can take a String and return an IO ().

You can chain show to putStrLn like this:

(putStrLn . show) (1 + 1)

If that's too many parentheses for your liking, get rid of them with the $ operator:

putStrLn . show $ 1 + 1

Generate UML Class Diagram from Java Project

How about the Omondo Plugin for Eclipse. I have used it and I find it to be quite useful. Although if you are generating diagrams for large sources, you might have to start Eclipse with more memory.

Force IE9 to emulate IE8. Possible?

Yes. Recent versions of IE (IE8 or above) let you adjust that. Here's how:

  • Fire up Internet Explorer.
  • Click the 'Tools' menu, then click 'Developer Tools'. Alternatively, just press F12.

That should open the Developer Tools window. That window has two menu items that are of interest:

  • Browser Mode. This setting determines the value of the user-agent header sent for every request.
  • Document Mode. This setting determines how the rendering engine renders the page.

More at http://blogs.msdn.com/b/ie/archive/2010/06/16/ie-s-compatibility-features-for-site-developers.aspx

Get properties of a class

Another solution, You can just iterate over the object keys like so, Note: you must use an instantiated object with existing properties:

printTypeNames<T>(obj: T) {
    const objectKeys = Object.keys(obj) as Array<keyof T>;
    for (let key of objectKeys)
    {
       console.log('key:' + key);
    }
}

SQL Server after update trigger

Here is my example after a test

CREATE TRIGGER [dbo].UpdateTasadoresName 
ON [dbo].Tasadores  
FOR  UPDATE
AS 
      UPDATE Tasadores 
      SET NombreCompleto = RTRIM( Tasadores.Nombre + ' ' + isnull(Tasadores.ApellidoPaterno,'') + ' ' + isnull(Tasadores.ApellidoMaterno,'')    )  
      FROM Tasadores 
    INNER JOIN INSERTED i ON Tasadores.id = i.id

The inserted special table will have the information from the updated record.

Converting int to string in C

void itos(int value, char* str, size_t size) {
    snprintf(str, size, "%d", value);
}

..works with call by reference. Use it like this e.g.:

int someIntToParse;
char resultingString[length(someIntToParse)];

itos(someIntToParse, resultingString, length(someIntToParse));

now resultingString will hold your C-'string'.

How to get the IP address of the docker host from inside a docker container

The solution I use is based on a "server" that returns the external address of the Docker host when it receives a http request.

On the "server":

1) Start jwilder/nginx-proxy

# docker run -d -p <external server port>:80 -v /var/run/docker.sock:/tmp/docker.sock:ro jwilder/nginx-proxy

2) Start ipify container

# docker run -e VIRTUAL_HOST=<external server name/address> --detach --name ipify osixia/ipify-api:0.1.0

Now when a container sends a http request to the server, e.g.

# curl http://<external server name/address>:<external server port>

the IP address of the Docker host is returned by ipify via http header "X-Forwarded-For"

Example (ipify server has name "ipify.example.com" and runs on port 80, docker host has IP 10.20.30.40):

# docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock:ro jwilder/nginx-proxy
# docker run -e VIRTUAL_HOST=ipify.example.com --detach --name ipify osixia/ipify-api:0.1.0

Inside the container you can now call:

# curl http://ipify.example.com
10.20.30.40

How to set background color of a button in Java GUI?

Simple:

btn.setBackground(Color.red);

To use RGB values:

btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));

Extracting hours from a DateTime (SQL Server 2005)

I can't extract hours, with HOUR(Date())

There is a way to call HOUR (I would not recommend to use it though because there is DATEPART function) using ODBC Scalar Functions:

SELECT {fn HOUR(GETDATE())} AS hour

LiveDemo

How to write a link like <a href="#id"> which link to the same page in PHP?

try this

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <body>
        <a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
        <div name="name" id="name">here</div>
    </body>
    </html>

How to recursively find and list the latest modified files in a directory with subdirectories and times

@anubhava's answer is great, but unfortunately won't work on BSD tools – i.e. it won't work with the find that comes installed by default on macOS, because BSD find doesn't have the -printf operator.

So here's a variation that works with macOS + BSD (tested on my Catalina Mac), which combines BSD find with xargs and stat:

$ find . -type f -print0 \
      | xargs -0 -n1 -I{} stat -f '%Fm %N' "{}" \
      | sort -rn 

While I'm here, here's BSD command sequence I like to use, which puts the timestamp in ISO-8601 format

$ find . -type f -print0 \
    | xargs -0 -n1 -I{} \
       stat  -f '%Sm %N' -t '%Y-%m-%d %H:%M:%S' "{}" \
    | sort -rn

(note that both my answers, unlike @anubhava's, pass the filenames from find to xargs as a single argument rather than a \0 terminated list, which changes what gets piped out at the very end)

And here's the GNU version (i.e. @anubhava's answer, but in iso-8601 format):

$ gfind . -type f -printf "%T+ %p\0" | sort -zk1nr

Related q: find lacks the option -printf, now what?

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


Show/Hide Multiple Divs with Jquery

If you want to be able to show / hide singular divs and / or groups of divs with less code, just apply several classes to them, to insert them into groups if needed.

Example :

.group1 {}
.group2 {}
.group3 {}

<div class="group3"></div>
<div class="group1 group2"></div>
<div class="group1 group3 group2"></div>

Then you just need to use an identifier to link the action to he target, and with 5,6 lines of jquery code you have everything you need.

How to consume REST in Java

From your question its not clear whether you are using any frameworks.For REST you will be getting an WADL & Apache CXF recently added support for WADL-first development of REST services.Please go through http://cxf.apache.org/docs/index.html

Pandas Merging 101

A supplemental visual view of pd.concat([df0, df1], kwargs). Notice that, kwarg axis=0 or axis=1 's meaning is not as intuitive as df.mean() or df.apply(func)


on pd.concat([df0, df1])

How to consume a webApi from asp.net Web API to store result in database?

public class EmployeeApiController : ApiController
{
    private readonly IEmployee _employeeRepositary;

    public EmployeeApiController()
    {
        _employeeRepositary = new EmployeeRepositary();
    }

    public async Task<HttpResponseMessage> Create(EmployeeModel Employee)
    {
        var returnStatus = await _employeeRepositary.Create(Employee);
        return Request.CreateResponse(HttpStatusCode.OK, returnStatus);
    }
} 

Persistance

public async Task<ResponseStatusViewModel> Create(EmployeeModel Employee)
{    
    var responseStatusViewModel = new ResponseStatusViewModel();
    var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
                var command = new SqlCommand("usp_CreateEmployee", connection);
                command.CommandType = CommandType.StoredProcedure;
                var pEmployeeName = new SqlParameter("@EmployeeName", SqlDbType.VarChar, 50);
                pEmployeeName.Value = Employee.EmployeeName;
                command.Parameters.Add(pEmployeeName);


                try
                {
                    await connection.OpenAsync();
                    await command.ExecuteNonQueryAsync();

                    command.Dispose();
                    connection.Dispose();

                }
                catch (Exception ex)
                {

                    throw ex;
                }
                return responseStatusViewModel;
            }

Repository

Task<ResponseStatusViewModel> Create(EmployeeModel Employee);

public class EmployeeConfig
{
    public static string EmployeeConnectionString;
    private const string EmployeeConnectionStringKey = "EmployeeConnectionString";
    public static void InitializeConfig()
    {
        EmployeeConnectionString = GetConnectionStringValue(EmployeeConnectionStringKey);
    }

    private static string GetConnectionStringValue(string connectionStringName)
    {
        return Convert.ToString(ConfigurationManager.ConnectionStrings[connectionStringName]);
    }
}

How to convert current date to epoch timestamp?

enter image description hereI think this answer needs an update and the solution would go better this way.

from datetime import datetime

datetime.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S").strftime("%s")

or you may use datetime object and format the time using %s to convert it into epoch time.

How to use passive FTP mode in Windows command prompt?

The quote PASV command is not a command to the ftp.exe program, it is a command to the FTP server requesting a high order port for data transfer. A passive transfer is one in which the FTP data over these high order ports while control is maintained in the lower ports.

The windows ftp.exe program can be used to send the FTP server commands to make a passive data transfer between two FTP servers. A standard windows installation will not, and probably should not, have FTP server service running as an endpoint for passive transfers. So if passive transfers are needed with a standard windows box, a solution other than ftp.exe is necessary as FTPing to localhost as one of the connections won't work in most windows environments.

You can effect a passive FTP transfer between two different hosts (but not two connections on the same host) as follows:

Open up two prompts, use one to ftp.exe connect to your source FTP server and one to ftp.exe connect to your destination FTP server.

Now establish a passive connection between the servers using the raw commands PASV and PORT. The quote PASV command will respond with an IP/port in ellipsis. Use that data for the quote PORT <data> command. Your passive link is now established assuming that firewalls haven't blocked one or more of the four ports (2 for FTP control, 2 for FTP data)

Next start receive of data with the quote STOR <filename> command to the receiving FTP server then send the control command quote RETR <filename> to the source FTP server.

so for me:

client 1
> ftp.exe server1
ftp> quote PASV
227 Entering Passive Mode (10,0,3,1,54,161)

client 2 
> ftp.exe server2
ftp> quote PORT 10,0,3,1,54,54,161
ftp> quote STOR myFile

client 1
ftp> quote RETR myFile

Cavet: I'm connecting to some old FTP servers YMMV

How to create query parameters in Javascript?

This should do the job:

const createQueryParams = params => 
      Object.keys(params)
            .map(k => `${k}=${encodeURI(params[k])}`)
            .join('&');

Example:

const params = { name : 'John', postcode: 'W1 2DL'}
const queryParams = createQueryParams(params)

Result:

name=John&postcode=W1%202DL

Convert double to string

a = 0.000006;
b = 6;
c = a/b;

textbox.Text = c.ToString("0.000000");

As you requested:

textbox.Text = c.ToString("0.######");

This will only display out to the 6th decimal place if there are 6 decimals to display.

How do you remove duplicates from a list whilst preserving order?

A solution without using imported modules or sets:

text = "ask not what your country can do for you ask what you can do for your country"
sentence = text.split(" ")
noduplicates = [(sentence[i]) for i in range (0,len(sentence)) if sentence[i] not in sentence[:i]]
print(noduplicates)

Gives output:

['ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you']

Resetting a setTimeout

i know this is an old thread but i came up with this today

var timer       = []; //creates a empty array called timer to store timer instances
var afterTimer = function(timerName, interval, callback){
    window.clearTimeout(timer[timerName]); //clear the named timer if exists
    timer[timerName] = window.setTimeout(function(){ //creates a new named timer 
        callback(); //executes your callback code after timer finished
    },interval); //sets the timer timer
}

and you invoke using

afterTimer('<timername>string', <interval in milliseconds>int, function(){
   your code here
});

How to HTML encode/escape a string? Is there a built-in?

Comparaison of the different methods:

> CGI::escapeHTML("quote ' double quotes \"")
=> "quote &#39; double quotes &quot;"

> Rack::Utils.escape_html("quote ' double quotes \"")
=> "quote &#x27; double quotes &quot;"

> ERB::Util.html_escape("quote ' double quotes \"")
=> "quote &#39; double quotes &quot;"

I wrote my own to be compatible with Rails ActiveMailer escaping:

def escape_html(str)
  CGI.escapeHTML(str).gsub("&#39;", "'")
end

What are Aggregates and PODs and how/why are they special?

What changes for C++11?

Aggregates

The standard definition of an aggregate has changed slightly, but it's still pretty much the same:

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

Ok, what changed?

  1. Previously, an aggregate could have no user-declared constructors, but now it can't have user-provided constructors. Is there a difference? Yes, there is, because now you can declare constructors and default them:

    struct Aggregate {
        Aggregate() = default; // asks the compiler to generate the default implementation
    };
    

    This is still an aggregate because a constructor (or any special member function) that is defaulted on the first declaration is not user-provided.

  2. Now an aggregate cannot have any brace-or-equal-initializers for non-static data members. What does this mean? Well, this is just because with this new standard, we can initialize members directly in the class like this:

    struct NotAggregate {
        int x = 5; // valid in C++11
        std::vector<int> s{1,2,3}; // also valid
    };
    

    Using this feature makes the class no longer an aggregate because it's basically equivalent to providing your own default constructor.

So, what is an aggregate didn't change much at all. It's still the same basic idea, adapted to the new features.

What about PODs?

PODs went through a lot of changes. Lots of previous rules about PODs were relaxed in this new standard, and the way the definition is provided in the standard was radically changed.

The idea of a POD is to capture basically two distinct properties:

  1. It supports static initialization, and
  2. Compiling a POD in C++ gives you the same memory layout as a struct compiled in C.

Because of this, the definition has been split into two distinct concepts: trivial classes and standard-layout classes, because these are more useful than POD. The standard now rarely uses the term POD, preferring the more specific trivial and standard-layout concepts.

The new definition basically says that a POD is a class that is both trivial and has standard-layout, and this property must hold recursively for all non-static data members:

A POD struct is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). Similarly, a POD union is a union that is both a trivial class and a standard layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). A POD class is a class that is either a POD struct or a POD union.

Let's go over each of these two properties in detail separately.

Trivial classes

Trivial is the first property mentioned above: trivial classes support static initialization. If a class is trivially copyable (a superset of trivial classes), it is ok to copy its representation over the place with things like memcpy and expect the result to be the same.

The standard defines a trivial class as follows:

A trivially copyable class is a class that:

— has no non-trivial copy constructors (12.8),

— has no non-trivial move constructors (12.8),

— has no non-trivial copy assignment operators (13.5.3, 12.8),

— has no non-trivial move assignment operators (13.5.3, 12.8), and

— has a trivial destructor (12.4).

A trivial class is a class that has a trivial default constructor (12.1) and is trivially copyable.

[ Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes.—end note ]

So, what are all those trivial and non-trivial things?

A copy/move constructor for class X is trivial if it is not user-provided and if

— class X has no virtual functions (10.3) and no virtual base classes (10.1), and

— the constructor selected to copy/move each direct base class subobject is trivial, and

— for each non-static data member of X that is of class type (or array thereof), the constructor selected to copy/move that member is trivial;

otherwise the copy/move constructor is non-trivial.

Basically this means that a copy or move constructor is trivial if it is not user-provided, the class has nothing virtual in it, and this property holds recursively for all the members of the class and for the base class.

The definition of a trivial copy/move assignment operator is very similar, simply replacing the word "constructor" with "assignment operator".

A trivial destructor also has a similar definition, with the added constraint that it can't be virtual.

And yet another similar rule exists for trivial default constructors, with the addition that a default constructor is not-trivial if the class has non-static data members with brace-or-equal-initializers, which we've seen above.

Here are some examples to clear everything up:

// empty classes are trivial
struct Trivial1 {};

// all special members are implicit
struct Trivial2 {
    int x;
};

struct Trivial3 : Trivial2 { // base class is trivial
    Trivial3() = default; // not a user-provided ctor
    int y;
};

struct Trivial4 {
public:
    int a;
private: // no restrictions on access modifiers
    int b;
};

struct Trivial5 {
    Trivial1 a;
    Trivial2 b;
    Trivial3 c;
    Trivial4 d;
};

struct Trivial6 {
    Trivial2 a[23];
};

struct Trivial7 {
    Trivial6 c;
    void f(); // it's okay to have non-virtual functions
};

struct Trivial8 {
     int x;
     static NonTrivial1 y; // no restrictions on static members
};

struct Trivial9 {
     Trivial9() = default; // not user-provided
      // a regular constructor is okay because we still have default ctor
     Trivial9(int x) : x(x) {};
     int x;
};

struct NonTrivial1 : Trivial3 {
    virtual void f(); // virtual members make non-trivial ctors
};

struct NonTrivial2 {
    NonTrivial2() : z(42) {} // user-provided ctor
    int z;
};

struct NonTrivial3 {
    NonTrivial3(); // user-provided ctor
    int w;
};
NonTrivial3::NonTrivial3() = default; // defaulted but not on first declaration
                                      // still counts as user-provided
struct NonTrivial5 {
    virtual ~NonTrivial5(); // virtual destructors are not trivial
};

Standard-layout

Standard-layout is the second property. The standard mentions that these are useful for communicating with other languages, and that's because a standard-layout class has the same memory layout of the equivalent C struct or union.

This is another property that must hold recursively for members and all base classes. And as usual, no virtual functions or virtual base classes are allowed. That would make the layout incompatible with C.

A relaxed rule here is that standard-layout classes must have all non-static data members with the same access control. Previously these had to be all public, but now you can make them private or protected, as long as they are all private or all protected.

When using inheritance, only one class in the whole inheritance tree can have non-static data members, and the first non-static data member cannot be of a base class type (this could break aliasing rules), otherwise, it's not a standard-layout class.

This is how the definition goes in the standard text:

A standard-layout class is a class that:

— has no non-static data members of type non-standard-layout class (or array of such types) or reference,

— has no virtual functions (10.3) and no virtual base classes (10.1),

— has the same access control (Clause 11) for all non-static data members,

— has no non-standard-layout base classes,

— either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and

— has no base classes of the same type as the first non-static data member.

A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class.

A standard-layout union is a standard-layout class defined with the class-key union.

[ Note: Standard-layout classes are useful for communicating with code written in other programming languages. Their layout is specified in 9.2.—end note ]

And let's see a few examples.

// empty classes have standard-layout
struct StandardLayout1 {};

struct StandardLayout2 {
    int x;
};

struct StandardLayout3 {
private: // both are private, so it's ok
    int x;
    int y;
};

struct StandardLayout4 : StandardLayout1 {
    int x;
    int y;

    void f(); // perfectly fine to have non-virtual functions
};

struct StandardLayout5 : StandardLayout1 {
    int x;
    StandardLayout1 y; // can have members of base type if they're not the first
};

struct StandardLayout6 : StandardLayout1, StandardLayout5 {
    // can use multiple inheritance as long only
    // one class in the hierarchy has non-static data members
};

struct StandardLayout7 {
    int x;
    int y;
    StandardLayout7(int x, int y) : x(x), y(y) {} // user-provided ctors are ok
};

struct StandardLayout8 {
public:
    StandardLayout8(int x) : x(x) {} // user-provided ctors are ok
// ok to have non-static data members and other members with different access
private:
    int x;
};

struct StandardLayout9 {
    int x;
    static NonStandardLayout1 y; // no restrictions on static members
};

struct NonStandardLayout1 {
    virtual f(); // cannot have virtual functions
};

struct NonStandardLayout2 {
    NonStandardLayout1 X; // has non-standard-layout member
};

struct NonStandardLayout3 : StandardLayout1 {
    StandardLayout1 x; // first member cannot be of the same type as base
};

struct NonStandardLayout4 : StandardLayout3 {
    int z; // more than one class has non-static data members
};

struct NonStandardLayout5 : NonStandardLayout3 {}; // has a non-standard-layout base class

Conclusion

With these new rules a lot more types can be PODs now. And even if a type is not POD, we can take advantage of some of the POD properties separately (if it is only one of trivial or standard-layout).

The standard library has traits to test these properties in the header <type_traits>:

template <typename T>
struct std::is_pod;
template <typename T>
struct std::is_trivial;
template <typename T>
struct std::is_trivially_copyable;
template <typename T>
struct std::is_standard_layout;

What svn command would list all the files modified on a branch?

You can also get a quick list of changed files if thats all you're looking for using the status command with the -u option

svn status -u

This will show you what revision the file is in the current code base versus the latest revision in the repository. I only use diff when I actually want to see differences in the files themselves.

There is a good tutorial on svn command here that explains a lot of these common scenarios: SVN Command Reference

Getting Access Denied when calling the PutObject operation with bucket-level permission

I was having a similar problem. I was not using the ACL stuff, so I didn't need s3:PutObjectAcl.

In my case, I was doing (in Serverless Framework YML):

- Effect: Allow
  Action:
    - s3:PutObject
  Resource: "arn:aws:s3:::MyBucketName"

Instead of:

- Effect: Allow
  Action:
    - s3:PutObject
  Resource: "arn:aws:s3:::MyBucketName/*"

Which adds a /* to the end of the bucket ARN.

Hope this helps.

Drop Down Menu/Text Field in one

I'd like to add a jQuery autocomplete based solution that does the job.

Step 1: Make the list fixed height and scrollable

Get the code from https://jqueryui.com/autocomplete/ "Scrollable" example, setting max height to the list of results so it behaves as a select box.

Step 2: Open the list on focus:

Display jquery ui auto-complete list on focus event

Step 3: Set minimum chars to 0 so it opens no matter how many chars are in the input

Final result:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Scrollable results</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  .ui-autocomplete {
    max-height: 100px;
    overflow-y: auto;
    /* prevent horizontal scrollbar */
    overflow-x: hidden;
  }
  /* IE 6 doesn't support max-height
   * we use height instead, but this forces the menu to always be this tall
   */
  * html .ui-autocomplete {
    height: 100px;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
//      source: availableTags, // uncomment this and comment the following to have normal autocomplete behavior
      source: function (request, response) {
          response( availableTags);
      },
      minLength: 0
    }).focus(function(){
//        $(this).data("uiAutocomplete").search($(this).val()); // uncomment this and comment the following to have autocomplete behavior when opening
        $(this).data("uiAutocomplete").search('');
    });
  } );
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>


</body>
</html>

Check jsfiddle here:

https://jsfiddle.net/bao7fhm3/1/

SQL Server - NOT IN

One issue could be that if either make, model, or [serial number] were null, values would never get returned. Because string concatenations with null values always result in null, and not in () with null will always return nothing. The remedy for this is to use an operator such as IsNull(make, '') + IsNull(Model, ''), etc.

How to put a UserControl into Visual Studio toolBox

In my case, I couldn't see any of the controls in the project. Only when right clicking on toolBox and selecting "Show All" I saw them, but yet they were disabled...

Changing Project type from Windows application to ClassLibrary made the fix.

How can I make the browser wait to display the page until it's fully loaded?

Don't use display:none. If you do, you will see images resize/reposition when you do the show(). Use visibility:hidden instead and it will lay everything out correctly, but it just won't be visible until you tell it to.

Converting json results to a date

If that number represents milliseconds, use the Date's constructor :

var myDate = new Date(1238540400000);

What is meant by the term "hook" in programming?

A hook is functionality provided by software for users of that software to have their own code called under certain circumstances. That code can augment or replace the current code.

In the olden days when computers were truly personal and viruses were less prevalent (I'm talking the '80's), it was as simple as patching the operating system software itself to call your code. I remember writing an extension to the Applesoft BASIC language on the Apple II which simply hooked my code into the BASIC interpreter by injecting a call to my code before any of the line was processed.

Some computers had pre-designed hooks, one example being the I/O stream on the Apple II. It used such a hook to inject the whole disk sub-system (Apple II ROMs were originally built in the days where cassettes were the primary storage medium for PCs). You controlled the disks by printing the ASCII code 4 (CTRL-D) followed by the command you wanted to execute then a CR, and it was intercepted by the disk sub-system, which had hooked itself into the Apple ROM print routines.

So for example, the lines:

PRINT CHR(4);"CATALOG"
PRINT CHR(4);"IN#6"

would list the disk contents then re-initialize the machine. This allowed such tricks as protecting your BASIC programs by setting the first line as:

123 REM XIN#6

then using POKE to insert the CTRL-D character in where the X was. Then, anyone trying to list your source would send the re-initialize sequence through the output routines where the disk sub-system would detect it.

That's often the sort of trickery we had to resort to, to get the behavior we wanted.

Nowadays, with the operating system more secure, it provides facilities for hooks itself, since you're no longer supposed to modify the operating system "in-flight" or on the disk.

They've been around for a long time. Mainframes had them (called exits) and a great deal of mainframe software uses those facilities even now. For example, the free source code control system that comes with z/OS (called SCLM) allows you to entirely replace the security subsystem by simply placing your own code in the exit.

JVM heap parameters

if you wrote: -Xms512m -Xmx512m when it start, java allocate in those moment 512m of ram for his process and cant increment.

-Xms64m -Xmx512m when it start, java allocate only 64m of ram for his process, but java can be increment his memory occupation while 512m.

I think that second thing is better because you give to java the automatic memory management.

PostgreSQL: How to change PostgreSQL user password?

In general, just use pg admin UI for doing db related activity.

If instead you are focusin more in automating database setup for your local development, or CI etc...

For example, you can use a simple combo like this.

(a) Create a dummy super user via jenkins with a command similar to this:

docker exec -t postgres11-instance1 createuser --username=postgres --superuser experiment001

this will create a super user called experiment001 in you postgres db.

(b) Give this user some password by running a NON-Interactive SQL command.

docker exec -t postgres11-instance1 psql -U experiment001 -d postgres -c "ALTER USER experiment001 WITH PASSWORD 'experiment001' "

Postgres is probably the best database out there for command line (non-interactive) tooling. Creating users, running SQL, making backup of database etc... In general it is all quite basic with postgres and it is overall quite trivial to integrate this into your development setup scripts or into automated CI configuration.

R Markdown - changing font size and font type in html output

I think fontsize: command in YAML only works for LaTeX / pdf. Apart, in standard latex classes (article, book, and report) only three font sizes are accepted (10pt, 11pt, and 12pt).

Regarding appearance (different font types and colors), you can specify a theme:. See Appearance and Style.

I guess, what you are looking for is your own css. Make a file called style.css, save it in the same folder as your .Rmd and include it in the YAML header:

---
output:
  html_document:
    css: style.css
---

In the css-file you define your font-type and size:

/* Whole document: */
body{
  font-family: Helvetica;
  font-size: 16pt;
}
/* Headers */
h1,h2,h3,h4,h5,h6{
  font-size: 24pt;
}

Why is json_encode adding backslashes?

This happens because the JSON format uses ""(Quotes) and anything in between these quotes is useful information (either key or the data).

Suppose your data was : He said "This is how it is done". Then the actual data should look like "He said \"This is how it is done\".".

This ensures that the \" is treated as "(Quotation mark) and not as JSON formatting. This is called escape character.

This usually happens when one tries to encode an already JSON encoded data, which is a common way I have seen this happen.

Try this

$arr = ['This is a sample','This is also a "sample"']; echo json_encode($arr);

OUTPUT:

["This is a sample","This is also a \"sample\""]

Inline functions in C#?

Inline methods are simply a compiler optimization where the code of a function is rolled into the caller.

There's no mechanism by which to do this in C#, and they're to be used sparingly in languages where they are supported -- if you don't know why they should be used somewhere, they shouldn't be.

Edit: To clarify, there are two major reasons they need to be used sparingly:

  1. It's easy to make massive binaries by using inline in cases where it's not necessary
  2. The compiler tends to know better than you do when something should, from a performance standpoint, be inlined

It's best to leave things alone and let the compiler do its work, then profile and figure out if inline is the best solution for you. Of course, some things just make sense to be inlined (mathematical operators particularly), but letting the compiler handle it is typically the best practice.

Why does this code using random strings print "hello world"?

It's all about the input seed. Same seed give the same results all the time. Even you re-run your program again and again it's the same output.

public static void main(String[] args) {

    randomString(-229985452);
    System.out.println("------------");
    randomString(-229985452);

}

private static void randomString(int i) {
    Random ran = new Random(i);
    System.out.println(ran.nextInt());
    System.out.println(ran.nextInt());
    System.out.println(ran.nextInt());
    System.out.println(ran.nextInt());
    System.out.println(ran.nextInt());

}

Output

-755142161
-1073255141
-369383326
1592674620
-1524828502
------------
-755142161
-1073255141
-369383326
1592674620
-1524828502

Open directory using C

Here is a simple way to implement ls command using c. To run use for example ./xls /tmp

    #include<stdio.h>
    #include <dirent.h>
    void main(int argc,char *argv[])
    {
   DIR *dir;
   struct dirent *dent;
   dir = opendir(argv[1]);   

   if(dir!=NULL)
      {
   while((dent=readdir(dir))!=NULL)
                    {
        if((strcmp(dent->d_name,".")==0 || strcmp(dent->d_name,"..")==0 || (*dent->d_name) == '.' ))
            {
            }
       else
              {
        printf(dent->d_name);
        printf("\n");
              }
                    }
       }
       close(dir);
     }

How do I copy a version of a single file from one git branch to another?

1) Ensure you're in branch where you need a copy of the file. for eg: i want sub branch file in master so you need to checkout or should be in master git checkout master

2) Now checkout specific file alone you want from sub branch into master,

git checkout sub_branch file_path/my_file.ext

here sub_branch means where you have that file followed by filename you need to copy.

Convert char to int in C#

Comparison of some of the methods based on the result when the character is not an ASCII digit:

char c1 = (char)('0' - 1), c2 = (char)('9' + 1); 

Debug.Print($"{c1 & 15}, {c2 & 15}");                                   // 15, 10
Debug.Print($"{c1 ^ '0'}, {c2 ^ '0'}");                                 // 31, 10
Debug.Print($"{c1 - '0'}, {c2 - '0'}");                                 // -1, 10
Debug.Print($"{(uint)c1 - '0'}, {(uint)c2 - '0'}");                     // 4294967295, 10
Debug.Print($"{char.GetNumericValue(c1)}, {char.GetNumericValue(c2)}"); // -1, -1

After installation of Gulp: “no command 'gulp' found”

That's perfectly normal. If you want gulp-cli available on the command line, you need to install it globally.

npm install --global gulp-cli

See the install instruction.

Also, node_modules/.bin/ isn't in your $PATH. But it is automatically added by npm when running npm scripts (see this blog post for reference).

So you could add scripts to your package.json file:

{
    "name": "your-app",
    "version": "0.0.1",
    "scripts": {
        "gulp": "gulp",
        "minify": "gulp minify"
    }
}

You could then run npm run gulp or npm run minify to launch gulp tasks.

How can I get the current network interface throughput statistics on Linux/UNIX?

I couldn't get the parse ifconfig script to work for me on an AMI so got this to work measuring received traffic averaged over 10 seconds

date && rxstart=`ifconfig eth0 | grep bytes | awk '{print $2}' | cut -d : -f 2` && sleep 10 && rxend=`ifconfig eth0 | grep bytes | awk '{print $2}' | cut -d : -f 2` && difference=`expr $rxend - $rxstart` && echo "Received `expr $difference / 10` bytes per sec"

Sorry, it's ever so cheap and nasty but it worked!

SSIS Connection not found in package

In my case, one of the event handler task was pointing to old connection which was deleted, deleting the unused event handler task fixed the problem. I end up opening the package in XML format to understand that the problem is with event handler task!

Setting the zoom level for a MKMapView

Swift:

Map.setRegion(MKCoordinateRegion(center: locValue, latitudinalMeters: 200, longitudinalMeters: 200), animated: true)

locValue is your coordinate.

How to change facebook login button with my custom image

The method which you are using is rendering login button from the Facebook Javascript code. However, you can write your own Javascript code function to mimic the functionality. Here is how to do it -

  1. Create a simple anchor tag link with the image you want to show. Have a onclick method on anchor tag which would actually do the real job.
<a href="#" onclick="fb_login();"><img src="images/fb_login_awesome.jpg" border="0" alt=""></a>
  1. Next, we create the Javascript function which will show the actual popup and will fetch the complete user information, if user allows. We also handle the scenario if user disallows our facebook app.
window.fbAsyncInit = function() {
    FB.init({
        appId   : 'YOUR_APP_ID',
        oauth   : true,
        status  : true, // check login status
        cookie  : true, // enable cookies to allow the server to access the session
        xfbml   : true // parse XFBML
    });

  };

function fb_login(){
    FB.login(function(response) {

        if (response.authResponse) {
            console.log('Welcome!  Fetching your information.... ');
            //console.log(response); // dump complete info
            access_token = response.authResponse.accessToken; //get access token
            user_id = response.authResponse.userID; //get FB UID

            FB.api('/me', function(response) {
                user_email = response.email; //get user email
          // you can store this data into your database             
            });

        } else {
            //user hit cancel button
            console.log('User cancelled login or did not fully authorize.');

        }
    }, {
        scope: 'public_profile,email'
    });
}
(function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
}());
  1. We are done.

Please note that the above function is fully tested and works. You just need to put your facebook APP ID and it will work.

Windows 8.1 gets Error 720 on connect VPN

This solved my 720 problem. The idea is to change the driver of the faulty WAN to another network adaptar driver, and then we are able to uninstall the WAN device and then reboot the system.

https://forums.lenovo.com/t5/Windows-8-and-8-1/SOLVED-WAN-Miniport-2-yellow-exclamation-mark-in-Device-Manager/td-p/1051981

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

The bitmap constructor has resizing built in.

Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");

http://msdn.microsoft.com/en-us/library/0wh0045z.aspx

If you want control over interpolation modes see this post.

jQuery: Adding two attributes via the .attr(); method

Multiple Attribute

var tag = "tag name";
createNode(tag, target, attribute);

createNode: function(tag, target, attribute){
    var tag = jQuery("<" + tag + ">");
    jQuery.each(attribute, function(i,v){
        tag.attr(v);
    });
    target.append(tag);
    tag.appendTo(target);
}
var attribute = [
    {"data-level": "3"},
];

How do I get a value of a <span> using jQuery?

     $('span id').text(); worked with me

Find Locked Table in SQL Server

You can use sp_lock (and sp_lock2), but in SQL Server 2005 onwards this is being deprecated in favour of querying sys.dm_tran_locks:

select  
    object_name(p.object_id) as TableName, 
    resource_type, resource_description
from
    sys.dm_tran_locks l
    join sys.partitions p on l.resource_associated_entity_id = p.hobt_id

How I can get and use the header file <graphics.h> in my C++ program?

<graphics.h> is not a standard header. Most commonly it refers to the header for Borland's BGI API for DOS and is antiquated at best.

However it is nicely simple; there is a Win32 implementation of the BGI interface called WinBGIm. It is implemented using Win32 GDI calls - the lowest level Windows graphics interface. As it is provided as source code, it is perhaps a simple way of understanding how GDI works.

WinBGIm however is by no means cross-platform. If all you want are simple graphics primitives, most of the higher level GUI libraries such as wxWidgets and Qt support that too. There are simpler libraries suggested in the possible duplicate answers mentioned in the comments.