Programs & Examples On #Ota

Over-the-air wireless communication

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

"Failed to install the following Android SDK packages as some licences have not been accepted" error

I tried many solutions but didn't work for me. The below solution works for me.

locate the sdkmanager file in android SDK.

In my case : ~/Android/Sdk/tools/bin

go to that path : cd ~/Android/Sdk/tools/bin

Accept licenses manually : ./sdkmanager --licenses Enter Yes or y

Flutter: RenderBox was not laid out

I had a similir problem, but in my case, I put a row in the leading of the ListView, and it was consuming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recommend to check if the problem is a larger widget than its container can have.

Expanded(child:MyListView())

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

Can I use library that used android support with Androidx projects.

You need not to worry

Just enable Jetifier in your projet.

  • Update Android Studio to 3.2.0 or newer.
  • Open gradle.properties and add below two lines.

    android.enableJetifier=true
    android.useAndroidX=true
    

It will convert all support libraries of your dependency to AndroidX at run time (you may have compile time errors, but app will run).

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

If you are using windows, Change folder security settings by giving fully controlled to the current user. It's worked for me.

properties

Flutter : Vertically center column

Solution as proposed by Aziz would be:

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  crossAxisAlignment: CrossAxisAlignment.center,
  children:children,
)

It would not be in the exact center because of padding:

padding: new EdgeInsets.all(25.0),

To make exactly center Column - at least in this case - you would need to remove padding.

What is AndroidX?

AndroidX - Android Extension Library

From AndroidX documentation

We are rolling out a new package structure to make it clearer which packages are bundled with the Android operating system, and which are packaged with your app's APK. Going forward, the android.* package hierarchy will be reserved for Android packages that ship with the operating system. Other packages will be issued in the new androidx.* package hierarchy as part of the AndroidX library.

Need of AndroidX

AndroidX is a redesigned library to make package names more clear. So from now on android hierarchy will be for only android default classes, which comes with android operating system and other library/dependencies will be part of androidx (makes more sense). So from now on all the new development will be updated in androidx.

com.android.support.** : androidx.
com.android.support:appcompat-v7 : androidx.appcompat:appcompat com.android.support:recyclerview-v7 : androidx.recyclerview:recyclerview com.android.support:design : com.google.android.material:material

Complete Artifact mappings for AndroidX packages

AndroidX uses Semantic-version

Previously, support library used the SDK version but AndroidX uses the Semantic-version. It’s going to re-version from 28.0.0 ? 1.0.0.

How to migrate current project

In Android Studio 3.2 (September 2018), there is a direct option to migrate existing project to AndroidX. This refactor all packages automatically.

Before you migrate, it is strongly recommended to backup your project.

Existing project

  • Android Studio > Refactor Menu > Migrate to AndroidX...
  • It will analyze and will open Refractor window in bottom. Accept changes to be done.

image

New project

Put these flags in your gradle.properties

android.enableJetifier=true
android.useAndroidX=true

Check @Library mappings for equal AndroidX package.

Check @Official page of Migrate to AndroidX

What is Jetifier?

Bugs of migrating

  • If you build app, and find some errors after migrating, then you need to fix those minor errors. You will not get stuck there, because that can be easily fixed.
  • 3rd party libraries are not converted to AndroidX in directory, but they get converted at run time by Jetifier, so don't worry about compile time errors, your app will run perfectly.

Support 28.0.0 is last release?

From Android Support Revision 28.0.0

This will be the last feature release under the android.support packaging, and developers are encouraged to migrate to AndroidX 1.0.0

So go with AndroidX, because Android will update only androidx package from now.

Further Reading

https://developer.android.com/topic/libraries/support-library/androidx-overview

https://android-developers.googleblog.com/2018/05/hello-world-androidx.html

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

Based on your screenshot i found two working solutions:

First solution: add to dependencies of your gradle module this line

compile 'com.android.support:support-annotations:27.1.1'

and sync your project

Note: if you are using Android studio 3+ change compile to implementation

Second solution: Configure project-wide properties found in the documentation https://developer.android.com/studio/build/gradle-tips.html#configure-project-wide-properties

in project gradle add this line:

// This block encapsulates custom properties and makes them available to all
// modules in the project.
ext {
    // The following are only a few examples of the types of properties you can define.
    compileSdkVersion = 26
    // You can also use this to specify versions for dependencies. Having consistent
    // versions between modules can avoid behavior conflicts.
    supportLibVersion = "27.1.1"
}

Then to access this section change compileSdkVersionline to be

compileSdkVersion rootProject.ext.compileSdkVersion

and at dependencies section change the imported library to be like this:

compile "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"

and sync your project

Note: if you are using Android studio 3+ change compile to implementation

For the difference between compile and implementation look at this What's the difference between implementation and compile in gradle

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

If we need to move from one component to another service then we have to define that service into app.module providers array.

Flutter.io Android License Status Unknown

here is my solution:

  1. install SDKMan

    $ curl -s "https://get.sdkman.io" | bash

  2. setting your bash_profile

    $ source "$HOME/.sdkman/bin/sdkman-init.sh

    $ source ~/.bash_profile

  3. find java sdk, and select want to install version

    $ sdk ls java

    $ sdk install java 8.0.192-zulu

  4. copy your flutter doctor warning message to update sdkmanager

    $ /Users/YourUserName/Library/Android/sdk/tools/bin/sdkmanager --update

  5. after 1~4, redo it

    $ flutter doctor --android-licenses

error: resource android:attr/fontVariationSettings not found

I had this problem suddenly happening after trying to pull a dependency depending on sdk 28 (firebase crashlytics), but then decided to revert back the changes.

I tried automatic refactor Migrate to Androidx (which do half the job), added android.useAndroidX=true in gradle.properties at some points, and make the project work again.

But it was a lot of changes before a delivery. There was no way to have the project compile again with SDK 27. I git clean -fd, removed $HOME/.gradle, and kept seeing androidx in ./gradlew :app:dependencies

I ended up removing ~/.AndroidStudio3.5/ too (I'm on 3.5.3). This makes the project compile again, and I discovered the dark mode...

How to show all of columns name on pandas dataframe?

To get all column name you can iterate over the data_all2.columns.

columns = data_all2.columns
for col in columns:
    print col

You will get all column names. Or you can store all column names to another list variable and then print list.

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

It might be cause of a library, I faced it because of Glide.

It was

implementation 'com.github.bumptech.glide:glide:4.7.1'

So I added exclude group: "com.android.support" And it becomes

implementation ('com.github.bumptech.glide:glide:4.7.1') {
        exclude group: "com.android.support"
    }

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Configure Two DataSources in Spring Boot 2.0.* or above

If you need to configure multiple data sources, you have to mark one of the DataSource instances as @Primary, because various auto-configurations down the road expect to be able to get one by type.

If you create your own DataSource, the auto-configuration backs off. In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSource firstDataSource() {
    return firstDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@ConfigurationProperties("app.datasource.second")
public BasicDataSource secondDataSource() {
    return DataSourceBuilder.create().type(BasicDataSource.class).build();
}

firstDataSourceProperties has to be flagged as @Primary so that the database initializer feature uses your copy (if you use the initializer).

And your application.propoerties will look something like this:

app.datasource.first.url=jdbc:oracle:thin:@localhost/first
app.datasource.first.username=dbuser
app.datasource.first.password=dbpass
app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver

app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
app.datasource.second.username=dbuser
app.datasource.second.password=dbpass
app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver

The above method is the correct to way to init multiple database in spring boot 2.0 migration and above. More read can be found here.

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

In IntelliJ:

  1. Open Project Structure (?;) > Modules > YOUR MODULE -> Language level: set 9, in your case.
  2. Repeat for each module.

screenshot

Entity Framework Core: A second operation started on this context before a previous operation completed

I know this issue has been asked two years ago, but I just had this issue and the fix I used really helped.

If you are doing two queries with the same Context - you might need to remove the AsNoTracking. If you do use AsNoTracking you are creating a new data-reader for each read. Two data readers cannot read the same data.

ReferenceError: fetch is not defined

Node.js hasn't implemented the fetch() method, but you can use one of the external modules of this fantastic execution environment for JavaScript.

In one of the answers above, "node-fetch" is cited and that's a good choice.

In your project folder (the directory where you have the .js scripts) install that module with the command:

npm i node-fetch --save

Then use it as a constant in the script you want to execute with Node.js, something like this:

const fetch = require("node-fetch");

Python convert object to float

I eventually used:

weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)

It worked just fine, except that I got the following message.

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning:
convert_objects is deprecated.  Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I have resolved this issue after selecting the "Target Compatibility" to 1.8 Java version. File -> Project Structure -> Modules.

How to start up spring-boot application via command line?

A Spring Boot project configured through Maven can be run using the following command from the project source folder

mvn spring-boot:run

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

When I used policy before I set the default authentication scheme into it as well. I had modified the DefaultPolicy so it was slightly different. However the same should work for add policy as well.

services.AddAuthorization(options =>
        {
            options.AddPolicy(DefaultAuthorizedPolicy, policy =>
            {
                policy.Requirements.Add(new TokenAuthRequirement());
                policy.AuthenticationSchemes = new List<string>()
                                {
                                    CookieAuthenticationDefaults.AuthenticationScheme
                                }
            });
        });

Do take into consideration that by Default AuthenticationSchemes property uses a read only list. I think it would be better to implement that instead of List as well.

Failed to run sdkmanager --list with Java 9

You can set sdkmanager options with SDKMANAGER_OPTS.

Example:

export SDKMANAGER_OPTS="--add-modules java.se.ee"
sdkmanager --list

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

Android Studio 3.0 Execution failed for task: unable to merge dex

When the version of Android Studio is 3.0.1, Gradle Version is 4.1 and Android PluginVersion is 3.0.0, it will encounter this problem. Then I downgrade Gradle Version is 3.3, Android Android is zero, there is no such problem.

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

When I change my jupiter api version into latest one, it was solved. Meanwhile, my eclipse and other eclipse extensions ide's (such as STS) is getting build path error. For every maven update, ide forces me to set the JRE System Library.

Please add a @Pipe/@Directive/@Component annotation. Error

I was trying to use BrowserModule in a shared module (import and export). That was not allowed so instead I had to use the CommonModule instead and it worked.

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

In my case, I have Java 14 and need Java 8.

I'm in a Arch Linux and has installed jdk8-openjdk jre8-openjdk https://www.archlinux.org/packages/extra/x86_64/java8-openjdk/

For Debian users https://wiki.debian.org/Java, or Fedora https://docs.fedoraproject.org/en-US/quick-docs/installing-java/.

Install Java 8 (or desired version, in this case jdk8-openjdk jre8-openjdk) using your package manager before doing the following steps.


1. Figuring out where is my Java:

# which java
/usr/bin/java

2. Checking java files:

I can see all java files here are links to /usr/lib/jvm/default[something]. This means that the java command is linked to some specific version of java executable.

# ls -l /usr/bin/java*
lrwxrwxrwx 1 root root 37 May 16 06:30 /usr/bin/java -> /usr/lib/jvm/default-runtime/bin/java
lrwxrwxrwx 1 root root 30 May 16 06:30 /usr/bin/javac -> /usr/lib/jvm/default/bin/javac
lrwxrwxrwx 1 root root 32 May 16 06:30 /usr/bin/javadoc -> /usr/lib/jvm/default/bin/javadoc
lrwxrwxrwx 1 root root 30 May 16 06:30 /usr/bin/javah -> /usr/lib/jvm/default/bin/javah
lrwxrwxrwx 1 root root 30 May 16 06:30 /usr/bin/javap -> /usr/lib/jvm/default/bin/javap

3. Checking the default and default-runtime

Here I could see the default version was linked to 14 (unique installed version).

# cd /usr/lib/jvm
# ls -l
lrwxrwxrwx 1 root root   14 Aug  8 20:44 default -> java-14-openjdk
lrwxrwxrwx 1 root root   14 Aug  8 20:44 default-runtime -> java-14-openjdk
drwxr-xr-x 7 root root 4096 Jul 19 22:38 java-14-openjdk
drwxr-xr-x 6 root root 4096 Aug  8 20:42 java-8-openjdk

4. Switching the default version

First, remove the existing default and default-runtime which linked to java-14 version.

# rm default default-runtime

Then, create new links to the desired version (in this case, java-8).

# link -s java-8-openjdk default
# link -s java-8-openjdk default-runtime

The strategy is to make links to the desired version of software (java8 in this case) using ln -s above. Then, this links are linked to the binaries inside the java bin directory (without changing the $PATH environment variable!)


Or you might be wanted to change the Java version using archlinux-java command instead with more safely approach: https://wiki.archlinux.org/index.php/Java

TypeScript error TS1005: ';' expected (II)

I was injecting service like this:

private messageShowService MessageShowService

instead of:

private messageShowService: MessageShowService

and that was the reason of error, despite nothing related with ',' was there.

Unable to merge dex

In my case the error was importing the dependency:

implementation 'com.firebaseui:firebase-ui:2.3.0'

and I was not using it, it started working when I deleted it cleaned project and recomplied. Of course I also did what the people above did which was:

  • Changing complie to implementation throughout the whole app.grade
  • Changing testcomplie to testimplementation throughout the whole app.grade
  • Make sure I have multidexenabled true
  • Update compileSdk to 26
  • Deleted .gradle file (found in project), clean project and recompile

and finally...

  • Deleted implementation 'com.firebaseui:firebase-ui:2.3.0' (Since I was not using it in my code)

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

I had a similar issue which i solved by making two changes

  1. added below entry in application.yaml file

    spring: jackson: serialization.write_dates_as_timestamps: false

  2. add below two annotations in pojo

    1. @JsonDeserialize(using = LocalDateDeserializer.class)
    2. @JsonSerialize(using = LocalDateSerializer.class)

    sample example

    import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; public class Customer { //your fields ... @JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = LocalDateSerializer.class) protected LocalDate birthdate; }

then the following json requests worked for me

  1. sample request format as string

{ "birthdate": "2019-11-28" }

  1. sample request format as array

{ "birthdate":[2019,11,18] }

Hope it helps!!

Django - Reverse for '' not found. '' is not a valid view function or pattern name

Add store name to template like {% url 'app_name:url_name' %}

App_name = store

In urls.py, path('search', views.searched, name="searched"),

<form action="{% url 'store:searched' %}" method="POST">

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

So ridiculous, but I still wanna share my experience in case of that someone falls into the situation like me.

Please check if you changed: compileSdkVersion --> implementationSdkVersion by mistake

Error: fix the version conflict (google-services plugin)

Please change your project-level build.gradle file in which you have to change your dependencies class path of google-services or build.gradle path.

buildscript {

    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
        classpath 'com.google.gms:google-services:4.0.1'
    }
}

Using ffmpeg to change framerate

In general, to set a video's FPS to 24, almost always you can do:

With Audio and without re-encoding:

# Extract video stream
ffmpeg -y -i input_video.mp4 -c copy -f h264 output_raw_bitstream.h264
# Extract audio stream
ffmpeg -y -i input_video.mp4 -vn -acodec copy output_audio.aac
# Remux with new FPS 
ffmpeg -y -r 24 -i output_raw_bitstream.h264 -i output-audio.aac -c copy output.mp4

If you want to find the video format (H264 in this case), you can use FFprobe, like this

ffprobe -loglevel error -select_streams v -show_entries stream=codec_name -of default=nw=1:nk=1 input_video.mp4

which will output:

h264

Read more in How can I analyze file and detect if the file is in H.264 video format?


With re-encoding:

ffmpeg -y -i input_video.mp4 -vf -r 24 output.mp4

select rows in sql with latest date for each ID repeated multiple times

You can do this with a Correlated Subquery (That is a subquery wherein you reference a field in the main query). In this case:

SELECT * 
FROM yourtable t1
WHERE date = (SELECT max(date) from yourtable WHERE id = t1.id)

Here we give the yourtable table an alias of t1 and then use that alias in the subquery grabbing the max(date) from the same table yourtable for that id.

No String-argument constructor/factory method to deserialize from String value ('')

Use below code snippet This worked for me

ObjectMapper objectMapper = new ObjectMapper();
String jsonString = "{\"symbol\":\"ABCD\}";
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
Trade trade = objectMapper.readValue(jsonString, new TypeReference<Symbol>() {});

Model Class

@JsonIgnoreProperties    public class Symbol {
    @JsonProperty("symbol")
    private String symbol;
}

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

FormsModule should be added at imports array not declarations array.

  • imports array is for importing modules such as BrowserModule, FormsModule, HttpModule
  • declarations array is for your Components, Pipes, Directives

refer below change:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Angular CLI - Please add a @NgModule annotation when using latest

In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.

So register the ChildComponent in Shared Module manually.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Replace the dependency in the POM.xml file

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.2.3</version>
</dependency>

By the dependency

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
    </dependency>

Kubernetes Pod fails with CrashLoopBackOff

I had similar situation. I found that one of my config maps was duplicated. I had two configmaps for the same namespace. One had the correct namespace reference, the other was pointing to the wrong namespace.

I deleted and recreated the configmap with the correct file (or fixed file). I am only using one, and that seemed to make the particular cluster happier.

So I would check the files for any typos or duplicate items that could be causing conflict.

Android dependency has different version for the compile and runtime

In my case, I was having two different versions of the below implementation in two different modules, So i changed both implementation to versions ie : 6.0.2 and it worked. You may also need to write dependency resolution see the accepted answer.

app module

implementation 'com.karumi:dexter:5.0.0'

commons module

implementation 'com.karumi:dexter:6.0.2'

Cannot find control with name: formControlName in angular reactive form

I also had this error, and you helped me solve it. If formGroup or formGroupName are not written with the good case, then the name of the control is not found. Correct the case of formGroup or formGroupName and it is OK.

More than one file was found with OS independent path 'META-INF/LICENSE'

I faced this issue, first with some native libraries (.so files) and then with java/kotlin files. Turned out I was including a library from source as well as referencing artifactory through a transitive dependency. Check your dependency tree to see if there are any redundant entries. Use ./gradlew :app:dependencies to get the dependency tree. Replace "app" with your module name if the main module name is different.

Npm Error - No matching version found for

If none of this did not help, then try to swap ^ in "^version" to ~ "~version".

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

Above answers are correct. This version is easy to follow:

Because "Schema export directory is not provided to the annotation processor", So we need to provide the directory for schema export:

Step [1] In your file which extends the RoomDatabase, change the line to:

`@Database(entities = ???.class,version = 1, exportSchema = true)`

Or

`@Database(entities = ???.class,version = 1)` 

(because the default value is always true)

Step [2] In your build.gradle(project:????) file, inside the defaultConfig{ } (which is inside android{ } big section), add the javaCompileOptions{ } section, it will be like:

         android{
                defaultConfig{
                      //javaComplieOptions SECTION
                      javaCompileOptions {
                            annotationProcessorOptions {
                                     arguments = ["room.schemaLocation":"$projectDir/schemas".toString()]
                            }
                       }
                      //Other SECTION
                      ...
                }
         }

$projectDir:is a variable name, you cannot change it. it will get your own project directory

schemas:is a string, you can change it to any you like. For example: "$projectDir/MyOwnSchemas".toString()

Angular update object in object array

In angular/typescript we can avoid mutation of the objects in the array.

An example using your item arr as a BehaviorSubject:

// you can initialize the items$ with the default array
this.items$ = new BehaviorSubject<any>([user1, user2, ...])

updateUser(user){
   this.myservice.getUpdate(user.id).subscribe(newitem => {

     // remove old item
     const items = this.items$.value.filter((item) => item.id !== newitem.id);

     // add a the newItem and broadcast a new table
     this.items$.next([...items, newItem])
   });
}

And in the template you can subscribe on the items$

<tr *ngFor="let u of items$ | async; let i = index">
   <td>{{ u.id }}</td>
   <td>{{ u.name }}</td>
   <td>
        <input type="checkbox" checked="u.accepted" (click)="updateUser(u)">
        <label for="singleCheckbox-{{i}}"></label>
   </td>
</tr>

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Accessing webpages issues

I added yellow highlighted package and now my view page is accessible. in eclipse when we deploy our war it only deploy those stuff mention in the deployment assessment.

We set Deployment Assessment from right click on project --> Properties --> Apply and Close....

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

Spring boot: Unable to start embedded Tomcat servlet container

For me, the problem was in XML migrations. I deleted all tables and sequences and it works on next bootRun

How to predict input image using trained model in Keras?

keras predict_classes (docs) outputs A numpy array of class predictions. Which in your model case, the index of neuron of highest activation from your last(softmax) layer. [[0]] means that your model predicted that your test data is class 0. (usually you will be passing multiple image, and the result will look like [[0], [1], [1], [0]] )

You must convert your actual label (e.g. 'cancer', 'not cancer') into binary encoding (0 for 'cancer', 1 for 'not cancer') for binary classification. Then you will interpret your sequence output of [[0]] as having class label 'cancer'

How to Install Font Awesome in Laravel Mix

I found all answers above incomplete somehow, Below are exact steps to get it working.

  1. We use npm in order to install the package. For this open the Console and go to your Laravel application directory. Enter the following:

    npm install font-awesome --save-dev

  2. Now we have to copy the needed files to the public/css and public/fonts directory. In order to do this open the webpack.mix.js file and add the following:

    mix.copy('node_modules/font-awesome/css/font-awesome.min.css', 'public/css'); mix.copy('node_modules/font-awesome/fonts/*', 'public/fonts');

  3. Run the following command in order to execute Laravel Mix:

    npm run dev

  4. Add the stylesheet for the Font Awesome in your applications layout file (resources/views/layouts/app.blade.phpapp.blade.php):

    <link href="{{ asset('css/font-awesome.min.css') }}" rel="stylesheet" />

  5. Use font awesome icons in templates like

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

I hope it helps!

Seaborn Barplot - Displaying Values

Just in case if anyone is interested in labeling horizontal barplot graph, I modified Sharon's answer as below:

def show_values_on_bars(axs, h_v="v", space=0.4):
    def _show_on_single_plot(ax):
        if h_v == "v":
            for p in ax.patches:
                _x = p.get_x() + p.get_width() / 2
                _y = p.get_y() + p.get_height()
                value = int(p.get_height())
                ax.text(_x, _y, value, ha="center") 
        elif h_v == "h":
            for p in ax.patches:
                _x = p.get_x() + p.get_width() + float(space)
                _y = p.get_y() + p.get_height()
                value = int(p.get_width())
                ax.text(_x, _y, value, ha="left")

    if isinstance(axs, np.ndarray):
        for idx, ax in np.ndenumerate(axs):
            _show_on_single_plot(ax)
    else:
        _show_on_single_plot(axs)

Two parameters explained:

h_v - Whether the barplot is horizontal or vertical. "h" represents the horizontal barplot, "v" represents the vertical barplot.

space - The space between value text and the top edge of the bar. Only works for horizontal mode.

Example:

show_values_on_bars(sns_t, "h", 0.3)

enter image description here

How do I format currencies in a Vue component?

UPDATE: I suggest using a solution with filters, provided by @Jess.

I would write a method for that, and then where you need to format price you can just put the method in the template and pass value down

methods: {
    formatPrice(value) {
        let val = (value/1).toFixed(2).replace('.', ',')
        return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".")
    }
}

And then in template:

<template>
    <div>
        <div class="panel-group"v-for="item in list">
            <div class="col-md-8">
                <small>
                   Total: <b>{{ formatPrice(item.total) }}</b>
                </small>
            </div>
        </div>
    </div>
</template>

BTW - I didn't put too much care on replacing and regular expression. It could be improved.enter code here

_x000D_
_x000D_
Vue.filter('tableCurrency', num => {_x000D_
  if (!num) {_x000D_
    return '0.00';_x000D_
  }_x000D_
  const number = (num / 1).toFixed(2).replace(',', '.');_x000D_
  return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');_x000D_
});
_x000D_
_x000D_
_x000D_

Hibernate Error executing DDL via JDBC Statement

Dialects are removed in recent SQL so use

  <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect"/>

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

  • changed distrubutionUrl from 4.1 to 4.4

  • changed build gradle version to 3.1.1 under project/android

works for me.

'Field required a bean of type that could not be found.' error spring restful API using mongodb

I followed all steps and instructions followed by OP here, took care of blank space around username and password(even though spring takes care of whitespaces in properties file), still was either facing

could not find bean for ___Repository

(you interface which extends JPARepository)

OR after adding @EnableJPARepository

could not find bean for EntityManagerFactory

i solved it by changing spring boot starter parent version from 2.3.2 to 2.2.1 in pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

and adding following dependency

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

I did not need to add any of following, spring boot does it itself

  1. @EnableJPAReposity - since i already had all class with same root package
  2. spring.data.jpa.repositories.enabled in application.properties
  3. spring.datasource.driverClassName=com.mysql.jdbc.Driver in application properties

No provider for Router?

I have also received this error when developing automatic tests for components. In this context the following import should be done:

import { RouterTestingModule } from "@angular/router/testing";

const testBedConfiguration = {
  imports: [SharedModule,
    BrowserAnimationsModule,
    RouterTestingModule.withRoutes([]),
  ],

SQL Query Where Date = Today Minus 7 Days

DECLARE @Daysforward int
SELECT @Daysforward = 25 (no of days required)
Select * from table name

where CAST( columnDate AS date) < DATEADD(day,1+@Daysforward,CAST(GETDATE() AS date))

Why isn't this code to plot a histogram on a continuous value Pandas column working?

EDIT:

After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).


A quick rerun of your data:

In [25]: df.hist(column='Trip_distance')

enter image description here

Prints out absolutely fine.

The df.hist function comes with an optional keyword argument bins=10 which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:

In [34]: df.hist(column='Trip_distance', bins=50)

enter image description here

Model summary in pytorch

AFAK there is no model.summary() like equivalent in pytorch

Meanwhile you can refer script by szagoruyko, which gives a nice visualizaton like in resnet18-example

Cheers

Error:Cause: unable to find valid certification path to requested target

If you are running behind a corporate proxy with SSL interception, you will need to follow these steps to trust your proxy certificate for HTTPS:

  • In Android Studio, Open File -> Settings
    • In Tools -> Server Certificates
      • Tick ‘Accept non-trusted certificates automatically’
      • Also click the ‘+’ and manually add the corporate proxy root certificate.
    • In Appearance and Behaviour -> System Settings -> HTTP Proxy
      • Set your corporate proxy URL and port details
  • Download KeyStore Explorer: http://keystore-explorer.org/downloads.html
  • In KeyStore Explorer (run as admin), open the Android Studio JRE certificate store: C:\Program Files\Android\Android Studio\jre\jre\lib\security\cacerts
    • The password should be ‘changeit’
    • Import the corporate proxy root certificate, and save.
  • In Android Studio, select File -> Invalidate Cache and Restart

How can I serve static html from spring boot?

I had to add thymeleaf dependency to pom.xml. Without this dependency Spring boot didn't find static resources.

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

All com.android.support libraries must use the exact same version specification

You can solve this with one of the following solutions:

Update:

As of Android studio 3.0, it becomes much easier as it now shows a more helpful hint, so we only need to follow this hint.
for example: 1]

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 27.0.2, 26.1.0. Examples include com.android.support:animated-vector-drawable:27.0.2 and com.android.support:customtabs:26.1.0

there are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion.)

Solution:
Add explicitly the library with the old version but with a new version number.
in my case com.android.support:customtabs:26.1.0 so I need to add:

implementation "com.android.support:customtabs:27.0.2"  

ie: Take the library from the second item, and implement it with the version number from the first.

Note: don't forget to press sync now so gradle can rebuild the dependency graph and see if there are any more conflicts.

Explanation:
you may be confused by the error message as don't use customtabs so how I have a conflict!!
well.. you didn't use it directly but one of your libraries uses an old version of customtabs internally, so you need to ask for it directly.

if you curious to know which of your libraries is responsible for the old version and maybe ask the author to update his lib, Run a Gradle dependency report, see the old answer to know how.

Note this


Old answer:

inspired by CommonsWare answer:

Run a Gradle dependency report to see what your full tree of dependencies is.

From there, you will see which one of your libraries are asking for a different version of the Android Support libraries. For whatever it is asking for, you can ask for it directly with the 25.2.0 version or use Gradle's other conflict resolution approaches to get the same versions.


Update:

As of gradle plugin version: 3.0 compile has been replaced by implementation or api see this answer for the difference.

hence use instead:

./gradlew -q dependencies app:dependencies --configuration debugAndroidTestCompileClasspath

or for windows cmd:

gradlew -q dependencies app:dependencies --configuration debugAndroidTestCompileClasspath

and search for the conflicted version.

For me, the error disappeared after removing com.google.android.gms:play-services:10.2.0

And only include com.google.android.gms:play-services-location:10.2.0 and com.google.android.gms:play-services-maps:10.2.0 as they are the only two play services that I use.

I think the gms:play-services depend on some old components of the support library, so we need to add them explicitly ourselves.


for AS 3.0 an older.

Run:

./gradlew -q dependencies <module-name>:dependencies --configuration implementation

Example:

./gradlew -q dependencies app:dependencies --configuration implementation

if someone knows a better way in the new gradle plugin please let me know.

Job for mysqld.service failed See "systemctl status mysqld.service"

the issue is with the "/etc/mysql/my.cnf". this file must be modified by other libraries that you installed. this is how it originally should look like:

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0,
# as published by the Free Software Foundation.
#
# This program is also distributed with certain software (including
# but not limited to OpenSSL) that is licensed under separate terms,
# as designated in a particular file or component or in included license
# documentation.  The authors of MySQL hereby grant you an additional
# permission to link the program and your derivative works with the
# separately licensed software that they have included with MySQL.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License, version 2.0, for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA

#
# The MySQL  Server configuration file.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#

!includedir /etc/mysql/conf.d/
    
!includedir /etc/mysql/mysql.conf.d/

Angular 2: How to call a function after get a response from subscribe http.post

get_categories(number){
 return this.http.post( url, body, {headers: headers, withCredentials:true})
      .map(t=>  {
          this.total = t.json();
          return total;
      }).share();
  );     
}

then

this.get_category(1).subscribe(t=> {
      this.callfunc();
});

Warning: A non-numeric value encountered

Not exactly the issue you had but the same error for people searching.

This happened to me when I spent too much time on JavaScript.

Coming back to PHP I concatenated two strings with + instead of . and got that error.

'this' implicitly has type 'any' because it does not have a type annotation

For method decorator declaration with configuration "noImplicitAny": true, you can specify type of this variable explicitly depends on @tony19's answer

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment as you can see above).

Try checking to see if Hibernate core is put in as dependency:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.0.11.Final</version>
  <scope>compile</scope>
</dependency>

gradlew command not found?

If you are using VS Code with flutter, you should find it in your app folder, under the android folder:

C:\myappFolder\android

You can run this in the terminal:

./gradlew signingReport

How to add fonts to create-react-app based projects?

Local fonts linking to your react js may be a failure. So, I prefer to use online css file from google to link fonts. Refer the following code,

<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

or

<style>
    @import url('https://fonts.googleapis.com/css?family=Roboto');
</style>

Consider defining a bean of type 'service' in your configuration [Spring boot]

You have to update your

scanBasePackages = { "com.exm.java" }

to add the path to your service (after annotating it with @service )

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

so I am assuming that this project you are doing in your private eclipse (not company provided eclipse where you work). The same problem I resolved just as below

quick fix : got to .m2 file --> create a backup of settings.xml --> remove settings.xml --> restart your eclipse.

UnsatisfiedDependencyException: Error creating bean with name

That was the version incompatibility where their was the inclusion of lettuce. When i excluded , it worked for me.

<!--Spring-Boot 2.0.0 -->
    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
                <exclusions>
                    <exclusion>
                        <groupId>io.lettuce</groupId>
                        <artifactId>lettuce-core</artifactId>
                    </exclusion>
                </exclusions>    
            </dependency>
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
            </dependency>

Mount current directory as a volume in Docker on Windows 10

  1. Open Settings on Docker Desktop (Docker for Windows).
  2. Select Shared Drives.
  3. Select the drive that you want to use inside your containers (e.g., C).
  4. Click Apply. You may be asked to provide user credentials. Enabling drives for containers on Windows

  5. The command below should now work on PowerShell (command prompt does not support ${PWD}):

    docker run --rm -v ${PWD}:/data alpine ls /data

IMPORTANT: if/when you change your Windows domain password, the mount will stop working silently, that is, -v will work but the container will not see your host folders and files. Solution: go back to Settings, uncheck the shared drives, Apply, check them again, Apply, and enter the new password when prompted.

React setState not updating state

Using async/await

async changeHandler(event) {
    await this.setState({ yourName: event.target.value });
    console.log(this.state.yourName);
}

Count unique values using pandas groupby

This is just an add-on to the solution in case you want to compute not only unique values but other aggregate functions:

df.groupby(['group']).agg(['min','max','count','nunique'])

Hope you find it useful

Specifying Font and Size in HTML table

The font tag has been deprecated for some time now.

That being said, the reason why both of your tables display with the same font size is that the 'size' attribute only accepts values ranging from 1 - 7. The smallest size is 1. The largest size is 7. The default size is 3. Any values larger than 7 will just display the same as if you had used 7, because 7 is the maximum value allowed.

And as @Alex H said, you should be using CSS for this.

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

Unfortunately it's out of our hands whether the package writer bothers with a declaration file. What I tend to do is have a file such index.d.ts that'll contain all the missing declaration files from various packages:

Index.ts:

declare module 'v-tooltip';
declare module 'parse5';
declare module 'emoji-mart-vue-fast';

Get total of Pandas column

Another option you can go with here:

df.loc["Total", "MyColumn"] = df.MyColumn.sum()

#         X  MyColumn      Y       Z
#0        A     84.0    13.0    69.0
#1        B     76.0    77.0   127.0
#2        C     28.0    69.0    16.0
#3        D     28.0    28.0    31.0
#4        E     19.0    20.0    85.0
#5        F     84.0   193.0    70.0
#Total  NaN    319.0     NaN     NaN

You can also use append() method:

df.append(pd.DataFrame(df.MyColumn.sum(), index = ["Total"], columns=["MyColumn"]))

enter image description here


Update:

In case you need to append sum for all numeric columns, you can do one of the followings:

Use append to do this in a functional manner (doesn't change the original data frame):

# select numeric columns and calculate the sums
sums = df.select_dtypes(pd.np.number).sum().rename('total')

# append sums to the data frame
df.append(sums)
#         X  MyColumn      Y      Z
#0        A      84.0   13.0   69.0
#1        B      76.0   77.0  127.0
#2        C      28.0   69.0   16.0
#3        D      28.0   28.0   31.0
#4        E      19.0   20.0   85.0
#5        F      84.0  193.0   70.0
#total  NaN     319.0  400.0  398.0

Use loc to mutate data frame in place:

df.loc['total'] = df.select_dtypes(pd.np.number).sum()
df
#         X  MyColumn      Y      Z
#0        A      84.0   13.0   69.0
#1        B      76.0   77.0  127.0
#2        C      28.0   69.0   16.0
#3        D      28.0   28.0   31.0
#4        E      19.0   20.0   85.0
#5        F      84.0  193.0   70.0
#total  NaN     638.0  800.0  796.0

Adding Lombok plugin to IntelliJ project

For me it didn't work after doing all of the steps suggested in the question and in the top answer. Initially the import didn't work, and then when I restarted IntelliJ, I got these messages from the Gradle Plugin:

Gradle DSL method not found: 'annotationProcessor()'
Possible causes:<ul><li>The project 'wq-handler-service' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0).
Upgrade plugin to version 2.3.2 and sync project</li><li>The project 'wq-handler-service' may be using a version of Gradle that does not contain the method.
Open Gradle wrapper file</li><li>The build file may be missing a Gradle plugin.
Apply Gradle plugin</li>

This was weird because I don't develop for Android, just using IntelliJ for Mac OS.

To be fair, my build.gradle file had these lines in the dependencies section, which I copied from a colleague:

compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.16.20'
annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.16.20'

After checking versions, the only thing that completely solved my problem was adding the below to the plugins section of build.gradle, which I found on this page:

id 'net.ltgt.apt' version '0.15'

Looks like it's a

Gradle plugin making it easier/safer to use Java annotation processors

(ltgt plugin page)

Spring @Autowired and @Qualifier

The @Qualifier annotation is used to resolve the autowiring conflict, when there are multiple beans of same type.

The @Qualifier annotation can be used on any class annotated with @Component or on methods annotated with @Bean. This annotation can also be applied on constructor arguments or method parameters.

Ex:-

public interface Vehicle {
     public void start();
     public void stop();
}

There are two beans, Car and Bike implements Vehicle interface

@Component(value="car")
public class Car implements Vehicle {

     @Override
     public void start() {
           System.out.println("Car started");
     }

     @Override
     public void stop() {
           System.out.println("Car stopped");
     }
 }

@Component(value="bike")
public class Bike implements Vehicle {

     @Override
     public void start() {
          System.out.println("Bike started");
     }

     @Override
     public void stop() {
          System.out.println("Bike stopped");
     }
}

Injecting Bike bean in VehicleService using @Autowired with @Qualifier annotation. If you didn't use @Qualifier, it will throw NoUniqueBeanDefinitionException.

@Component
public class VehicleService {

    @Autowired
    @Qualifier("bike")
    private Vehicle vehicle;

    public void service() {
         vehicle.start();
         vehicle.stop();
    }
}

Reference:- @Qualifier annotation example

Center Plot title in ggplot2

The ggeasy package has a function called easy_center_title() to do just that. I find it much more appealing than theme(plot.title = element_text(hjust = 0.5)) and it's so much easier to remember.

ggplot(data = dat, aes(time, total_bill, fill = time)) + 
  geom_bar(colour = "black", fill = "#DD8888", width = .8, stat = "identity") + 
  guides(fill = FALSE) +
  xlab("Time of day") +
  ylab("Total bill") +
  ggtitle("Average bill for 2 people") +
  ggeasy::easy_center_title()

enter image description here

Note that as of writing this answer you will need to install the development version of ggeasy from GitHub to use easy_center_title(). You can do so by running remotes::install_github("jonocarroll/ggeasy").

Spring security CORS Filter

With Spring Security in Spring Boot 2 to configure CORS globally (e.g. enabled all request for development) you can do:

@Bean
protected CorsConfigurationSource corsConfigurationSource() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
    return source;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors()
            .and().authorizeRequests()
            .anyRequest().permitAll()
            .and().csrf().disable();
}

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

For me - using Spring Boot with MongoDB, the following was the Problem:

In my POM.xml I had:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-starter-data-mongodb</artifactId>
</dependency>

but I needed the following:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>

(Short: Add "spring-boot-..." instead of only "spring-...")

error: package com.android.annotations does not exist

You shouldn't edit any code manually jetify should do this job for you, if you are running/building from cli using react-native you dont' need to do anything but if you are running/building Andriod studio you need to run jetify as pre-build, here is how can you automate this:

1- From the above menu go to edit configurations:

enter image description here

2- Add the bottom of the screen you will find before launch click on the plus and choose Run External Tool

enter image description here

2- Fill the following information, note that the working directory is your project root directory (not the android directory):

enter image description here

3- Make sure this run before anything else, in the end, your configuration should look something like this: enter image description here

Set selected item in Android BottomNavigationView

IF YOU NEED TO DYNAMICALLY PASS FRAGMENT ARGUMENTS DO THIS

There are plenty of (mostly repeated or outdated) answers here but none of them handles a very common need: dynamically passing different arguments to the Fragment loaded into a tab.

You can't dynamically pass different arguments to the loaded Fragment by using setSelectedItemId(R.id.second_tab), which ends up calling the static OnNavigationItemSelectedListener. To overcome this limitation I've ended up doing this in my MainActivity that contains the tabs:

fun loadArticleTab(articleId: String) {
    bottomNavigationView.menu.findItem(R.id.tab_article).isChecked = true // use setChecked() in Java
    supportFragmentManager
        .beginTransaction()
        .replace(R.id.main_fragment_container, ArticleFragment.newInstance(articleId))
        .commit()
}

The ArticleFragment.newInstance() method is implemented as usual:

private const val ARG_ARTICLE_ID = "ARG_ARTICLE_ID"

class ArticleFragment : Fragment() {

    companion object {
        /**
         * @return An [ArticleFragment] that shows the article with the given ID.
         */
        fun newInstance(articleId: String): ArticleFragment {
            val args = Bundle()
            args.putString(ARG_ARTICLE_ID, day)
            val fragment = ArticleFragment()
            fragment.arguments = args
            return fragment
        }
    }

}

Returning Promises from Vuex actions

actions in Vuex are asynchronous. The only way to let the calling function (initiator of action) to know that an action is complete - is by returning a Promise and resolving it later.

Here is an example: myAction returns a Promise, makes a http call and resolves or rejects the Promise later - all asynchronously

actions: {
    myAction(context, data) {
        return new Promise((resolve, reject) => {
            // Do something here... lets say, a http call using vue-resource
            this.$http("/api/something").then(response => {
                // http success, call the mutator and change something in state
                resolve(response);  // Let the calling function know that http is done. You may send some data back
            }, error => {
                // http failed, let the calling function know that action did not work out
                reject(error);
            })
        })
    }
}

Now, when your Vue component initiates myAction, it will get this Promise object and can know whether it succeeded or not. Here is some sample code for the Vue component:

export default {
    mounted: function() {
        // This component just got created. Lets fetch some data here using an action
        this.$store.dispatch("myAction").then(response => {
            console.log("Got some data, now lets show something in this component")
        }, error => {
            console.error("Got nothing from server. Prompt user to check internet connection and try again")
        })
    }
}

As you can see above, it is highly beneficial for actions to return a Promise. Otherwise there is no way for the action initiator to know what is happening and when things are stable enough to show something on the user interface.

And a last note regarding mutators - as you rightly pointed out, they are synchronous. They change stuff in the state, and are usually called from actions. There is no need to mix Promises with mutators, as the actions handle that part.

Edit: My views on the Vuex cycle of uni-directional data flow:

If you access data like this.$store.state["your data key"] in your components, then the data flow is uni-directional.

The promise from action is only to let the component know that action is complete.

The component may either take data from promise resolve function in the above example (not uni-directional, therefore not recommended), or directly from $store.state["your data key"] which is unidirectional and follows the vuex data lifecycle.

The above paragraph assumes your mutator uses Vue.set(state, "your data key", http_data), once the http call is completed in your action.

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

There are some processes left in the background on that port, several reasons can cause this problem, but you can solve easily if you end process which is related to 8080 or Spring.

If you are using Linux there is steps how to end process:

  1. Open terminal and type command "htop"
  2. press key F3(it will allow you to search)
  3. Type "8080" if there was no result on 8080 after that try "spring"
  4. Then Press F9(KILL) And press "9"(SIGKILL)

this will kill process which is left on 8080 port and let you run application.

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

Try adding the following dependencies.

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
</dependency> 

Pandas group-by and sum

A variation on the .agg() function; provides the ability to (1) persist type DataFrame, (2) apply averages, counts, summations, etc. and (3) enables groupby on multiple columns while maintaining legibility.

df.groupby(['att1', 'att2']).agg({'att1': "count", 'att3': "sum",'att4': 'mean'})

using your values...

df.groupby(['Name', 'Fruit']).agg({'Number': "sum"})

Vue 2 - Mutating props vue-warn

I want to give this answer which helps avoid using a lot of code, watchers and computed properties. In some cases this can be a good solution:

Props are designed to provide one-way communication.

When you have a modal show/hide button with a prop the best solution to me is to emit an event:

<button @click="$emit('close')">Close Modal</button>

Then add listener to modal element:

<modal :show="show" @close="show = false"></modal>

(In this case the prop show is probably unnecessary because you can use an easy v-if="show" directly on the base-modal)

Concatenating variables and strings in React

the best way to concat props/variables:

var sample = "test";    
var result = `this is just a ${sample}`;    
//this is just a test

Error: Unexpected value 'undefined' imported by the module

For anyone facing this same error, my situation was that I have double commas in the imports section

imports: [
      BrowserModule,
      HttpModule,
      FormsModule,
      RouterModule.forRoot(appRoutes), , // <-- this was the error
      // .... 
],

Unable to find a @SpringBootConfiguration when doing a JpaTest

Configuration is attached to the application class, so the following will set up everything correctly:

@SpringBootTest(classes = Application.class)

Example from the JHipster project here.

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

@GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

@GetMapping is the newer annotaion. It supports consumes

Consume options are :

consumes = "text/plain"
consumes = {"text/plain", "application/*"}

For Further details see: GetMapping Annotation

or read: request mapping variants

RequestMapping supports consumes as well

GetMapping we can apply only on method level and RequestMapping annotation we can apply on class level and as well as on method level

Make the size of a heatmap bigger with seaborn

I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:

f, ax = plt.subplots(figsize=(16, 12))

at the meantime until you get a matched size colobar. This worked for me.

React Native: Possible unhandled promise rejection

Adding here my experience that hopefully might help somebody.

I was experiencing the same issue on Android emulator in Linux with hot reload. The code was correct as per accepted answer and the emulator could reach the internet (I needed a domain name).

Refreshing manually the app made it work. So maybe it has something to do with the hot reloading.

Can't push to the heroku

Read this doc which will explain to you what to do.
https://devcenter.heroku.com/articles/buildpacks

Setting a buildpack on an application

You can change the buildpack used by an application by setting the buildpack value.
When the application is next pushed, the new buildpack will be used.

$ heroku buildpacks:set heroku/php

Buildpack set. Next release on random-app-1234 will use heroku/php.
Run git push heroku master to create a new release using this buildpack.

This is whay its not working for you since you did not set it up.

... When the application is next pushed, the new buildpack will be used.

You may also specify a buildpack during app creation:

$ heroku create myapp --buildpack heroku/python

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

This may be work.

Find the CATALINA_HOME/webapps/manager/META-INF/context.xml file and add the comment markers around the Valve.

<Context antiResourceLocking="false" privileged="true" >

<!--
<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
-->

</Context>

You can find more details at this page.

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

A solution I came up with is to use a vis.js instance in an iframe. This shows an interactive 3D plot inside a notebook, which still works in nbviewer. The visjs code is borrowed from the example code on the 3D graph page

A small notebook to illustrate this: demo

The code itself:

from IPython.core.display import display, HTML
import json

def plot3D(X, Y, Z, height=600, xlabel = "X", ylabel = "Y", zlabel = "Z", initialCamera = None):

    options = {
        "width": "100%",
        "style": "surface",
        "showPerspective": True,
        "showGrid": True,
        "showShadow": False,
        "keepAspectRatio": True,
        "height": str(height) + "px"
    }

    if initialCamera:
        options["cameraPosition"] = initialCamera

    data = [ {"x": X[y,x], "y": Y[y,x], "z": Z[y,x]} for y in range(X.shape[0]) for x in range(X.shape[1]) ]
    visCode = r"""
       <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" type="text/css" rel="stylesheet" />
       <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
       <div id="pos" style="top:0px;left:0px;position:absolute;"></div>
       <div id="visualization"></div>
       <script type="text/javascript">
        var data = new vis.DataSet();
        data.add(""" + json.dumps(data) + """);
        var options = """ + json.dumps(options) + """;
        var container = document.getElementById("visualization");
        var graph3d = new vis.Graph3d(container, data, options);
        graph3d.on("cameraPositionChange", function(evt)
        {
            elem = document.getElementById("pos");
            elem.innerHTML = "H: " + evt.horizontal + "<br>V: " + evt.vertical + "<br>D: " + evt.distance;
        });
       </script>
    """
    htmlCode = "<iframe srcdoc='"+visCode+"' width='100%' height='" + str(height) + "px' style='border:0;' scrolling='no'> </iframe>"
    display(HTML(htmlCode))

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

The error message says your DbContext(LogManagerContext ) needs a constructor which accepts a DbContextOptions. But i couldn't find such a constructor in your DbContext. So adding below constructor probably solves your problem.

    public LogManagerContext(DbContextOptions options) : base(options)
    {
    }

Edit for comment

If you don't register IHttpContextAccessor explicitly, use below code:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

Using custom exception class you can return different HTTP status code and dto object.

@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
    if(userDto.getId() != null) {
        throw new UserNotFoundException("A new user cannot already have an ID");
    }
    return ResponseEntity.ok(userService.saveUser(userDto));
}

Exception class

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "user not found")
public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {

        super(message);
    }
}

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

How to get request URL in Spring Boot RestController

Allows getting any URL on your system, not just a current one.

import org.springframework.hateoas.mvc.ControllerLinkBuilder
...
ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId))

URI methodUri = linkBuilder.Uri()
String methodUrl = methodUri.getPath()

Adb install failure: INSTALL_CANCELED_BY_USER

For MIUI OS Device

1) Go to Setting

2) Scroll down to Additional Setting

3) You will find Developer option at bottom

4) Turn this on - Install via USB: Toggle On

By turning this on, It is working charm in my MIUI8 device.

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

If anyone facing similar type of error while adding ShimmerRecyclerView Loader in android , make sure to add maven { url "https://jitpack.io" } under allprojects like below.

    allprojects {
    repositories {
        google()
        jcenter()
        //add it here
        maven { url "https://jitpack.io" }
      }
   }

react-native :app:installDebug FAILED

In my case (with React Native), my Android phone was unrecognized by my PC where I was running the server, which can be seen by the message:

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: No online devices found.

If that is the case, as highlighted in ADB Android Device Unauthorized, make sure that in Developer Options on your phone USB Debugging is set to true, and enter the following commands in terminal or cmd to restart the Android server.

adb kill-server
adb start-server

And adb devices should list your phone as device instead of unauthorized

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

Ubuntu comes with a version of PIP from precambrian and that's how you have to upgrade it if you do not want to spend hours and hours debugging pip related issues.

apt-get remove python-pip python3-pip
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py
python3 get-pip.py

As you observed I included information for both Python 2.x and 3.x

Change Spinner dropdown icon

You need to create custom background like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <layer-list>
            <item>
                <shape>
                    <gradient android:angle="90" android:endColor="#ffffff" android:startColor="#ffffff" android:type="linear"/>

                    <stroke android:width="1dp" android:color="#504a4b"/>

                    <corners android:radius="5dp"/>

                    <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp"/>
                </shape>
            </item>
            <item>
                <bitmap android:gravity="bottom|right" android:src="@drawable/drop_down"/> // you can place your dropdown image
            </item>
        </layer-list>
    </item>

</selector>

Then create style for spinner like this:

<style name="spinner_style">
        <item name="android:background">@drawable/YOURCUSTOMBACKGROUND</item>
        <item name="android:layout_marginLeft">5dp</item>
        <item name="android:layout_marginRight">5dp</item>
        <item name="android:layout_marginBottom">5dp</item>
</style>

after that apply this style to your spinner

How to remove specific substrings from a set of strings in Python?

Strings are immutable. string.replace (python 2.x) or str.replace (python 3.x) creates a new string. This is stated in the documentation:

Return a copy of string s with all occurrences of substring old replaced by new. ...

This means you have to re-allocate the set or re-populate it (re-allocating is easier with set comprehension):

new_set = {x.replace('.good', '').replace('.bad', '') for x in set1}

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

For react-native-firebase, adding this to app/build.gradle dependencies section made it work for me:

implementation('com.squareup.okhttp3:okhttp:3.12.1') { force = true }
implementation('com.squareup.okio:okio:1.15.0') { force = true }
implementation('com.google.code.findbugs:jsr305:3.0.2') { force = true}

Add Favicon with React and Webpack

This worked for me:

Add this in index.html (inside src folder along with favicon.ico)

**<link rel="icon" href="/src/favicon.ico" type="image/x-icon" />**

webpack.config.js is like:

 plugins: [new HtmlWebpackPlugin({`enter code here`
        template: './src/index.html'
    })],

What is username and password when starting Spring Boot with Tomcat?

If you can't find the password based on other answers that point to a default one, the log message wording in recent versions changed to

Using generated security password: <some UUID>

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

How to sum the values of one column of a dataframe in spark/scala

You must first import the functions:

import org.apache.spark.sql.functions._

Then you can use them like this:

val df = CSV.load(args(0))
val sumSteps =  df.agg(sum("steps")).first.get(0)

You can also cast the result if needed:

val sumSteps: Long = df.agg(sum("steps").cast("long")).first.getLong(0)

Edit:

For multiple columns (e.g. "col1", "col2", ...), you could get all aggregations at once:

val sums = df.agg(sum("col1").as("sum_col1"), sum("col2").as("sum_col2"), ...).first

Edit2:

For dynamically applying the aggregations, the following options are available:

  • Applying to all numeric columns at once:
df.groupBy().sum()
  • Applying to a list of numeric column names:
val columnNames = List("col1", "col2")
df.groupBy().sum(columnNames: _*)
  • Applying to a list of numeric column names with aliases and/or casts:
val cols = List("col1", "col2")
val sums = cols.map(colName => sum(colName).cast("double").as("sum_" + colName))
df.groupBy().agg(sums.head, sums.tail:_*).show()

How do I filter an array with TypeScript in Angular 2?

You need to put your code into ngOnInit and use the this keyword:

ngOnInit() {
  this.booksByStoreID = this.books.filter(
          book => book.store_id === this.store.id);
}

You need ngOnInit because the input store wouldn't be set into the constructor:

ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)

In your code, the books filtering is directly defined into the class content...

How to configure CORS in a Spring Boot + Spring Security application?

Spring Security can now leverage Spring MVC CORS support described in this blog post I wrote.

To make it work, you need to explicitly enable CORS support at Spring Security level as following, otherwise CORS enabled requests may be blocked by Spring Security before reaching Spring MVC.

If you are using controller level @CrossOrigin annotations, you just have to enable Spring Security CORS support and it will leverage Spring MVC configuration:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

If you prefer using CORS global configuration, you can declare a CorsConfigurationSource bean as following:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}

This approach supersedes the filter-based approach previously recommended.

You can find more details in the dedicated CORS section of Spring Security documentation.

Keras model.summary() result - Understanding the # of Parameters

For Dense Layers:

output_size * (input_size + 1) == number_parameters 

For Conv Layers:

output_channels * (input_channels * window_size + 1) == number_parameters

Consider following example,

model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=input_shape),
Conv2D(64, (3, 3), activation='relu'),
Conv2D(128, (3, 3), activation='relu'),
Dense(num_classes, activation='softmax')
])

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 222, 222, 32)      896       
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 220, 220, 64)      18496     
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 218, 218, 128)     73856     
_________________________________________________________________
dense_9 (Dense)              (None, 218, 218, 10)      1290      
=================================================================

Calculating params,

assert 32 * (3 * (3*3) + 1) == 896
assert 64 * (32 * (3*3) + 1) == 18496
assert 128 * (64 * (3*3) + 1) == 73856
assert num_classes * (128 + 1) == 1290

What are functional interfaces used for in Java 8?

An interface with only one abstract method is called Functional Interface. It is not mandatory to use @FunctionalInterface, but it’s best practice to use it with functional interfaces to avoid addition of extra methods accidentally. If the interface is annotated with @FunctionalInterface annotation and we try to have more than one abstract method, it throws compiler error.

package com.akhi;
    @FunctionalInterface
    public interface FucnctionalDemo {

      void letsDoSomething();
      //void letsGo();      //invalid because another abstract method does not allow
      public String toString();    // valid because toString from Object 
      public boolean equals(Object o); //valid

      public static int sum(int a,int b)   // valid because method static
        {   
            return a+b;
        }
        public default int sub(int a,int b)   //valid because method default
        {
            return a-b;
        }
    }

The number of method references in a .dex file cannot exceed 64k API 17

You have too many methods. There can only be 65536 methods for dex.

As suggested you can use the multidex support.

Just add these lines in the module/build.gradle:

android {

    defaultConfig {
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
  implementation 'com.android.support:multidex:1.0.3'  //with support libraries
  //implementation 'androidx.multidex:multidex:2.0.1'  //with androidx libraries
}

Also in your Manifest add the MultiDexApplication class from the multidex support library to the application element

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.android.multidex.myapplication">
        <application
            ...
            android:name="android.support.multidex.MultiDexApplication">

            <!-- If you are using androidx use android:name="androidx.multidex.MultiDexApplication" -->

            <!--If you are using your own custom Application class then extend -->
            <!--MultiDexApplication and change above line as-->
            <!--android:name=".YourCustomApplicationClass"> -->

            ...
        </application>
    </manifest>

If you are using your own Application class, change the parent class from Application to MultiDexApplication.
If you can't do it, in your Application class override the attachBaseContext method with:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(newBase);
    MultiDex.install(this);
}

Another solution is to try to remove unused code with ProGuard - Configure the ProGuard settings for your app to run ProGuard and ensure you have shrinking enabled for release builds.

VBA: Convert Text to Number

For large datasets a faster solution is required.

Making use of 'Text to Columns' functionality provides a fast solution.

Example based on column F, starting range at 25 to LastRow

Sub ConvTxt2Nr()

Dim SelectR As Range
Dim sht As Worksheet
Dim LastRow As Long

Set sht = ThisWorkbook.Sheets("DumpDB")

LastRow = sht.Cells(sht.Rows.Count, "F").End(xlUp).Row

Set SelectR = ThisWorkbook.Sheets("DumpDB").Range("F25:F" & LastRow)

SelectR.TextToColumns Destination:=Range("F25"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True

End Sub

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

How to extend / inherit components?

You can inherit @Input, @Output, @ViewChild, etc. Look at the sample:

@Component({
    template: ''
})
export class BaseComponent {
    @Input() someInput: any = 'something';

    @Output() someOutput: EventEmitter<void> = new EventEmitter<void>();

}

@Component({
    selector: 'app-derived',
    template: '<div (click)="someOutput.emit()">{{someInput}}</div>',
    providers: [
        { provide: BaseComponent, useExisting: DerivedComponent }
    ]
})
export class DerivedComponent {

}

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

I had this error with MySQL as my database and the only solution was reinstall all components of MySQL, because before I installed just the server.

So try to download other versions of PostgreSQL and get all the components

React native text going off my screen, refusing to wrap. What to do?

<View style={{flexDirection:'row'}}> 
   <Text style={{ flex: number }}> You miss fdddddd dddddddd 
     You miss fdd
   </Text>
</View>

{ flex: aNumber } is all you need!

Just set 'flex' to a number that suit for you. And then the text will wrap.

disabling spring security in spring boot app

The accepted answer didn't work for me.

If you have a multi configuration, adding the following to your WebSecurityConfig class worked for me (ensure that your Order(1) is lower than all of your other Order annotations in the class):

/* UNCOMMENT TO DISABLE SPRING SECURITY */
    /*@Configuration
    @Order(1)
    public static class DisableSecurityConfigurationAdapater extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();
        }
    }*/

Getting Access Denied when calling the PutObject operation with bucket-level permission

Similar to one post above, (except I was using admin credentials) to get S3 uploads to work with large 50M file.

Initially my error was:

An error occurred (AccessDenied) when calling the CreateMultipartUpload operation: Access Denied

I switched the multipart_threshold to be above the 50M

aws configure set default.s3.multipart_threshold 64MB

and I got:

An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

I checked bucket public access settings and all was allowed. So I found that public access can be blocked on account level for all S3 buckets:

S3 can block public ACL on account level

Execution failed for task ':app:processDebugResources' even with latest build tools

I want to add that sometimes android studio loses track of the resources file and can't build on launch. If the above answers are to no avail, try

Build => Rebuild Project

I lost many hours to this when I was a beginner at Android Studio.

Fine control over the font size in Seaborn plots for academic papers

It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:

sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:

axs.set_ylabel('mylabel',size=6)

you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.

def set_pubfig:
    sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.

Note: If you specify these numbers, specifying font_scale in sns.set_context is ignored for all specified font elements, even if you set it.

Could not autowire field:RestTemplate in Spring boot application

It's exactly what the error says. You didn't create any RestTemplate bean, so it can't autowire any. If you need a RestTemplate you'll have to provide one. For example, add the following to TestMicroServiceApplication.java:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Note, in earlier versions of the Spring cloud starter for Eureka, a RestTemplate bean was created for you, but this is no longer true.

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

Permissions

You need the s3:GetObject permission for this operation. For more information, see Specifying Permissions in a Policy. If the object you request does not exist, the error Amazon S3 returns depends on whether you also have the s3:ListBucket permission.

If you have the s3:ListBucket permission on the bucket, Amazon S3 returns an HTTP status code 404 ("no such key") error.

If you don’t have the s3:ListBucket permission, Amazon S3 returns an HTTP status code 403 ("access denied") error.

The following operation is related to HeadObject:

GetObject

Source: https://docs.aws.amazon.com/AmazonS3/latest/API/API_HeadObject.html

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

Pretty sure pk_OrderID is the PK of AC_Shipping_Addresses

And you are trying to insert a duplicate via the _Order.OrderNumber

Do a

select * from AC_Shipping_Addresses where pk_OrderID = 165863;

or select count(*) ....

Pretty sure you will get a row returned.

What it is telling you is you are already using pk_OrderID = 165863 and cannot have another row with that value.

if you want to not insert if there is a row

insert into table (pk, value) 
select 11 as pk, 'val' as value 
where not exists (select 1 from table where pk = 11) 

Disable Tensorflow debugging information

2.0 Update (10/8/19) Setting TF_CPP_MIN_LOG_LEVEL should still work (see below in v0.12+ update), but there is currently an issue open (see issue #31870). If setting TF_CPP_MIN_LOG_LEVEL does not work for you (again, see below), try doing the following to set the log level:

import tensorflow as tf
tf.get_logger().setLevel('INFO')

In addition, please see the documentation on tf.autograph.set_verbosity which sets the verbosity of autograph log messages - for example:

# Can also be set using the AUTOGRAPH_VERBOSITY environment variable
tf.autograph.set_verbosity(1)

v0.12+ Update (5/20/17), Working through TF 2.0+:

In TensorFlow 0.12+, per this issue, you can now control logging via the environmental variable called TF_CPP_MIN_LOG_LEVEL; it defaults to 0 (all logs shown) but can be set to one of the following values under the Level column.

  Level | Level for Humans | Level Description                  
 -------|------------------|------------------------------------ 
  0     | DEBUG            | [Default] Print all messages       
  1     | INFO             | Filter out INFO messages           
  2     | WARNING          | Filter out INFO & WARNING messages 
  3     | ERROR            | Filter out all messages      

See the following generic OS example using Python:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # or any {'0', '1', '2'}
import tensorflow as tf

You can set this environmental variable in the environment that you run your script in. For example, with bash this can be in the file ~/.bashrc, /etc/environment, /etc/profile, or in the actual shell as:

TF_CPP_MIN_LOG_LEVEL=2 python my_tf_script.py

To be thorough, you call also set the level for the Python tf_logging module, which is used in e.g. summary ops, tensorboard, various estimators, etc.

# append to lines above
tf.logging.set_verbosity(tf.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}

For 1.14 you will receive warnings if you do not change to use the v1 API as follows:

# append to lines above
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}

**For Prior Versions of TensorFlow or TF-Learn Logging (v0.11.x or lower):**

View the page below for information on TensorFlow logging; with the new update, you're able to set the logging verbosity to either DEBUG, INFO, WARN, ERROR, or FATAL. For example:

tf.logging.set_verbosity(tf.logging.ERROR)

The page additionally goes over monitors which can be used with TF-Learn models. Here is the page.

This doesn't block all logging, though (only TF-Learn). I have two solutions; one is a 'technically correct' solution (Linux) and the other involves rebuilding TensorFlow.

script -c 'python [FILENAME].py' | grep -v 'I tensorflow/'

For the other, please see this answer which involves modifying source and rebuilding TensorFlow.

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

I know it's a bit of an old question, but still. Everytime this happens to me, it's because I've included all of the play-services libraries. Just change play-services:x.x.x to play-service-:x.x.x in the build.gradle(module) file

ApiNotActivatedMapError for simple html page using google-places-api

I had the same error. To fix the error:

  1. Open the console menu Gallery Menu and select API Manager.
  2. On the left, click Credentials and then click New Credentials.
  3. Click Create Credentials.
  4. Click API KEY.
  5. Click Navigator Key (there are more options; It depends on when consumed).

You must use this new API Navigator Key, generated by the system.

How to force Docker for a clean build of an image

There's a --no-cache option:

docker build --no-cache -t u12_core -f u12_core .

In older versions of Docker you needed to pass --no-cache=true, but this is no longer the case.

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

In Linux, folders are case sensitive. I was getting this error because folder name TestAPI and was putting TestApi.

AttributeError: 'dict' object has no attribute 'predictors'

The dict.items iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items() will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items). And now, just as an example:

>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
...   print key, value
...
world 2999
hello 34

The AttributeError is an exception thrown when an object does not have the attribute you tried to access. The class dict does not have any predictors attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.

Google Maps JavaScript API RefererNotAllowedMapError

I add 2 website domains, set "*" in subdomain is not working but specific subdomain "WWW" and non-subdomain have been worked for my websites using the same Google Map API key.

dont' use "*" in subdomain

Hope it help.

Swift Error: Editor placeholder in source file

Sometimes, XCode does not forget the line which had an "Editor Placeholder" even if you have replaced it with a value. Cut the portion of the code where XCode is complaining and paste the code back to the same place to make the error message go away. This worked for me.

Spring RequestMapping for controllers that produce and consume JSON

You can use the @RestController instead of @Controller annotation.

ng-if check if array is empty

Verify the length property of the array to be greater than 0:

<p ng-if="post.capabilities.items.length > 0">
   <strong>Topics</strong>: 
   <span ng-repeat="topic in post.capabilities.items">
     {{topic.name}}
   </span>
</p>

Arrays (objects) in JavaScript are truthy values, so your initial verification <p ng-if="post.capabilities.items"> evaluates always to true, even if the array is empty.

Angular 2 @ViewChild annotation returns undefined

My workaround was to use [style.display]="getControlsOnStyleDisplay()" instead of *ngIf="controlsOn". The block is there but it is not displayed.

@Component({
selector: 'app',
template:  `
    <controls [style.display]="getControlsOnStyleDisplay()"></controls>
...

export class AppComponent {
  @ViewChild(ControlsComponent) controls:ControlsComponent;

  controlsOn:boolean = false;

  getControlsOnStyleDisplay() {
    if(this.controlsOn) {
      return "block";
    } else {
      return "none";
    }
  }
....

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Simpal an easy In my case it solved by as below

enter image description here

Make sure your pakage name in mainifests file same as your gradle's applicationId.

Angular 2 router no base href set

it is just that add below code in the index.html head tag

   <html>
    <head>
     <base href="/">
      ...

that worked like a charm for me.

Spring Boot @autowired does not work, classes in different package

Just put the packages inside the @SpringBootApplication tag.

@SpringBootApplication(scanBasePackages = { "com.pkg1", "com.pkg2", .....})

Let me know.

android : Error converting byte to dex

Please add this block inside android in build.gradle

dexOptions { preDexLibraries = false }

How to prevent tensorflow from allocating the totality of a GPU memory?

All the answers above assume execution with a sess.run() call, which is becoming the exception rather than the rule in recent versions of TensorFlow.

When using the tf.Estimator framework (TensorFlow 1.4 and above) the way to pass the fraction along to the implicitly created MonitoredTrainingSession is,

opts = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)
conf = tf.ConfigProto(gpu_options=opts)
trainingConfig = tf.estimator.RunConfig(session_config=conf, ...)
tf.estimator.Estimator(model_fn=..., 
                       config=trainingConfig)

Similarly in Eager mode (TensorFlow 1.5 and above),

opts = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)
conf = tf.ConfigProto(gpu_options=opts)
tfe.enable_eager_execution(config=conf)

Edit: 11-04-2018 As an example, if you are to use tf.contrib.gan.train, then you can use something similar to bellow:

tf.contrib.gan.gan_train(........, config=conf)

How to select the first row of each group?

A nice way of doing this with the dataframe api is using the argmax logic like so

  val df = Seq(
    (0,"cat26",30.9), (0,"cat13",22.1), (0,"cat95",19.6), (0,"cat105",1.3),
    (1,"cat67",28.5), (1,"cat4",26.8), (1,"cat13",12.6), (1,"cat23",5.3),
    (2,"cat56",39.6), (2,"cat40",29.7), (2,"cat187",27.9), (2,"cat68",9.8),
    (3,"cat8",35.6)).toDF("Hour", "Category", "TotalValue")

  df.groupBy($"Hour")
    .agg(max(struct($"TotalValue", $"Category")).as("argmax"))
    .select($"Hour", $"argmax.*").show

 +----+----------+--------+
 |Hour|TotalValue|Category|
 +----+----------+--------+
 |   1|      28.5|   cat67|
 |   3|      35.6|    cat8|
 |   2|      39.6|   cat56|
 |   0|      30.9|   cat26|
 +----+----------+--------+

React onClick function fires on render

JSX will evaluate JavaScript expressions in curly braces

In this case, this.props.removeTaskFunction(todo) is invoked and the return value is assigned to onClick

What you have to provide for onClick is a function. To do this, you can wrap the value in an anonymous function.

export const samepleComponent = ({todoTasks, removeTaskFunction}) => {
    const taskNodes = todoTasks.map(todo => (
                <div>
                    {todo.task}
                    <button type="submit" onClick={() => removeTaskFunction(todo)}>Submit</button>
                </div>
            );
    return (
        <div className="todo-task-list">
            {taskNodes}
        </div>
        );
    }
});

RecyclerView - Get view at particular position

Keep in mind that you have to wait until adapter will added to list, then you can try to getting view by position

final int i = 0;
recyclerView.setAdapter(adapter);
recyclerView.post(new Runnable() {
    @Override
    public void run() {
        View view = recyclerView.getLayoutManager().findViewByPosition(i);
    }
});

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

Dont go crazy I just clean , then rebuild project and error was gone

Conda update failed: SSL error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

For those of us on corporate networks using web filters that implement trusted man in the middle SSL solutions, it is necessary to add the web-filter certificate to the certifi cacert.pem.

A guide to doing this is here.

Main steps are:

  1. connect to https site with browser
  2. view and save root certificate
  3. convert cert to .pem
  4. copy and paste onto end of existing cacert.pem
  5. save
  6. SSL happiness

What is the reason for the error message "System cannot find the path specified"?

You just need to:

Step 1: Go home directory of C:\ with typing cd.. (2 times)

Step 2: It appears now C:\>

Step 3: Type dir Windows\System32\run

That's all, it shows complete files & folder details inside target folder.

enter image description here

Details: I used Windows\System32\com folder as example, you should type your own folder name etc. Windows\System32\run

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

Important note: You should only apply plugin at bottom of build.gradle (App level)

apply plugin: 'com.google.gms.google-services'

I mistakenly apply this plugin at top of the build.gradle. So I get error.

One more tips : You no need to remove even you use the 3.1.0 or above. Because google not officially announced

   classpath 'com.google.gms:google-services:3.1.0' 

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

I had the same issue. The problem is that the Spring Boot annotation processor generates the spring-configuration-metadata.json file inside your /target/classes/META-INF folder.

If you happen to have ignored this folder in IntelliJ like me (because what the heck, who cares about classes files?), the file won't be indexed by your IDE. Therefore, no completion, and the annoying message.

Just remove target from the ignore files/folders list, located in Settings > Editor > File Types > Ignore files and folders.

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

I was getting this error

Error:Execution failed for task ':app:preDebugAndroidTestBuild'. Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.

I was having following dependencies in my build.gradle file under Gradle Scripts

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

So, I resolved it by commenting the following dependencies

testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

So my dependencies look like this

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
//testImplementation 'junit:junit:4.12'
//androidTestImplementation 'com.android.support.test:runner:1.0.2'
//androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Hope it helps!

Spring Boot application can't resolve the org.springframework.boot package

In my project, updated the dependency on spring-boot-starter-parent from 2.0.0.release to 2.0.5.relese. Doing this resolved the issue The import org.springframework.boot.SpringApplication cannot be resolved

The type or namespace name 'System' could not be found

For the folks that like me got here because they're trying to host aspnet.core mvc in a console application: The ONLY way I was able to solve this was by converting the .csproj to the new format and add the Sdk property to the Project tag on the very first line.

<Project Sdk="Microsoft.NET.Sdk.Razor">

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

In terminal execute in root project folder:

./gradlew clean

It helped me.

Spring boot - configure EntityManager

With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the

application.properties

spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass

spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true

Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.

@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}

And if you still need to use the Entity Manager you can create another class.

public class ObjectRepositoryImpl implements ObjectCustomMethods{

    @PersistenceContext
    private EntityManager em;

}

This should be in your pom.xml

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

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
</dependencies>

How to execute raw queries with Laravel 5.1?

you can run raw query like this way too.

DB::table('setting_colleges')->first();

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

Hibernate-sequence doesn't exist

I was getting the same error "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mylocaldb.hibernate_sequence' doesn't exist".

Using spring mvc 4.3.7 and hibernate version 5.2.9, application is made using spring java based configuration. Now I have to add the hibernate.id.new_generator_mappings property mentioned by @Eva Mariam in my code like this:

@Autowired
    @Bean(name = "sessionFactory")
    public SessionFactory getSessionFactory(DataSource dataSource) {

        LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
        sessionBuilder.addProperties(getHibernateProperties());
        sessionBuilder.addAnnotatedClasses(User.class);

        return sessionBuilder.buildSessionFactory();
    }

    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        properties.put("hibernate.id.new_generator_mappings","false");
        return properties;
    }

And it worked like charm.

How to set base url for rest in spring boot?

I might be a bit late, BUT... I believe it is the best solution. Set it up in your application.yml (or analogical config file):

spring:
    data:
        rest:
            basePath: /api

As I can remember that's it - all of your repositories will be exposed beneath this URI.

How to return JSON data from spring Controller using @ResponseBody

I was using groovy+springboot and got this error.

Adding getter/setter is enough if we are using below dependency.

implementation 'org.springframework.boot:spring-boot-starter-web'

As Jackson core classes come with it.

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

I had the same its because of version incompatibility check for version or remove version if using spring boot

Simple way to measure cell execution time in ipython notebook

When in trouble what means what:

?%timeit or ??timeit

To get the details:

Usage, in line mode:
  %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
or in cell mode:
  %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
  code
  code...

Time execution of a Python statement or expression using the timeit
module.  This function can be used both as a line and cell magic:

- In line mode you can time a single-line statement (though multiple
  ones can be chained with using semicolons).

- In cell mode, the statement in the first line is used as setup code
  (executed but not timed) and the body of the cell is timed.  The cell
  body has access to any variables created in the setup code.

Retrofit 2 - Dynamic URL

You can use the encoded flag on the @Path annotation:

public interface APIService {
  @GET("{fullUrl}")
  Call<Users> getUsers(@Path(value = "fullUrl", encoded = true) String fullUrl);
}
  • This will prevent the replacement of / with %2F.
  • It will not save you from ? being replaced by %3F, however, so you still can't pass in dynamic query strings.

React proptype array with shape

And there it is... right under my nose:

From the react docs themselves: https://facebook.github.io/react/docs/reusable-components.html

// An array of a certain type
    optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

I got the same error when I executed the Spring JPA deleteAll() method from Junit test cases. I simply used the deleteInBatch() & deleteAllInBatch() and its perfectly works. We do not need to mark @Transactional at the test cases level.

How to rotate x-axis tick labels in Pandas barplot

The follows might be helpful:

# Valid font size are xx-small, x-small, small, medium, large, x-large, xx-large, larger, smaller, None

plt.xticks(
    rotation=45,
    horizontalalignment='right',
    fontweight='light',
    fontsize='medium',
)

Here is the function xticks[reference] with example and API

def xticks(ticks=None, labels=None, **kwargs):
    """
    Get or set the current tick locations and labels of the x-axis.

    Call signatures::

        locs, labels = xticks()            # Get locations and labels
        xticks(ticks, [labels], **kwargs)  # Set locations and labels

    Parameters
    ----------
    ticks : array_like
        A list of positions at which ticks should be placed. You can pass an
        empty list to disable xticks.

    labels : array_like, optional
        A list of explicit labels to place at the given *locs*.

    **kwargs
        :class:`.Text` properties can be used to control the appearance of
        the labels.

    Returns
    -------
    locs
        An array of label locations.
    labels
        A list of `.Text` objects.

    Notes
    -----
    Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
    equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
    the current axes.
    Calling this function with arguments is the pyplot equivalent of calling
    `~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current axes.

    Examples
    --------
    Get the current locations and labels:

        >>> locs, labels = xticks()

    Set label locations:

        >>> xticks(np.arange(0, 1, step=0.2))

    Set text labels:

        >>> xticks(np.arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue'))

    Set text labels and properties:

        >>> xticks(np.arange(12), calendar.month_name[1:13], rotation=20)

    Disable xticks:

        >>> xticks([])
    """

If "0" then leave the cell blank

An example of an IF Statement that can be used to add a calculation into the cell you wish to hide if value = 0 but displayed upon another cell value reference.

=IF(/Your reference cell/=0,"",SUM(/Here you put your SUM/))

How to find distinct rows with field in list using JPA and Spring?

Can you not use like this?

@Query("SELECT DISTINCT name FROM people p (nolock) WHERE p.name NOT IN (:myparam)")
List<String> findNonReferencedNames(@Param("myparam")List<String> names);

P.S. I write queries in SQL Server 2012 a lot and using nolock in server is a good practice, you can ignore nolock if a local db is used.

Seems like your db name is not being mapped correctly (after you've updated your question)

Angular and debounce

It could be implemented as Directive

import { Directive, Input, Output, EventEmitter, OnInit, OnDestroy } from '@angular/core';
import { NgControl } from '@angular/forms';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { Subscription } from 'rxjs';

@Directive({
  selector: '[ngModel][onDebounce]',
})
export class DebounceDirective implements OnInit, OnDestroy {
  @Output()
  public onDebounce = new EventEmitter<any>();

  @Input('debounce')
  public debounceTime: number = 300;

  private isFirstChange: boolean = true;
  private subscription: Subscription;

  constructor(public model: NgControl) {
  }

  ngOnInit() {
    this.subscription =
      this.model.valueChanges
        .debounceTime(this.debounceTime)
        .distinctUntilChanged()
        .subscribe(modelValue => {
          if (this.isFirstChange) {
            this.isFirstChange = false;
          } else {
            this.onDebounce.emit(modelValue);
          }
        });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

}

use it like

<input [(ngModel)]="value" (onDebounce)="doSomethingWhenModelIsChanged($event)">

component sample

import { Component } from "@angular/core";

@Component({
  selector: 'app-sample',
  template: `
<input[(ngModel)]="value" (onDebounce)="doSomethingWhenModelIsChanged($event)">
<input[(ngModel)]="value" (onDebounce)="asyncDoSomethingWhenModelIsChanged($event)">
`
})
export class SampleComponent {
  value: string;

  doSomethingWhenModelIsChanged(value: string): void {
    console.log({ value });
  }

  async asyncDoSomethingWhenModelIsChanged(value: string): Promise<void> {
    return new Promise<void>(resolve => {
      setTimeout(() => {
        console.log('async', { value });
        resolve();
      }, 1000);
    });
  }
} 

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

Spring Boot: Cannot access REST Controller on localhost (404)

SpringBoot developers recommend to locate your main application class in a root package above other classes. Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute. Detailed info But be sure that the custom root package exists.

Git Clone from GitHub over https with two-factor authentication

Find out how to fix this here:

https://github.com/blog/1614-two-factor-authentication#how-does-it-work-for-command-line-git

How does it work for command-line Git?

If you are using SSH for Git authentication, rest easy: you don't need to do anything. If you are using HTTPS Git, instead of entering your password, enter a personal access token. These can be created by going to your personal access tokens page.

PHP: Call to undefined function: simplexml_load_string()

I think it can be something like in this Post: Class 'SimpleXMLElement' not found on puphpet PHP 5.6 So maybe you could install/activate

php-xml or php-simplexml

Do not forget to activate the libraries in the php.ini file. (like the top comment)

ionic build Android | error: No installed build tools found. Please install the Android build tools

Mac IOS

Edit ~/.bash_profile by using vi or other shell editor

vi ~/.bash_profile

Add the following lines:

export ANDROID_HOME=~/Library/Android/sdk
export PATH=${PATH}:~/Software/android-sdk-macosx/tools:~/Software/android-sdk-macosx/platform-tools"

(save the file, and exit) load those updated env variables to the current shell env:

. ~/.bash_profile
  • If from some reason you have an old version of the build tools, you can update them from the android development studio:
  • Configure --> SDK Manager --> select "Android SDK Build-Tools
  • Check the "Show Package details"
  • review the versions of this package, update if needed

How to subscribe to an event on a service in Angular2?

Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

Cordova - Error code 1 for command | Command failed for

I found answer myself; and if someone will face same issue, i hope my solution will work for them as well.

  • Downgrade NodeJs to 0.10.36
  • Upgrade Android SDK 22

How does the class_weight parameter in scikit-learn work?

The first answer is good for understanding how it works. But I wanted to understand how I should be using it in practice.

SUMMARY

  • for moderately imbalanced data WITHOUT noise, there is not much of a difference in applying class weights
  • for moderately imbalanced data WITH noise and strongly imbalanced, it is better to apply class weights
  • param class_weight="balanced" works decent in the absence of you wanting to optimize manually
  • with class_weight="balanced" you capture more true events (higher TRUE recall) but also you are more likely to get false alerts (lower TRUE precision)
    • as a result, the total % TRUE might be higher than actual because of all the false positives
    • AUC might misguide you here if the false alarms are an issue
  • no need to change decision threshold to the imbalance %, even for strong imbalance, ok to keep 0.5 (or somewhere around that depending on what you need)

NB

The result might differ when using RF or GBM. sklearn does not have class_weight="balanced" for GBM but lightgbm has LGBMClassifier(is_unbalance=False)

CODE

# scikit-learn==0.21.3
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, classification_report
import numpy as np
import pandas as pd

# case: moderate imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.8]) #,flip_y=0.1,class_sep=0.5)
np.mean(y) # 0.2

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.184
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X).mean() # 0.296 => seems to make things worse?
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.292 => seems to make things worse?

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.83
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X)) # 0.86 => about the same
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.86 => about the same

# case: strong imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.95])
np.mean(y) # 0.06

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.02
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X).mean() # 0.25 => huh??
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.22 => huh??
(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).mean() # same as last

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.64
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X)) # 0.84 => much better
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.85 => similar to manual
roc_auc_score(y,(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).astype(int)) # same as last

print(classification_report(y,LogisticRegression(C=1e9).fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True,normalize='index') # few prediced TRUE with only 28% TRUE recall and 86% TRUE precision so 6%*28%~=2%

print(classification_report(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True,normalize='index') # 88% TRUE recall but also lot of false positives with only 23% TRUE precision, making total predicted % TRUE > actual % TRUE

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

If you don't want to use

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>(...)</version>
</parent>

as a parent POM, you may use the

mvn org.springframework.boot:spring-boot-maven-plugin:run

command instead.

How to customize the configuration file of the official PostgreSQL Docker image?

With Docker Compose

When working with Docker Compose, you can use command: postgres -c option=value in your docker-compose.yml to configure Postgres.

For example, this makes Postgres log to a file:

command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs

Adapting Vojtech Vitek's answer, you can use

command: postgres -c config_file=/etc/postgresql.conf

to change the config file Postgres will use. You'd mount your custom config file with a volume:

volumes:
   - ./customPostgresql.conf:/etc/postgresql.conf

Here's the docker-compose.yml of my application, showing how to configure Postgres:

# Start the app using docker-compose pull && docker-compose up to make sure you have the latest image
version: '2.1'
services:
  myApp:
    image: registry.gitlab.com/bullbytes/myApp:latest
    networks:
      - myApp-network
  db:
     image: postgres:9.6.1
     # Make Postgres log to a file.
     # More on logging with Postgres: https://www.postgresql.org/docs/current/static/runtime-config-logging.html
     command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs
     environment:
       # Provide the password via an environment variable. If the variable is unset or empty, use a default password
       - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-4WXUms893U6j4GE&Hvk3S*hqcqebFgo!vZi}
     # If on a non-Linux OS, make sure you share the drive used here. Go to Docker's settings -> Shared Drives
     volumes:
       # Persist the data between container invocations
       - postgresVolume:/var/lib/postgresql/data
       - ./logs:/logs
     networks:
       myApp-network:
         # Our application can communicate with the database using this hostname
         aliases:
           - postgresForMyApp
networks:
  myApp-network:
    driver: bridge
# Creates a named volume to persist our data. When on a non-Linux OS, the volume's data will be in the Docker VM
# (e.g., MobyLinuxVM) in /var/lib/docker/volumes/
volumes:
  postgresVolume:

Permission to write to the log directory

Note that when on Linux, the log directory on the host must have the right permissions. Otherwise you'll get the slightly misleading error

FATAL: could not open log file "/logs/postgresql-2017-02-04_115222.log": Permission denied

I say misleading, since the error message suggests that the directory in the container has the wrong permission, when in reality the directory on the host doesn't permit writing.

To fix this, I set the correct permissions on the host using

chgroup ./logs docker && chmod 770 ./logs

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

Include import androidx.appcompat.app.AppCompatActivity; in your MainActivity.java with other import statements. This would look like: enter image description here

this resolved my issue

How to inject a Map using the @Value Spring Annotation?

Here is how we did it. Two sample classes as follow:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
@EnableKafka
@Configuration
@EnableConfigurationProperties(KafkaConsumerProperties.class)
public class KafkaContainerConfig {

    @Autowired
    protected KafkaConsumerProperties kafkaConsumerProperties;

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(kafkaConsumerProperties.getKafkaConsumerConfig());
    }
...

@Configuration
@ConfigurationProperties
public class KafkaConsumerProperties {
    protected Map<String, Object> kafkaConsumerConfig = new HashMap<>();

    @ConfigurationProperties("kafkaConsumerConfig")
    public Map<String, Object> getKafkaConsumerConfig() {
        return (kafkaConsumerConfig);
    }
...

To provide the kafkaConsumer config from a properties file, you can use: mapname[key]=value

//application.properties
kafkaConsumerConfig[bootstrap.servers]=localhost:9092, localhost:9093, localhost:9094
kafkaConsumerConfig[group.id]=test-consumer-group-local
kafkaConsumerConfig[value.deserializer]=org.apache.kafka.common.serialization.StringDeserializer
kafkaConsumerConfig[key.deserializer=org.apache.kafka.common.serialization.StringDeserializer

To provide the kafkaConsumer config from a yaml file, you can use "[key]": value In application.yml file:

kafkaConsumerConfig:
  "[bootstrap.servers]": localhost:9092, localhost:9093, localhost:9094
  "[group.id]": test-consumer-group-local
  "[value.deserializer]": org.apache.kafka.common.serialization.StringDeserializer
  "[key.deserializer]": org.apache.kafka.common.serialization.StringDeserializer

Docker error : no space left on device

Don't just run the docker prune command. It will delete all the docker networks, containers, and images. So you might end up losing the important data as well.

The error shows that "No space left on device" so we just need to free up some space.

The easiest way to free some space is to remove dangling images.

When the old created images are not being used those images are referred to as dangling images or there are some cache images as well which you can remove.

Use the below commands. To list all dangling images image id.

docker images -f "dangling=true" -q

to remove the images by image id.

docker rmi IMAGE_ID

This way you can free up some space and start hacking with docker again :)

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

In my case there was problem in URL. I've use https://example.com - but they ensure 'www.' - so when i switched to https://www.example.com everything was ok. The proper header was sent 'Host: www.example.com'.

You can try make a request in firefox brwoser, persist it and copy as cURL - that how I've found it.

Callback to a Fragment from a DialogFragment

I followed this simple steps to do this stuff.

  1. Create interface like DialogFragmentCallbackInterface with some method like callBackMethod(Object data). Which you would calling to pass data.
  2. Now you can implement DialogFragmentCallbackInterface interface in your fragment like MyFragment implements DialogFragmentCallbackInterface
  3. At time of DialogFragment creation set your invoking fragment MyFragment as target fragment who created DialogFragment use myDialogFragment.setTargetFragment(this, 0) check setTargetFragment (Fragment fragment, int requestCode)

    MyDialogFragment dialogFrag = new MyDialogFragment();
    dialogFrag.setTargetFragment(this, 1); 
    
  4. Get your target fragment object into your DialogFragment by calling getTargetFragment() and cast it to DialogFragmentCallbackInterface.Now you can use this interface to send data to your fragment.

    DialogFragmentCallbackInterface callback = 
               (DialogFragmentCallbackInterface) getTargetFragment();
    callback.callBackMethod(Object data);
    

    That's it all done! just make sure you have implemented this interface in your fragment.

How do I replace multiple spaces with a single space in C#?

myString = Regex.Replace(myString, " {2,}", " ");

'module' object has no attribute 'DataFrame'

Please make sure that your file name should not be panda.py or pd.py. Also, make sure that panda is there in your Lib/site-packages directory, if not that you need to install panda using below command line:

pip install pandas

if you work with proxy then try calling below in command prompt:

python.exe -m pip install pandas --proxy="YOUR_PROXY_IP:PORT"

IIS7 folder permissions for web application

Running IIS 7.5, I had luck adding permissions for the local computer user IUSR. The app pool user didn't work.

How to get height and width of device display in angular2 using typescript?

You may use the typescript getter method for this scenario. Like this

public get height() {
  return window.innerHeight;
}

public get width() {
  return window.innerWidth;
}

And use that in template like this:

<section [ngClass]="{ 'desktop-view': width >= 768, 'mobile-view': width < 768 
}"></section>

Print the value

console.log(this.height, this.width);

You won't need any event handler to check for resizing of window, this method will check for size every time automatically.

ASP.NET MVC: No parameterless constructor defined for this object

I got the same error when:

Using a custom ModelView, both Actions (GET and POST) were passing the ModelView that contained two objects:

public ActionResult Add(int? categoryID)
{
    ...
    ProductViewModel productViewModel = new ProductViewModel(
            product,
            rootCategories
            );
    return View(productViewModel); 
}

And the POST also accepting the same model view:

[HttpPost]
[ValidateInput(false)]
public ActionResult Add(ProductModelView productModelView)
{...}

Problem was the View received the ModelView (needed both product and list of categories info), but after submitted was returning only the Product object, but as the POST Add expected a ProductModelView it passed a NULL but then the ProductModelView only constructor needed two parameters(Product, RootCategories), then it tried to find another constructor with no parameters for this NULL case then fails with "no parameterles..."

So, fixing the POST Add as follows correct the problem:

[HttpPost]
[ValidateInput(false)]
public ActionResult Add(Product product)
{...}

Hope this can help somebody (I spent almost half day to find this out!).

Search for exact match of string in excel row using VBA Macro

Never mind, I found the answer.

This will do the trick.

Dim colIndex As Long    
colIndex = Application.Match(colName, Range(Cells(rowIndex, 1), Cells(rowIndex, 100)), 0)

Delete files older than 10 days using shell script in Unix

Just spicing up the shell script above to delete older files but with logging and calculation of elapsed time

#!/bin/bash

path="/data/backuplog/"
timestamp=$(date +%Y%m%d_%H%M%S)    
filename=log_$timestamp.txt    
log=$path$filename
days=7

START_TIME=$(date +%s)

find $path -maxdepth 1 -name "*.txt"  -type f -mtime +$days  -print -delete >> $log

echo "Backup:: Script Start -- $(date +%Y%m%d_%H%M)" >> $log


... code for backup ...or any other operation .... >> $log


END_TIME=$(date +%s)

ELAPSED_TIME=$(( $END_TIME - $START_TIME ))


echo "Backup :: Script End -- $(date +%Y%m%d_%H%M)" >> $log
echo "Elapsed Time ::  $(date -d 00:00:$ELAPSED_TIME +%Hh:%Mm:%Ss) "  >> $log

The code adds a few things.

  • log files named with a timestamp
  • log folder specified
  • find looks for *.txt files only in the log folder
  • type f ensures you only deletes files
  • maxdepth 1 ensures you dont enter subfolders
  • log files older than 7 days are deleted ( assuming this is for a backup log)
  • notes the start / end time
  • calculates the elapsed time for the backup operation...

Note: to test the code, just use -print instead of -print -delete. But do check your path carefully though.

Note: Do ensure your server time is set correctly via date - setup timezone/ntp correctly . Additionally check file times with 'stat filename'

Note: mtime can be replaced with mmin for better control as mtime discards all fractions (older than 2 days (+2 days) actually means 3 days ) when it deals with getting the timestamps of files in the context of days

-mtime +$days  --->  -mmin  +$((60*24*$days))

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

  1. First of all, there is no difference between View.OnClickListener and OnClickListener. If you just use View.OnClickListener directly, then you don't need to write-

    import android.view.View.OnClickListener

  2. You set an OnClickListener instance (e.g. myListener named object)as the listener to a view via setOnclickListener(). When a click event is fired, that myListener gets notified and it's onClick(View view) method is called. Thats where we do our own task. Hope this helps you.

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

There are some good answers here already. But it's worthwhile to drive home the difference in parallelism offered:

  • success() returns the original promise
  • then() returns a new promise

The difference is then() drives sequential operations, since each call returns a new promise.

$http.get(/*...*/).
  then(function seqFunc1(response){/*...*/}).
  then(function seqFunc2(response){/*...*/})
  1. $http.get()
  2. seqFunc1()
  3. seqFunc2()

success() drives parallel operations, since handlers are chained on the same promise.

$http(/*...*/).
  success(function parFunc1(data){/*...*/}).
  success(function parFunc2(data){/*...*/})
  1. $http.get()
  2. parFunc1(), parFunc2() in parallel

How do I change the text of a span element using JavaScript?

You can do

 document.querySelector("[Span]").textContent = "content_to_display"; 

How many concurrent requests does a single Flask process receive?

No- you can definitely handle more than that.

Its important to remember that deep deep down, assuming you are running a single core machine, the CPU really only runs one instruction* at a time.

Namely, the CPU can only execute a very limited set of instructions, and it can't execute more than one instruction per clock tick (many instructions even take more than 1 tick).

Therefore, most concurrency we talk about in computer science is software concurrency. In other words, there are layers of software implementation that abstract the bottom level CPU from us and make us think we are running code concurrently.

These "things" can be processes, which are units of code that get run concurrently in the sense that each process thinks its running in its own world with its own, non-shared memory.

Another example is threads, which are units of code inside processes that allow concurrency as well.

The reason your 4 worker processes will be able to handle more than 4 requests is that they will fire off threads to handle more and more requests.

The actual request limit depends on HTTP server chosen, I/O, OS, hardware, network connection etc.

Good luck!

*instructions are the very basic commands the CPU can run. examples - add two numbers, jump from one instruction to another

How to convert Nonetype to int or string?

This can happen if you forget to return a value from a function: it then returns None. Look at all places where you are assigning to that variable, and see if one of them is a function call where the function lacks a return statement.

Display a float with two decimal places in Python

String formatting:

print "%.2f" % 5

TypeError: 'str' object is not callable (Python)

FWIW I just hit this on a slightly different use case. I scoured and scoured my code looking for where I might've used a 'str' variable, but could not find it. I started to suspect that maybe one of the modules I imported was the culprit... but alas, it was a missing '%' character in a formatted print statement.

Here's an example:

x=5
y=6
print("x as a string is: %s.  y as a string is: %s" (str(x) , str(y)) )

This will result in the output:

   TypeError: 'str' object is not callable

The correction is:

x=5
y=6
print("x as a string is: %s.  y as a string is: %s" % (str(x) , str(y)) )

Resulting in our expected output:

x as a string is: 5. y as a string is: 6

Android: How to change CheckBox size?

If you want to add a custom image to checkbox then set button to null and just add background to checkbox that's solve

 <CheckBox
    android:layout_width="22dp"
    android:layout_height="22dp"
    android:layout_marginLeft="-10dp"
    android:button="@null"
    android:background="@drawable/memory_selector"/>

iOS9 Untrusted Enterprise Developer with no option to trust

In iOS 9.1 and lower, go to Settings - General - Profiles - tap on your Profile - tap on Trust button.

In iOS 9.2+ & iOS 11+ go to: Settings - General - Profiles & Device Management - tap on your Profile - tap on Trust button.

In iOS 10+, go to: Settings - General - Device Management - tap on your Profile - tap on Trust button.

JavaScript Infinitely Looping slideshow with delays?

The correct approach is to use a single timer. Using setInterval, you can achieve what you want as follows:

window.onload = function start() {
    slide();
}
function slide() {
    var num = 0, style = document.getElementById('container').style;
    window.setInterval(function () {
        // increase by num 1, reset to 0 at 4
        num = (num + 1) % 4;

        // -600 * 1 = -600, -600 * 2 = -1200, etc 
        style.marginLeft = (-600 * num) + "px"; 
    }, 3000); // repeat forever, polling every 3 seconds
}

How can I implement the Iterable interface?

First off:

public class ProfileCollection implements Iterable<Profile> {

Second:

return m_Profiles.get(m_ActiveProfile);

How to change color of SVG image using CSS (jQuery SVG image replacement)?

Alternatively you could use CSS mask, granted browser support isn't good but you could use a fallback

.frame {
    background: blue;
    -webkit-mask: url(image.svg) center / contain no-repeat;
}

cannot resolve symbol javafx.application in IntelliJ Idea IDE

This should be your perfect solution. Try and enjoy. If some command does not work properly that means if you get any error, try to solve it yourself. I have given you the main thing you need. If your application is in a different location, or your system architecture is different, solve it yourself. It's very easy to do it. Just follow my given solution.

Step 0:

sudo apt-get install openjdk-8-jre

Step: 1

sudo apt-get install openjfx

Step 2:

sudo cp /usr/share/java/openjfx/jre/lib/ext/* /usr/lib/jvm/java-1.8.0-openjdk-amd64/lib

Step 3:

sudo cp /usr/share/java/openjfx/lib/* /usr/lib/jvm/java-1.8.0-openjdk-amd64/lib

Step 4:

sudo chmod 777 -R /usr/lib/jvm/java-1.8.0-openjdk-amd64

now open a new project or rebuild your project. Good luck.

Google Play app description formatting

Another alternative to cut, copy and paste emojis is:

https://emojicut.com/

Initialize value of 'var' in C# to null

var variables still have a type - and the compiler error message says this type must be established during the declaration.

The specific request (assigning an initial null value) can be done, but I don't recommend it. It doesn't provide an advantage here (as the type must still be specified) and it could be viewed as making the code less readable:

var x = (String)null;

Which is still "type inferred" and equivalent to:

String x = null;

The compiler will not accept var x = null because it doesn't associate the null with any type - not even Object. Using the above approach, var x = (Object)null would "work" although it is of questionable usefulness.

Generally, when I can't use var's type inference correctly then

  1. I am at a place where it's best to declare the variable explicitly; or
  2. I should rewrite the code such that a valid value (with an established type) is assigned during the declaration.

The second approach can be done by moving code into methods or functions.

Can I use a :before or :after pseudo-element on an input field?

According to a note in the CSS 2.1 spec, the specification “does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.” Although input is not really a replaced element any more, the basic situation has not changed: the effect of :before and :after on it in unspecified and generally has no effect.

The solution is to find a different approach to the problem you are trying to address this way. Putting generated content into a text input control would be very misleading: to the user, it would appear to be part of the initial value in the control, but it cannot be modified – so it would appear to be something forced at the start of the control, but yet it would not be submitted as part of form data.

How to set the component size with GridLayout? Is there a better way?

An alternative to other layouts, might be to put your panel with the GridLayout, inside another panel that is a FlowLayout. That way your spacing will be intact but will not expand across the entire available space.

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Only using Session.Clear() when a user logs out can pose a security hole. As the session is still valid as far as the Web Server is concerned. It is then a reasonably trivial matter to sniff, and grab the session Id, and hijack that session.

For this reason, when logging a user out it would be safer and more sensible to use Session.Abandon() so that the session is destroyed, and a new session created (even though the logout UI page would be part of the new session, the new session would not have any of the users details in it and hijacking the new session would be equivalent to having a fresh session, hence it would be mute).

How to hide a div element depending on Model value? MVC

The below code should apply different CSS classes based on your Model's CanEdit Property value .

<div class="@(Model.CanEdit?"visible-item":"hidden-item")">Some links</div>

But if it is something important like Edit/Delete links, you shouldn't be simply hiding,because people can update the css class/HTML markup in their browser and get access to your important link. Instead you should be simply not Rendering the important stuff to the browser.

@if(Model.CanEdit)
{
  <div>Edit/Delete link goes here</div>
}

await is only valid in async function

I had the same problem and the following block of code was giving the same error message:

repositories.forEach( repo => {
        const commits = await getCommits(repo);
        displayCommit(commits);
});

The problem is that the method getCommits() was async but I was passing it the argument repo which was also produced by a Promise. So, I had to add the word async to it like this: async(repo) and it started working:

repositories.forEach( async(repo) => {
        const commits = await getCommits(repo);
        displayCommit(commits);
});

Http post and get request in angular 6

You can do a post/get using a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Traditional approach

In the traditional approach you return Observable<HttpResponse<T>> from Service API. This is tied to HttpResponse.

With this approach you have to use .subscribe(x => ...) in the rest of your code.

This creates a tight coupling between the http layer and the rest of your code.

Strongly-typed callback approach

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models


export class SearchModel {
    code: string;
}

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { SearchModel, RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.post<SearchModel, RacingResponse>(url, model, 
                                                      ResponseType.IObservable, success, 
                                                      ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the searchRaceInfo API called as shown below.

  search() {    


    this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,
                                                  error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

String date to xmlgregoriancalendar conversion

For me the most elegant solution is this one:

XMLGregorianCalendar result = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar("2014-01-07");

Using Java 8.

Extended example:

XMLGregorianCalendar result = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar("2014-01-07");
System.out.println(result.getDay());
System.out.println(result.getMonth());
System.out.println(result.getYear());

This prints out:

7
1
2014

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

Yes or No confirm box using jQuery

I've used these codes:

HTML:

<a id="delete-button">Delete</a>

jQuery:

<script>
$("#delete-button").click(function(){
    if(confirm("Are you sure you want to delete this?")){
        $("#delete-button").attr("href", "query.php?ACTION=delete&ID='1'");
    }
    else{
        return false;
    }
});
</script>

These codes works for me, but I'm not really sure if this is proper. What do you think?

Do I cast the result of malloc?

The returned type is void*, which can be cast to the desired type of data pointer in order to be dereferenceable.

Get a substring of a char*

char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';

Job done :)

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

Depending which date picker for Bootstrap you're using, this is a known bug currently with this one:

Code: https://github.com/uxsolutions/bootstrap-datepicker

(Docs: https://bootstrap-datepicker.readthedocs.io/en/latest/)

Here's a bug report:

https://github.com/uxsolutions/bootstrap-datepicker/issues/1957

If anyone has a solution/workaround for this one, would be great if you'd include it.

git stash blunder: git stash pop and ended up with merge conflicts

Note that Git 2.5 (Q2 2015) a future Git might try to make that scenario impossible.

See commit ed178ef by Jeff King (peff), 22 Apr 2015.
(Merged by Junio C Hamano -- gitster -- in commit 05c3967, 19 May 2015)

Note: This has been reverted. See below.

stash: require a clean index to apply/pop

Problem

If you have staged contents in your index and run "stash apply/pop", we may hit a conflict and put new entries into the index.
Recovering to your original state is difficult at that point, because tools like "git reset --keep" will blow away anything staged.

In other words:

"git stash pop/apply" forgot to make sure that not just the working tree is clean but also the index is clean.
The latter is important as a stash application can conflict and the index will be used for conflict resolution.

Solution

We can make this safer by refusing to apply when there are staged changes.

That means if there were merges before because of applying a stash on modified files (added but not committed), now they would not be any merges because the stash apply/pop would stop immediately with:

Cannot apply stash: Your index contains uncommitted changes.

Forcing you to commit the changes means that, in case of merges, you can easily restore the initial state( before git stash apply/pop) with a git reset --hard.


See commit 1937610 (15 Jun 2015), and commit ed178ef (22 Apr 2015) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit bfb539b, 24 Jun 2015)

That commit was an attempt to improve the safety of applying a stash, because the application process may create conflicted index entries, after which it is hard to restore the original index state.

Unfortunately, this hurts some common workflows around "git stash -k", like:

git add -p       ;# (1) stage set of proposed changes
git stash -k     ;# (2) get rid of everything else
make test        ;# (3) make sure proposal is reasonable
git stash apply  ;# (4) restore original working tree

If you "git commit" between steps (3) and (4), then this just works. However, if these steps are part of a pre-commit hook, you don't have that opportunity (you have to restore the original state regardless of whether the tests passed or failed).

Delete from a table based on date

This is pretty vague. Do you mean like in SQL:

DELETE FROM myTable
WHERE dateColumn < '2007'

What are the differences between normal and slim package of jquery?

Looking at the code I found the following differences between jquery.js and jquery.slim.js:

In the jquery.slim.js, the following features are removed:

  1. jQuery.fn.extend
  2. jquery.fn.load
  3. jquery.each // Attach a bunch of functions for handling common AJAX events
  4. jQuery.expr.filters.animated
  5. ajax settings like jQuery.ajaxSettings.xhr, jQuery.ajaxPrefilter, jQuery.ajaxSetup, jQuery.ajaxPrefilter, jQuery.ajaxTransport, jQuery.ajaxSetup
  6. xml parsing like jQuery.parseXML,
  7. animation effects like jQuery.easing, jQuery.Animation, jQuery.speed

Difference between java.exe and javaw.exe

java.exe is the console app while javaw.exe is windows app (console-less). You can't have Console with javaw.exe.

React native ERROR Packager can't listen on port 8081

On a mac, run the following command to find id of the process which is using port 8081
sudo lsof -i :8081
Then run the following to terminate process:
kill -9 23583

Here is how it will look like enter image description here

How to rebuild docker container in docker-compose.yml?

For me it only fetched new dependencies from Docker Hub with both --no-cache and --pull (which are available for docker-compose build.

# other steps before rebuild
docker-compose build --no-cache --pull nginx # rebuild nginx
# other steps after rebuild, e.g. up (see other answers)

Create a BufferedImage from file and make it TYPE_INT_ARGB

try {
    File img = new File("somefile.png");
    BufferedImage image = ImageIO.read(img ); 
    System.out.println(image);
} catch (IOException e) { 
    e.printStackTrace(); 
}

Example output for my image file:

BufferedImage@5d391d: type = 5 ColorModel: #pixelBits = 24 
numComponents = 3 color 
space = java.awt.color.ICC_ColorSpace@50a649 
transparency = 1 
has alpha = false 
isAlphaPre = false 
ByteInterleavedRaster: 
width = 800 
height = 600 
#numDataElements 3 
dataOff[0] = 2

You can run System.out.println(object); on just about any object and get some information about it.

Trying to use fetch and pass in mode: no-cors

If you are using Express as back-end you just have to install cors and import and use it in app.use(cors());. If it is not resolved then try switching ports. It will surely resolve after switching ports

There is already an object named in the database

In my case, the issue was in Seeder. I was calling _ctx.Database.EnsureCreated() inside of it and as far as I understood, the update database command has successfully executed, but then seeder tried to create database "second" time.

How to address:

  1. Do nut run update, just start application and call EnsureCreated(). Database will be created/updated
  2. Comment out or remove seeder.

Angular2 Routing with Hashtag to page anchor

Although Günter's answer is correct, it doesn't cover the "jump to" the anchor tag part.

Therefore, additionally to:

<a [routerLink]="['somepath']" fragment="Test">Jump to 'Test' anchor </a>
this._router.navigate( ['/somepath', id ], {fragment: 'test'});

... in the component (parent) where you need a "jump to" behavior, add:

import { Router, NavigationEnd } from '@angular/router';

class MyAppComponent {
  constructor(router: Router) {

    router.events.subscribe(s => {
      if (s instanceof NavigationEnd) {
        const tree = router.parseUrl(router.url);
        if (tree.fragment) {
          const element = document.querySelector("#" + tree.fragment);
          if (element) { element.scrollIntoView(true); }
        }
      }
    });

  }
}

Please note that this is a workaround! Follow this github issue for future updates. Credits to Victor Savkin for providing the solution!

Choose folders to be ignored during search in VS Code

Make sure the 'Use Exclude Settings and Ignore Files' cog is selected enter image description here

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

I had same problem while trying to install cucumber gem. However I noticed that bundler gem already installed with ruby 2.0. I created a Gemfile.rb in the project folder with required gems and followed this steps

  1. Navigate to project folder
  2. Type bundle install

All the required gems installed.

Event listener for when element becomes visible?

var targetNode = document.getElementById('elementId');
var observer = new MutationObserver(function(){
    if(targetNode.style.display != 'none'){
        // doSomething
    }
});
observer.observe(targetNode, { attributes: true, childList: true });

I might be a little late, but you could just use the MutationObserver to observe any changes on the desired element. If any change occurs, you'll just have to check if the element is displayed.

Difference between Math.Floor() and Math.Truncate()

Math.floor() will always round down ie., it returns LESSER integer. While round() will return the NEAREST integer

math.floor()

Returns the largest integer less than or equal to the specified number.

math.truncate()

Calculates the integral part of a number.

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

I found that my version of Xcode was too outdated and installing command-line-tools wasn't helping. Here's what I did:

  • I completely uninstalled the outdated XCode
  • I reinstalled the most recent XCode from the app store
  • That was all. Git was restored.

Where is JAVA_HOME on macOS Mojave (10.14) to Lion (10.7)?

This answer is related to Mountain Lion and not Lion. I needed to do this for the AWS Command Line Tools. According to the AWS docs, running which java returns /usr/bin/java.

So, I set JAVA_HOME=/usr in my .bashrc.

Apparently, /usr/bin/java is a symbolic link to /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java which makes it all work.

Update

As mentioned in the comment below, this JAVA_HOME value is not an ideal solution when the JAVA_HOME environment variable is to be used by things other than the AWS Command Line Tools. It works fine for the AWS Command Line Tools, though, as given in their docs.

How return error message in spring mvc @Controller

return new ResponseEntity<>(GenericResponseBean.newGenericError("Error during the calling the service", -1L), HttpStatus.EXPECTATION_FAILED);

What's the difference between abstraction and encapsulation?

Developer A, who is inherently utilising the concept of abstraction will use a module/library function/widget, concerned only with what it does (and what it will be used for) but not how it does it. The interface of that module/library function/widget (the 'levers' the Developer A is allowed to pull/push) is the personification of that abstraction.

Developer B, who is seeking to create such a module/function/widget will utilise the concept of encapsulation to ensure Developer A (and any other developer who uses the widget) can take advantage of the resulting abstraction. Developer B is most certainly concerned with how the widget does what it does.

TLDR;

  • Abstraction - I care about what something does, but not how it does it.
  • Encapsulation - I care about how something does what it does such that others only need to care about what it does.

(As a loose generalisation, to abstract something, you must encapsulate something else. And by encapsulating something, you have created an abstraction.)

How do I save a String to a text file using Java?

import java.io.*;

private void stringToFile( String text, String fileName )
 {
 try
 {
    File file = new File( fileName );

    // if file doesnt exists, then create it 
    if ( ! file.exists( ) )
    {
        file.createNewFile( );
    }

    FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
    BufferedWriter bw = new BufferedWriter( fw );
    bw.write( text );
    bw.close( );
    //System.out.println("Done writing to " + fileName); //For testing 
 }
 catch( IOException e )
 {
 System.out.println("Error: " + e);
 e.printStackTrace( );
 }
} //End method stringToFile

You can insert this method into your classes. If you are using this method in a class with a main method, change this class to static by adding the static key word. Either way you will need to import java.io.* to make it work otherwise File, FileWriter and BufferedWriter will not be recognized.

String representation of an Enum

If you've come here looking to implement a simple "Enum" but whose values are strings instead of ints, here is the simplest solution:

    public sealed class MetricValueList
    {
        public static readonly string Brand = "A4082457-D467-E111-98DC-0026B9010912";
        public static readonly string Name = "B5B5E167-D467-E111-98DC-0026B9010912";
    }

Implementation:

var someStringVariable = MetricValueList.Brand;

Disable a Button

in order for this to work:

yourButton.isEnabled = false

you need to create an outlet in addition to your UI button.

Cannot find firefox binary in PATH. Make sure firefox is installed

I have also face same issue on Windows 10-64 bit OS.

When I am installed firefox on my PC its installed location is "C:\Program Files\Mozilla Firefox\firefox.exe" instead of "C:\Program Files (x86)\Mozilla Firefox", because OS is 64 bit,

So I just copy & paste "Mozilla Firefox" folder in "C:\Program Files (x86)" folder and execute selenium scripts, its work for me.

How to save and extract session data in codeigniter

In CodeIgniter you can store your session value as single or also in array format as below:

If you want store any user’s data in session like userId, userName, userContact etc, then you should store in array:

<?php
$this->load->library('session');
$this->session->set_userdata(array(
'userId'  => $user->userId,
'userName' => $user->userName,
'userContact '  => $user->userContact 
)); 
?>

Get in details with Example Demo :

http://devgambit.com/how-to-store-and-get-session-value-in-codeigniter/

How to get ASCII value of string in C#

Or in LINQ:

string value = "9quali52ty3";
var ascii_values = value.Select(x => (int)x);
var as_hex = value.Select(x => ((int)x).ToString("X02"));

How to configure Fiddler to listen to localhost?

Go to proxy settings in Firefox and choose "Use system proxy" but be sure to check if there is no exception for localhost in "no proxy for" field.

enter image description here enter image description here

JavaScript: Difference between .forEach() and .map()

  • Array.forEach “executes a provided function once per array element.”

  • Array.map “creates a new array with the results of calling a provided function on every element in this array.”

So, forEach doesn’t actually return anything. It just calls the function for each array element and then it’s done. So whatever you return within that called function is simply discarded.

On the other hand, map will similarly call the function for each array element but instead of discarding its return value, it will capture it and build a new array of those return values.

This also means that you could use map wherever you are using forEach but you still shouldn’t do that so you don’t collect the return values without any purpose. It’s just more efficient to not collect them if you don’t need them.

Which method performs better: .Any() vs .Count() > 0?

If you are starting with something that has a .Length or .Count (such as ICollection<T>, IList<T>, List<T>, etc) - then this will be the fastest option, since it doesn't need to go through the GetEnumerator()/MoveNext()/Dispose() sequence required by Any() to check for a non-empty IEnumerable<T> sequence.

For just IEnumerable<T>, then Any() will generally be quicker, as it only has to look at one iteration. However, note that the LINQ-to-Objects implementation of Count() does check for ICollection<T> (using .Count as an optimisation) - so if your underlying data-source is directly a list/collection, there won't be a huge difference. Don't ask me why it doesn't use the non-generic ICollection...

Of course, if you have used LINQ to filter it etc (Where etc), you will have an iterator-block based sequence, and so this ICollection<T> optimisation is useless.

In general with IEnumerable<T> : stick with Any() ;-p

Simplest way to do a recursive self-join?

WITH    q AS 
        (
        SELECT  *
        FROM    mytable
        WHERE   ParentID IS NULL -- this condition defines the ultimate ancestors in your chain, change it as appropriate
        UNION ALL
        SELECT  m.*
        FROM    mytable m
        JOIN    q
        ON      m.parentID = q.PersonID
        )
SELECT  *
FROM    q

By adding the ordering condition, you can preserve the tree order:

WITH    q AS 
        (
        SELECT  m.*, CAST(ROW_NUMBER() OVER (ORDER BY m.PersonId) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN AS bc
        FROM    mytable m
        WHERE   ParentID IS NULL
        UNION ALL
        SELECT  m.*,  q.bc + '.' + CAST(ROW_NUMBER() OVER (PARTITION BY m.ParentID ORDER BY m.PersonID) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN
        FROM    mytable m
        JOIN    q
        ON      m.parentID = q.PersonID
        )
SELECT  *
FROM    q
ORDER BY
        bc

By changing the ORDER BY condition you can change the ordering of the siblings.

How to cancel/abort jQuery AJAX request?

You should also check for readyState 0. Because when you use xhr.abort() this function set readyState to 0 in this object, and your if check will be always true - readyState !=4

$(document).ready(
    var xhr;

    var fn = function(){
        if(xhr && xhr.readyState != 4 && xhr.readyState != 0){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
); 

Getting "type or namespace name could not be found" but everything seems ok?

I encountered this problem when upgrading existing projects from VS2008 to VS2012. I found that two projects (the only two that I created) were targeting different .Net Frameworks (3.5 and 4.0). I resolved this on the Application tab of the projects by making sure that both projects had ".NET Framework 4" in the Target Framework box.

How do I hide an element when printing a web page?

The accepted answer by diodus is not working for some if not all of us. I could not still hide my Print this button from going out on to paper.

The little adjustment by Clint Pachl of calling css file by adding on

      media="screen, print" 

and not just

      media="screen"

is solving this problem. So for clarity and because it is not easy to see Clint Pachl hidden additional help in comments. The user should include the ",print" in css file with the desired formating.

     <link rel="stylesheet" href="my_cssfile.css" media="screen, print"type="text/css">

and not the default media = "screen" only.

    <link rel="stylesheet" href="my_cssfile.css" media="screen" type="text/css">

That i think solves this problem for everyone.

Mockito: List Matchers with generics

Before Java 8 (versions 7 or 6) I use the new method ArgumentMatchers.anyList:

import static org.mockito.Mockito.*;
import org.mockito.ArgumentMatchers;

verify(mock, atLeastOnce()).process(ArgumentMatchers.<Bar>anyList());

How to scroll to an element inside a div?

You would have to find the position of the element in the DIV you want to scroll to, and set the scrollTop property.

divElem.scrollTop = 0;

Update:

Sample code to move up or down

  function move_up() {
    document.getElementById('divElem').scrollTop += 10;
  }

  function move_down() {
    document.getElementById('divElem').scrollTop -= 10;
  }

Formatting a number with exactly two decimals in JavaScript

_x000D_
_x000D_
parse = function (data) {_x000D_
       data = Math.round(data*Math.pow(10,2))/Math.pow(10,2);_x000D_
       if (data != null) {_x000D_
            var lastone = data.toString().split('').pop();_x000D_
            if (lastone != '.') {_x000D_
                 data = parseFloat(data);_x000D_
            }_x000D_
       }_x000D_
       return data;_x000D_
  };_x000D_
_x000D_
$('#result').html(parse(200)); // output 200_x000D_
$('#result1').html(parse(200.1)); // output 200.1_x000D_
$('#result2').html(parse(200.10)); // output 200.1_x000D_
$('#result3').html(parse(200.109)); // output 200.11
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<div id="result"></div>_x000D_
<div id="result1"></div>_x000D_
<div id="result2"></div>_x000D_
<div id="result3"></div>
_x000D_
_x000D_
_x000D_

How do I use reflection to call a generic method?

You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod:

MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);

For a static method, pass null as the first argument to Invoke. That's nothing to do with generic methods - it's just normal reflection.

As noted, a lot of this is simpler as of C# 4 using dynamic - if you can use type inference, of course. It doesn't help in cases where type inference isn't available, such as the exact example in the question.

How to create a Java cron job

You can use TimerTask for Cronjobs.

Main.java

public class Main{
   public static void main(String[] args){

     Timer t = new Timer();
     MyTask mTask = new MyTask();
     // This task is scheduled to run every 10 seconds

     t.scheduleAtFixedRate(mTask, 0, 10000);
   }

}

MyTask.java

class MyTask extends TimerTask{

   public MyTask(){
     //Some stuffs
   }

   @Override
   public void run() {
     System.out.println("Hi see you after 10 seconds");
   }

}

Alternative You can also use ScheduledExecutorService.

How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

Thanks for above answer , here is my jQuery code that is working now:

      $(".header-login-li").click(function(){
        activaTab('pane_login');                
      });

      $(".header-register-li").click(function(){
        activaTab('pane_reg');
        $("#reg_log_modal_header_text").css()
      });

      function activaTab(tab){
        $('.nav-tabs a[href="#' + tab + '"]').tab('show');
      };

close fxml window by code, javafx

  1. give your close button an fx:id, if you haven't yet: <Button fx:id="closeButton" onAction="#closeButtonAction">
  2. In your controller class:

    @FXML private javafx.scene.control.Button closeButton;
    
    @FXML
    private void closeButtonAction(){
        // get a handle to the stage
        Stage stage = (Stage) closeButton.getScene().getWindow();
        // do what you have to do
        stage.close();
    }
    

Using braces with dynamic variable names in PHP

I was in a position where I had 6 identical arrays and I needed to pick the right one depending on another variable and then assign values to it. In the case shown here $comp_cat was 'a' so I needed to pick my 'a' array ( I also of course had 'b' to 'f' arrays)

Note that the values for the position of the variable in the array go after the closing brace.

${'comp_cat_'.$comp_cat.'_arr'}[1][0] = "FRED BLOGGS";

${'comp_cat_'.$comp_cat.'_arr'}[1][1] = $file_tidy;

echo 'First array value is '.$comp_cat_a_arr[1][0].' and the second value is .$comp_cat_a_arr[1][1];

How do I wait for an asynchronously dispatched block to finish?

Trying to use a dispatch_semaphore. It should look something like this:

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

[object runSomeLongOperationAndDo:^{
    STAssert…

    dispatch_semaphore_signal(sema);
}];

if (![NSThread isMainThread]) {
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
} else {
    while (dispatch_semaphore_wait(sema, DISPATCH_TIME_NOW)) { 
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0]]; 
    }
}

This should behave correctly even if runSomeLongOperationAndDo: decides that the operation isn't actually long enough to merit threading and runs synchronously instead.

How to have git log show filenames like svn log -v

For full path names of changed files:

git log --name-only

For full path names and status of changed files:

git log --name-status

For abbreviated pathnames and a diffstat of changed files:

git log --stat

There's a lot more options, check out the docs.

How to link to a <div> on another page?

You simply combine the ideas of a link to another page, as with href=foo.html, and a link to an element on the same page, as with href=#bar, so that the fragment like #bar is written immediately after the URL that refers to another page:

<a href="foo.html#bar">Some nice link text</a>

The target is specified the same was as when linking inside one page, e.g.

<div id="bar">
<h2>Some heading</h2>
Some content
</div>

or (if you really want to link specifically to a heading only)

<h2 id="bar">Some heading</h2>

Iterating over ResultSet and adding its value in an ArrayList

If I've understood your problem correctly, there are two possible problems here:

  • resultset is null - I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.
  • The second problem is that resultset.getString(i++) will get columns 1,2,3 and so on from each subsequent row.

I think that the second point is probably your problem here.

Lets say you only had 1 row returned, as follows:

Col 1, Col 2, Col 3 
A    ,     B,     C

Your code as it stands would only get A - it wouldn't get the rest of the columns.

I suggest you change your code as follows:

ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>(); 
while (resultset.next()) {                      
    int i = 1;
    while(i <= numberOfColumns) {
        arrayList.add(resultset.getString(i++));
    }
    System.out.println(resultset.getString("Col 1"));
    System.out.println(resultset.getString("Col 2"));
    System.out.println(resultset.getString("Col 3"));                    
    System.out.println(resultset.getString("Col n"));
}

Edit:

To get the number of columns:

ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();

Object Library Not Registered When Adding Windows Common Controls 6.0

You can run the tool from Microsoft in this KB http://support.microsoft.com/default.aspx?scid=kb;en-us;Q195353 to fix the licensing issues for earlier ActiveX controls. This worked for me.

function declaration isn't a prototype

Try:

extern int testlib(void);

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Since the name is likely to change in future versions of Android (currently the latest is AppCompatActivity but it will probably change at some point), I believe a good thing to have is a class Activity that extends AppCompatActivity and then all your activities extend from that one. If tomorrow, they change the name to AppCompatActivity2 for instance you will have to change it just in one place.

storing user input in array

You're not actually going out after the values. You would need to gather them like this:

var title   = document.getElementById("title").value;
var name    = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;

You could put all of these in one array:

var myArray = [ title, name, tickets ];

Or many arrays:

var titleArr   = [ title ];
var nameArr    = [ name ];
var ticketsArr = [ tickets ];

Or, if the arrays already exist, you can use their .push() method to push new values onto it:

var titleArr = [];

function addTitle ( title ) {
  titleArr.push( title );
  console.log( "Titles: " + titleArr.join(", ") );
}

Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:

I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit

The new form follows:

<form>
  <h1>Please enter data</h1>
  <input id="title" type="text" />
  <input id="name" type="text" />
  <input id="tickets" type="text" />
  <input type="button" value="Save" onclick="insert()" />
  <input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>

There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).

I've also made some changes to your JavaScript. I start by creating three empty arrays:

var titles  = [];
var names   = [];
var tickets = [];

Now that we have these, we'll need references to our input fields.

var titleInput  = document.getElementById("title");
var nameInput   = document.getElementById("name");
var ticketInput = document.getElementById("tickets");

I'm also getting a reference to our message display box.

var messageBox  = document.getElementById("display");

The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.

Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.

function insert ( ) {
 titles.push( titleInput.value );
 names.push( nameInput.value );
 tickets.push( ticketInput.value );

 clearAndShow();
}

This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.

function clearAndShow () {
  titleInput.value = "";
  nameInput.value = "";
  ticketInput.value = "";

  messageBox.innerHTML = "";

  messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
  messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
  messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}

The final result can be used online at http://jsbin.com/ufanep/2/edit

Hash table runtime complexity (insert, search and delete)

Ideally, a hashtable is O(1). The problem is if two keys are not equal, however they result in the same hash.

For example, imagine the strings "it was the best of times it was the worst of times" and "Green Eggs and Ham" both resulted in a hash value of 123.

When the first string is inserted, it's put in bucket 123. When the second string is inserted, it would see that a value already exists for bucket 123. It would then compare the new value to the existing value, and see they are not equal. In this case, an array or linked list is created for that key. At this point, retrieving this value becomes O(n) as the hashtable needs to iterate through each value in that bucket to find the desired one.

For this reason, when using a hash table, it's important to use a key with a really good hash function that's both fast and doesn't often result in duplicate values for different objects.

Make sense?

Java Class.cast() vs. cast operator

It's always problematic and often misleading to try and translate constructs and concepts between languages. Casting is no exception. Particularly because Java is a dynamic language and C++ is somewhat different.

All casting in Java, no matter how you do it, is done at runtime. Type information is held at runtime. C++ is a bit more of a mix. You can cast a struct in C++ to another and it's merely a reinterpretation of the bytes that represent those structs. Java doesn't work that way.

Also generics in Java and C++ are vastly different. Don't concern yourself overly with how you do C++ things in Java. You need to learn how to do things the Java way.

Execute command on all files in a directory

I'm doing this on my raspberry pi from the command line by running:

for i in *;do omxplayer "$i";done

How do you post to an iframe?

This function creates a temporary form, then send data using jQuery :

function postToIframe(data,url,target){
    $('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
    $.each(data,function(n,v){
        $('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
    });
    $('#postToIframe').submit().remove();
}

target is the 'name' attr of the target iFrame, and data is a JS object :

data={last_name:'Smith',first_name:'John'}

PHP: If internet explorer 6, 7, 8 , or 9

PHP has a function called get_browser() that will return an object (or array if you so choose) with details about the users' browser and what it can do.

A simple look through gave me this code:

$browser = get_browser( null, true );
if( $browser['name'] == "Firefox" )
    if( $browser['majorversion'] == 4 )
        echo "You're using Firefox version 4!";

This is not a surefire way (as it reads from HTTP_USER_AGENT, which can be spoofed, and will sometimes be analyzed wrong by php), but it's the easiest one that you can find as far as I know.

How can I print to the same line?

You could print the backspace character '\b' as many times as necessary to delete the line before printing the updated progress bar.

Set background image in CSS using jquery

Try this:

<div class="rmz-srchbg">
    <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
    <input type="submit" value="&nbsp;" id="srchbtn" class="rmz-srchico">
    <br style="clear:both;">
</div>
<script>
$(function(){
   $('#globalsearchstr').on('focus mouseenter', function(){
    $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
   });
});
</script>

How do you select the entire excel sheet with Range using VBA?

Sub SelectAllCellsInSheet(SheetName As String)
    lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
    Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
    Sheets(SheetName).Range("A1", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub

To use with ActiveSheet:

Call SelectAllCellsInSheet(ActiveSheet.Name)

MySQL - length() vs char_length()

LENGTH() returns the length of the string measured in bytes.
CHAR_LENGTH() returns the length of the string measured in characters.

This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:

select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1

As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC in UTF-8) even though it's only one character.

What are the retransmission rules for TCP?

What exactly are the rules for requesting retransmission of lost data?

The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.

Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ

are detailed in the RFC 3366.

At what time frequency are the retransmission requests performed?

The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)

The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.

Is there an upper bound on the number?

Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.

Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?

The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)

How to unblock with mysqladmin flush hosts

You can easily restart your MySql service. This kicks the error off.

2 column div layout: right column with fixed width, left fluid

Hey, What you can do is apply a fixed width to both the containers and then use another div class where clear:both, like

div#left {

width: 600px;
float: left;
}

div#right {

width: 240px;
float: right;

}

div.clear {

clear:both;

}

place a the clear div under left and right container.

Mergesort with Python

You can initialise the whole result list in the top level call to mergesort:

result = [0]*len(x)   # replace 0 with a suitable default element if necessary. 
                      # or just copy x (result = x[:])

Then for the recursive calls you can use a helper function to which you pass not sublists, but indices into x. And the bottom level calls read their values from x and write into result directly.

That way you can avoid all that poping and appending which should improve performance.

Are there any free Xml Diff/Merge tools available?

I wrote and released a Windows application that specifically solves the problem of comparing and merging XML files.

Project: Merge can perform two and three way comparisons and merges of any XML file (where two of the files are considered to be independent revisions of a common base file). You can instruct it to identify elements within the input files by attribute values, or the content of child elements, among other things.

It is fully controllable via the command line and can also generate text reports containing the differences between the files.

Project: Merge merging three XML files

How To: Execute command line in C#, get STD OUT results

The accepted answer on this page has a weakness that is troublesome in rare situations. There are two file handles which programs write to by convention, stdout, and stderr. If you just read a single file handle such as the answer from Ray, and the program you are starting writes enough output to stderr, it will fill up the output stderr buffer and block. Then your two processes are deadlocked. The buffer size may be 4K. This is extremely rare on short-lived programs, but if you have a long running program which repeatedly outputs to stderr, it will happen eventually. This is tricky to debug and track down.

There are a couple good ways to deal with this.

  1. One way is to execute cmd.exe instead of your program and use the /c argument to cmd.exe to invoke your program along with the "2>&1" argument to cmd.exe to tell it to merge stdout and stderr.

            var p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "/c mycmd.exe 2>&1";
    
  2. Another way is to use a programming model which reads both handles at the same time.

            var p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = @"/c dir \windows";
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = false;
            p.OutputDataReceived += (a, b) => Console.WriteLine(b.Data);
            p.ErrorDataReceived += (a, b) => Console.WriteLine(b.Data);
            p.Start();
            p.BeginErrorReadLine();
            p.BeginOutputReadLine();
            p.WaitForExit();
    

How to create a readonly textbox in ASP.NET MVC3 Razor

UPDATE: Now it's very simple to add HTML attributes to the default editor templates. It neans instead of doing this:

@Html.TextBoxFor(m => m.userCode, new { @readonly="readonly" })

you simply can do this:

@Html.EditorFor(m => m.userCode, new { htmlAttributes = new { @readonly="readonly" } })

Benefits: You haven't to call .TextBoxFor, etc. for templates. Just call .EditorFor.


While @Shark's solution works correctly, and it is simple and useful, my solution (that I use always) is this one: Create an editor-template that can handles readonly attribute:

  1. Create a folder named EditorTemplates in ~/Views/Shared/
  2. Create a razor PartialView named String.cshtml
  3. Fill the String.cshtml with this code:

    @if(ViewData.ModelMetadata.IsReadOnly) {
        @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
            new { @class = "text-box single-line readonly", @readonly = "readonly", disabled = "disabled" })
    } else {
        @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
            new { @class = "text-box single-line" })
    }
    
  4. In model class, put the [ReadOnly(true)] attribute on properties which you want to be readonly.

For example,

public class Model {
    // [your-annotations-here]
    public string EditablePropertyExample { get; set; }

    // [your-annotations-here]
    [ReadOnly(true)]
    public string ReadOnlyPropertyExample { get; set; }
}

Now you can use Razor's default syntax simply:

@Html.EditorFor(m => m.EditablePropertyExample)
@Html.EditorFor(m => m.ReadOnlyPropertyExample)

The first one renders a normal text-box like this:

<input class="text-box single-line" id="field-id" name="field-name" />

And the second will render to;

<input readonly="readonly" disabled="disabled" class="text-box single-line readonly" id="field-id" name="field-name" />

You can use this solution for any type of data (DateTime, DateTimeOffset, DataType.Text, DataType.MultilineText and so on). Just create an editor-template.

PHP expects T_PAAMAYIM_NEKUDOTAYIM?

Edit: Unfortunately, as of PHP 8.0, the answer is not "No, not anymore". This RFC was not accepted as I hoped, proposing to change T_PAAMAYIM_NEKUDOTAYIM to T_DOUBLE_COLON; but it was declined.

Note: I keep this answer for historical purposes. Actually, because of the creation of the RFC and the votes ratio at some point, I created this answer. Also, I keep this for hoping it to be accepted in the near future.

Excel formula to get ranking position

The way I've done this, which is a bit convoluted, is as follows:

  1. Sort rows by the points in descending order
  2. Create an additional column (D) starting at D2 with numbers 1,2,3,... total number of positions
  3. In the cell for the actual positions (D2) use the formula if(C2=C1), D2, C1). This checks if the points in this row are the same as the points in the previous row. If it is it gives you the position of the previous row, otherwise it uses the value from column D and thus handle people with equal positions.
  4. Copy this formula down the entire column
  5. Copy the positions column(C), then paste special >> values to overwrite the formula with positions
  6. Resort the rows to their original order

That's worked for me! If there's a better way I'd love to know it!

Take a full page screenshot with Firefox on the command-line

You can use selenium and the webdriver for Firefox.

import selenium.webdriver
import selenium.common

options = selenium.webdriver.firefox.options.Options()
# options.headless = True
with selenium.webdriver.Firefox(options=options) as driver:
    driver.get('http://google.com')
    time.sleep(2)
    root=driver.find_element_by_tag_name('html')
    root.screenshot('whole page screenshot.png')

How do I set the size of an HTML text box?

Try this code :

input[type="text"]{
 padding:10px 0;}

This way it remains independent of what textsize has been set for the textbox. You are increasing the height using padding instead.

How to find substring from string?

Use std::string and find.

std::string str = "/user/desktop/abc/post/";
bool exists = str.find("/abc/") != std::string::npos;

How to make HTML Text unselectable

The full modern solution to your problem is purely CSS-based, but note that older browsers won't support it, in which cases you'd need to fallback to solutions such as the others have provided.

So in pure CSS:

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;

However the mouse cursor will still change to a caret when over the element's text, so you add to that:

cursor: default;

Modern CSS is pretty elegant.

How to copy a file from remote server to local machine?

The scp operation is separate from your ssh login. You will need to issue an ssh command similar to the following one assuming jdoe is account with which you log into the remote system and that the remote system is example.com:

scp [email protected]:/somedir/table /home/me/Desktop/.

The scp command issued from the system where /home/me/Desktop resides is followed by the userid for the account on the remote server. You then add a ":" followed by the directory path and file name on the remote server, e.g., /somedir/table. Then add a space and the location to which you want to copy the file. If you want the file to have the same name on the client system, you can indicate that with a period, i.e. "." at the end of the directory path; if you want a different name you could use /home/me/Desktop/newname, instead. If you were using a nonstandard port for SSH connections, you would need to specify that port with a "-P n" (capital P), where "n" is the port number. The standard port is 22 and if you aren't specifying it for the SSH connection then you won't need that.

How do I get a list of files in a directory in C++?

Solving this will require a platform specific solution. Look for opendir() on unix/linux or FindFirstFile() on Windows. Or, there are many libraries that will handle the platform specific part for you.

Installing Bower on Ubuntu

At Least from Ubuntu 12.04, an old version (0.6.x) of Node is in the standard repository. To install, just run:

sudo apt-get install nodejs

NPM comes with latest version of nodejs. Once you have that, then run

sudo npm install bower -g

Should be good to go after that. You may need to run some updates, but it should be fairly straight forward.

Refresh DataGridView when updating data source

The cleanest, most efficient and paradigm-friendly solution in this case is to use a System.Windows.Forms.BindingSource as a proxy between your list of items (datasource) and your DataGridView:

var itemStates = new List<ItemState>();
var bindingSource1 = new System.Windows.Forms.BindingSource { DataSource = itemStates };
dataGridView1.DataSource = bindingSource1;

Then, when adding items, use Add() method of BindingSource instead of your list's Add() method:

for (var i = 0; i < 10; i++)
{
    bindingSource1.Add(new ItemState { Id = i.ToString() });
    System.Threading.Thread.Sleep(500);
}

This way you adding items to your list and notifying DataGridView about those additions with the same line of code. No need to reset DataGridView's DataSource every time you make a change to the list.

It also worth mentioning that you can drop a BindingSource onto your form directly in Visual Studio's Forms Designer and attach it as a data source to your DataGridView there as well, which saves you a line of code in the above example where I'm doing it manually.

PDOException “could not find driver”

I had the same exception when trying to use pdo_sqlite. The problem was that the automatically created 20-pdo_sqlite.ini and 20-sqlite3.ini symlinks (in /etc/php5/mods-enabled) were broken.

Removeing the broken symlinks and adding them manually with:

  • sudo ln -s /etc/php5/mods-avaliable/pdo_sqlite.ini /etc/php5/mods-enabled/20-pdo_sqlite.ini
  • sudo ln -s /etc/php5/mods-avaliable/sqlite3.ini /etc/php5/mods-enabled/20-sqlite3.ini

fixed the problem.

Note: this won't work for older php versions as they did not look for configs in /etc/php5/mods-enabled

Convert Rows to columns using 'Pivot' in SQL Server

select * from (select name, ID from Empoyee) Visits
    pivot(sum(ID) for name
    in ([Emp1],
    [Emp2],
    [Emp3]
    ) ) as pivottable;

How to use Bash to create a folder if it doesn't already exist?

Simply do:

mkdir /path/to/your/potentially/existing/folder

mkdir will throw an error if the folder already exists. To ignore the errors write:

mkdir -p /path/to/your/potentially/existing/folder

No need to do any checking or anything like that.


For reference:

-p, --parents no error if existing, make parent directories as needed http://man7.org/linux/man-pages/man1/mkdir.1.html

Do sessions really violate RESTfulness?

First, let's define some terms:

  • RESTful:

    One can characterise applications conforming to the REST constraints described in this section as "RESTful".[15] If a service violates any of the required constraints, it cannot be considered RESTful.

    according to wikipedia.

  • stateless constraint:

    We next add a constraint to the client-server interaction: communication must be stateless in nature, as in the client-stateless-server (CSS) style of Section 3.4.3 (Figure 5-3), such that each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.

    according to the Fielding dissertation.

So server side sessions violate the stateless constraint of REST, and so RESTfulness either.

As such, to the client, a session cookie is exactly the same as any other HTTP header based authentication mechanism, except that it uses the Cookie header instead of the Authorization or some other proprietary header.

By session cookies you store the client state on the server and so your request has a context. Let's try to add a load balancer and another service instance to your system. In this case you have to share the sessions between the service instances. It is hard to maintain and extend such a system, so it scales badly...

In my opinion there is nothing wrong with cookies. The cookie technology is a client side storing mechanism in where the stored data is attached automatically to cookie headers by every request. I don't know of a REST constraint which has problem with that kind of technology. So there is no problem with the technology itself, the problem is with its usage. Fielding wrote a sub-section about why he thinks HTTP cookies are bad.

From my point of view:

  • authentication is not prohibited for RESTfulness (otherwise there'd be little use in RESTful services)
  • authentication is done by sending an authentication token in the request, usually the header
  • this authentication token needs to be obtained somehow and may be revoked, in which case it needs to be renewed
  • the authentication token needs to be validated by the server (otherwise it wouldn't be authentication)

Your point of view was pretty solid. The only problem was with the concept of creating authentication token on the server. You don't need that part. What you need is storing username and password on the client and send it with every request. You don't need more to do this than HTTP basic auth and an encrypted connection:

Figure 1. - Stateless authentication by trusted clients

  • Figure 1. - Stateless authentication by trusted clients

You probably need an in-memory auth cache on server side to make things faster, since you have to authenticate every request.

Now this works pretty well by trusted clients written by you, but what about 3rd party clients? They cannot have the username and password and all the permissions of the users. So you have to store separately what permissions a 3rd party client can have by a specific user. So the client developers can register they 3rd party clients, and get an unique API key and the users can allow 3rd party clients to access some part of their permissions. Like reading the name and email address, or listing their friends, etc... After allowing a 3rd party client the server will generate an access token. These access token can be used by the 3rd party client to access the permissions granted by the user, like so:

Figure 2. - Stateless authentication by 3rd party clients

  • Figure 2. - Stateless authentication by 3rd party clients

So the 3rd party client can get the access token from a trusted client (or directly from the user). After that it can send a valid request with the API key and access token. This is the most basic 3rd party auth mechanism. You can read more about the implementation details in the documentation of every 3rd party auth system, e.g. OAuth. Of course this can be more complex and more secure, for example you can sign the details of every single request on server side and send the signature along with the request, and so on... The actual solution depends on your application's need.

Change WPF controls from a non-main thread using Dispatcher.Invoke

japf has answer it correctly. Just in case if you are looking at multi-line actions, you can write as below.

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => { 
    this.progressBar.Value = 50;
  }));

Information for other users who want to know about performance:

If your code NEED to be written for high performance, you can first check if the invoke is required by using CheckAccess flag.

if(Application.Current.Dispatcher.CheckAccess())
{
    this.progressBar.Value = 50;
}
else
{
    Application.Current.Dispatcher.BeginInvoke(
      DispatcherPriority.Background,
      new Action(() => { 
        this.progressBar.Value = 50;
      }));
}

Note that method CheckAccess() is hidden from Visual Studio 2015 so just write it without expecting intellisense to show it up. Note that CheckAccess has overhead on performance (overhead in few nanoseconds). It's only better when you want to save that microsecond required to perform the 'invoke' at any cost. Also, there is always option to create two methods (on with invoke, and other without) when calling method is sure if it's in UI Thread or not. It's only rarest of rare case when you should be looking at this aspect of dispatcher.

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

Above suggestions didn't worked for me. I got it running on my windows, using inspiration from http://butlerccwebdev.net/support/testingserver/vhosts-setup-win.html

For Http inside httpd-vhosts.conf

<Directory "D:/Projects">       
AllowOverride All
Require all granted
</Directory>

##Letzgrow
<VirtualHost *:80>
DocumentRoot "D:/Projects/letzgrow"
ServerName letz.dev
ServerAlias letz.dev    
</VirtualHost>

For using Https (Open SSL) inside httpd-ssl.conf

<Directory "D:/Projects">       
AllowOverride All
Require all granted
</Directory>

##Letzgrow
<VirtualHost *:443>
DocumentRoot "D:/Projects/letzgrow"
ServerName letz.dev
ServerAlias letz.dev    
</VirtualHost>

Hope it helps someone !!

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

As johnnyynnoj mentioned ng-repeat creates a new scope. I would in fact use a function to set the value. See plunker

JS:

$scope.setSelected = function(selected) {
  $scope.selected = selected;
}

HTML:

{{ selected }}

<ul>
  <li ng-class="{current: selected == 100}">
     <a href ng:click="setSelected(100)">ABC</a>
  </li>
  <li ng-class="{current: selected == 101}">
     <a href ng:click="setSelected(101)">DEF</a>
  </li>
  <li ng-class="{current: selected == $index }" 
      ng-repeat="x in [4,5,6,7]">
     <a href ng:click="setSelected($index)">A{{$index}}</a>
  </li>
</ul>

<div  
  ng:show="selected == 100">
  100        
</div>
<div  
  ng:show="selected == 101">
  101        
</div>
<div ng-repeat="x in [4,5,6,7]" 
  ng:show="selected == $index">
  {{ $index }}        
</div>

How to use the priority queue STL for objects?

A priority queue is an abstract data type that captures the idea of a container whose elements have "priorities" attached to them. An element of highest priority always appears at the front of the queue. If that element is removed, the next highest priority element advances to the front.

The C++ standard library defines a class template priority_queue, with the following operations:

push: Insert an element into the prioity queue.

top: Return (without removing it) a highest priority element from the priority queue.

pop: Remove a highest priority element from the priority queue.

size: Return the number of elements in the priority queue.

empty: Return true or false according to whether the priority queue is empty or not.

The following code snippet shows how to construct two priority queues, one that can contain integers and another one that can contain character strings:

#include <queue>

priority_queue<int> q1;
priority_queue<string> q2;

The following is an example of priority queue usage:

#include <string>
#include <queue>
#include <iostream>

using namespace std;  // This is to make available the names of things defined in the standard library.

int main()
{
    piority_queue<string> pq; // Creates a priority queue pq to store strings, and initializes the queue to be empty.

    pq.push("the quick");
    pq.push("fox");
    pq.push("jumped over");
    pq.push("the lazy dog");

    // The strings are ordered inside the priority queue in lexicographic (dictionary) order:
    // "fox", "jumped over", "the lazy dog", "the quick"
    //  The lowest priority string is "fox", and the highest priority string is "the quick"

    while (!pq.empty()) {
       cout << pq.top() << endl;  // Print highest priority string
       pq.pop();                    // Remmove highest priority string
    }

    return 0;
}

The output of this program is:

the quick
the lazy dog
jumped over
fox

Since a queue follows a priority discipline, the strings are printed from highest to lowest priority.

Sometimes one needs to create a priority queue to contain user defined objects. In this case, the priority queue needs to know the comparison criterion used to determine which objects have the highest priority. This is done by means of a function object belonging to a class that overloads the operator (). The overloaded () acts as < for the purpose of determining priorities. For example, suppose we want to create a priority queue to store Time objects. A Time object has three fields: hours, minutes, seconds:

struct Time {
    int h; 
    int m; 
    int s;
};

class CompareTime {
    public:
    bool operator()(Time& t1, Time& t2) // Returns true if t1 is earlier than t2
    {
       if (t1.h < t2.h) return true;
       if (t1.h == t2.h && t1.m < t2.m) return true;
       if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
       return false;
    }
}

A priority queue to store times according the the above comparison criterion would be defined as follows:

priority_queue<Time, vector<Time>, CompareTime> pq;

Here is a complete program:

#include <iostream>
#include <queue>
#include <iomanip>

using namespace std;

struct Time {
    int h; // >= 0
    int m; // 0-59
    int s; // 0-59
};

class CompareTime {
public:
    bool operator()(Time& t1, Time& t2)
    {
       if (t1.h < t2.h) return true;
       if (t1.h == t2.h && t1.m < t2.m) return true;
       if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
       return false;
    }
};

int main()
{
    priority_queue<Time, vector<Time>, CompareTime> pq;

    // Array of 4 time objects:

    Time t[4] = { {3, 2, 40}, {3, 2, 26}, {5, 16, 13}, {5, 14, 20}};

    for (int i = 0; i < 4; ++i)
       pq.push(t[i]);

    while (! pq.empty()) {
       Time t2 = pq.top();
       cout << setw(3) << t2.h << " " << setw(3) << t2.m << " " <<
       setw(3) << t2.s << endl;
       pq.pop();
    }

    return 0;
}

The program prints the times from latest to earliest:

5  16  13
5  14  20
3   2  40
3   2  26

If we wanted earliest times to have the highest priority, we would redefine CompareTime like this:

class CompareTime {
public:
    bool operator()(Time& t1, Time& t2) // t2 has highest prio than t1 if t2 is earlier than t1
    {
       if (t2.h < t1.h) return true;
       if (t2.h == t1.h && t2.m < t1.m) return true;
       if (t2.h == t1.h && t2.m == t1.m && t2.s < t1.s) return true;
       return false;
    }
};

How to read file binary in C#?

Use simple FileStream.Read then print it with Convert.ToString(b, 2)

How to read a line from the console in C?

A very simple but unsafe implementation to read line for static allocation:

char line[1024];

scanf("%[^\n]", line);

A safer implementation, without the possibility of buffer overflow, but with the possibility of not reading the whole line, is:

char line[1024];

scanf("%1023[^\n]", line);

Not the 'difference by one' between the length specified declaring the variable and the length specified in the format string. It is a historical artefact.

Converting string to double in C#

In your string I see: 15.5859949000000662452.23862099999999 which is not a double (it has two decimal points). Perhaps it's just a legitimate input error?

You may also want to figure out if your last String will be empty, and account for that situation.

How to set my default shell on Mac?

How to get the latest version of bash on modern macOS (tested on Mojave).

brew install bash
which bash | sudo tee -a /etc/shells
chsh -s $(which bash)

Then you are ready to get vim style tab completion which is only available on bash>=4 (current version in brew is 5.0.2

# If there are multiple matches for completion, Tab should cycle through them
bind 'TAB':menu-complete

# Display a list of the matching files
bind "set show-all-if-ambiguous on"

# Perform partial completion on the first Tab press,
# only start cycling full results on the second Tab press
bind "set menu-complete-display-prefix on"

How to generate unique IDs for form labels in React?

Don't use IDs at all if you don't need to, instead wrap the input in a label like this:

<label>
   My Label
   <input type="text"/>
</label>

Then you won't need to worry about unique IDs.

Ruby: How to turn a hash into HTTP parameters?

Update: This functionality was removed from the gem.

Julien, your self-answer is a good one, and I've shameless borrowed from it, but it doesn't properly escape reserved characters, and there are a few other edge cases where it breaks down.

require "addressable/uri"
uri = Addressable::URI.new
uri.query_values = {:a => "a", :b => ["c", "d", "e"]}
uri.query
# => "a=a&b[0]=c&b[1]=d&b[2]=e"
uri.query_values = {:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}]}
uri.query
# => "a=a&b[0][c]=c&b[0][d]=d&b[1][e]=e&b[1][f]=f"
uri.query_values = {:a => "a", :b => {:c => "c", :d => "d"}}
uri.query
# => "a=a&b[c]=c&b[d]=d"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}}
uri.query
# => "a=a&b[c]=c&b[d]"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}, :e => []}
uri.query
# => "a=a&b[c]=c&b[d]"

The gem is 'addressable'

gem install addressable

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I had a similar issue when I checked out a web project from a github repo on my eclipse. src/main/java was directly inside the project root in Package Explorer. My expectation was that src/main/java be visible inside a source folder "Java Resources". There were few things which I did to achieve this.

  1. Right click on Project > Build Path > Configure Build Path..
  2. Select filter "Java Build Path" and click on Tab "Libraries" Verify your "JRE System Library". If it is not pointing to your latest JDK, then you can click on Edit Button and follow the subsequent dialog boxes to select most appropriate JDK home path in your system. Once done click Apply, Apply and Close, Finish to close all the associated open boxes for the current filter.
  3. Select filter "Java Compiler" and ensure your JDK Compliance points to correct JDK. Click Aapply
  4. Select filter "Project Facets". Ensure both Java and Dynamic Web Module is selected with correct version.
  5. Click Apply and Close.
  6. Source folder "Java Resources" gets created with src/main/java in it when viewed in Project Explorer.

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

I tried everything above but nothing worked for me. I am using macOS Catalina: 10.15.6 and it doesn't have .itmstransporter/

Until I...

  • I was uploading in US peak time-zone. So, I waited and tried again in the morning here (India) GMT +5:30.
  • I cleared the cache of my laptop and re-added the account.
  • Made another Archive.

It took me 5 minutes total to upload the archive.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

In my opinion, a dynamic PL/SQL block is somewhat obscure. While is very flexible, is also hard to tune, hard to debug and hard to figure out what's up. My vote goes to your first option,

EXECUTE IMMEDIATE v_query_str INTO v_num_of_employees USING p_job;

Both uses bind variables, but first, for me, is more redeable and tuneable than @jonearles option.

No converter found capable of converting from type to type

Return ABDeadlineType from repository:

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<ABDeadlineType> findAllSummarizedBy();
}

and then convert to DeadlineType. Manually or use mapstruct.

Or call constructor from @Query annotation:

public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {

    @Query("select new package.DeadlineType(a.id, a.code) from ABDeadlineType a ")
    List<DeadlineType> findAllSummarizedBy();
}

Or use @Projection:

@Projection(name = "deadline", types = { ABDeadlineType.class })
public interface DeadlineType {

    @Value("#{target.id}")
    String getId();

    @Value("#{target.code}")
    String getText();

}

Update: Spring can work without @Projection annotation:

public interface DeadlineType {
    String getId();    
    String getText();
}

How to strip all non-alphabetic characters from string in SQL Server?

Using a CTE generated numbers table to examine each character, then FOR XML to concat to a string of kept values you can...

CREATE FUNCTION [dbo].[PatRemove](
    @pattern varchar(50),
    @expression varchar(8000) 
    )
RETURNS varchar(8000)
AS
BEGIN
    WITH 
        d(d) AS (SELECT d FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) digits(d)),
        nums(n) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM d d1, d d2, d d3, d d4),
        chars(c) AS (SELECT SUBSTRING(@expression, n, 1) FROM nums WHERE n <= LEN(@expression))
    SELECT 
        @expression = (SELECT c AS [text()] FROM chars WHERE c NOT LIKE @pattern FOR XML PATH(''));

    RETURN @expression;
END

Why does Lua have no "continue" statement?

We can achieve it as below, it will skip even numbers

local len = 5
for i = 1, len do
    repeat 
        if i%2 == 0 then break end
        print(" i = "..i)
        break
    until true
end

O/P:

i = 1
i = 3
i = 5

How can I show/hide a specific alert with twitter bootstrap?

I had this problem today, was in a lot of time crunch, so below idea worked:

  • setTimeout with 1 sec -- call a function that shows the div
  • setTimeout with 10 sec -- call a function that hides the div

Fade is not there, but that bootstrap feeling will be there.

Hope that helps.

How can I merge two MySQL tables?

It depends on the semantic of the primary key. If it's just autoincrement, then use something like:

insert into table1 (all columns except pk)
select all_columns_except_pk 
from table2;

If PK means something, you need to find a way to determine which record should have priority. You could create a select query to find duplicates first (see answer by cpitis). Then eliminate the ones you don't want to keep and use the above insert to add records that remain.

How to extract svg as file from web page

They are all logged under Elements in google chromes developer tools.

page

_x000D_
_x000D_
<svg><path xmlns="http://www.w3.org/2000/svg" d="M18.6 6.8l-4.3-2.2a.8.8 0 0 0-.6 0l-4 2-4.1-2a.7.7 0 0 0-.7.1.7.7 0 0 0-.3.6v10.8a.7.7 0 0 0 .4.6l4.3 2.1a.8.8 0 0 0 .6 0l4-2 4 2a.6.6 0 0 0 .3.1.7.7 0 0 0 .4-.1.7.7 0 0 0 .4-.6V7.4a.7.7 0 0 0-.4-.6zm-1.1 1.4v5.7a.4.4 0 0 1-.6.4c-1.2-.4-.3-2.3-1.1-3.3-.7-.9-1.7 0-2.6-1.4-.9-1.4.3-2.5 1.4-3a.5.5 0 0 1 .4 0l2.2 1.1a.5.5 0 0 1 .3.5zm-6.1 8.3a.5.5 0 0 1-.5-.1 1.6 1.6 0 0 1-.6-1.1c0-.7-1.2-.4-1.2-1.9 0-1.2-1.3-1.5-2.5-1.3a.5.5 0 0 1-.5-.5V7.2a.4.4 0 0 1 .6-.4l2.6 1.3a.1.1 0 0 1 .1 0l.1.1c1.1.6.8 1.1.4 1.9-.5.9-.7 0-1.4-.3s-1.5.3-1.2.8.9 0 1.4.4.5 1.2 1.9.8 1.7-.3 2.2.2a1.5 1.5 0 0 1 0 2.2c-.4.4-.6 1.3-.8 1.9a.5.5 0 0 1-.2.3z"/></svg>
_x000D_
_x000D_
_x000D_

What is the difference between a port and a socket?

Summary

A TCP socket is an endpoint instance defined by an IP address and a port in the context of either a particular TCP connection or the listening state.

A port is a virtualisation identifier defining a service endpoint (as distinct from a service instance endpoint aka session identifier).

A TCP socket is not a connection, it is the endpoint of a specific connection.

There can be concurrent connections to a service endpoint, because a connection is identified by both its local and remote endpoints, allowing traffic to be routed to a specific service instance.

There can only be one listener socket for a given address/port combination.

Exposition

This was an interesting question that forced me to re-examine a number of things I thought I knew inside out. You'd think a name like "socket" would be self-explanatory: it was obviously chosen to evoke imagery of the endpoint into which you plug a network cable, there being strong functional parallels. Nevertheless, in network parlance the word "socket" carries so much baggage that a careful re-examination is necessary.

In the broadest possible sense, a port is a point of ingress or egress. Although not used in a networking context, the French word porte literally means door or gateway, further emphasising the fact that ports are transportation endpoints whether you ship data or big steel containers.

For the purpose of this discussion I will limit consideration to the context of TCP-IP networks. The OSI model is all very well but has never been completely implemented, much less widely deployed in high-traffic high-stress conditions.

The combination of an IP address and a port is strictly known as an endpoint and is sometimes called a socket. This usage originates with RFC793, the original TCP specification.

A TCP connection is defined by two endpoints aka sockets.

An endpoint (socket) is defined by the combination of a network address and a port identifier. Note that address/port does not completely identify a socket (more on this later).

The purpose of ports is to differentiate multiple endpoints on a given network address. You could say that a port is a virtualised endpoint. This virtualisation makes multiple concurrent connections on a single network interface possible.

It is the socket pair (the 4-tuple consisting of the client IP address, client port number, server IP address, and server port number) that specifies the two endpoints that uniquely identifies each TCP connection in an internet. (TCP-IP Illustrated Volume 1, W. Richard Stevens)

In most C-derived languages, TCP connections are established and manipulated using methods on an instance of a Socket class. Although it is common to operate on a higher level of abstraction, typically an instance of a NetworkStream class, this generally exposes a reference to a socket object. To the coder this socket object appears to represent the connection because the connection is created and manipulated using methods of the socket object.

In C#, to establish a TCP connection (to an existing listener) first you create a TcpClient. If you don't specify an endpoint to the TcpClient constructor it uses defaults - one way or another the local endpoint is defined. Then you invoke the Connect method on the instance you've created. This method requires a parameter describing the other endpoint.

All this is a bit confusing and leads you to believe that a socket is a connection, which is bollocks. I was labouring under this misapprehension until Richard Dorman asked the question.

Having done a lot of reading and thinking, I'm now convinced that it would make a lot more sense to have a class TcpConnection with a constructor that takes two arguments, LocalEndpoint and RemoteEndpoint. You could probably support a single argument RemoteEndpoint when defaults are acceptable for the local endpoint. This is ambiguous on multihomed computers, but the ambiguity can be resolved using the routing table by selecting the interface with the shortest route to the remote endpoint.

Clarity would be enhanced in other respects, too. A socket is not identified by the combination of IP address and port:

[...]TCP demultiplexes incoming segments using all four values that comprise the local and foreign addresses: destination IP address, destination port number, source IP address, and source port number. TCP cannot determine which process gets an incoming segment by looking at the destination port only. Also, the only one of the [various] endpoints at [a given port number] that will receive incoming connection requests is the one in the listen state. (p255, TCP-IP Illustrated Volume 1, W. Richard Stevens)

As you can see, it is not just possible but quite likely for a network service to have numerous sockets with the same address/port, but only one listener socket on a particular address/port combination. Typical library implementations present a socket class, an instance of which is used to create and manage a connection. This is extremely unfortunate, since it causes confusion and has lead to widespread conflation of the two concepts.

Hagrawal doesn't believe me (see comments) so here's a real sample. I connected a web browser to http://dilbert.com and then ran netstat -an -p tcp. The last six lines of the output contain two examples of the fact that address and port are not enough to uniquely identify a socket. There are two distinct connections between 192.168.1.3 (my workstation) and 54.252.94.236:80 (the remote HTTP server)

  TCP    192.168.1.3:63240      54.252.94.236:80       SYN_SENT
  TCP    192.168.1.3:63241      54.252.94.236:80       SYN_SENT
  TCP    192.168.1.3:63242      207.38.110.62:80       SYN_SENT
  TCP    192.168.1.3:63243      207.38.110.62:80       SYN_SENT
  TCP    192.168.1.3:64161      65.54.225.168:443      ESTABLISHED

Since a socket is the endpoint of a connection, there are two sockets with the address/port combination 207.38.110.62:80 and two more with the address/port combination 54.252.94.236:80.

I think Hagrawal's misunderstanding arises from my very careful use of the word "identifies". I mean "completely, unambiguously and uniquely identifies". In the above sample there are two endpoints with the address/port combination 54.252.94.236:80. If all you have is address and port, you don't have enough information to tell these sockets apart. It's not enough information to identify a socket.

Addendum

Paragraph two of section 2.7 of RFC793 says

A connection is fully specified by the pair of sockets at the ends. A local socket may participate in many connections to different foreign sockets.

This definition of socket is not helpful from a programming perspective because it is not the same as a socket object, which is the endpoint of a particular connection. To a programmer, and most of this question's audience are programmers, this is a vital functional difference.

@plugwash makes a salient observation.

The fundamental problem is that the TCP RFC definition of socket is in conflict with the defintion of socket used by all major operating systems and libraries.

By definition the RFC is correct. When a library misuses terminology, this does not supersede the RFC. Instead, it imposes a burden of responsibility on users of that library to understand both interpretations and to be careful with words and context. Where RFCs do not agree, the most recent and most directly applicable RFC takes precedence.

References

  1. TCP-IP Illustrated Volume 1 The Protocols, W. Richard Stevens, 1994 Addison Wesley

  2. RFC793, Information Sciences Institute, University of Southern California for DARPA

  3. RFC147, The Definition of a Socket, Joel M. Winett, Lincoln Laboratory

What is the simplest way to SSH using Python?

For benefit of those who reach here googling for python ssh sample. The original question and answer are almost a decode old now. It seems that the paramiko has gain a bit of functionalities (Ok. I'll admit - pure guessing here - I'm new to Python) and you can create ssh client directly with paramiko.

import base64
import paramiko

client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.1.1', username='user', password='password')
stdin, stdout, stderr = client.exec_command('cat /proc/meminfo')
for line in stdout:
    print('... ' + line.strip('\n'))
client.close()

This code was adapted from demo of https://github.com/paramiko/paramiko It works for me.

Autowiring fails: Not an managed Type

For Controllers, @SpringBootApplication(scanBasePackages = {"com.school.controllers"})

For Respositories, @EnableJpaRepositories(basePackages = {"com.school.repos"})

For Entities, @EntityScan(basePackages = {"com.school.models"})

This will slove

"Can't Autowire @Repository annotated interface"

problem as well as

Not an managed Type

problem. Sample configuration below

package com.school.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;


@SpringBootApplication(scanBasePackages = {"com.school.controllers"})
@EnableJpaRepositories(basePackages = {"com.school.repos"})
@EntityScan(basePackages = {"com.school.models"})
public class SchoolApplication {

    public static void main(String[] args) {
        SpringApplication.run(SchoolApplication.class, args);
    }

}

Convert UTC/GMT time to local time

I'd just like to add a general note of caution.

If all you are doing is getting the current time from the computer's internal clock to put a date/time on the display or a report, then all is well. But if you are saving the date/time information for later reference or are computing date/times, beware!

Let's say you determine that a cruise ship arrived in Honolulu on 20 Dec 2007 at 15:00 UTC. And you want to know what local time that was.
1. There are probably at least three 'locals' involved. Local may mean Honolulu, or it may mean where your computer is located, or it may mean the location where your customer is located.
2. If you use the built-in functions to do the conversion, it will probably be wrong. This is because daylight savings time is (probably) currently in effect on your computer, but was NOT in effect in December. But Windows does not know this... all it has is one flag to determine if daylight savings time is currently in effect. And if it is currently in effect, then it will happily add an hour even to a date in December.
3. Daylight savings time is implemented differently (or not at all) in various political subdivisions. Don't think that just because your country changes on a specific date, that other countries will too.

add class with JavaScript

I like to use a custom "foreach" function of sorts for these kinds of things:

function Each( objs, func )
{
    if ( objs.length ) for ( var i = 0, ol = objs.length, v = objs[ 0 ]; i < ol && func( v, i ) !== false; v = objs[ ++i ] );
    else for ( var p in objs ) if ( func( objs[ p ], p ) === false ) break;
}

(Can't remember where I found the above function, but it has been quite useful.)

Then after fetching your objects (to elements in this example) just do

Each( elements, function( element )
{
    element.addEventListener( "mouseover", function()
    {
        element.classList.add( "active" );
        //element.setAttribute( "class", "active" );
        element.setAttribute( "src", "newsource" );
    });

    // Remove class and new src after "mouseover" ends, if you wish.
    element.addEventListener( "mouseout", function()
    {
        element.classList.remove( "active" );
        element.setAttribute( "src", "originalsource" );
    });
});

classList is a simple way for handling elements' classes. Just needs a shim for a few browsers. If you must use setAttribute you must remember that whatever is set with it will overwrite the previous values.

EDIT: Forgot to mention that you need to use attachEvent instead of addEventListener on some IE versions. Test with if ( document.addEventListener ) {...}.

How to use OpenCV SimpleBlobDetector

Note: all the examples here are using the OpenCV 2.X API.

In OpenCV 3.X, you need to use:

Ptr<SimpleBlobDetector> d = SimpleBlobDetector::create(params);

See also: the transition guide: http://docs.opencv.org/master/db/dfa/tutorial_transition_guide.html#tutorial_transition_hints_headers

How print out the contents of a HashMap<String, String> in ascending order based on its values?

Java 8

map.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(System.out::println);

Is it better practice to use String.format over string Concatenation in Java?

It takes a little time to get used to String.Format, but it's worth it in most cases. In the world of NRA (never repeat anything) it's extremely useful to keep your tokenized messages (logging or user) in a Constant library (I prefer what amounts to a static class) and call them as necessary with String.Format regardless of whether you are localizing or not. Trying to use such a library with a concatenation method is harder to read, troubleshoot, proofread, and manage with any any approach that requires concatenation. Replacement is an option, but I doubt it's performant. After years of use, my biggest problem with String.Format is the length of the call is inconveniently long when I'm passing it into another function (like Msg), but that's easy to get around with a custom function to serve as an alias.

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

I got the same error and ended up using a pre-built distribution of numpy available in SourceForge (similarly, a distribution of matplotlib can be obtained).

Builds for both 32-bit 2.7 and 3.3/3.4 are available.
PyCharm detected them straight away, of course.

How to change value of process.env.PORT in node.js?

use the below command to set the port number in node process while running node JS programme:

set PORT =3000 && node file_name.js

The set port can be accessed in the code as

process.env.PORT 

Assembly Language - How to do Modulo?

If your modulus / divisor is a known constant, and you care about performance, see this and this. A multiplicative inverse is even possible for loop-invariant values that aren't known until runtime, e.g. see https://libdivide.com/ (But without JIT code-gen, that's less efficient than hard-coding just the steps necessary for one constant.)

Never use div for known powers of 2: it's much slower than and for remainder, or right-shift for divide. Look at C compiler output for examples of unsigned or signed division by powers of 2, e.g. on the Godbolt compiler explorer. If you know a runtime input is a power of 2, use lea eax, [esi-1] ; and eax, edi or something like that to do x & (y-1). Modulo 256 is even more efficient: movzx eax, cl has zero latency on recent Intel CPUs (mov-elimination), as long as the two registers are separate.


In the simple/general case: unknown value at runtime

The DIV instruction (and its counterpart IDIV for signed numbers) gives both the quotient and remainder. For unsigned, remainder and modulus are the same thing. For signed idiv, it gives you the remainder (not modulus) which can be negative:
e.g. -5 / 2 = -2 rem -1. x86 division semantics exactly match C99's % operator.

DIV r32 divides a 64-bit number in EDX:EAX by a 32-bit operand (in any register or memory) and stores the quotient in EAX and the remainder in EDX. It faults on overflow of the quotient.

Unsigned 32-bit example (works in any mode)

mov eax, 1234          ; dividend low half
mov edx, 0             ; dividend high half = 0.  prefer  xor edx,edx

mov ebx, 10            ; divisor can be any register or memory

div ebx       ; Divides 1234 by 10.
        ; EDX =   4 = 1234 % 10  remainder
        ; EAX = 123 = 1234 / 10  quotient

In 16-bit assembly you can do div bx to divide a 32-bit operand in DX:AX by BX. See Intel's Architectures Software Developer’s Manuals for more information.

Normally always use xor edx,edx before unsigned div to zero-extend EAX into EDX:EAX. This is how you do "normal" 32-bit / 32-bit => 32-bit division.

For signed division, use cdq before idiv to sign-extend EAX into EDX:EAX. See also Why should EDX be 0 before using the DIV instruction?. For other operand-sizes, use cbw (AL->AX), cwd (AX->DX:AX), cdq (EAX->EDX:EAX), or cqo (RAX->RDX:RAX) to set the top half to 0 or -1 according to the sign bit of the low half.

div / idiv are available in operand-sizes of 8, 16, 32, and (in 64-bit mode) 64-bit. 64-bit operand-size is much slower than 32-bit or smaller on current Intel CPUs, but AMD CPUs only care about the actual magnitude of the numbers, regardless of operand-size.

Note that 8-bit operand-size is special: the implicit inputs/outputs are in AH:AL (aka AX), not DL:AL. See 8086 assembly on DOSBox: Bug with idiv instruction? for an example.

Signed 64-bit division example (requires 64-bit mode)

   mov    rax,  0x8000000000000000   ; INT64_MIN = -9223372036854775808
   mov    ecx,  10           ; implicit zero-extension is fine for positive numbers

   cqo                       ; sign-extend into RDX, in this case = -1 = 0xFF...FF
   idiv   rcx
       ; quotient  = RAX = -922337203685477580 = 0xf333333333333334
       ; remainder = RDX = -8                  = 0xfffffffffffffff8

Limitations / common mistakes

div dword 10 is not encodeable into machine code (so your assembler will report an error about invalid operands).

Unlike with mul/imul (where you should normally use faster 2-operand imul r32, r/m32 or 3-operand imul r32, r/m32, imm8/32 instead that don't waste time writing a high-half result), there is no newer opcode for division by an immediate, or 32-bit/32-bit => 32-bit division or remainder without the high-half dividend input.

Division is so slow and (hopefully) rare that they didn't bother to add a way to let you avoid EAX and EDX, or to use an immediate directly.


div and idiv will fault if the quotient doesn't fit into one register (AL / AX / EAX / RAX, the same width as the dividend). This includes division by zero, but will also happen with a non-zero EDX and a smaller divisor. This is why C compilers just zero-extend or sign-extend instead of splitting up a 32-bit value into DX:AX.

And also why INT_MIN / -1 is C undefined behaviour: it overflows the signed quotient on 2's complement systems like x86. See Why does integer division by -1 (negative one) result in FPE? for an example of x86 vs. ARM. x86 idiv does indeed fault in this case.

The x86 exception is #DE - divide exception. On Unix/Linux systems, the kernel delivers a SIGFPE arithmetic exception signal to processes that cause a #DE exception. (On which platforms does integer divide by zero trigger a floating point exception?)

For div, using a dividend with high_half < divisor is safe. e.g. 0x11:23 / 0x12 is less than 0xff so it fits in an 8-bit quotient.

Extended-precision division of a huge number by a small number can be implemented by using the remainder from one chunk as the high-half dividend (EDX) for the next chunk. This is probably why they chose remainder=EDX quotient=EAX instead of the other way around.

ORA-00984: column not allowed here

Replace double quotes with single ones:

INSERT
INTO    MY.LOGFILE
        (id,severity,category,logdate,appendername,message,extrainfo)
VALUES  (
       'dee205e29ec34',
       'FATAL',
       'facade.uploader.model',
       '2013-06-11 17:16:31',
       'LOGDB',
       NULL,
       NULL
       )

In SQL, double quotes are used to mark identifiers, not string constants.

JSONException: Value of type java.lang.String cannot be converted to JSONObject

I think the problem may be in the charset that you are trying to use. It is probably best to use UTF-8 instead of iso-8859-1.

Also open whatever file is being used for your InputStream and make sure no special characters were accidentally inserted. Sometimes you have to specifically tell your editor to display hidden / special characters.

How to disable back swipe gesture in UINavigationController on iOS 7

Please set this in root vc:

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;

}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

How to increase time in web.config for executing sql query

I think you can't increase the time for query execution, but you need to increase the timeout for the request.

Execution Timeout Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. (Default time is 110 seconds.)

For Details, please have a look at https://msdn.microsoft.com/en-us/library/e1f13641%28v=vs.100%29.aspx

You can do in the web.config. e.g

<httpRuntime maxRequestLength="2097152" executionTimeout="600" />

Determining the path that a yum package installed to

Not in Linux at the moment, so can't double check, but I think it's:

rpm -ql ffmpeg

That should list all the files installed as part of the ffmpeg package.

How can I set the 'backend' in matplotlib in Python?

Your currently selected backend, 'agg' does not support show().

AGG backend is for writing to file, not for rendering in a window. See the backend FAQ at the matplotlib web site.

ImportError: No module named _backend_gdk

For the second error, maybe your matplotlib distribution is not compiled with GTK support, or you miss the PyGTK package. Try to install it.

Do you call the show() method inside a terminal or application that has access to a graphical environment?

Try other GUI backends, in this order:

  • TkAgg
  • WX
  • QTAgg
  • QT4Agg

specifying goal in pom.xml

The error message which you specified is nothing but you are not specifying goal for maven build.

you can specify any goal in your run configuration for maven build like clear, compile, install, package.

please following below step to resolve it.

  1. right click on your project.
  2. click 'Run as' and select 'Maven Build'
  3. edit Configuration window will open. write any goal but your problem specific write 'package' in Goal text box.
  4. click on 'Run'

Reading e-mails from Outlook with Python through MAPI

I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)

class CheckMailer:

        def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
            self.f = FileWriter(filename)
            self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
            self.inbox = self.outlook.Folders(folderindex)


        def check(self):                
        #===============================================================================
        # for i in xrange(1,100):                           #Uncomment this section if index 3 does not work for you
        #     try:
        #         self.inbox = self.outlook.Folders(i)     # "6" refers to the index of inbox for Default User Mailbox
        #         print "%i %s" % (i,self.inbox)            # "3" refers to the index of inbox for Another user's mailbox
        #     except:
        #         print "%i does not work"%i
        #===============================================================================

                self.f.pl(time.strftime("%H:%M:%S"))
                tot = 0                
                messages = self.inbox.Items
                message = messages.GetFirst()
                while message:
                    self.f.pl (message.Subject)
                    message = messages.GetNext()
                    tot += 1
                self.f.pl("Total Messages found: %i" % tot)
                self.f.pl("-" * 80)
                self.f.flush()

if __name__ == "__main__":
    mail = CheckMailer()
    for i in xrange(320):  # this is 10.6 hours approximately
            mail.check()
            time.sleep(120.00)

For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because trying to pipe UTF8 to a file in windows did not work.

class FileWriter(object):
    '''
    convenient file wrapper for writing to files
    '''


    def __init__(self, filename):
        '''
        Constructor
        '''
        self.file = open(filename, "w")

    def pl(self, a_string):
        str_uni = a_string.encode('utf-8')
        self.file.write(str_uni)
        self.file.write("\n")

    def flush(self):
        self.file.flush()

Input group - two inputs close to each other

I was not content with any of the answers on this page, so I fiddled with this myself for a bit. I came up with the following

_x000D_
_x000D_
angular.module('showcase', []).controller('Ctrl', function() {_x000D_
  var vm = this;_x000D_
  vm.focusParent = function(event) {_x000D_
    angular.element(event.target).parent().addClass('focus');_x000D_
  };_x000D_
_x000D_
  vm.blurParent = function(event) {_x000D_
    angular.element(event.target).parent().removeClass('focus');_x000D_
  };_x000D_
});
_x000D_
.input-merge .col-xs-2,_x000D_
.input-merge .col-xs-4,_x000D_
.input-merge .col-xs-6 {_x000D_
  padding-left: 0;_x000D_
  padding-right: 0;_x000D_
}_x000D_
.input-merge div:first-child .form-control {_x000D_
  border-top-right-radius: 0;_x000D_
  border-bottom-right-radius: 0;_x000D_
}_x000D_
.input-merge div:last-child .form-control {_x000D_
  border-top-left-radius: 0;_x000D_
  border-bottom-left-radius: 0;_x000D_
}_x000D_
.input-merge div:not(:first-child) {_x000D_
  margin-left: -1px;_x000D_
}_x000D_
.input-merge div:not(:first-child):not(:last-child) .form-control {_x000D_
  border-radius: 0;_x000D_
}_x000D_
.focus {_x000D_
  z-index: 2;_x000D_
}
_x000D_
<html ng-app="showcase">_x000D_
_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>_x000D_
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />_x000D_
</head>_x000D_
_x000D_
<body class="container">_x000D_
  <label class="control-label">Person</label>_x000D_
  <div class="input-merge" ng-controller="Ctrl as showCase">_x000D_
    <div class="col-xs-4">_x000D_
      <input class="form-control input-sm" name="initials" type="text" id="initials"_x000D_
             ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
             ng-model="person.initials" placeholder="Initials" />_x000D_
    </div>_x000D_
_x000D_
    <div class="col-xs-2">_x000D_
      <input class="form-control input-sm" name="prefixes" type="text" id="prefixes"_x000D_
             ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
             ng-model="persoon.prefixes" placeholder="Prefixes" />_x000D_
    </div>_x000D_
_x000D_
    <div class="col-xs-6">_x000D_
      <input class="form-control input-sm" name="surname" type="text" id="surname"_x000D_
             ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
             ng-model="persoon.surname" placeholder="Surname" />_x000D_
    </div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

With this it is possible to set the width of the individual inputs to your liking. Also a minor issue with the above snippets was that the input looks incomplete when focussed or when it is not valid. I fixed this with some angular code, but you can just as easily do this with jQuery or native javascript or whatever.

The code adds the class .focus to the containing div's, so it can get a higher z-index then the others when the input is focussed.

Creating for loop until list.length

The answer depends on what do you need a loop for.

of course you can have a loop similar to Java:

for i in xrange(len(my_list)):

but I never actually used loops like this,

because usually you want to iterate

for obj in my_list

or if you need an index as well

for index, obj in enumerate(my_list)

or you want to produce another collection from a list

map(some_func, my_list)

[somefunc[x] for x in my_list]

also there are itertools module that covers most of iteration related cases

also please take a look at the builtins like any, max, min, all, enumerate

I would say - do not try to write Java-like code in python. There is always a pythonic way to do it.

blur vs focusout -- any real differences?

As stated in the JQuery documentation

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

Stop node.js program from command line

Or alternatively you can do all of these in one line:

kill -9 $(ps aux | grep '\snode\s' | awk '{print $2}')

You can replace node inside '\snode\s' with any other process name.

How do I change an HTML selected option using JavaScript?

If you are adding the option with javascript

function AddNewOption(userRoutes, text, id) 
{
    var option = document.createElement("option");
    option.text = text;
    option.value = id;
    option.selected = "selected";
    userdRoutes.add(option);
}

Multiple INNER JOIN SQL ACCESS

Thanks HansUp for your answer, it is very helpful and it works!

I found three patterns working in Access, yours is the best, because it works in all cases.

  • INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM
         ((class
           INNER JOIN person AS cr 
           ON class.C_P_ClassRep=cr.P_Nr
         )
         INNER JOIN person AS cr2
         ON class.C_P_ClassRep2nd=cr2.P_Nr
      )
    

    ;

  • INNER JOIN "chained-set pattern"

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM person AS cr
    INNER JOIN ( class 
       INNER JOIN ( person AS cr2
       ) ON class.C_P_ClassRep2nd=cr2.P_Nr
    ) ON class.C_P_ClassRep=cr.P_Nr
    ;
    
  • CROSS JOIN with WHERE

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM class, person AS cr, person AS cr2
    WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
    ;
    

GitLab git user password

You may usually if you have multiple keys setup via ssh on your system (my device is running Windows 10), you will encounter this issue, the fix is to:

Precondition: Setup up your SSH Keys as indicated by GitLab

  1. open /c/Users//.ssh/config file with Notepad++ or your favourite editor
  2. paste the following inside it. Host IdentityFile ~/.ssh/

Please note, there is a space before the second line, very important to avoid this solution not working.

Getting list of lists into pandas DataFrame

Even without pop the list we can do with set_index

pd.DataFrame(table).T.set_index(0).T
Out[11]: 
0 Heading1 Heading2
1        1        2
2        3        4

Update from_records

table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]

pd.DataFrame.from_records(table[1:],columns=table[0])
Out[58]: 
   Heading1  Heading2
0         1         2
1         3         4

PHP exec() vs system() vs passthru()

It really all comes down to how you want to handle output that the command might return and whether you want your PHP script to wait for the callee program to finish or not.

  • exec executes a command and passes output to the caller (or returns it in an optional variable).

  • passthru is similar to the exec() function in that it executes a command . This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser.

  • system executes an external program and displays the output, but only the last line.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

where is gacutil.exe?

  1. Open Developer Command prompt.
  2. type

where gacutil

replace special characters in a string python

You need to call replace on z and not on str, since you want to replace characters located in the string variable z

removeSpecialChars = z.replace("!@#$%^&*()[]{};:,./<>?\|`~-=_+", " ")

But this will not work, as replace looks for a substring, you will most likely need to use regular expression module re with the sub function:

import re
removeSpecialChars = re.sub("[!@#$%^&*()[]{};:,./<>?\|`~-=_+]", " ", z)

Don't forget the [], which indicates that this is a set of characters to be replaced.

Is there a way of setting culture for a whole application? All current threads and new threads?

For ASP.NET5, i.e. ASPNETCORE, you can do the following in configure:

app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture(new CultureInfo("en-gb")),
    SupportedCultures = new List<CultureInfo>
    {
        new CultureInfo("en-gb")
    },
            SupportedUICultures = new List<CultureInfo>
    {
        new CultureInfo("en-gb")
    }
});

Here's a series of blog posts that gives more information.

HTML form with multiple "actions"

As @AliK mentioned, this can be done easily by looking at the value of the submit buttons.

When you submit a form, unset variables will evaluate false. If you set both submit buttons to be part of the same form, you can just check and see which button has been set.

HTML:

<form action="handle_user.php" method="POST" />
  <input type="submit" value="Save" name="save" />
  <input type="submit" value="Submit for Approval" name="approve" />
</form>

PHP

if($_POST["save"]) {
  //User hit the save button, handle accordingly
}
//You can do an else, but I prefer a separate statement
if($_POST["approve"]) {
  //User hit the Submit for Approval button, handle accordingly
}

EDIT


If you'd rather not change your PHP setup, try this: http://pastebin.com/j0GUF7MV
This is the JavaScript method @AliK was reffering to.

Related:

How to sum a list of integers with java streams?

Most of the aspects are covered. But there could be a requirement to find the aggregation of other data types apart from Integer, Long(for which specialized stream support is already present). For e.g. stram with BigInteger For such a type we can use reduce operation like

list.stream().reduce((bigInteger1, bigInteger2) -> bigInteger1.add(bigInteger2))

How to retrieve the dimensions of a view?

Are you trying to get sizes in a constructor, or any other method that is run BEFORE you get the actual picture?

You won't be getting any dimensions before all components are actually measured (since your xml doesn't know about your display size, parents positions and whatever)

Try getting values after onSizeChanged() (though it can be called with zero), or just simply waiting when you'll get an actual image.

Python: how to capture image from webcam on click using OpenCV

Breaking down your code example (Explanations are under the line of code.)

import cv2

imports openCV for usage

camera = cv2.VideoCapture(0)

creates an object called camera, of type openCV video capture, using the first camera in the list of cameras connected to the computer.

for i in range(10):

tells the program to loop the following indented code 10 times

    return_value, image = camera.read()

read values from the camera object, using it's read method. it resonds with 2 values save the 2 data values into two temporary variables called "return_value" and "image"

    cv2.imwrite('opencv'+str(i)+'.png', image)

use the openCV method imwrite (that writes an image to a disk) and write an image using the data in the temporary data variable

fewer indents means that the loop has now ended...

del(camera)

deletes the camrea object, we no longer needs it.

you can what you request in many ways, one could be to replace the for loop with a while loop, (running forever, instead of 10 times), and then wait for a keypress (like answered by danidee while I was typing)

or create a much more evil service that hides in the background and captures an image everytime someone presses the keyboard...

How to fire an event when v-model changes?

You can actually simplify this by removing the v-on directives:

<input type="radio" name="optionsRadios" id="optionsRadios1" value="1" v-model="srStatus">

And use the watch method to listen for the change:

new Vue ({
    el: "#app",
    data: {
        cases: [
            { name: 'case A', status: '1' },
            { name: 'case B', status: '0' },
            { name: 'case C', status: '1' }
        ],
        activeCases: [],
        srStatus: ''
    },
    watch: {
        srStatus: function(val, oldVal) {
            for (var i = 0; i < this.cases.length; i++) {
                if (this.cases[i].status == val) {
                    this.activeCases.push(this.cases[i]);
                    alert("Fired! " + val);
                }
            }
        }
    }
});

OS X Terminal Colors

If you want to have your ls colorized you have to edit your ~/.bash_profile file and add the following line (if not already written) :

source .bashrc

Then you edit or create ~/.bashrc file and write an alias to the ls command :

alias ls="ls -G"

Now you have to type source .bashrc in a terminal if already launched, or simply open a new terminal.

If you want more options in your ls juste read the manual ( man ls ). Options are not exactly the same as in a GNU/Linux system.

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

You can try to "Pod update" and/or "flutter clean"

I also set this setting in xcode.

The Objective-C interface setting is as follows:

ObjectiveC interface setting

Shortest way to check for null and assign another value if not

To assign a non-empty variable without repeating the actual variable name (and without assigning anything if variable is null!), you can use a little helper method with a Action parameter:

public static void CallIfNonEmpty(string value, Action<string> action)
{
    if (!string.IsNullOrEmpty(value))
        action(value);
}

And then just use it:

CallIfNonEmpty(this.approved_by, (s) => planRec.approved_by = s);

Concatenating two one-dimensional NumPy arrays

An alternative ist to use the short form of "concatenate" which is either "r_[...]" or "c_[...]" as shown in the example code beneath (see http://wiki.scipy.org/NumPy_for_Matlab_Users for additional information):

%pylab
vector_a = r_[0.:10.] #short form of "arange"
vector_b = array([1,1,1,1])
vector_c = r_[vector_a,vector_b]
print vector_a
print vector_b
print vector_c, '\n\n'

a = ones((3,4))*4
print a, '\n'
c = array([1,1,1])
b = c_[a,c]
print b, '\n\n'

a = ones((4,3))*4
print a, '\n'
c = array([[1,1,1]])
b = r_[a,c]
print b

print type(vector_b)

Which results in:

[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]
[1 1 1 1]
[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.  1.  1.  1.  1.] 


[[ 4.  4.  4.  4.]
 [ 4.  4.  4.  4.]
 [ 4.  4.  4.  4.]] 

[[ 4.  4.  4.  4.  1.]
 [ 4.  4.  4.  4.  1.]
 [ 4.  4.  4.  4.  1.]] 


[[ 4.  4.  4.]
 [ 4.  4.  4.]
 [ 4.  4.  4.]
 [ 4.  4.  4.]] 

[[ 4.  4.  4.]
 [ 4.  4.  4.]
 [ 4.  4.  4.]
 [ 4.  4.  4.]
 [ 1.  1.  1.]]

How to declare a global variable in php?

Let's think a little different, You can use static parameters:

class global {
    static $foo = "bar";
}

And you can use and modify it every where you like, like:

function func() {
    echo global::$foo;
}

Get UTC time in seconds

One might consider adding this line to ~/.bash_profile (or similar) in order to can quickly get the current UTC both as current time and as seconds since the epoch.

alias utc='date -u && date -u +%s'

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

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

svn resolve --accept working <YourPath>

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

JQuery datepicker language

Include language file source in your head script of the HTML body.

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>

Example on JSFiddle

How to generate XML file dynamically using PHP?

Take a look at the Tiny But Strong templating system. It's generally used for templating HTML but there's an extension that works with XML files. I use this extensively for creating reports where I can have one code file and two template files - htm and xml - and the user can then choose whether to send a report to screen or spreadsheet.

Another advantage is you don't have to code the xml from scratch, in some cases I've been wanting to export very large complex spreadsheets, and instead of having to code all the export all that is required is to save an existing spreadsheet in xml and substitute in code tags where data output is required. It's a quick and a very efficient way to work.

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

I defined two functions in Site.Master:

    <script type="text/javascript">
    var spinnerVisible = false;
    function showProgress() {
        if (!spinnerVisible) {
            $("div#spinner").fadeIn("fast");
            spinnerVisible = true;
        }
    };
    function hideProgress() {
        if (spinnerVisible) {
            var spinner = $("div#spinner");
            spinner.stop();
            spinner.fadeOut("fast");
            spinnerVisible = false;
        }
    };
</script>

And special section:

    <div id="spinner">
        Loading...
    </div>

Visual style is defined in CSS:

div#spinner
{
    display: none;
    width:100px;
    height: 100px;
    position: fixed;
    top: 50%;
    left: 50%;
    background:url(spinner.gif) no-repeat center #fff;
    text-align:center;
    padding:10px;
    font:normal 16px Tahoma, Geneva, sans-serif;
    border:1px solid #666;
    margin-left: -50px;
    margin-top: -50px;
    z-index:2;
    overflow: auto;
}

Remove a character at a certain position in a string - javascript

    var str = 'Hello World';
                str = setCharAt(str, 3, '');
                alert(str);

function setCharAt(str, index, chr)
        {
            if (index > str.length - 1) return str;
            return str.substr(0, index) + chr + str.substr(index + 1);
        }

Pick any kind of file via an Intent in Android

This gives me the best result:

    Intent intent;
    if (android.os.Build.MANUFACTURER.equalsIgnoreCase("samsung")) {
        intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
        intent.putExtra("CONTENT_TYPE", "*/*");
        intent.addCategory(Intent.CATEGORY_DEFAULT);
    } else {

        String[] mimeTypes =
                {"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
                        "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
                        "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
                        "text/plain",
                        "application/pdf",
                        "application/zip", "application/vnd.android.package-archive"};

        intent = new Intent(Intent.ACTION_GET_CONTENT); // or ACTION_OPEN_DOCUMENT
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    }

How to connect to remote Redis server?

There are two ways to connect remote redis server using redis-cli:

1. Using host & port individually as options in command

redis-cli -h host -p port

If your instance is password protected

redis-cli -h host -p port -a password

e.g. if my-web.cache.amazonaws.com is the host url and 6379 is the port

Then this will be the command:

redis-cli -h my-web.cache.amazonaws.com -p 6379

if 92.101.91.8 is the host IP address and 6379 is the port:

redis-cli -h 92.101.91.8 -p 6379

command if the instance is protected with password pass123:

redis-cli -h my-web.cache.amazonaws.com -p 6379 -a pass123

2. Using single uri option in command

redis-cli -u redis://password@host:port

command in a single uri form with username & password

redis-cli -u redis://username:password@host:port

e.g. for the same above host - port configuration command would be

redis-cli -u redis://[email protected]:6379

command if username is also provided user123

redis-cli -u redis://user123:[email protected]:6379

This detailed answer was for those who wants to check all options. For more information check documentation: Redis command line usage

Xcode warning: "Multiple build commands for output file"

Commenting use_frameworks! in PodFile worked for me.

#use_frameworks!

Note: Did this on XCode 10.1, pod version 1.8.4

Convert a 1D array to a 2D array in numpy

You want to reshape the array.

B = np.reshape(A, (-1, 2))

where -1 infers the size of the new dimension from the size of the input array.

Can I use git diff on untracked files?

For one file:

git diff --no-index /dev/null new_file

For all new files:

for next in $( git ls-files --others --exclude-standard ) ; do git --no-pager diff --no-index /dev/null $next; done;

As alias:

alias gdnew="for next in \$( git ls-files --others --exclude-standard ) ; do git --no-pager diff --no-index /dev/null \$next; done;"

For all modified and new files combined as one command:

{ git --no-pager diff; gdnew }

Read and parse a Json File in C#

How about making everything easier with Json.NET?

    public void LoadJson()
    {
        using (StreamReader r = new StreamReader("file.json"))
        {
            string json = r.ReadToEnd();
            List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
        }
    }

    public class Item
    {
        public int millis;
        public string stamp;
        public DateTime datetime;
        public string light;
        public float temp;
        public float vcc;
    }

You can even get the values dynamically without declaring Item class.

    dynamic array = JsonConvert.DeserializeObject(json);
    foreach(var item in array)
    {
        Console.WriteLine("{0} {1}", item.temp, item.vcc);
    }

Read a text file line by line in Qt

Use this code:

QFile inputFile(fileName);
if (inputFile.open(QIODevice::ReadOnly))
{
   QTextStream in(&inputFile);
   while (!in.atEnd())
   {
      QString line = in.readLine();
      ...
   }
   inputFile.close();
}

How to stop a thread created by implementing runnable interface?

Stopping (Killing) a thread mid-way is not recommended. The API is actually deprecated.

However,you can get more details including workarounds here: How do you kill a thread in Java?

Favorite Visual Studio keyboard shortcuts

Ctrl + .

To include a missing library.

How do I convert a decimal to an int in C#?

I find that the casting operator does not work if you have a boxed decimal (i.e. a decimal value inside an object type). Convert.ToInt32(decimal as object) works fine in this case.

This situation comes up when retrieving IDENTITY/AUTONUMBER values from the database:

SqlCommand foo = new SqlCommand("INSERT INTO...; SELECT SCOPE_IDENTITY()", conn);
int ID = Convert.ToInt32(foo.ExecuteScalar());  // works
int ID = (int)foo.ExecuteScalar();              // throws InvalidCastException

See 4.3.2 Unboxing conversions

Create a root password for PHPMyAdmin

I believe the command you are looking for is passwd

Jmeter - Run .jmx file through command line and get the summary report in a excel

Running JMeter in command line mode:

1.Navigate to JMeter’s bin directory

Now enter following command,

jmeter -n –t test.jmx

-n: specifies JMeter is to run in non-gui mode

-t: specifies name of JMX file that contains the Test Plan

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

List<String> arrayList = new ArrayList<String>();
for (String s : arrayList) {
    if(s.equals(value)){
        //do something
    }
}

or

for (int i = 0; i < arrayList.size(); i++) {
    if(arrayList.get(i).equals(value)){
        //do something
    }
}

But be carefull ArrayList can hold null values. So comparation should be

value.equals(arrayList.get(i))

when you are sure that value is not null or you should check if given element is null.

Java 8 Stream and operation on arrays

There are new methods added to java.util.Arrays to convert an array into a Java 8 stream which can then be used for summing etc.

int sum =  Arrays.stream(myIntArray)
                 .sum();

Multiplying two arrays is a little more difficult because I can't think of a way to get the value AND the index at the same time as a Stream operation. This means you probably have to stream over the indexes of the array.

//in this example a[] and b[] are same length
int[] a = ...
int[] b = ...

int[] result = new int[a.length];

IntStream.range(0, a.length)
         .forEach(i -> result[i] = a[i] * b[i]);

EDIT

Commenter @Holger points out you can use the map method instead of forEach like this:

int[] result = IntStream.range(0, a.length).map(i -> a[i] * b[i]).toArray();

count of entries in data frame in R

using sqldf fits here:

library(sqldf)
sqldf("SELECT Believe, Count(1) as N FROM Santa
       GROUP BY Believe")

Making an iframe responsive

iFrames CAN be FULLY responsive while keeping their aspect ratio with a little CSS technique called the Intrinsic Ratio Technique. I wrote a blog post addressing this question specifically: https://benmarshall.me/responsive-iframes/

This gist is:

_x000D_
_x000D_
.intrinsic-container {_x000D_
  position: relative;_x000D_
  height: 0;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
_x000D_
/* 16x9 Aspect Ratio */_x000D_
_x000D_
.intrinsic-container-16x9 {_x000D_
  padding-bottom: 56.25%;_x000D_
}_x000D_
_x000D_
_x000D_
/* 4x3 Aspect Ratio */_x000D_
_x000D_
.intrinsic-container-4x3 {_x000D_
  padding-bottom: 75%;_x000D_
}_x000D_
_x000D_
.intrinsic-container iframe {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}
_x000D_
<div class="intrinsic-container intrinsic-container-16x9">_x000D_
  <iframe src="//www.youtube.com/embed/KMYrIi_Mt8A" allowfullscreen></iframe>_x000D_
</div>
_x000D_
_x000D_
_x000D_

BOOM, fully responsive!