Programs & Examples On #Color wheel

How to show all privileges from a user in oracle?

Another useful resource:

http://psoug.org/reference/roles.html

  • DBA_SYS_PRIVS
  • DBA_TAB_PRIVS
  • DBA_ROLE_PRIVS

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

An unmodifiable map may still change. It is only a view on a modifiable map, and changes in the backing map will be visible through the unmodifiable map. The unmodifiable map only prevents modifications for those who only have the reference to the unmodifiable view:

Map<String, String> realMap = new HashMap<String, String>();
realMap.put("A", "B");

Map<String, String> unmodifiableMap = Collections.unmodifiableMap(realMap);

// This is not possible: It would throw an 
// UnsupportedOperationException
//unmodifiableMap.put("C", "D");

// This is still possible:
realMap.put("E", "F");

// The change in the "realMap" is now also visible
// in the "unmodifiableMap". So the unmodifiableMap
// has changed after it has been created.
unmodifiableMap.get("E"); // Will return "F". 

In contrast to that, the ImmutableMap of Guava is really immutable: It is a true copy of a given map, and nobody may modify this ImmutableMap in any way.

Update:

As pointed out in a comment, an immutable map can also be created with the standard API using

Map<String, String> immutableMap = 
    Collections.unmodifiableMap(new LinkedHashMap<String, String>(realMap)); 

This will create an unmodifiable view on a true copy of the given map, and thus nicely emulates the characteristics of the ImmutableMap without having to add the dependency to Guava.

Prevent the keyboard from displaying on activity start

Just Add in AndroidManifest.xml

<activity android:name=".HomeActivity"  android:windowSoftInputMode="stateHidden">
</activity>

Spring Boot application as a Service

I know this is an older question, but I wanted to present yet another way which is the appassembler-maven-plugin. Here's the relevant part from my POM that includes a lot of additional option values we found useful:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>appassembler-maven-plugin</artifactId>
    <configuration>
        <generateRepository>true</generateRepository>
        <repositoryLayout>flat</repositoryLayout>
        <useWildcardClassPath>true</useWildcardClassPath>
        <includeConfigurationDirectoryInClasspath>true</includeConfigurationDirectoryInClasspath>
        <configurationDirectory>config</configurationDirectory>
        <target>${project.build.directory}</target>
        <daemons>
            <daemon>
                <id>${installer-target}</id>
                <mainClass>${mainClass}</mainClass>
                <commandLineArguments>
                    <commandLineArgument>--spring.profiles.active=dev</commandLineArgument>
                    <commandLineArgument>--logging.config=${rpmInstallLocation}/config/${installer-target}-logback.xml</commandLineArgument>
                </commandLineArguments>
                <platforms>
                    <platform>jsw</platform>
                </platforms>
                <generatorConfigurations>
                    <generatorConfiguration>
                        <generator>jsw</generator>
                        <includes>
                            <include>linux-x86-64</include>
                        </includes>
                        <configuration>
                            <property>
                                <name>wrapper.logfile</name>
                                <value>logs/${installer-target}-wrapper.log</value>
                            </property>
                            <property>
                                <name>wrapper.logfile.maxsize</name>
                                <value>5m</value>
                            </property>
                            <property>
                                <name>run.as.user.envvar</name>
                                <value>${serviceUser}</value>
                            </property>
                            <property>
                                <name>wrapper.on_exit.default</name>
                                <value>RESTART</value>
                            </property>
                        </configuration>
                    </generatorConfiguration>
                </generatorConfigurations>
                <jvmSettings>
                    <initialMemorySize>256M</initialMemorySize>
                    <maxMemorySize>1024M</maxMemorySize>
                    <extraArguments>
                        <extraArgument>-server</extraArgument>
                    </extraArguments>
                </jvmSettings>
            </daemon>
        </daemons>
    </configuration>
    <executions>
        <execution>
            <id>generate-jsw-scripts</id>
            <phase>package</phase>
            <goals>
                <goal>generate-daemons</goal>
            </goals>
        </execution>
    </executions>
</plugin>

How to debug a referenced dll (having pdb)

It must work. I used to debug a .exe file and a dll at the same time ! What I suggest is 1) Include the path of the dll in your B project, 2) Then compile in debug your A project 3) Control that the path points on the A dll and de pdb file.... 4)After that you start in debug the B project and if all is ok, you will be able to debug in both projects !

How to know Hive and Hadoop versions from command prompt?

/usr/bin/hive --version worked for me.

[qa@ip-10-241-1-222 ~]$ /usr/bin/hive --version
Hive 0.13.1-cdh5.3.1
Subversion file:///data/1/jenkins/workspace/generic-package-rhel64-6-0/topdir/BUILD/hive-0.13.1-cdh5.3.1 -r Unknown
Compiled by jenkins on Tue Jan 27 16:38:55 PST 2015
From source with checksum 1bb86e4899928ce29cbcaec8cf43c9b6
[qa@ip-10-241-1-222 ~]$

How do I check if a directory exists? "is_dir", "file_exists" or both?

A way to check if a path is directory can be following:

function isDirectory($path) {
    $all = @scandir($path);
    return $all !== false;
}

NOTE: It will return false for non-existant path too, but works perfectly for UNIX/Windows

Why does the 260 character path length limit exist in Windows?

As to how to cope with the path size limitation on Windows - using 7zip to pack (and unpack) your path-length sensitive files seems like a viable workaround. I've used it to transport several IDE installations (those Eclipse plugin paths, yikes!) and piles of autogenerated documentation and haven't had a single problem so far.

Not really sure how it evades the 260 char limit set by Windows (from a technical PoV), but hey, it works!

More details on their SourceForge page here:

"NTFS can actually support pathnames up to 32,000 characters in length."

7-zip also support such long names.

But it's disabled in SFX code. Some users don't like long paths, since they don't understand how to work with them. That is why I have disabled it in SFX code.

and release notes:

9.32 alpha 2013-12-01

  • Improved support for file pathnames longer than 260 characters.

4.44 beta 2007-01-20

  • 7-Zip now supports file pathnames longer than 260 characters.

IMPORTANT NOTE: For this to work properly, you'll need to specify the destination path in the 7zip "Extract" dialog directly, rather than dragging & dropping the files into the intended folder. Otherwise the "Temp" folder will be used as an interim cache and you'll bounce into the same 260 char limitation once Windows Explorer starts moving the files to their "final resting place". See the replies to this question for more information.

Unresolved reference issue in PyCharm

I tried everything here twice and even more. I finally solved it doing something I hadn't seen anywhere online. If you go to Settings>Editor>File Types there is an 'Ignore Files and folders' line at the bottom. In my case, I was ignoring 'venv', which is what I always name my virtual environments. So I removed venv; from the list of directories to ignore and VOILA!! I was FINALLY able to fix this problem. Literally all of my import problems were fixed for the project.

BTW, I had installed each and every package using PyCharm, and not through a terminal. (Meaning, by going to Settings>Interpreter...). I had invalidated cache, changed 'Source Root', restarted PyCharm, refreshed my interpreters paths, changed interpreters, deleted my venv... I tried everything. This finally worked. Obviously there are multiple problems going on here with different people, so this may not work for you, but it's definitely worth a shot if nothing else has worked, and easy to reverse if it doesn't.

How SID is different from Service name in Oracle tnsnames.ora

Quote by @DAC

In short: SID = the unique name of your DB, ServiceName = the alias used when connecting

Not strictly true. SID = unique name of the INSTANCE (eg the oracle process running on the machine). Oracle considers the "Database" to be the files.

Service Name = alias to an INSTANCE (or many instances). The main purpose of this is if you are running a cluster, the client can say "connect me to SALES.acme.com", the DBA can on the fly change the number of instances which are available to SALES.acme.com requests, or even move SALES.acme.com to a completely different database without the client needing to change any settings.

How to prevent gcc optimizing some statements in C?

You can use

#pragma GCC push_options
#pragma GCC optimize ("O0")

your code

#pragma GCC pop_options

to disable optimizations since GCC 4.4.

See the GCC documentation if you need more details.

Is there a function to round a float in C or do I need to write my own?

Sure, you can use roundf(). If you want to round to one decimal, then you could do something like: roundf(10 * x) / 10

How to put Google Maps V2 on a Fragment using ViewPager

According to https://developer.android.com/about/versions/android-4.2.html#NestedFragments, you can use nested fragments to achieve this by calling getChildFragmentManager() if you still want to use the Google Maps fragment instead of the view inside your own fragment:

SupportMapFragment mapFragment = new SupportMapFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.content, mapFragment).commit();

where "content" is the root layout in your fragment (preferably a FrameLayout). The advantage of using a map fragment is that then the map lifecycle is managed automatically by the system.

Although the documentation says "You cannot inflate a layout into a fragment when that layout includes a <fragment>. Nested fragments are only supported when added to a fragment dynamically. ", I have somehow successfully done this and it worked fine. Here is my code:
In the fragment's onCreateView() method:

View view = inflater.inflate(R.layout.layout_maps, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(...);

In the layout:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Hope it helps!

How do I revert back to an OpenWrt router configuration?

Some addition to previous comments: 'firstboot' won't be available until you run 'mount_root' command.

So here is a full recap of what needs to be done. All manipulations I did on Windows 8.1.

  • Enter Failsafe mode (hold the reset button on boot for a few seconds)
  • Assign a static IP address, 192.168.1.2, to your PC. Example of a command: netsh interface ip set address name="Ethernet" static 192.168.1.2 255.255.255.0 192.168.1.1
  • Connect to address 192.168.1.1 from telnet (I use PuTTY) and login/password isn't required).
  • Run 'mount_root' (otherwise 'firstboot' won't be available).
  • Run 'firstboot' to reset.
  • Run 'reboot -f' to reboot.

Now you can enter to the router console from a browser. Also don't forget to return your PC from static to DHCP address assignment. Example: netsh interface ip set address name="Ethernet" source=dhcp

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

Try to create an javax.mail.Authenticator Object, and send that in with the properties object to the Session object.

Authenticator edit:

You can modify this to accept a username and password and you can store them there, or where ever you want.

public class SmtpAuthenticator extends Authenticator {
public SmtpAuthenticator() {

    super();
}

@Override
public PasswordAuthentication getPasswordAuthentication() {
 String username = "user";
 String password = "password";
    if ((username != null) && (username.length() > 0) && (password != null) 
      && (password.length   () > 0)) {

        return new PasswordAuthentication(username, password);
    }

    return null;
}

In your class where you send the email:

SmtpAuthenticator authentication = new SmtpAuthenticator();
javax.mail.Message msg = new MimeMessage(Session
                    .getDefaultInstance(emailProperties, authenticator));

C# 30 Days From Todays Date

A possible solution would be on first run, create a file containing the current date and put it in IsolatedStorage. For subsequent runs, check the contents of the file and compare with the current date; if the date difference is greater than 30 days, inform the user and close the application.

Forcing a postback

You can try redirecting to same page.

Response.Redirect(Request.RawUrl);

Create an array of strings

You need to use cell-arrays:

names = cell(10,1);
for i=1:10
    names{i} = ['Sample Text ' num2str(i)];
end

Compiler warning - suggest parentheses around assignment used as truth value

While that particular idiom is common, even more common is for people to use = when they mean ==. The convention when you really mean the = is to use an extra layer of parentheses:

while ((list = list->next)) { // yes, it's an assignment

Convert array into csv

I'm using the following function for that; it's an adaptation from one of the man entries in the fputscsv comments. And you'll probably want to flatten that array; not sure what happens if you pass in a multi-dimensional one.

/**
  * Formats a line (passed as a fields  array) as CSV and returns the CSV as a string.
  * Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120
  */
function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $output = array();
    foreach ( $fields as $field ) {
        if ($field === null && $nullToMysqlNull) {
            $output[] = 'NULL';
            continue;
        }

        // Enclose fields containing $delimiter, $enclosure or whitespace
        if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
            $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
        }
        else {
            $output[] = $field;
        }
    }

    return implode( $delimiter, $output );
}

How to update values using pymongo?

With my pymongo version: 3.2.2 I had do the following

from bson.objectid import ObjectId
import pymongo

client = pymongo.MongoClient("localhost", 27017)
db = client.mydbname

db.ProductData.update_one({
  '_id': ObjectId(p['_id']['$oid'])
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False)

How to show the last queries executed on MySQL?

1) If general mysql logging is enabled then we can check the queries in the log file or table based what we have mentioned in the config. Check what is enabled with the following command

mysql> show variables like 'general_log%';
mysql> show variables like 'log_output%';

If we need query history in table then

Execute SET GLOBAL log_output = 'TABLE';
Execute SET GLOBAL general_log = 'ON';

Take a look at the table mysql.general_log

If you prefer to output to a file:

SET GLOBAL log_output = "FILE"; which is set by default.
SET GLOBAL general_log_file = "/path/to/your/logfile.log";
SET GLOBAL general_log = 'ON';

2) We can also check the queries in the .mysql_history file cat ~/.mysql_history

"No backupset selected to be restored" SQL Server 2012

I thought I was not stupid enough to mix up the versions - however, I didn't realize that on my new server, a SQL Server 2005 instance was already installed from birth named SQLEXPRESS. When trying to restore my SQL Server 2008 R2 backed up database in SSMS 2012 to the SQLEXPRESS instance, the list of backup sets was empty.

Eventually I realized that the SQLEXPRESS instance on the server was not a 2012 instance, but a 2005. I disconnected and connected to the actual 2012 instance (in my case named SQLEXPRESS2012), and it (obviously) worked.

Apache Proxy: No protocol handler was valid

For me all above-mentioned answers was enabled on xampp still not working. Enabling below module made virtual host work again

LoadModule slotmem_shm_module modules/mod_slotmem_shm.so

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

I got this error too, but my problem was that I was using an older version of GACUTIL.EXE.

Once I had the correct GACUTIL for the latest .NET version installed, it worked fine.

The error is misleading because it makes it look like it's the DLL you're trying to register that incorrect.

Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags

One good thing about @LazyCollection(LazyCollectionOption.FALSE) is that several fields with this annotation can coexist while FetchType.EAGER cannot, even in the situations where such coexistence is legit.

For example, an Order may have a list of OrderGroup(a short one) as well as a list of Promotions(also short). @LazyCollection(LazyCollectionOption.FALSE) can be used on both without causing LazyInitializationException neither MultipleBagFetchException.

In my case @Fetch did solve my problem of MultipleBacFetchException but then causes LazyInitializationException, the infamous no Session error.

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

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

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

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

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

What are FTL files

Have a look here.

Following files have FTL extension:

  • Family Tree Legends Family File
  • FreeMarker Template
  • Future Tense Texture

jquery json to string?

Edit: You should use the json2.js library from Douglas Crockford instead of implementing the code below. It provides some extra features and better/older browser support.

Grab the json2.js file from: https://github.com/douglascrockford/JSON-js


// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};

var tmp = {one: 1, two: "2"};
JSON.stringify(tmp); // '{"one":1,"two":"2"}'

Code from: http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/

C++ Redefinition Header Files (winsock2.h)

I've run into the same issue and here is what I have discovered so far:

From this output fragment -

c:\program files\microsoft sdks\windows\v6.0a\include\ws2def.h(91) : warning C4005: 'AF_IPX' : macro redefinition
c:\program files\microsoft sdks\windows\v6.0a\include\winsock.h(460) : see previous definition of 'AF_IPX'

-It appears that both ws2def.h and winsock.h have been included in your solution.

If you look at the file ws2def.h it starts with the following comment -

/*++

Copyright (c) Microsoft Corporation. All rights reserved.

Module Name:

    ws2def.h

Abstract:

    This file contains the core definitions for the Winsock2
    specification that can be used by both user-mode and 
    kernel mode modules.

    This file is included in WINSOCK2.H. User mode applications
    should include WINSOCK2.H rather than including this file
    directly. This file can not be included by a module that also
    includes WINSOCK.H.

Environment:

    user mode or kernel mode

--*/

Pay attention to the last line - "This file can not be included by a module that also includes WINSOCK.H"

Still trying to rectify the problem without making changes to the code.

Let me know if this makes sense.

Disable Buttons in jQuery Mobile

If I'm reading this question correctly, you may be missing that a jQuery mobile "button" widget is not the same thing as an HTML button element. I think this boils down to you can't call $('input').button('disable') unless you have previously called $('input').button(); to initialize a jQuery Mobile button widget on your input.

Of course, you may not want to be using jQuery button widget functionality, in which case Alexander's answer should set you right.

Flutter - Layout a Grid

There are few named constructors in GridView for different scenarios,

Constructors

  1. GridView
  2. GridView.builder
  3. GridView.count
  4. GridView.custom
  5. GridView.extent

Below is a example of GridView constructor:

import 'package:flutter/material.dart';

void main() => runApp(
  MaterialApp(
    home: ExampleGrid(),
  ),
);

class ExampleGrid extends StatelessWidget {
  List<String> images = [
    "https://uae.microless.com/cdn/no_image.jpg",
    "https://images-na.ssl-images-amazon.com/images/I/81aF3Ob-2KL._UX679_.jpg",
    "https://www.boostmobile.com/content/dam/boostmobile/en/products/phones/apple/iphone-7/silver/device-front.png.transform/pdpCarousel/image.jpg",
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgUgs8_kmuhScsx-J01d8fA1mhlCR5-1jyvMYxqCB8h3LCqcgl9Q",
    "https://ae01.alicdn.com/kf/HTB11tA5aiAKL1JjSZFoq6ygCFXaw/Unlocked-Samsung-GALAXY-S2-I9100-Mobile-Phone-Android-Wi-Fi-GPS-8-0MP-camera-Core-4.jpg_640x640.jpg",
    "https://media.ed.edmunds-media.com/gmc/sierra-3500hd/2018/td/2018_gmc_sierra-3500hd_f34_td_411183_1600.jpg",
    "https://hips.hearstapps.com/amv-prod-cad-assets.s3.amazonaws.com/images/16q1/665019/2016-chevrolet-silverado-2500hd-high-country-diesel-test-review-car-and-driver-photo-665520-s-original.jpg",
    "https://www.galeanasvandykedodge.net/assets/stock/ColorMatched_01/White/640/cc_2018DOV170002_01_640/cc_2018DOV170002_01_640_PSC.jpg",
    "https://media.onthemarket.com/properties/6191869/797156548/composite.jpg",
    "https://media.onthemarket.com/properties/6191840/797152761/composite.jpg",
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView(
        physics: BouncingScrollPhysics(), // if you want IOS bouncing effect, otherwise remove this line
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),//change the number as you want
        children: images.map((url) {
          return Card(child: Image.network(url));
        }).toList(),
      ),
    );
  }
}

If you want your GridView items to be dynamic according to the content, you can few lines to do that but the simplest way to use StaggeredGridView package. I have provided an answer with example here.

Below is an example for a GridView.count:

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: ExampleGrid(),
      ),
    );

class ExampleGrid extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView.count(
        crossAxisCount: 4,
        children: List.generate(40, (index) {
          return Card(
            child: Image.network("https://robohash.org/$index"),
          ); //robohash.org api provide you different images for any number you are giving
        }),
      ),
    );
  }
}

Screenshot for above snippet:

Flutter gridview example by blasanka using card widget and robohash api

Example for a SliverGridView:

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: ExampleGrid(),
      ),
    );

class ExampleGrid extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        primary: false,
        slivers: <Widget>[
          SliverPadding(
            padding: const EdgeInsets.all(20.0),
            sliver: SliverGrid.count(
              crossAxisSpacing: 10.0,
              crossAxisCount: 2,
              children: List.generate(20, (index) {
                return Card(child: Image.network("https://robohash.org/$index"));
              }),
            ),
          ),
        ],
      )
    );
  }
}

Webpack - webpack-dev-server: command not found

The script webpack-dev-server is already installed inside ./node_modules directory. You can either install it again globally by

sudo npm install -g webpack-dev-server

or run it like this

./node_modules/webpack-dev-server/bin/webpack-dev-server.js -d --config webpack.dev.config.js --content-base public/ --progress --colors

. means look it in current directory.

Remove all spaces from a string in SQL Server

I had this issue today and replace / trim did the trick..see below.

update table_foo 
set column_bar  = REPLACE(LTRIM(RTRIM(column_bar)), '  ', '')

before and after :

old-bad:  column_bar    |   New-fixed:   column_bar
       '  xyz  '        |                'xyz'   
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 

How to describe table in SQL Server 2008?

May be this can help:

Use MyTest
Go
select * from information_schema.COLUMNS where TABLE_NAME='employee'

{ where: MyTest= DatabaseName Employee= TableName } --Optional conditions

update query with join on two tables

this is Postgres UPDATE JOIN format:

UPDATE address 
SET cid = customers.id
FROM customers 
WHERE customers.id = address.id

Here's the other variations: http://mssql-to-postgresql.blogspot.com/2007/12/updates-in-postgresql-ms-sql-mysql.html

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

VirtualBox Cannot register the hard disk already exists

1 - Open the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid (take note to revert this change on step 6)

Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox

Change:

<HardDisks>
        <HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

To:

<HardDisks>
        <HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

2 - Reboot machine

4 - Stop Virtual Machine (if started)

5 - On terminal:

su vbox
cd /home/virtualbox/WindowsServer/
VBoxManage modifyhd WindowsServer.vdi --resize SIZE
exit
exit

change SIZE for a number in Megabytes, example 80000 (80GB)

6 - Open again the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid whith the original value

Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox

Change:

<HardDisks>
        <HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

To:

<HardDisks>
        <HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

7 - Reboot machine

Why does Git say my master branch is "already up to date" even though it is not?

I think your basic issue here is that you're misinterpreting and/or misunderstanding what git does and why it does it.

When you clone some other repository, git makes a copy of whatever is "over there". It also takes "their" branch labels, such as master, and makes a copy of that label whose "full name" in your git tree is (normally) remotes/origin/master (but in your case, remotes/upstream/master). Most of the time you get to omit the remotes/ part too, so you can refer to that original copy as upstream/master.

If you now make and commit some change(s) to some file(s), you're the only one with those changes. Meanwhile other people may use the original repository (from which you made your clone) to make other clones and change those clones. They are the only ones with their changes, of course. Eventually though, someone may have changes they send back to the original owner (via "push" or patches or whatever).

The git pull command is mostly just shorthand for git fetch followed by git merge. This is important because it means you need to understand what those two operations actually do.

The git fetch command says to go back to wherever you cloned from (or have otherwise set up as a place to fetch from) and find "new stuff someone else added or changed or removed". Those changes are copied over and applied to your copy of what you got from them earlier. They are not applied to your own work, only to theirs.

The git merge command is more complicated and is where you are going awry. What it does, oversimplified a bit, is compare "what you changed in your copy" to "changes you fetched from someone-else and thus got added to your-copy-of-the-someone-else's-work". If your changes and their changes don't seem to conflict, the merge operation mushes them together and gives you a "merge commit" that ties your development and their development together (though there is a very common "easy" case in which you have no changes and you get a "fast forward").

The situation you're encountering now is one in which you have made changes and committed them—nine times, in fact, hence the "ahead 9"—and they have made no changes. So, fetch dutifully fetches nothing, and then merge takes their lack-of-changes and also does nothing.

What you want is to look at, or maybe even "reset" to, "their" version of the code.

If you merely want to look at it, you can simply check out that version:

git checkout upstream/master

That tells git that you want to move the current directory to the branch whose full name is actually remotes/upstream/master. You'll see their code as of the last time you ran git fetch and got their latest code.

If you want to abandon all your own changes, what you need to do is change git's idea of which revision your label, master, should name. Currently it names your most recent commit. If you get back onto that branch:

git checkout master

then the git reset command will allow you to "move the label", as it were. The only remaining problem (assuming you're really ready to abandon everything you've don) is finding where the label should point.

git log will let you find the numeric names—those things like 7cfcb29—which are permanent (never changing) names, and there are a ridiculous number of other ways to name them, but in this case you just want the name upstream/master.

To move the label, wiping out your own changes (any that you have committed are actually recoverable for quite a while but it's a lot harder after this so be very sure):

git reset --hard upstream/master

The --hard tells git to wipe out what you have been doing, move the current branch label, and then check out the given commit.

It's not super-common to really want to git reset --hard and wipe out a bunch of work. A safer method (making it a lot easier to recover that work if you decide some of it was worthwhile after all) is to rename your existing branch:

git branch -m master bunchofhacks

and then make a new local branch named master that "tracks" (I don't really like this term as I think it confuses people but that's the git term :-) ) the origin (or upstream) master:

git branch -t master upstream/master

which you can then get yourself on with:

git checkout master

What the last three commands do (there's shortcuts to make it just two commands) is to change the name pasted on the existing label, then make a new label, then switch to it:

before doing anything:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "master"

after git branch -m:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

after git branch -t master upstream/master:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

Here C0 is the latest commit (a complete source tree) that you got when you first did your git clone. C1 through C9 are your commits.

Note that if you were to git checkout bunchofhacks and then git reset --hard HEAD^^, this would change the last picture to:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 -    "bunchofhacks"
                                                      \
                                                       \- C8 --- C9

The reason is that HEAD^^ names the revision two up from the head of the current branch (which just before the reset would be bunchofhacks), and reset --hard then moves the label. Commits C8 and C9 are now mostly invisible (you can use things like the reflog and git fsck to find them but it's no longer trivial). Your labels are yours to move however you like. The fetch command takes care of the ones that start with remotes/. It's conventional to match "yours" with "theirs" (so if they have a remotes/origin/mauve you'd name yours mauve too), but you can type in "theirs" whenever you want to name/see commits you got "from them". (Remember that "one commit" is an entire source tree. You can pick out one specific file from one commit, with git show for instance, if and when you want that.)

A CORS POST request works from plain JavaScript, but why not with jQuery?

You are sending "params" in js: request.send(params);

but "data" in jquery". Is data defined?: data:data,

Also, you have an error in the URL:

$.ajax( {url:url,
         type:"POST",
         dataType:"json",
         data:data, 
         success:function(data, textStatus, jqXHR) {alert("success");},
         error: function(jqXHR, textStatus, errorThrown) {alert("failure");}
});

You are mixing the syntax with the one for $.post


Update: I was googling around based on monsur answer, and I found that you need to add Access-Control-Allow-Headers: Content-Type (below is the full paragraph)

http://metajack.im/2010/01/19/crossdomain-ajax-for-xmpp-http-binding-made-easy/

How CORS Works

CORS works very similarly to Flash's crossdomain.xml file. Basically, the browser will send a cross-domain request to a service, setting the HTTP header Origin to the requesting server. The service includes a few headers like Access-Control-Allow-Origin to indicate whether such a request is allowed.

For the BOSH connection managers, it is enough to specify that all origins are allowed, by setting the value of Access-Control-Allow-Origin to *. The Content-Type header must also be white-listed in the Access-Control-Allow-Headers header.

Finally, for certain types of requests, including BOSH connection manager requests, the permissions check will be pre-flighted. The browser will do an OPTIONS request and expect to get back some HTTP headers that indicate which origins are allowed, which methods are allowed, and how long this authorization will last. For example, here is what the Punjab and ejabberd patches I did return for OPTIONS:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type 
Access-Control-Max-Age: 86400

How to populate a dropdownlist with json data in jquery?

var listItems= "";
var jsonData = jsonObj.d;
    for (var i = 0; i < jsonData.Table.length; i++){
      listItems+= "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
    }
    $("#<%=DLState.ClientID%>").html(listItems);

Example

   <html>
    <head></head>
    <body>
      <select id="DLState">
      </select>
    </body>
    </html>

    /*javascript*/
    var jsonList = {"Table" : [{"stateid" : "2","statename" : "Tamilnadu"},
                {"stateid" : "3","statename" : "Karnataka"},
                {"stateid" : "4","statename" : "Andaman and Nicobar"},
                 {"stateid" : "5","statename" : "Andhra Pradesh"},
                 {"stateid" : "6","statename" : "Arunachal Pradesh"}]}

    $(document).ready(function(){
      var listItems= "";
      for (var i = 0; i < jsonList.Table.length; i++){
        listItems+= "<option value='" + jsonList.Table[i].stateid + "'>" + jsonList.Table[i].statename + "</option>";
      }
      $("#DLState").html(listItems);
    });    

How to copy sheets to another workbook using vba?

I would like to slightly rewrite keytarhero's response:

Sub CopyWorkbook()

Dim sh as Worksheet,  wb as workbook

Set wb = workbooks("Target workbook")
For Each sh in workbooks("source workbook").Worksheets
   sh.Copy After:=wb.Sheets(wb.sheets.count) 
Next sh

End Sub

Edit: You can also build an array of sheet names and copy that at once.

Workbooks("source workbook").Worksheets(Array("sheet1","sheet2")).Copy _
         After:=wb.Sheets(wb.sheets.count)

Note: copying a sheet from an XLS? to an XLS will result into an error. The opposite works fine (XLS to XLSX)

Why do I get a SyntaxError for a Unicode escape in my file path?

C:\\Users\\expoperialed\\Desktop\\Python This syntax worked for me.

Git Clone - Repository not found

open Credential Manager -> look for your GIT devops profile -> click on it -> edit -> add user and password generated in DevOps and save.

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

I saw this answer and it worked for me. https://msdn.microsoft.com/en-us/library/ms712362%28v=vs.85%29.aspx

After you have installed an ODBC driver from the driver's setup program, you can define one or more data sources for it. The data source name (DSN) should provide a unique description of the data; for example, Payroll or Accounts Payable. The user and system data sources that are defined for all currently installed drivers are listed in the User DSN or System DSN tabs of the ODBC Data Source Administrator dialog box. The file data sources in a given directory are listed in the File DSN tab; the directory to be shown is entered in the Look in box in the File DSN tab. System_CAPS_noteNote

To manage a data source that connects to a 32-bit driver under 64-bit platform, use c:\windows\sysWOW64\odbcad32.exe. To manage a data source that connects to a 64-bit driver, use c:\windows\system32\odbcad32.exe. In Administrative Tools on a 64-bit Windows 8 operating system, there are icons for both the 32-bit and 64-bit ODBC Data Source Administrator dialog box.

If you use the 64-bit odbcad32.exe to configure or remove a DSN that connects to a 32-bit driver, for example, Driver do Microsoft Access (*.mdb), you will receive the following error message:

The specified DSN contains an architecture mismatch between the Driver and Application

To resolve this error, use the 32-bit odbcad32.exe to configure or remove the DSN.

A data source associates a particular ODBC driver with the data you want to access through that driver. For example, you might create a data source to use the ODBC dBASE driver to access one or more dBASE files found in a specific directory on your hard disk or a network drive. Using the ODBC Data Source Administrator, you can add, modify, and delete data sources, as described in the following table.

How to find first element of array matching a boolean condition in JavaScript?

What about using filter and getting the first index from the resulting array?

var result = someArray.filter(isNotNullNorUndefined)[0];

jQuery Datepicker onchange event issue

I wrote this because I needed a solution to trigger an event only if the date changed.

It is a simple solution. Each time the dialog box closes we test to see if the data has changed. If it has, we trigger a custom event and reset the stored value.

$('.datetime').datepicker({
    onClose: function(dateText,datePickerInstance) {
        var oldValue = $(this).data('oldValue') || "";
        if (dateText !== oldValue) {
            $(this).data('oldValue',dateText);
            $(this).trigger('dateupdated');
        }
    }
});

Now we can hook up handlers for that custom event...

$('body').on('dateupdated','.datetime', function(e) {
    // do something
});

Unable to call the built in mb_internal_encoding method?

For Debian/Ubuntu:

sudo apt-get install php7.0-mbstring

jQuery textbox change event doesn't fire until textbox loses focus?

Binding to both events is the typical way to do it. You can also bind to the paste event.

You can bind to multiple events like this:

$("#textbox").on('change keyup paste', function() {
    console.log('I am pretty sure the text box changed');
});

If you wanted to be pedantic about it, you should also bind to mouseup to cater for dragging text around, and add a lastValue variable to ensure that the text actually did change:

var lastValue = '';
$("#textbox").on('change keyup paste mouseup', function() {
    if ($(this).val() != lastValue) {
        lastValue = $(this).val();
        console.log('The text box really changed this time');
    }
});

And if you want to be super duper pedantic then you should use an interval timer to cater for auto fill, plugins, etc:

var lastValue = '';
setInterval(function() {
    if ($("#textbox").val() != lastValue) {
        lastValue = $("#textbox").val();
        console.log('I am definitely sure the text box realy realy changed this time');
    }
}, 500);

What is the difference between a static method and a non-static method?

Well, more technically speaking, the difference between a static method and a virtual method is the way the are linked.

A traditional "static" method like in most non OO languages gets linked/wired "statically" to its implementation at compile time. That is, if you call method Y() in program A, and link your program A with library X that implements Y(), the address of X.Y() is hardcoded to A, and you can not change that.

In OO languages like JAVA, "virtual" methods are resolved "late", at run-time, and you need to provide an instance of a class. So in, program A, to call virtual method Y(), you need to provide an instance, B.Y() for example. At runtime, every time A calls B.Y() the implementation called will depend on the instance used, so B.Y() , C.Y() etc... could all potential provide different implementations of Y() at runtime.

Why will you ever need that? Because that way you can decouple your code from the dependencies. For example, say program A is doing "draw()". With a static language, thats it, but with OO you will do B.draw() and the actual drawing will depend on the type of object B, which, at runtime, can change to square a circle etc. That way your code can draw multiple things with no need to change, even if new types of B are provided AFTER the code was written. Nifty -

Random strings in Python

Sometimes, I've wanted random strings that are semi-pronounceable, semi-memorable.

import random

def randomWord(length=5):
    consonants = "bcdfghjklmnpqrstvwxyz"
    vowels = "aeiou"

    return "".join(random.choice((consonants, vowels)[i%2]) for i in range(length))

Then,

>>> randomWord()
nibit
>>> randomWord()
piber
>>> randomWord(10)
rubirikiro

To avoid 4-letter words, don't set length to 4.

Jim

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

How to use a switch case 'or' in PHP

I won't repost the other answers because they're all correct, but I'll just add that you can't use switch for more "complicated" statements, eg: to test if a value is "greater than 3", "between 4 and 6", etc. If you need to do something like that, stick to using if statements, or if there's a particularly strong need for switch then it's possible to use it back to front:

switch (true) {
    case ($value > 3) :
        // value is greater than 3
    break;
    case ($value >= 4 && $value <= 6) :
        // value is between 4 and 6
    break;
}

but as I said, I'd personally use an if statement there.

How to call a web service from jQuery

Incase people have a problem like myself following Marwan Aouida's answer ... the code has a small typo. Instead of "success" it says "sucess" change the spelling and the code works fine.

jQuery Mobile - back button

This is for version 1.4.4

  <div data-role="header" >
        <h1>CHANGE HOUSE ANIMATION</h1>
        <a href="#" data-rel="back" class="ui-btn-left ui-btn ui-icon-back ui-btn-icon-notext ui-shadow ui-corner-all"  data-role="button" role="button">Back</a>
    </div>

MySQL CONCAT returns NULL if any field contain NULL

SELECT CONCAT(isnull(`affiliate_name`,''),'-',isnull(`model`,''),'-',isnull(`ip`,''),'-',isnull(`os_type`,''),'-',isnull(`os_version`,'')) AS device_name
FROM devices

Multi-dimensional arrays in Bash

echo "Enter no of terms"
read count
for i in $(seq 1 $count)
do
  t=` expr $i - 1 `
  for j in $(seq $t -1 0)
  do
    echo -n " "
  done
  j=` expr $count + 1 `
  x=` expr $j - $i `
  for k in $(seq 1 $x)
  do
    echo -n "* "
  done
  echo ""
done

Refresh/reload the content in Div using jquery/ajax

I always use this, works perfect.

$(document).ready(function(){
        $(function(){
        $('#ideal_form').submit(function(e){
                e.preventDefault();
                var form = $(this);
                var post_url = form.attr('action');
                var post_data = form.serialize();
                $('#loader3', form).html('<img src="../../images/ajax-loader.gif" />       Please wait...');
                $.ajax({
                    type: 'POST',
                    url: post_url, 
                    data: post_data,
                    success: function(msg) {
                        $(form).fadeOut(800, function(){
                            form.html(msg).fadeIn().delay(2000);

                        });
                    }
                });
            });
        });
         });

TypeError: sequence item 0: expected string, int found

you can convert the integer dataframe into string first and then do the operation e.g.

df3['nID']=df3['nID'].astype(str)
grp = df3.groupby('userID')['nID'].aggregate(lambda x: '->'.join(tuple(x)))

How should I pass an int into stringWithFormat?

Do this:

label.text = [NSString stringWithFormat:@"%d", count];

Staging Deleted files

To stage all manually deleted files you can use:

git rm $(git ls-files --deleted)

To add an alias to this command as git rm-deleted, run:

git config --global alias.rm-deleted '!git rm $(git ls-files --deleted)'

PHP 7 RC3: How to install missing MySQL PDO

First install php-mysql

sudo apt-get install php7.0-mysql
//change the version number based on the php version

then enable the module

sudo phpenmod pdo_mysql

and restart apache

sudo service apache2 restart 

How to check if a file contains a specific string using Bash

if grep -q [string] [filename]
then
    [whatever action]
fi

Example

if grep -q 'my cat is in a tree' /tmp/cat.txt
then
    mkdir cat
fi

How to navigate to a directory in C:\ with Cygwin?

You already accepted an answer, but I just thought I'd mention that the following also works in Cygwin:

cd "C:\Foo"

I think the cd /cygdrive/c method is better, but sometimes it's useful to know that you can do this too.

How to read a single character from the user?

The answers here were informative, however I also wanted a way to get key presses asynchronously and fire off key presses in separate events, all in a thread-safe, cross-platform way. PyGame was also too bloated for me. So I made the following (in Python 2.7 but I suspect it's easily portable), which I figured I'd share here in case it was useful for anyone else. I stored this in a file named keyPress.py.

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen. From http://code.activestate.com/recipes/134892/"""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            try:
                self.impl = _GetchMacCarbon()
            except(AttributeError, ImportError):
                self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

class _GetchMacCarbon:
    """
    A function which returns the current ASCII key that is down;
    if no ASCII key is down, the null string is returned.  The
    page http://www.mactech.com/macintosh-c/chap02-1.html was
    very helpful in figuring out how to do this.
    """
    def __init__(self):
        import Carbon
        Carbon.Evt #see if it has this (in Unix, it doesn't)

    def __call__(self):
        import Carbon
        if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask
            return ''
        else:
            #
            # The event contains the following info:
            # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
            #
            # The message (msg) contains the ASCII char which is
            # extracted with the 0x000000FF charCodeMask; this
            # number is converted to an ASCII character with chr() and
            # returned
            #
            (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
            return chr(msg & 0x000000FF)

import threading
            
            
# From  https://stackoverflow.com/a/2022629/2924421
class Event(list):
    def __call__(self, *args, **kwargs):
        for f in self:
            f(*args, **kwargs)

    def __repr__(self):
        return "Event(%s)" % list.__repr__(self)            


def getKey():
    inkey = _Getch()
    import sys
    for i in xrange(sys.maxint):
        k=inkey()
        if k<>'':break
    return k

class KeyCallbackFunction():
    callbackParam = None
    actualFunction = None
    
    def __init__(self, actualFunction, callbackParam):
        self.actualFunction = actualFunction
        self.callbackParam = callbackParam

    def doCallback(self, inputKey):
        if not self.actualFunction is None:
            if self.callbackParam is None:
                callbackFunctionThread = threading.Thread(target=self.actualFunction, args=(inputKey,))
            else:
                callbackFunctionThread = threading.Thread(target=self.actualFunction, args=(inputKey,self.callbackParam))
            
            callbackFunctionThread.daemon = True
            callbackFunctionThread.start()
        
        

class KeyCapture():


    gotKeyLock = threading.Lock()
    gotKeys = []
    gotKeyEvent = threading.Event()

    keyBlockingSetKeyLock = threading.Lock()

    addingEventsLock = threading.Lock()
    keyReceiveEvents = Event()


    keysGotLock = threading.Lock()
    keysGot = []

    keyBlockingKeyLockLossy = threading.Lock()
    keyBlockingKeyLossy = None
    keyBlockingEventLossy = threading.Event()
    
    keysBlockingGotLock = threading.Lock()
    keysBlockingGot = []
    keyBlockingGotEvent = threading.Event()
    

    
    wantToStopLock = threading.Lock()
    wantToStop = False
    
    stoppedLock = threading.Lock()
    stopped = True
    
    isRunningEvent = False
    
    getKeyThread = None
    
    keyFunction = None
    keyArgs = None
    
    # Begin capturing keys. A seperate thread is launched that
    # captures key presses, and then these can be received via get,
    # getAsync, and adding an event via addEvent. Note that this
    # will prevent the system to accept keys as normal (say, if
    # you are in a python shell) because it overrides that key
    # capturing behavior.
    
    # If you start capture when it's already been started, a
    # InterruptedError("Keys are still being captured")
    # will be thrown
    
    # Note that get(), getAsync() and events are independent, so if a key is pressed:
    #
    # 1: Any calls to get() that are waiting, with lossy on, will return
    #    that key
    # 2: It will be stored in the queue of get keys, so that get() with lossy
    #    off will return the oldest key pressed not returned by get() yet.
    # 3: All events will be fired with that key as their input
    # 4: It will be stored in the list of getAsync() keys, where that list
    #    will be returned and set to empty list on the next call to getAsync().
    # get() call with it, aand add it to the getAsync() list.
    def startCapture(self, keyFunction=None, args=None):
        # Make sure we aren't already capturing keys
        self.stoppedLock.acquire()
        if not self.stopped:
            self.stoppedLock.release()
            raise InterruptedError("Keys are still being captured")
            return
        self.stopped = False
        self.stoppedLock.release()
        
        # If we have captured before, we need to allow the get() calls to actually
        # wait for key presses now by clearing the event
        if self.keyBlockingEventLossy.is_set():
            self.keyBlockingEventLossy.clear()
            
        # Have one function that we call every time a key is captured, intended for stopping capture
        # as desired
        self.keyFunction = keyFunction
        self.keyArgs = args
        
        # Begin capturing keys (in a seperate thread)
        self.getKeyThread = threading.Thread(target=self._threadProcessKeyPresses)
        self.getKeyThread.daemon = True
        self.getKeyThread.start()
        
        # Process key captures (in a seperate thread)
        self.getKeyThread = threading.Thread(target=self._threadStoreKeyPresses)
        self.getKeyThread.daemon = True
        self.getKeyThread.start()
    
    
    def capturing(self):
        self.stoppedLock.acquire()
        isCapturing = not self.stopped
        self.stoppedLock.release()
        return isCapturing
    # Stops the thread that is capturing keys on the first opporunity
    # has to do so. It usually can't stop immediately because getting a key
    # is a blocking process, so this will probably stop capturing after the
    # next key is pressed.
    #
    # However, Sometimes if you call stopCapture it will stop before starting capturing the
    # next key, due to multithreading race conditions. So if you want to stop capturing
    # reliably, call stopCapture in a function added via addEvent. Then you are
    # guaranteed that capturing will stop immediately after the rest of the callback
    # functions are called (before starting to capture the next key).
    def stopCapture(self):
        self.wantToStopLock.acquire()
        self.wantToStop = True 
        self.wantToStopLock.release()

    # Takes in a function that will be called every time a key is pressed (with that
    # key passed in as the first paramater in that function)
    def addEvent(self, keyPressEventFunction, args=None):   
        self.addingEventsLock.acquire()
        callbackHolder = KeyCallbackFunction(keyPressEventFunction, args)
        self.keyReceiveEvents.append(callbackHolder.doCallback)
        self.addingEventsLock.release()
    def clearEvents(self):
        self.addingEventsLock.acquire()
        self.keyReceiveEvents = Event()
        self.addingEventsLock.release()
    # Gets a key captured by this KeyCapture, blocking until a key is pressed.
    # There is an optional lossy paramater:
    # If True all keys before this call are ignored, and the next pressed key
    #   will be returned.
    # If False this will return the oldest key captured that hasn't
    #   been returned by get yet. False is the default.
    def get(self, lossy=False):
        if lossy:
            # Wait for the next key to be pressed
            self.keyBlockingEventLossy.wait()
            self.keyBlockingKeyLockLossy.acquire()
            keyReceived = self.keyBlockingKeyLossy
            self.keyBlockingKeyLockLossy.release()
            return keyReceived
        else:
            while True:
                # Wait until a key is pressed
                self.keyBlockingGotEvent.wait()
                
                # Get the key pressed
                readKey = None
                self.keysBlockingGotLock.acquire()
                # Get a key if it exists
                if len(self.keysBlockingGot) != 0:
                    readKey = self.keysBlockingGot.pop(0)
                # If we got the last one, tell us to wait
                if len(self.keysBlockingGot) == 0:
                    self.keyBlockingGotEvent.clear()
                self.keysBlockingGotLock.release()
                
                # Process the key (if it actually exists)
                if not readKey is None:
                    return readKey
                
                # Exit if we are stopping
                self.wantToStopLock.acquire()
                if self.wantToStop:
                    self.wantToStopLock.release()
                    return None
                self.wantToStopLock.release()
            
            
            
    
    def clearGetList(self):
        self.keysBlockingGotLock.acquire()
        self.keysBlockingGot = []
        self.keysBlockingGotLock.release()
    
    # Gets a list of all keys pressed since the last call to getAsync, in order
    # from first pressed, second pressed, .., most recent pressed
    def getAsync(self):
        self.keysGotLock.acquire();
        keysPressedList = list(self.keysGot)
        self.keysGot = []
        self.keysGotLock.release()
        return keysPressedList
    
    def clearAsyncList(self):
        self.keysGotLock.acquire();
        self.keysGot = []
        self.keysGotLock.release();

    def _processKey(self, readKey):
        # Append to list for GetKeyAsync
        self.keysGotLock.acquire()
        self.keysGot.append(readKey)
        self.keysGotLock.release()
        
        # Call lossy blocking key events
        self.keyBlockingKeyLockLossy.acquire()
        self.keyBlockingKeyLossy = readKey
        self.keyBlockingEventLossy.set()
        self.keyBlockingEventLossy.clear()
        self.keyBlockingKeyLockLossy.release()
        
        # Call non-lossy blocking key events
        self.keysBlockingGotLock.acquire()
        self.keysBlockingGot.append(readKey)
        if len(self.keysBlockingGot) == 1:
            self.keyBlockingGotEvent.set()
        self.keysBlockingGotLock.release()
        
        # Call events added by AddEvent
        self.addingEventsLock.acquire()
        self.keyReceiveEvents(readKey)
        self.addingEventsLock.release()

    def _threadProcessKeyPresses(self):
        while True:
            # Wait until a key is pressed
            self.gotKeyEvent.wait()
            
            # Get the key pressed
            readKey = None
            self.gotKeyLock.acquire()
            # Get a key if it exists
            if len(self.gotKeys) != 0:
                readKey = self.gotKeys.pop(0)
            # If we got the last one, tell us to wait
            if len(self.gotKeys) == 0:
                self.gotKeyEvent.clear()
            self.gotKeyLock.release()
            
            # Process the key (if it actually exists)
            if not readKey is None:
                self._processKey(readKey)
            
            # Exit if we are stopping
            self.wantToStopLock.acquire()
            if self.wantToStop:
                self.wantToStopLock.release()
                break
            self.wantToStopLock.release()
            
    def _threadStoreKeyPresses(self):
        while True:
            # Get a key
            readKey = getKey()
            
            # Run the potential shut down function
            if not self.keyFunction is None:
                self.keyFunction(readKey, self.keyArgs)
        
            # Add the key to the list of pressed keys
            self.gotKeyLock.acquire()
            self.gotKeys.append(readKey)
            if len(self.gotKeys) == 1:
                self.gotKeyEvent.set()
            self.gotKeyLock.release()
            
            # Exit if we are stopping
            self.wantToStopLock.acquire()
            if self.wantToStop:
                self.wantToStopLock.release()
                self.gotKeyEvent.set()
                break
            self.wantToStopLock.release()
    
        
        # If we have reached here we stopped capturing
        
        # All we need to do to clean up is ensure that
        # all the calls to .get() now return None.
        # To ensure no calls are stuck never returning,
        # we will leave the event set so any tasks waiting
        # for it immediately exit. This will be unset upon
        # starting key capturing again.
        
        self.stoppedLock.acquire()
        
        # We also need to set this to True so we can start up
        # capturing again.
        self.stopped = True
        self.stopped = True
        
        self.keyBlockingKeyLockLossy.acquire()
        self.keyBlockingKeyLossy = None
        self.keyBlockingEventLossy.set()
        self.keyBlockingKeyLockLossy.release()
        
        self.keysBlockingGotLock.acquire()
        self.keyBlockingGotEvent.set()
        self.keysBlockingGotLock.release()
        
        self.stoppedLock.release()

The idea is that you can either simply call keyPress.getKey(), which will read a key from the keyboard, then return it.

If you want something more than that, I made a KeyCapture object. You can create one via something like keys = keyPress.KeyCapture().

Then there are three things you can do:

addEvent(functionName) takes in any function that takes in one parameter. Then every time a key is pressed, this function will be called with that key's string as it's input. These are ran in a separate thread, so you can block all you want in them and it won't mess up the functionality of the KeyCapturer nor delay the other events.

get() returns a key in the same blocking way as before. It is now needed here because the keys are being captured via the KeyCapture object now, so keyPress.getKey() would conflict with that behavior and both of them would miss some keys since only one key can be captured at a time. Also, say the user presses 'a', then 'b', you call get(), the user presses 'c'. That get() call will immediately return 'a', then if you call it again it will return 'b', then 'c'. If you call it again it will block until another key is pressed. This ensures that you don't miss any keys, in a blocking way if desired. So in this way it's a little different than keyPress.getKey() from before

If you want the behavior of getKey() back, get(lossy=True) is like get(), except that it only returns keys pressed after the call to get(). So in the above example, get() would block until the user presses 'c', and then if you call it again it will block until another key is pressed.

getAsync() is a little different. It's designed for something that does a lot of processing, then occasionally comes back and checks which keys were pressed. Thus getAsync() returns a list of all the keys pressed since the last call to getAsync(), in order from oldest key pressed to most recent key pressed. It also doesn't block, meaning that if no keys have been pressed since the last call to getAsync(), an empty [] will be returned.

To actually start capturing keys, you need to call keys.startCapture() with your keys object made above. startCapture is non-blocking, and simply starts one thread that just records the key presses, and another thread to process those key presses. There are two threads to ensure that the thread that records key presses doesn't miss any keys.

If you want to stop capturing keys, you can call keys.stopCapture() and it will stop capturing keys. However, since capturing a key is a blocking operation, the thread capturing keys might capture one more key after calling stopCapture().

To prevent this, you can pass in an optional parameter(s) into startCapture(functionName, args) of a function that just does something like checks if a key equals 'c' and then exits. It's important that this function does very little before, for example, a sleep here will cause us to miss keys.

However, if stopCapture() is called in this function, key captures will be stopped immediately, without trying to capture any more, and that all get() calls will be returned immediately, with None if no keys have been pressed yet.

Also, since get() and getAsync() store all the previous keys pressed (until you retrieve them), you can call clearGetList() and clearAsyncList() to forget the keys previously pressed.

Note that get(), getAsync() and events are independent, so if a key is pressed:

  1. One call to get() that is waiting, with lossy on, will return that key. The other waiting calls (if any) will continue waiting.
  2. That key will be stored in the queue of get keys, so that get() with lossy off will return the oldest key pressed not returned by get() yet.
  3. All events will be fired with that key as their input
  4. That key will be stored in the list of getAsync() keys, where that lis twill be returned and set to empty list on the next call to getAsync()

If all this is too much, here is an example use case:

import keyPress
import time
import threading

def KeyPressed(k, printLock):
    printLock.acquire()
    print "Event: " + k
    printLock.release()
    time.sleep(4)
    printLock.acquire()
    print "Event after delay: " + k
    printLock.release()

def GetKeyBlocking(keys, printLock):    
    while keys.capturing():
        keyReceived = keys.get()
        time.sleep(1)
        printLock.acquire()
        if not keyReceived is None:
            print "Block " + keyReceived
        else:
            print "Block None"
        printLock.release()

def GetKeyBlockingLossy(keys, printLock):   
    while keys.capturing():
        keyReceived = keys.get(lossy=True)
        time.sleep(1)
        printLock.acquire()
        if not keyReceived is None:
            print "Lossy: " + keyReceived
        else:
            print "Lossy: None"
        printLock.release()

def CheckToClose(k, (keys, printLock)):
    printLock.acquire()
    print "Close: " + k
    printLock.release()
    if k == "c":
        keys.stopCapture()
        
printLock = threading.Lock()

print "Press a key:"
print "You pressed: " + keyPress.getKey()
print ""

keys = keyPress.KeyCapture()

keys.addEvent(KeyPressed, printLock)



print "Starting capture"
            
keys.startCapture(CheckToClose, (keys, printLock))
            
getKeyBlockingThread = threading.Thread(target=GetKeyBlocking, args=(keys, printLock))
getKeyBlockingThread.daemon = True
getKeyBlockingThread.start()

            
getKeyBlockingThreadLossy = threading.Thread(target=GetKeyBlockingLossy, args=(keys, printLock))
getKeyBlockingThreadLossy.daemon = True
getKeyBlockingThreadLossy.start()

while keys.capturing():
    keysPressed = keys.getAsync()
    printLock.acquire()
    if keysPressed != []:
        print "Async: " + str(keysPressed)
    printLock.release()
    time.sleep(1)

print "done capturing"

It is working well for me from the simple test I made, but I will happily take others feedback as well if there is something I missed.

I posted this here as well.

How can I remove all text after a character in bash?

Let's say you have a path with a file in this format:

/dirA/dirB/dirC/filename.file

Now you only want the path which includes four "/". Type

$ echo "/dirA/dirB/dirC/filename.file" | cut -f1-4 -d"/"

and your output will be

/dirA/dirB/dirC

The advantage of using cut is that you can also cut out the uppest directory as well as the file (in this example), so if you type

$ echo "/dirA/dirB/dirC/filename.file" | cut -f1-3 -d"/"

your output would be

/dirA/dirB

Though you can do the same from the other side of the string, it would not make that much sense in this case as typing

$ echo "/dirA/dirB/dirC/filename.file" | cut -f2-4 -d"/"

results in

dirA/dirB/dirC

In some other cases the last case might also be helpful. Mind that there is no "/" at the beginning of the last output.

how to create a logfile in php?

This is my working code. Thanks to Paulo for the links. You create a custom error handler and call the trigger_error function with the correct $errno exception, even if it's not an error. Make sure you can write to the log file directory without administrator access.

<?php
    $logfile_dir = "C:\workspace\logs\\";   // or "/var/log/" for Linux
    $logfile = $logfile_dir . "php_" . date("y-m-d") . ".log";
    $logfile_delete_days = 30;

    function error_handler($errno, $errstr, $errfile, $errline)
    {
        global $logfile_dir, $logfile, $logfile_delete_days;

        if (!(error_reporting() & $errno)) {
            // This error code is not included in error_reporting, so let it fall
            // through to the standard PHP error handler
            return false;
        }

        $filename = basename($errfile);

        switch ($errno) {
            case E_USER_ERROR:
                file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "ERROR >> message = [$errno] $errstr\n", FILE_APPEND | LOCK_EX);
                exit(1);
                break;

            case E_USER_WARNING:
                file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "WARNING >> message = $errstr\n", FILE_APPEND | LOCK_EX);
                break;

            case E_USER_NOTICE:
                file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "NOTICE >> message = $errstr\n", FILE_APPEND | LOCK_EX);
                break;

            default:
                file_put_contents($logfile, date("y-m-d H:i:s.").gettimeofday()["usec"] . " $filename ($errline): " . "UNKNOWN >> message = $errstr\n", FILE_APPEND | LOCK_EX);
                break;
        }

        // delete any files older than 30 days
        $files = glob($logfile_dir . "*");
        $now   = time();

        foreach ($files as $file)
            if (is_file($file))
                if ($now - filemtime($file) >= 60 * 60 * 24 * $logfile_delete_days)
                    unlink($file);

        return true;    // Don't execute PHP internal error handler
    }

    set_error_handler("error_handler");

    trigger_error("testing 1,2,3", E_USER_NOTICE);
?>

Hide div by default and show it on click with bootstrap

Here I propose a way to do this exclusively using the Bootstrap framework built-in functionality.

  1. You need to make sure the target div has an ID.
  2. Bootstrap has a class "collapse", this will hide your block by default. If you want your div to be collapsible AND be shown by default you need to add "in" class to the collapse. Otherwise the toggle behavior will not work properly.
  3. Then, on your hyperlink (also works for buttons), add an href attribute that points to your target div.
  4. Finally, add the attribute data-toggle="collapse" to instruct Bootstrap to add an appropriate toggle script to this tag.

Here is a code sample than can be copy-pasted directly on a page that already includes Bootstrap framework (up to version 3.4.1):

<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>
<button href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</button>
<div id="Foo" class="collapse">
    This div (Foo) is hidden by default
</div>
<div id="Bar" class="collapse in">
    This div (Bar) is shown by default and can toggle
</div>

Change a web.config programmatically with C# (.NET)

This is a method that I use to update AppSettings, works for both web and desktop applications. If you need to edit connectionStrings you can get that value from System.Configuration.ConnectionStringSettings config = configFile.ConnectionStrings.ConnectionStrings["YourConnectionStringName"]; and then set a new value with config.ConnectionString = "your connection string";. Note that if you have any comments in the connectionStrings section in Web.Config these will be removed.

private void UpdateAppSettings(string key, string value)
{
    System.Configuration.Configuration configFile = null;
    if (System.Web.HttpContext.Current != null)
    {
        configFile =
            System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
    }
    else
    {
        configFile =
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    }
    var settings = configFile.AppSettings.Settings;
    if (settings[key] == null)
    {
        settings.Add(key, value);
    }
    else
    {
        settings[key].Value = value;
    }
    configFile.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}

"Large data" workflows using pandas

I know this is an old thread but I think the Blaze library is worth checking out. It's built for these types of situations.

From the docs:

Blaze extends the usability of NumPy and Pandas to distributed and out-of-core computing. Blaze provides an interface similar to that of the NumPy ND-Array or Pandas DataFrame but maps these familiar interfaces onto a variety of other computational engines like Postgres or Spark.

Edit: By the way, it's supported by ContinuumIO and Travis Oliphant, author of NumPy.

Android Emulator sdcard push error: Read-only file system

Try this in a Terminal Emulator as root:

restorecon -v -R /data/media

check if directory exists and delete in one command unix

Here is another one liner:

[[ -d /tmp/test ]] && rm -r /tmp/test
  • && means execute the statement which follows only if the preceding statement executed successfully (returned exit code zero)

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

In my case, I was using the ASP.NET Identity Framework. I had used the built in UserManager.FindByNameAsync method to retrieve an ApplicationUser entity. I then tried to reference this entity on a newly created entity on a different DbContext. This resulted in the exception you originally saw.

I solved this by creating a new ApplicationUser entity with only the Id from the UserManager method and referencing that new entity.

How to avoid HTTP error 429 (Too Many Requests) python

Receiving a status 429 is not an error, it is the other server "kindly" asking you to please stop spamming requests. Obviously, your rate of requests has been too high and the server is not willing to accept this.

You should not seek to "dodge" this, or even try to circumvent server security settings by trying to spoof your IP, you should simply respect the server's answer by not sending too many requests.

If everything is set up properly, you will also have received a "Retry-after" header along with the 429 response. This header specifies the number of seconds you should wait before making another call. The proper way to deal with this "problem" is to read this header and to sleep your process for that many seconds.

You can find more information on status 429 here: http://tools.ietf.org/html/rfc6585#page-3

Embedding VLC plugin on HTML page

Unfortunately, IE and VLC don't really work right now... I found this on the vlc forums:

VLC included activex support up until version 0.8.6, I believe. At that time, you could
access a cab on the videolan and therefore 'automatic' installation into IE and Firefox
family browsers was fine. Thereafter support for activex seemed to stop; no cab, no
activex component.

VLC 1.0.* once again contains activex support, and that's brilliant. A good decision in
my opinion. What's lacking is a cab installer for the latest version.

This basically means that even if you found a way to make it work, anyone trying to view the video on your site in IE would have to download and install the entire VLC player program to have it work in IE, and users probably don't want to do that. I can't get your code to work in firefox or IE8 on my boyfriends computer, although I might not have been putting the video address in properly... I get some message about no video output...

I'll take a guess and say it probably works for you locally because you have VLC installed, but your server doesn't. Unfortunately you'll probably have to use Windows media player or something similar (Microsoft is great at forcing people to use their stuff!)

And if you're wondering, it appears that the reason there is no cab file is because of the cost of having an active-x control signed.

It's rather simple to have your page use VLC for firefox and chrome users, and Windows Media Player for IE users, if that would work for you.

Can you have a <span> within a <span>?

HTML4 specification states that:

Inline elements may contain only data and other inline elements

Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.

HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.

frequent issues arising in android view, Error parsing XML: unbound prefix

You just need to add proper name space in your root tag . xmlns:android="http://schemas.android.com/apk/res/android" Android elemets are declared in this name space.Its same as importing class or package.

How to Implement Custom Table View Section Headers and Footers with Storyboard

In iOS 6.0 and above, things have changed with the new dequeueReusableHeaderFooterViewWithIdentifier API.

I have written a guide (tested on iOS 9), which can be summarised as such:

  1. Subclass UITableViewHeaderFooterView
  2. Create Nib with the subclass view, and add 1 container view which contains all other views in the header/footer
  3. Register the Nib in viewDidLoad
  4. Implement viewForHeaderInSection and use dequeueReusableHeaderFooterViewWithIdentifier to get back the header/footer

The remote certificate is invalid according to the validation procedure

Even shorter version of the solution from Dominic Zukiewicz:

ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

But this means that you will trust all certificates. For a service that isn't just run locally, something a bit smarter will be needed. In the first instance you could use this code to just test whether it solves your problem.

Get all rows from SQLite

Using Android's built in method

If you want every column and every row, then just pass in null for the SQLiteDatabase column and selection parameters.

Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null, null);

More details

The other answers use rawQuery, but you can use Android's built in SQLiteDatabase. The documentation for query says that you can just pass in null to the selection parameter to get all the rows.

selection Passing null will return all rows for the given table.

And while you can also pass in null for the column parameter to get all of the columns (as in the one-liner above), it is better to only return the columns that you need. The documentation says

columns Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.

Example

SQLiteDatabase db = mHelper.getReadableDatabase();
String[] columns = {
        MyDatabaseHelper.COLUMN_1,
        MyDatabaseHelper.COLUMN_2,
        MyDatabaseHelper.COLUMN_3};
String selection = null; // this will select all rows
Cursor cursor = db.query(MyDatabaseHelper.MY_TABLE, columns, selection,
        null, null, null, null, null);

How to pass data to all views in Laravel 5?

I think that the best way is with View Composers. If someone came here and want to find how can do it with View Composers way, read my answer => How to share a variable across all views?

How to get the jQuery $.ajax error response text?

For me, this simply works:

error: function(xhr, status, error) {
  alert(xhr.responseText);
}

How can I shuffle an array?

Use the modern version of the Fisher–Yates shuffle algorithm:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6) version

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.

Use

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

Implementing prototype

Using Object.defineProperty (method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr). The following will allow you to call arr.shuffle() to shuffle the array arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

ASP.NET strange compilation error

I have crawled through a lot of blog posts including a few Stack Overflow pots, and I already had everything in place what these posts suggested (see below) when I got this error.

  1. My app pool is running under ApplicationPoolIdentity
  2. Load user Profile was set to True in Process Model section
  3. IIS AppPool\DefaultAppPool has full permissions on temp ASP.NET files folder

Finally I found some clues in the below mentioned blog post. It looks like there is heap contention with the same user account. So I changed the app pool identity to LocalSystem, for the app which is failing with this error - and my app started working fine.

See blog post C# compiler or Visual Basic .Net compilers fail with error code -1073741502 when generating assemblies for your ASP.net site.

Note: LocalSystem account will not have much permissions. In my case my application does not need any special permissions. So I was fine. If your application needs special permissions try configuring a custom account.

Finding the number of days between two dates

function howManyDays($startDate,$endDate) {

    $date1  = strtotime($startDate." 0:00:00");
    $date2  = strtotime($endDate." 23:59:59");
    $res    =  (int)(($date2-$date1)/86400);        

return $res;
} 

How do I set a variable to the output of a command in Bash?

When setting a variable make sure you have no spaces before and/or after the = sign. I literally spent an hour trying to figure this out, trying all kinds of solutions! This is not cool.

Correct:

WTFF=`echo "stuff"`
echo "Example: $WTFF"

Will Fail with error "stuff: not found" or similar

WTFF= `echo "stuff"`
echo "Example: $WTFF"

How to send data in request body with a GET when using jQuery $.ajax()

we all know generally that for sending the data according to the http standards we generally use POST request. But if you really want to use Get for sending the data in your scenario I would suggest you to use the query-string or query-parameters.

1.GET use of Query string as. {{url}}admin/recordings/some_id

here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.

2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true

here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.

3.GET Sending arrays {{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]

and you can access those array values at server side like this

let osValues = JSON.parse(req.query.os);
        if(osValues.length > 0)
        {
            for (let i=0; i<osValues.length; i++)
            {
                console.log(osValues[i])
                //do whatever you want to do here
            }
        }

How to iterate through a table rows and get the cell values using jQuery

Hello every one thanks for the help below is the working code for my question

$("#TableView tr.item").each(function() { 
    var quantity1=$(this).find("input.name").val(); 
    var quantity2=$(this).find("input.id").val(); 
});

How to render pdfs using C#

Here is my answer from a different question.

First you need to reference the Adobe Reader ActiveX Control

Adobe Acrobat Browser Control Type Library 1.0

%programfiles&\Common Files\Adobe\Acrobat\ActiveX\AcroPDF.dll

Then you just drag it into your Windows Form from the Toolbox.

And use some code like this to initialize the ActiveX Control.

private void InitializeAdobe(string filePath)
{
    try
    {
        this.axAcroPDF1.LoadFile(filePath);
        this.axAcroPDF1.src = filePath;
        this.axAcroPDF1.setShowToolbar(false);
        this.axAcroPDF1.setView("FitH");
        this.axAcroPDF1.setLayoutMode("SinglePage");
        this.axAcroPDF1.Show();
    }
    catch (Exception ex)
    {
        throw;
    }
}

Make sure when your Form closes that you dispose of the ActiveX Control

this.axAcroPDF1.Dispose();
this.axAcroPDF1 = null;

otherwise Acrobat might be left lying around.

Associating enums with strings in C#

I wanted to avoid using string literals completely, and also I didn't need to have space in item descriptions. More importantly, I wanted to have a mechanism to check if the provided string is a valid item, so I came up with this solution:

public class Seasons
{
    public static string Spring { get; }
    public static string Summer { get; }
    public static string Fall { get; }
    public static string Winter { get; }

    public static bool IsValid(string propertyName)
    {
        if (string.IsNullOrEmpty(propertyName))
        {
            return false;
        }

        try
        {           
            return typeof(Seasons).GetProperty(propertyName) != null;
        }
        catch
        {
            return false;
        }       
    }
}

And here is how it works:

void Main()
{
    string s = nameof(Seasons.Fall);
    Console.WriteLine($"Fall is valid: {Seasons.IsValid(s)}"); // true

    s = "WrongSeason";
    Console.WriteLine($"WrongSeason is valid: {Seasons.IsValid(s)}"); // false
}

I tried to refactor IsValid() into a base class and use reflection to read the type (MethodBase.GetCurrentMethod().DeclaringType), but since I wanted to have it static, it returns the base class type, not the inherited type. Your remedy to this will be very welcomed! Here is what I was trying to achieve:

public  class Seasons : ConstantStringsBase
{
    // ... same
}

public  class ConstantStringsBase
{
    public static bool IsValid(string propertyName)
    {       
        return MethodBase.GetCurrentMethod().DeclaringType.GetProperty(propertyName) != null;
    }
}

Align Bootstrap Navigation to Center

.navbar-nav {
   float: left;
   margin: 0;
   margin-left: 40%;
}

.navbar-nav.navbar-right:last-child {
   margin-right: -15px;
   margin-left: 0;
}

Updated Fiddle

Since You Have used the float property we don't have many options except to adjust it manually.

Jetty: HTTP ERROR: 503/ Service Unavailable

None of these answers worked for me.

I had to remove all deployed java web app:

  • Windows/Show View/Other...
  • Go the the Server folder and select "Servers"
  • Right-click on the J2EE Preview at localhost
  • Click to Add and Remove... Click Remove all

Then run the project on the server

The Error is gone!

You will have to stop the server before deploying another project because it will not be found by the server. Otherwise you will get a 404 error

How to explicitly obtain post data in Spring MVC?

Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter() for this:

String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");

The HttpServletRequest should already be available to you inside Spring MVC as one of the method arguments of the handleRequest() method.

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I had the same error today, after deploying our service calling an external service to the staging environment in azure. Local the service called the external service without errors, but after deployment it didn't.

In the end it turned out to be that the external service has a IP validation. The new environment in Azure has another IP and it was rejected.

So if you ever get this error calling external services

It might be an IP restriction.

Conda environments not showing up in Jupyter Notebook

We have struggle a lot with this issue, and here's what works for us. If you use the conda-forge channel, it's important to make sure you are using updated packages from conda-forge, even in your Miniconda root environment.

So install Miniconda, and then do:

conda config --add channels conda-forge --force
conda update --all  -y
conda install nb_conda_kernels -y
conda env create -f custom_env.yml -q --force
jupyter notebook

and your custom environment will show up in Jupyter as an available kernel, as long as ipykernel was listed for installation in your custom_env.yml file, like this example:

name: bqplot
channels:
- conda-forge
- defaults
dependencies:
- python>=3.6
- bqplot
- ipykernel

Just to prove it working with a bunch of custom environments, here's a screen grab from Windows:

enter image description here

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

What is two way binding?

Two-way binding means that any data-related changes affecting the model are immediately propagated to the matching view(s), and that any changes made in the view(s) (say, by the user) are immediately reflected in the underlying model. When app data changes, so does the UI, and conversely.

This is a very solid concept to build a web application on top of, because it makes the "Model" abstraction a safe, atomic data source to use everywhere within the application. Say, if a model, bound to a view, changes, then its matching piece of UI (the view) will reflect that, no matter what. And the matching piece of UI (the view) can safely be used as a mean of collecting user inputs/data, so as to maintain the application data up-to-date.

A good two-way binding implementation should obviously make this connection between a model and some view(s) as simple as possible, from a developper point of view.

It is then quite untrue to say that Backbone does not support two-way binding: while not a core feature of the framework, it can be performed quite simply using Backbone's Events though. It costs a few explicit lines of code for the simple cases; and can become quite hazardous for more complex bindings. Here is a simple case (untested code, written on the fly just for the sake of illustration):

Model = Backbone.Model.extend
  defaults:
    data: ''

View = Backbone.View.extend
  template: _.template("Edit the data: <input type='text' value='<%= data %>' />")

  events:
    # Listen for user inputs, and edit the model.
    'change input': @setData

  initialize: (options) ->
    # Listen for model's edition, and trigger UI update
    @listenTo @model, 'change:data', @render

  render: ->
    @$el.html @template(@model.attributes)
    @

  setData: (e) =>
    e.preventDefault()
    @model.set 'data', $(e.currentTarget).value()

model: new Model()
view = new View {el: $('.someEl'), model: model}

This is a pretty typical pattern in a raw Backbone application. As one can see, it requires a decent amount of (pretty standard) code.

AngularJS and some other alternatives (Ember, Knockout…) provide two-way binding as a first-citizen feature. They abstract many edge-cases under some DSL, and do their best at integrating two-way binding within their ecosystem. Our example would look something like this with AngularJS (untested code, see above):

<div ng-app="app" ng-controller="MainCtrl">
  Edit the data:
  <input name="mymodel.data" ng-model="mymodel.data">
</div>
angular.module('app', [])
  .controller 'MainCtrl', ($scope) ->
    $scope.mymodel = {data: ''}

Rather short!

But, be aware that some fully-fledged two-way binding extensions do exist for Backbone as well (in raw, subjective order of decreasing complexity): Epoxy, Stickit, ModelBinder

One cool thing with Epoxy, for instance, is that it allows you to declare your bindings (model attributes <-> view's DOM element) either within the template (DOM), or within the view implementation (JavaScript). Some people strongly dislike adding "directives" to the DOM/template (such as the ng-* attributes required by AngularJS, or the data-bind attributes of Ember).

Taking Epoxy as an example, one can rework the raw Backbone application into something like this (…):

Model = Backbone.Model.extend
  defaults:
    data: ''

View = Backbone.Epoxy.View.extend
  template: _.template("Edit the data: <input type='text' />")
  # or, using the inline form: <input type='text' data-bind='value:data' />

  bindings:
    'input': 'value:data'

  render: ->
    @$el.html @template(@model.attributes)
    @

model: new Model()
view = new View {el: $('.someEl'), model: model}

All in all, pretty much all "mainstream" JS frameworks support two-way binding. Some of them, such as Backbone, do require some extra work to make it work smoothly, but those are the same which do not enforce a specific way to do it, to begin with. So it is really about your state of mind.

Also, you may be interested in Flux, a different architecture for web applications promoting one-way binding through a circular pattern. It is based on the concept of fast, holistic re-rendering of UI components upon any data change to ensure cohesiveness and make it easier to reason about the code/dataflow. In the same trend, you might want to check the concept of MVI (Model-View-Intent), for instance Cycle.

C# - Substring: index and length must refer to a location within the string

You need to check your statement like this :

string url = "www.example.com/aaa/bbb.jpg";
string lenght = url.Lenght-4;
if(url.Lenght > 15)//eg 15
{
 string newString = url.Substring(18, lenght);
}

"Fade" borders in CSS

How to fade borders with CSS:

<div style="border-style:solid;border-image:linear-gradient(red, transparent) 1;border-bottom:0;">Text</div>

Please excuse the inline styles for the sake of demonstration. The 1 property for the border-image is border-image-slice, and in this case defines the border as a single continuous region.

Source: Gradient Borders

Is there a way to programmatically minimize a window

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
     if(e.KeyChar == 'm')
         this.WindowState = FormWindowState.Minimized;
}

HtmlEncode from Class Library

Add a reference to System.Web.dll and then you can use the System.Web.HtmlUtility class

What is Android keystore file, and what is it used for?

The answer I would provide is that a keystore file is to authenticate yourself to anyone who is asking. It isn't restricted to just signing .apk files, you can use it to store personal certificates, sign data to be transmitted and a whole variety of authentication.

In terms of what you do with it for Android and probably what you're looking for since you mention signing apk's, it is your certificate. You are branding your application with your credentials. You can brand multiple applications with the same key, in fact, it is recommended that you use one certificate to brand multiple applications that you write. It easier to keep track of what applications belong to you.

I'm not sure what you mean by implications. I suppose it means that no one but the holder of your certificate can update your application. That means that if you release it into the wild, lose the cert you used to sign the application, then you cannot release updates so keep that cert safe and backed up if need be.

But apart from signing apks to release into the wild, you can use it to authenticate your device to a server over SSL if you so desire, (also Android related) among other functions.

How do I kill an Activity when the Back button is pressed?

First of all, finish() doesn't destroy your process and free up the memory. It just removes the activity from the activity stack. You'd need to kill the process, which is answered in a bunch of questions (since this is being asked several times).

But the proper answer is - Don't do it. the Android OS will automatically free up memory when it needs memory. By not freeing up memory, your app will start up faster if the user gets back to it.

Please see here for a great write-up on the topic.

How to pass a datetime parameter?

One possible solution is to use Ticks:

public long Ticks { get; }

Then in the controller's method:

public DateTime(long ticks);

How to get only filenames within a directory using c#?

You can use the method Path.GetFileName(yourFileName); (MSDN) to just get the name of the file.

Python concatenate text files

If the files are not gigantic:

with open('newfile.txt','wb') as newf:
    for filename in list_of_files:
        with open(filename,'rb') as hf:
            newf.write(hf.read())
            # newf.write('\n\n\n')   if you want to introduce
            # some blank lines between the contents of the copied files

If the files are too big to be entirely read and held in RAM, the algorithm must be a little different to read each file to be copied in a loop by chunks of fixed length, using read(10000) for example.

How to add url parameter to the current url?

It is not elegant but possible to do it as one-liner <a> element

_x000D_
_x000D_
<a href onclick="event.preventDefault(); location+='&like=like'">Like</a>
_x000D_
_x000D_
_x000D_

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

What about using the javascript FileReader function to open the local file, ie:

<input type="file" name="filename" id="filename">
<script>
$("#filename").change(function (e) {
  if (e.target.files != undefined) {
    var reader = new FileReader();
    reader.onload = function (e) {
        // Get all the contents in the file
        var data = e.target.result; 
        // other stuffss................            
    };
    reader.readAsText(e.target.files.item(0));
  }
});
</script>

Now Click Choose file button and browse to the file file:///C:/path/to/XSL%20Website/data/home.xml

How to get the top position of an element?

Try: $('#mytable').attr('offsetTop')

SOAP PHP fault parsing WSDL: failed to load external entity?

If anyone has the same problem, one possible solution is to set the bindto stream context configuration parameter (assuming you're connecting from 11.22.33.44 to 55.66.77.88):

$context = [
    'socket' => [
        'bindto' => '55.66.77.88'
    ]
];

$options = [
    'soapVersion' => SOAP_1_1,
    'stream_context' => stream_context_create($context)
];

$client = new Client('11.22.33.44', $options);

Superscript in markdown (Github flavored)?

Comments about previous answers

The universal solution is using the HTML tag <sup>, as suggested in the main answer.
However, the idea behind Markdown is precisely to avoid the use of such tags:
The document should look nice as plain text, not only when rendered.

Another answer proposes using Unicode characters, which makes the document look nice as a plain text document but could reduce compatibility.

Finally, I would like to remember the simplest solution for some documents: the character ^.
Some Markdown implementation (e.g. MacDown in macOS) interprets the caret as an instruction for superscript.

Ex.
Sin^2 + Cos^2 = 1
Clearly, Stack Overflow does not interpret the caret as a superscript instruction. However, the text is comprehensible, and this is what really matters when using Markdown.

Self-reference for cell, column and row in worksheet functions

There is a better way that is safer and will not slow down your application. How Excel is set up, a cell can have either a value or a formula; the formula can not refer to its own cell. Otherwise, You end up with an infinite loop, since the new value would cause another calculation... .

Use a helper column to calculate the value based on what you put in the other cell.

For Example:

Column A is a True or False, Column B contains a monetary value, Column C contains the following formula:

=B1

Now, to calculate that column B will be highlighted yellow in a conditional format only if Column A is True and Column B is greater than Zero...

=AND(A1=True,C1>0)

You can then choose to hide column C

Is it possible to specify condition in Count()?

Note with PrestoDB SQL (from Facebook), there is a shortcut:

https://prestodb.io/docs/current/functions/aggregate.html

count_if(x) ? bigint

Returns the number of TRUE input values. This function is equivalent to count(CASE WHEN x THEN 1 END)

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

I liked the (C#) code in the following which sets the registry settings for your app. Not sure if it will cut it after installation though if permissions are required. For me it solved an issue with WebSocket not being available inside a WebBrowser control in WPF.

C# webbrowser Ajax call

JavaScript .replace only replaces first Match

Try using a regex instead of a string for the first argument.

"this is a test".replace(/ /g,'%20') // #=> "this%20is%20a%20test"

Setting the default Java character encoding

Following @Caspar comment on accepted answer, the preferred way to fix this according to Sun is :

"change the locale of the underlying platform before starting your Java program."

http://bugs.java.com/view_bug.do?bug_id=4163515

For docker see:

http://jaredmarkell.com/docker-and-locales/

string to string array conversion in java

String strName = "name";
String[] strArray = new String[] {strName};
System.out.println(strArray[0]); //prints "name"

The second line allocates a String array with the length of 1. Note that you don't need to specify a length yourself, such as:

String[] strArray = new String[1];

instead, the length is determined by the number of elements in the initalizer. Using

String[] strArray = new String[] {strName, "name1", "name2"};

creates an array with a length of 3.

NULL or BLANK fields (ORACLE)

A NULL column is not countable, however a row that has a NULL column is. So, this should do what you're looking for:

SELECT COUNT (*) FROM TABLE WHERE COL_NAME IS NULL OR LENGTH(TRIM (COL_NAME)) = 0

Note, that there are non-printing characters that this will not address. For example U+00A0 is the non-breaking space character and a line containing that will visually appear empty, but will not be found by the tests above.

React Native version mismatch

I've never seen this error before, but whenever I can't get Xcode and React-Native to play well together, I do a couple of things. Check what version of Xcode I'm working with. If it needs to be updated, I update it. Then clearing watchman and the cache are the second place I go. I don't use the reset cache command. It always says that I need to verify the cache, so I skip that (you can do it though, I just get confused). I use rm -rf $TMPDIR/react-* to get rid of any cached builds. If that doesn't work, I try to build the app in Xcode, then work my way from there, to build it with react-native run-ios. With this error message, it seems you might start by trying to build it with Xcode. Hope that helps...let me know your progress with it. Good luck! (Also, you could update to RN 0.51 as another attempt to get your versions synced.)

Warning message: In `...` : invalid factor level, NA generated

If you are reading directly from CSV file then do like this.

myDataFrame <- read.csv("path/to/file.csv", header = TRUE, stringsAsFactors = FALSE)

Oracle comparing timestamp with date

You can truncate the date

SELECT *
FROM Table1
WHERE trunc(field1) = to_Date('2012-01-01','YYY-MM-DD')

Look at the SQL Fiddle for more examples.

Multiple SQL joins

 SELECT
 B.Title, B.Edition, B.Year, B.Pages, B.Rating     --from Books
, C.Category                                        --from Categories
, P.Publisher                                       --from Publishers
, W.LastName                                        --from Writers

FROM Books B

JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID

Namespace not recognized (even though it is there)

I was working on Xamarin project and as always, deleting obj folder and rebuilding solved my issue, the namespace my VS was not recognizing was a code in my own project BTW

How can I make my match non greedy in vim?

Instead of .* use .\{-}.

%s/style=".\{-}"//g

Also, see :help non-greedy

How can I use Timer (formerly NSTimer) in Swift?

NSTimer has been renamed to Timer in Swift 4.2. this syntax will work in 4.2:

let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(UIMenuController.update), userInfo: nil, repeats: true)

DataGridView AutoFit and Fill

public static void Fill(DataGridView dgv2)
   {
        try
        {
            dgv = dgv2;
            foreach (DataGridViewColumn GridCol in dgv.Columns)
            {
                for (int j = 0; j < GridCol.DataGridView.ColumnCount; j++)
                {
                    GridCol.DataGridView.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    GridCol.DataGridView.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                    GridCol.DataGridView.Columns[j].FillWeight = 1;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

C++ "Access violation reading location" Error

You haven't posted the findvertex method, but Access Reading Violation with an offset like 0x00000048 means that the Vertex* f; in your getCost function is receiving null, and when trying to access the member adj in the null Vertex pointer (that is, in f), it is offsetting to adj (in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0 or null memory address.

Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex isn't returning null, or do a comparisong for null on f before using it to keep yourself sane (or use an assert):

assert( f != null ); // A good sanity check

EDIT:

If you have a map for doing something like a find, you can just use the map's find method to make sure the vertex exists:

Vertex* Graph::findvertex(string s)
{
    vmap::iterator itr = map1.find( s );
    if ( itr == map1.end() )
    {
        return NULL;
    }
    return itr->second;
}

Just make sure you're still careful to handle the error case where it does return NULL. Otherwise, you'll keep getting this access violation.

How do I print out the contents of a vector?

In C++11, a range-based for loop might be a good solution:

vector<char> items = {'a','b','c'};
for (char n : items)
    cout << n << ' ';

Output:

a b c 

regex with space and letters only?

$('#input').on('keyup', function() {
     var RegExpression = /^[a-zA-Z\s]*$/;  
     ...

});

\s will allow the space

What are the best PHP input sanitizing functions?

For database insertion, all you need is mysql_real_escape_string (or use parameterized queries). You generally don't want to alter data before saving it, which is what would happen if you used htmlentities. That would lead to a garbled mess later on when you ran it through htmlentities again to display it somewhere on a webpage.

Use htmlentities when you are displaying the data on a webpage somewhere.

Somewhat related, if you are sending submitted data somewhere in an email, like with a contact form for instance, be sure to strip newlines from any data that will be used in the header (like the From: name and email address, subect, etc)

$input = preg_replace('/\s+/', ' ', $input);

If you don't do this it's just a matter of time before the spam bots find your form and abuse it, I've learned the hard way.

Is it possible to see more than 65536 rows in Excel 2007?

According to this MSDN entry, the limit is 1 million rows. You could be running in compatibility mode, which would limit you to the old standard of 65k. Does your excel say compatibility mode in the title? If so, you can save the file as a new style file under the "save as" menu, or change your default to always use the 2007 file standard.

How to delete all files and folders in a directory?

string directoryPath = "C:\Temp";
Directory.GetFiles(directoryPath).ToList().ForEach(File.Delete);
Directory.GetDirectories(directoryPath).ToList().ForEach(Directory.Delete);

Drawing Circle with OpenGL

I have done it using the following code,

glBegin(GL.GL_LINE_LOOP);
     for(int i =0; i <= 300; i++){
         double angle = 2 * Math.PI * i / 300;
         double x = Math.cos(angle);
         double y = Math.sin(angle);
         gl.glVertex2d(x,y);
     }
glEnd();

Pass path with spaces as parameter to bat file

I think the OP's problem was that he wants to do BOTH of the following:

  • Pass a parameter which may contain spaces
  • Test whether the parameter is missing

As several posters have mentioned, to pass a parameter containing spaces, you must surround the actual parameter value with double quotes.

To test whether a parameter is missing, the method I always learned was:

if "%1" == ""

However, if the actual parameter is quoted (as it must be if the value contains spaces), this becomes

if ""actual parameter value"" == ""

which causes the "unexpected" error. If you instead use

if %1 == ""

then the error no longer occurs for quoted values. But in that case, the test no longer works when the value is missing -- it becomes

if  == ""

To fix this, use any other characters (except ones with special meaning to DOS) instead of quotes in the test:

if [%1] == []
if .%1. == ..
if abc%1xyz == abcxyz

Shortest distance between a point and a line segment

Eigen C++ Version for 3D line segment and point

// Return minimum distance between line segment: head--->tail and point
double MinimumDistance(Eigen::Vector3d head, Eigen::Vector3d tail,Eigen::Vector3d point)
{
    double l2 = std::pow((head - tail).norm(),2);
    if(l2 ==0.0) return (head - point).norm();// head == tail case

    // Consider the line extending the segment, parameterized as head + t (tail - point).
    // We find projection of point onto the line.
    // It falls where t = [(point-head) . (tail-head)] / |tail-head|^2
    // We clamp t from [0,1] to handle points outside the segment head--->tail.

    double t = max(0,min(1,(point-head).dot(tail-head)/l2));
    Eigen::Vector3d projection = head + t*(tail-head);

    return (point - projection).norm();
}

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

Form.Close() is use to close an instance of a Form with in .NET application it does not kill the entire application. Application.exit() kills your application.

Is there a numpy builtin to reject outliers from a list

I would like to provide two methods in this answer, solution based on "z score" and solution based on "IQR".

The code provided in this answer works on both single dim numpy array and multiple numpy array.

Let's import some modules firstly.

import collections
import numpy as np
import scipy.stats as stat
from scipy.stats import iqr

z score based method

This method will test if the number falls outside the three standard deviations. Based on this rule, if the value is outlier, the method will return true, if not, return false.

def sd_outlier(x, axis = None, bar = 3, side = 'both'):
    assert side in ['gt', 'lt', 'both'], 'Side should be `gt`, `lt` or `both`.'

    d_z = stat.zscore(x, axis = axis)

    if side == 'gt':
        return d_z > bar
    elif side == 'lt':
        return d_z < -bar
    elif side == 'both':
        return np.abs(d_z) > bar

IQR based method

This method will test if the value is less than q1 - 1.5 * iqr or greater than q3 + 1.5 * iqr, which is similar to SPSS's plot method.

def q1(x, axis = None):
    return np.percentile(x, 25, axis = axis)

def q3(x, axis = None):
    return np.percentile(x, 75, axis = axis)

def iqr_outlier(x, axis = None, bar = 1.5, side = 'both'):
    assert side in ['gt', 'lt', 'both'], 'Side should be `gt`, `lt` or `both`.'

    d_iqr = iqr(x, axis = axis)
    d_q1 = q1(x, axis = axis)
    d_q3 = q3(x, axis = axis)
    iqr_distance = np.multiply(d_iqr, bar)

    stat_shape = list(x.shape)

    if isinstance(axis, collections.Iterable):
        for single_axis in axis:
            stat_shape[single_axis] = 1
    else:
        stat_shape[axis] = 1

    if side in ['gt', 'both']:
        upper_range = d_q3 + iqr_distance
        upper_outlier = np.greater(x - upper_range.reshape(stat_shape), 0)
    if side in ['lt', 'both']:
        lower_range = d_q1 - iqr_distance
        lower_outlier = np.less(x - lower_range.reshape(stat_shape), 0)

    if side == 'gt':
        return upper_outlier
    if side == 'lt':
        return lower_outlier
    if side == 'both':
        return np.logical_or(upper_outlier, lower_outlier)

Finally, if you want to filter out the outliers, use a numpy selector.

Have a nice day.

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

Seems your resource POSTmethod won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).

Since in you already add Access-Control-Allow-Origin headers to your Response, you can add new OPTIONS method to your resource class.

    @OPTIONS
@Path("{path : .*}")
public Response options() {
    return Response.ok("")
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
            .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
            .header("Access-Control-Max-Age", "2000")
            .build();
}

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

Using stored procedure output parameters in C#

In your C# code, you are using transaction for the command. Just commit the transaction and after that access your parameter value, you will get the value. Worked for me. :)

How to remove default chrome style for select Input?

-webkit-appearance: none;

and add your own style

SQL exclude a column using SELECT * [except columnA] FROM tableA?

Basically, you cannot do what you would like - but you can get the right tools to help you out making things a bit easier.

If you look at Red-Gate's SQL Prompt, you can type "SELECT * FROM MyTable", and then move the cursor back after the "*", and hit <TAB> to expand the list of fields, and remove those few fields you don't need.

It's not a perfect solution - but a darn good one! :-) Too bad MS SQL Server Management Studio's Intellisense still isn't intelligent enough to offer this feature.......

Marc

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

Sometimes this error comes because it's simply the wrong folder. :-(

It shall be the folder which contains the pom.xml.

Check to see if cURL is installed locally?

cURL is disabled for most hosting control panels for security reasons, but it's required for a lot of php applications. It's not unusual for a client to request it. Since the risk of enabling cURL is minimal, you are probably better off enabling it than losing a customer. It's simply a utility that helps php scripts fetch things using standard Internet URLs.

To enable cURL, you will remove curl_exec from the "disabled list" in the control panel php advanced settings. You will also find a disabled list in the various php.ini files; look in /etc/php.ini and other paths that might exist for your control panel. You will need to restart Apache to make the change take effect.

service httpd restart

To confirm whether cURL is enabled or disabled, create a file somewhere in your system and paste the following contents.

<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>

Save the file as testcurl.php and then run it as a php script.

php testcurl.php

If cURL is disabled you will see this error.

Fatal error: Call to undefined function curl_version() in testcurl.php on line 2

If cURL is enabled you will see a long list of attributes, like this.

array(9) {
["version_number"]=>
int(461570)
["age"]=>
int(1)
["features"]=>
int(540)
["ssl_version_number"]=>
int(9465919)
["version"]=>
string(6) "7.11.2"
["host"]=>
string(13) "i386-pc-win32"
["ssl_version"]=>
string(15) " OpenSSL/0.9.7c"
["libz_version"]=>
string(5) "1.1.4"
["protocols"]=>
array(9) {
[0]=>
string(3) "ftp"
[1]=>
string(6) "gopher"
[2]=>
string(6) "telnet"
[3]=>
string(4) "dict"
[4]=>
string(4) "ldap"
[5]=>
string(4) "http"
[6]=>
string(4) "file"
[7]=>
string(5) "https"
[8]=>
string(4) "ftps"
}
}

How do I convert from a money datatype in SQL server?

I had this issue as well, and was tripped up for a while on it. I wanted to display 0.00 as 0 and otherwise keep the decimal point. The following didn't work:

CASE WHEN Amount= 0 THEN CONVERT(VARCHAR(30), Amount, 1) ELSE Amount END

Because the resulting column was forced to be a MONEY column. To resolve it, the following worked

CASE WHEN Amount= 0 THEN CONVERT(VARCHAR(30), '0', 1) ELSE CONVERT (VARCHAR(30), Amount, 1) END

This mattered because my final destination column was a VARCHAR(30), and the consumers of that column would error out if an amount was '0.00' instead of '0'.

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

There are several sources on the net suggesting a hack by reinstalling the package with the -m option and then just removing the .egg file in lib/ and the binaries in bin/. Also, discussion about this setuptools issue can be found on the python bug tracker as setuptools issue 21.

Edit: Added the link to the python bugtracker.

How to display HTML tags as plain text

As many others have said, htmlentities() will do the trick... but it will look like shit.

Wrap it up with a <pre> tag and you'll preserve your indentation.

echo '<pre>';
echo htmlspecialchars($YOUR_HTML);
echo '</pre>';

onclick on a image to navigate to another page using Javascript

I'd set up your HTML like so:

<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />

Then use the following code:

<script>
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
    var image = images[i];
    image.onclick = function(event) {
         window.location.href = this.id + '.html';
    };
}
</script>

That assigns an onclick event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id attribute plus the .html extension. It's essentially the pure Javascript implementation of @JanPöschko's jQuery answer.

Best Regular Expression for Email Validation in C#

I would like to suggest new EmailAddressAttribute().IsValid(emailTxt) for additional validation before/after validating using RegEx

Remember EmailAddressAttribute is part of System.ComponentModel.DataAnnotations namespace.

What is IPV6 for localhost and 0.0.0.0?

IPv6 localhost

::1 is the loopback address in IPv6.

Within URLs

Within a URL, use square brackets []:

  • http://[::1]/
    Defaults to port 80.
  • http://[::1]:80/
    Specify port.

Enclosing the IPv6 literal in square brackets for use in a URL is defined in RFC 2732 – Format for Literal IPv6 Addresses in URL's.

Pure CSS collapse/expand div

Or a super simple version with barely any css :)

<style>   
.faq ul li {
    display:block;
    float:left;
    padding:5px;
}

.faq ul li div {
    display:none;
}

.faq ul li div:target {
    display:block;
}


</style>


<div class="faq">
   <ul>
   <li><a href="#question1">Question 1</a>   
   <div id="question1">Answer 1 </div>
   </li>


   <li><a href="#question2">Question 2</a>
   <div id="question2">Answer 2 </div>
   </li>
   <li><a href="#question3">Question 3</a>
   <div id="question3">Answer 3 </div>
   </li>
   <li><a href="#question4">Question 4</a>
   <div id="question4">Answer 4 </div>
   </li>
   <li><a href="#question5">Question 5</a>
   <div id="question5">Answer 5 </div>
   </li>
   <li><a href="#question6">Question 6</a>
   <div id="question6">Answer 6 </div>
   </li>
   </ul>  
</div>

http://jsfiddle.net/ionko22/4sKD3/

How to add a footer in ListView?

In this Question, best answer not work for me. After that i found this method to show listview footer,

LayoutInflater inflater = getLayoutInflater();
ViewGroup footerView = (ViewGroup)inflater.inflate(R.layout.footer_layout,listView,false);
listView.addFooterView(footerView, null, false);

And create new layout call footer_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Done"
        android:textStyle="italic"
        android:background="#d6cf55"
        android:padding="10dp"/>
</LinearLayout>

If not work refer this article hear

Concrete Javascript Regex for Accented Characters (Diacritics)

How about this?

/^[a-zA-ZÀ-ÖØ-öø-ÿ]+$/

How would you make two <div>s overlap?

With absolute or relative positioning, you can do all sorts of overlapping. You've probably want the logo to be styled as such:

div#logo {
  position: absolute;
  left: 100px; // or whatever
}

Note: absolute position has its eccentricities. You'll probably have to experiment a little, but it shouldn't be too hard to do what you want.

Check if a file exists with wildcard in shell script

Maybe this will help someone:

if [ "`echo xorg-x11-fonts*`" != "xorg-x11-fonts*" ]; then
    printf "BLAH"
fi

What’s the best way to get an HTTP response code from a URL?

Update using the wonderful requests library. Note we are using the HEAD request, which should happen more quickly then a full GET or POST request.

import requests
try:
    r = requests.head("https://stackoverflow.com")
    print(r.status_code)
    # prints the int of the status code. Find more at httpstatusrappers.com :)
except requests.ConnectionError:
    print("failed to connect")

builtins.TypeError: must be str, not bytes

The outfile should be in binary mode.

outFile = open('output.xml', 'wb')

Android new Bottom Navigation bar or BottomNavigationView

I think this is also be useful.

Snippet

public class MainActivity : AppCompatActivity, BottomNavigationBar.Listeners.IOnTabSelectedListener
{
    private BottomBar _bottomBar;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.MainActivity);

        _bottomBar = BottomBar.Attach(this, bundle);
        _bottomBar.SetItems(
            new BottomBarTab(Resource.Drawable.ic_recents, "Recents"),
            new BottomBarTab(Resource.Drawable.ic_favorites, "Favorites"),
            new BottomBarTab(Resource.Drawable.ic_nearby, "Nearby")
        );
        _bottomBar.SetOnItemSelectedListener(this);
        _bottomBar.HideShadow();
        _bottomBar.UseDarkTheme(true);
        _bottomBar.SetTypeFace("Roboto-Regular.ttf");

        var badge = _bottomBar.MakeBadgeForTabAt(1, Color.ParseColor("#f02d4c"), 1);
        badge.AutoShowAfterUnSelection = true;
    }

    public void OnItemSelected(int position)
    {

    }

    protected override void OnSaveInstanceState(Bundle outState)
    {
        base.OnSaveInstanceState(outState);

        // Necessary to restore the BottomBar's state, otherwise we would
        // lose the current tab on orientation change.
        _bottomBar.OnSaveInstanceState(outState);
    }
}

Links

https://github.com/pocheshire/BottomNavigationBar

It's https://github.com/roughike/BottomBar ported to C# for Xamarin developers

Issue with virtualenv - cannot activate

You can run the source command on cygwin terminal

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

Recently I came across the same issue. I was able to ssh to my pi on my network, but not from outside my home network.

I had already:

  • installed and tested ssh on my home network.
  • Set a static IP for my pi.
  • Set up a Dynamic DNS service and installed the software on my pi. I referenced these instructions for setting up the static ip, and there are many more instructional resources out there.

Also, I set up port forward on my router for hosting a web site and I had even port forward port 22 to my pi's static IP for ssh, but I left the field blank where you specify the application you are performing the port forwarding for on the router. Anyway, I added 'ssh' into this field and, VOILA! A working ssh connection from anywhere to my pi.

I'll write out my router's port forwarding settings.

(ApplicationTextField)_ssh     (external port)_22     (Internal Port)_22     (Protocal)_Both     (To IP Address)_192.168.1.###     (Enabled)_checkBox

Port forwarding settings can be different for different routers though, so look up directions for your router.

Now, when I am outside of my home network I connect to my pi by typing:

ssh pi@[hostname]

Then I am able to input my password and connect.

How to tell if a file is git tracked (by shell exit code)?

using git log will give info about this. If the file is tracked in git the command shows some results(logs). Else it is empty.

For example if the file is git tracked,

root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
commit ad9180b772d5c64dcd79a6cbb9487bd2ef08cbfc
Author: User <[email protected]>
Date:   Mon Feb 20 07:45:04 2017 -0600

    fix eslint indentation errors
....
....

If the file is not git tracked,

root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
root@user-ubuntu:~/project-repo-directory#

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

This could be solved without VBA by the following technique.

In this example I am counting all the threes (3) in the range A:A of the sheets Page M904, Page M905 and Page M906.

List all the sheet names in a single continuous range like in the following example. Here listed in the range D3:D5.

enter image description here

Then by having the lookup value in cell B2, the result can be found in cell B4 by using the following formula:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D3:D5&"'!A:A"), B2))

How to compare strings in Bash

a="abc"
b="def"

# Equality Comparison
if [ "$a" == "$b" ]; then
    echo "Strings match"
else
    echo "Strings don't match"
fi

# Lexicographic (greater than, less than) comparison.
if [ "$a" \< "$b" ]; then
    echo "$a is lexicographically smaller then $b"
elif [ "$a" \> "$b" ]; then
    echo "$b is lexicographically smaller than $a"
else
    echo "Strings are equal"
fi

Notes:

  1. Spaces between if and [ and ] are important
  2. > and < are redirection operators so escape it with \> and \< respectively for strings.

How to send a POST request from node.js Express?

you can try like this:

var request = require('request');
request.post({ headers: {'content-type' : 'application/json'}
               , url: <your URL>, body: <req_body in json> }
               , function(error, response, body){
   console.log(body); 
}); 

Convert a string to datetime in PowerShell

ParseExact is told the format of the date it is expected to parse, not the format you wish to get out.

$invoice = '01-Jul-16'
[datetime]::parseexact($invoice, 'dd-MMM-yy', $null)

If you then wish to output a date string:

[datetime]::parseexact($invoice, 'dd-MMM-yy', $null).ToString('yyyy-MM-dd')

Chris

How to get Django and ReactJS to work together?

Hoping to provide a more nuanced answer than any of the ones here, especially as some things have changed since this was originally asked ~4 years ago, and because many of the top-voted answers claiming that you have to set this up as two separate applications are not accurate.

You have two primary architecture options:

  1. A completely decoupled client/server approach using something like create-react-app and Django REST Framework
  2. A hybrid architecture where you set up a React build pipeline (likely using webpack) and then include the compiled files as static files in your Django templates.

These might look something like this:

Option 1 (Client/Server Architecture):

Client / Server Architecture

Option 2 (Hybrid Architecture):

Hybrid Architecture

The decision between these two will depend on your / your team's experience, as well as the complexity of your UI. The first option is good if you have a lot of JS experience, want to keep your front-end / back-end developers separate, or want to write your entire application as a React single-page-app. The second option is generally better if you are more familiar with Django and want to move quickly while also using React for some parts of your app. I find it's a particularly good fit for full-stack solo-developers.

There is a lot more information in the series "Modern JavaScript for Django Developers", including choosing your architecture, integrating your JS build into a Django project and building a single-page React app.

Full disclosure, I'm the author of that series.

How do I write a RGB color value in JavaScript?

try:

parent.childNodes[1].style.color = "rgb(155, 102, 102)"; 

Or

parent.childNodes[1].style.color = "#"+(155).toString(16)+(102).toString(16)+(102).toString(16);

Select first 10 distinct rows in mysql

SELECT * 
FROM people 
WHERE names ='SMITH'
ORDER BY names asc
limit 10

If you need add group by clause. If you search Smith you would have to sort on something else.

DisplayName attribute from Resources?

If you use MVC 3 and .NET 4, you can use the new Display attribute in the System.ComponentModel.DataAnnotations namespace. This attribute replaces the DisplayName attribute and provides much more functionality, including localization support.

In your case, you would use it like this:

public class MyModel
{
    [Required]
    [Display(Name = "labelForName", ResourceType = typeof(Resources.Resources))]
    public string name{ get; set; }
}

As a side note, this attribute will not work with resources inside App_GlobalResources or App_LocalResources. This has to do with the custom tool (GlobalResourceProxyGenerator) these resources use. Instead make sure your resource file is set to 'Embedded resource' and use the 'ResXFileCodeGenerator' custom tool.

(As a further side note, you shouldn't be using App_GlobalResources or App_LocalResources with MVC. You can read more about why this is the case here)

Correct way of using log4net (logger naming)

Disadvantage of second approach is big repository with created loggers. This loggers do the same if root is defined and class loggers are not defined. Standard scenario on production system is using few loggers dedicated to group of class. Sorry for my English.

Do you get charged for a 'stopped' instance on EC2?

Short answer - no.

You will only be charged for the time that your instance is up and running, in hour increments. If you are using other services in conjunction you may be charged for those but it would be separate from your server instance.

Using "-Filter" with a variable

Try this:

$NameRegex = "chalmw-dm"  
$NameR = "$($NameRegex)*"
Get-ADComputer -Filter {name -like $NameR -and Enabled -eq $True}

python - if not in list

How about this?

for item in mylist:
    if item in checklist:
        pass
    else:
       # do something
       print item

How can I find out if an .EXE has Command-Line Options?

Really this is an extension to Marcin's answer.

But you could also try passing "rubbish" arguments to see if you get any errors back. Getting any response from the executable directly in the shell will mean that it is likely looking at the arguments you're passing, with an error response being close to a guarantee that it is.

Failing that you might have to directly ask the publishers/creators/owners... sniffing the binaries yourself just seems like far too much work for an end-user.

What is the single most influential book every programmer should read?

Working Effectively with Legacy Code is a really amazing book that goes into great detail about how to properly unit test your code and what the true benefit of it is. It really opened my eyes.

Sending a JSON to server and retrieving a JSON in return, without JQuery

Using new api fetch:

_x000D_
_x000D_
const dataToSend = JSON.stringify({"email": "[email protected]", "password": "101010"});
let dataReceived = ""; 
fetch("", {
    credentials: "same-origin",
    mode: "same-origin",
    method: "post",
    headers: { "Content-Type": "application/json" },
    body: dataToSend
})
    .then(resp => {
        if (resp.status === 200) {
            return resp.json()
        } else {
            console.log("Status: " + resp.status)
            return Promise.reject("server")
        }
    })
    .then(dataJson => {
        dataReceived = JSON.parse(dataJson)
    })
    .catch(err => {
        if (err === "server") return
        console.log(err)
    })

console.log(`Received: ${dataReceived}`)                
_x000D_
_x000D_
_x000D_ You need to handle when server sends other status rather than 200(ok), you should reject that result because if you were to left it in blank, it will try to parse the json but there isn't, so it will throw an error

Read a zipped file as a pandas DataFrame

It seems you don't even have to specify the compression any more. The following snippet loads the data from filename.zip into df.

import pandas as pd
df = pd.read_csv('filename.zip')

(Of course you will need to specify separator, header, etc. if they are different from the defaults.)

How do I modify fields inside the new PostgreSQL JSON datatype?

So, for example my string looks like this: {"a1":{"a11":"x","a22":"y","a33":"z"}}

I update jsons by using temp table, which is good enough for rather small ammounth of data (<1.000.000). I found a different way, but then went on vacation and forgot it...

So. the query will be something like this:

with temp_table as (
select 
a.id,
a->'a1'->>'a11' as 'a11',
a->'a1'->>'a22' as 'a22',
a->'a1'->>'a33' as 'a33',
u1.a11updated
from foo a
join table_with_updates u1 on u1.id = a.id)
    update foo a
    set a = ('{"a1": {"a11": "'|| t.a11updated ||'",
        "a22":"'|| t.a22 ||'",
        "a33":"'|| t.a33 ||'"}}')::jsonb
    from temp_table t
    where t.id = a.id;

It has more to do with string than json, but it works. Basically, it pulls all the data into temp table, creates a string while plugging concat holes with the data you backed up, and converts it into jsonb.

Json_set might be more efficient, but I'm still getting a hang of it. First time I tried to use it, I messed up the string completely...

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

I had the same problem but it had nothing to do with annotations. The problem happened while indexing beans in my container (Jboss EAP 6.3). One of my beans could not be indexed because it used Java 8 features an I got this sneaky little warning while deploying:

WARN [org.jboss.as.server.deployment] ... Could not index class ... java.lang.IllegalStateException: Unknown tag! pos=20 poolCount = 133

Then at the injection point I got the error:

Unsatisfied dependencies for type ... with qualifiers @Default

The solution is to update the Java annotations index. download new version of jandex (jandex-1.2.3.Final or newer) then put it into

JBOSS_HOME\modules\system\layers\base\org\jboss\jandex\main and then update reference to the new file in module.xml

NOTE: EAP 6.4.x already have this fixed

Sequence contains more than one element

The problem is that you are using SingleOrDefault. This method will only succeed when the collections contains exactly 0 or 1 element. I believe you are looking for FirstOrDefault which will succeed no matter how many elements are in the collection.

Wait for a process to finish

There is no builtin feature to wait for any process to finish.

You could send kill -0 to any PID found, so you don't get puzzled by zombies and stuff that will still be visible in ps (while still retrieving the PID list using ps).

How to draw a rectangle around a region of interest in python

As the other answers said, the function you need is cv2.rectangle(), but keep in mind that the coordinates for the bounding box vertices need to be integers if they are in a tuple, and they need to be in the order of (left, top) and (right, bottom). Or, equivalently, (xmin, ymin) and (xmax, ymax).

Change Bootstrap tooltip color

It will change the color of the tooltip in bootstrap4 you can use bottom, left, right to add CSS for respective in place of top in .bs-tooltip-top

.tooltip-inner {
background-color: #00acd6 !important;
color: #fff;
}
.bs-tooltip-top .arrow::before, .bs-tooltip-auto[x-placement^="top"] 
.arrow::before {
border-top-color: #00acd6;
}

How do I make a fully statically linked .exe with Visual Studio Express 2005?

For the C-runtime go to the project settings, choose C/C++ then 'Code Generation'. Change the 'runtime library' setting to 'multithreaded' instead of 'multithreaded dll'.

If you are using any other libraries you may need to tell the linker to ignore the dynamically linked CRT explicitly.

int to string in MySQL

You can do this:

select t2.*
from t1
join t2 on t2.url = 'site.com/path/' + CAST(t1.id AS VARCHAR(10)) + '/more' 
where t1.id > 9000

Pay attention to CAST(t1.id AS VARCHAR(10)).

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

There's a third-party service which provides a CORS-friendly REST API to perform DNS lookups from the browser - https://exana.io/tools/dns/

Registry Key '...' has value '1.7', but '1.6' is required. Java 1.7 is Installed and the Registry is Pointing to it

I've deleted java files at windows/system32 and I also have removed c:\ProgramData\Oracle\Java\javapath from the PATH variable, because there was 3 symlinks to java 1.8 files.

I had JDK 1.7 in the %JAVA_HOME% variable and java1.7/bin in the PATH.

PS1: My problem was between Java 1.7 and Java 1.8.

PS2: I can't add this as a comment to Victor's answer because I haven't enough points.

Error 0x80005000 and DirectoryServices

It's a permission problem.

When you run the console app, that app runs with your credentials, e.g. as "you".

The WCF service runs where? In IIS? Most likely, it runs under a separate account, which is not permissioned to query Active Directory.

You can either try to get the WCF impersonation thingie working, so that your own credentials get passed on, or you can specify a username/password on creating your DirectoryEntry:

DirectoryEntry directoryEntry = 
    new DirectoryEntry("LDAP://someserver.contoso.com/DC=contoso,DC=com", 
                       userName, password);

OK, so it might not be the credentials after all (that's usually the case in over 80% of the cases I see).

What about changing your code a little bit?

DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry);
directorySearcher.Filter = string.Format("(&(objectClass=user)(objectCategory=user) (sAMAccountName={0}))", username);

directorySearcher.PropertiesToLoad.Add("msRTCSIP-PrimaryUserAddress");

var result = directorySearcher.FindOne();

if(result != null)
{
   if(result.Properties["msRTCSIP-PrimaryUserAddress"] != null)
   {
      var resultValue = result.Properties["msRTCSIP-PrimaryUserAddress"][0];
   }
}

My idea is: why not tell the DirectorySearcher right off the bat what attribute you're interested in? Then you don't need to do another extra step to get the full DirectoryEntry from the search result (should be faster), and since you told the directory searcher to find that property, it's certainly going to be loaded in the search result - so unless it's null (no value set), then you should be able to retrieve it easily.

Marc

if checkbox is checked, do this

$('#checkbox').change(function(){
   (this.checked)?$('p').css('color','#0099ff'):$('p').css('color','another_color');
});

Java 8: Difference between two LocalDateTime in multiple units

TL;DR

Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());

and then use the methods period.getYears(), period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart().


Expanded answer

I'll answer the original question, i.e. how to get the time difference between two LocalDateTimes in years, months, days, hours & minutes, such that the "sum" (see note below) of all the values for the different units equals the total temporal difference, and such that the value in each unit is smaller than the next bigger unit—i.e. minutes < 60, hours < 24, and so on.

Given two LocalDateTimes start and end, e.g.

LocalDateTime start = LocalDateTime.of(2019, 11, 29, 17, 15);
LocalDateTime end = LocalDateTime.of(2020, 11, 30, 18, 44);

we can represent the absolute timespan between the two with a Duration—perhaps using Duration.between(start, end). But the biggest unit we can extract out of a Duration is days (as a temporal unit equivalent to 24h)—see the note below for an explanation. To use larger units (months, years) we can represent this Duration with a pair of (Period, Duration), where the Period measures the difference up to a precision of days and the Duration represents the remainder:

Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());

Now we can simply use the methods defined on Period and Duration to extract the individual units:

System.out.printf("%d years, %d months, %d days, %d hours, %d minutes, %d seconds",
        period.getYears(), period.getMonths(), period.getDays(), duration.toHoursPart(),
        duration.toMinutesPart(), duration.toSecondsPart());
1 years, 0 months, 1 days, 1 hours, 29 minutes, 0 seconds

or, using the default format:

System.out.println(period + " + " + duration);
P1Y1D + PT1H29M

Note on years, months & days

Note that, in java.time's conception, "units" like "month" or "year" don't represent a fixed, absolute temporal value—they're date- and calendar-dependent, as the following example illustrates:

LocalDateTime
        start1 = LocalDateTime.of(2020, 1, 1, 0, 0),
        end1 = LocalDateTime.of(2021, 1, 1, 0, 0),
        start2 = LocalDateTime.of(2021, 1, 1, 0, 0),
        end2 = LocalDateTime.of(2022, 1, 1, 0, 0);
System.out.println(Period.between(start1.toLocalDate(), end1.toLocalDate()));
System.out.println(Duration.between(start1, end1).toDays());
System.out.println(Period.between(start2.toLocalDate(), end2.toLocalDate()));
System.out.println(Duration.between(start2, end2).toDays());
P1Y
366
P1Y
365

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

I have build a sample android studio project for this question.

output screen shots :-

enter image description here

enter image description here

enter image description here

Download full project source code Click here

Please note: you have to add your API key in Androidmanifest.xml

Android: where are downloaded files saved?

Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard (or some variation of that name) which is usually symlinked to to a directory in /storage like /storage/sdcard0 or /storage/0 sometimes the emulated storage is mounted to /sdcard and the actual path is something like /storage/emulated/legacy. You should be able to use to get the downloads directory. You are best off using the api calls to get directories. Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

Since the filesystems and sdcard support varies among devices.

see similar question for more info how to access downloads folder in android?

Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

The in operator only works on objects. You are using it on a string. Make sure your value is an object before you using $.each. In this specific case, you have to parse the JSON:

$.each(JSON.parse(myData), ...);

What are these attributes: `aria-labelledby` and `aria-hidden`

Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control

Aria does not change anything visually. (Aria is scared of designers too).

aria-hidden:

aria-hidden attribute is used to hide content for visually impaired users who navigate through application using screen readers (JAWS, NVDA,...).

aria-hidden attribute is used with values true, false.

How To Use:

<i class = "fa fa-books" aria-hidden = "true"></i>

using aria-hidden = "true" on the <i> hides content to screen reader users with no visual change in the application.

aria-label

aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users

How To Use:

<input type = "edit" aria-label = "search" placeholder = "search">

There is no visual change in application. But screen readers can understand the purpose of control

aria-labelledby

Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually

Approach 1:

<span id = "sd"> Search </span>

<input type = "text" aria-labelledby = "sd">

aria-labelledby can also be used to combine two labels for screen reader users

Approach 2:

<span id = "de"> Billing Address </span>

<span id = "sd"> First Name </span>

<input type = "text" aria-labelledby = "de sd">

use Lodash to sort array of object by value

You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).

Your code could be like:

const myArray = [  
   {  
      "id":25,
      "name":"Anakin Skywalker",
      "createdAt":"2017-04-12T12:48:55.000Z",
      "updatedAt":"2017-04-12T12:48:55.000Z"
   },
   {  
      "id":1,
      "name":"Luke Skywalker",
      "createdAt":"2017-04-12T11:25:03.000Z",
      "updatedAt":"2017-04-12T11:25:03.000Z"
   }
]

const myOrderedArray = _.sortBy(myArray, o => o.name)

Linq : select value in a datatable column

var name = from r in MyTable
            where r.ID == 0
            select r.Name;

If the row is unique then you could even just do:

var row = DataContext.MyTable.SingleOrDefault(r => r.ID == 0);
var name = row != null ? row.Name : String.Empty;

How to get all checked checkboxes

Get all the checked checkbox value in an array - one liner

_x000D_
_x000D_
const data = [...document.querySelectorAll('.inp:checked')].map(e => e.value);_x000D_
console.log(data);
_x000D_
<div class="row">_x000D_
    <input class="custom-control-input inp"type="checkbox" id="inlineCheckbox1" Checked value="option1"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option1</label>_x000D_
    <input class="custom-control-input inp"  type="checkbox" id="inlineCheckbox1" value="option2"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option2</label>_x000D_
    <input class="custom-control-input inp" Checked  type="checkbox" id="inlineCheckbox1" value="option3"> _x000D_
    <label class="custom-control-label" for="inlineCheckbox1">Option3</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Android - implementing startForeground for a service?

This is my code to set the service to foreground:

private void runAsForeground(){
    Intent notificationIntent = new Intent(this, RecorderMainActivity.class);
    PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
            notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

    Notification notification=new NotificationCompat.Builder(this)
                                .setSmallIcon(R.drawable.ic_launcher)
                                .setContentText(getString(R.string.isRecording))
                                .setContentIntent(pendingIntent).build();

    startForeground(NOTIFICATION_ID, notification);

}

I need to build a notification using PendingIntent, so that I can start my main activity from the notification.

To remove the notification, just call the stopForeground(true);

It is called in the onStartCommand(). Please refer to my code at : https://github.com/bearstand/greyparrot/blob/master/src/com/xiong/richard/greyparrot/Mp3Recorder.java