Programs & Examples On #Horizontalscrollview

A layout container for a view hierarchy that can be scrolled by the user, allowing it to be larger than the physical display

How to implement HorizontalScrollView like Gallery?

Try this code:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="100dip"
tools:context=".MainActivity" >
<HorizontalScrollView
    android:id="@+id/hsv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:fillViewport="true"
    android:measureAllChildren="false"
    android:scrollbars="none" >
    <LinearLayout
        android:id="@+id/innerLay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal" >
        <LinearLayout
            android:id="@+id/asthma_action_plan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/action_plan" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/controlled_medication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/controlled" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/as_needed_medication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/as_needed" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/rescue_medication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/rescue" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/your_symptoms"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/symptoms" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/your_triggers"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/triggers" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/wheeze_rate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/wheeze_rate" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/peak_flow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/peak_flow" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>
</HorizontalScrollView>
<TextView
    android:layout_width="fill_parent"
    android:layout_height="0.2dp"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/hsv"
    android:background="@drawable/ln" />
<LinearLayout
    android:id="@+id/prev"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:paddingLeft="5dip"
    android:paddingRight="5dip"
    android:descendantFocusability="blocksDescendants" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:src="@drawable/prev_arrow" />
</LinearLayout>
<LinearLayout
    android:id="@+id/next"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:paddingLeft="5dip"
    android:paddingRight="5dip"
    android:descendantFocusability="blocksDescendants" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:src="@drawable/next_arrow" />
</LinearLayout>
</RelativeLayout>

grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
    android:id="@+id/imageView1"
    android:layout_width="fill_parent"
    android:layout_height="100dp"
    android:src="@drawable/ic_launcher" />
</LinearLayout>

MainActivity.java

import java.util.ArrayList;

import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity {

LinearLayout asthmaActionPlan, controlledMedication, asNeededMedication,
        rescueMedication, yourSymtoms, yourTriggers, wheezeRate, peakFlow;
LayoutParams params;
LinearLayout next, prev;
int viewWidth;
GestureDetector gestureDetector = null;
HorizontalScrollView horizontalScrollView;
ArrayList<LinearLayout> layouts;
int parentLeft, parentRight;
int mWidth;
int currPosition, prevPosition;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    prev = (LinearLayout) findViewById(R.id.prev);
    next = (LinearLayout) findViewById(R.id.next);
    horizontalScrollView = (HorizontalScrollView) findViewById(R.id.hsv);
    gestureDetector = new GestureDetector(new MyGestureDetector());
    asthmaActionPlan = (LinearLayout) findViewById(R.id.asthma_action_plan);
    controlledMedication = (LinearLayout) findViewById(R.id.controlled_medication);
    asNeededMedication = (LinearLayout) findViewById(R.id.as_needed_medication);
    rescueMedication = (LinearLayout) findViewById(R.id.rescue_medication);
    yourSymtoms = (LinearLayout) findViewById(R.id.your_symptoms);
    yourTriggers = (LinearLayout) findViewById(R.id.your_triggers);
    wheezeRate = (LinearLayout) findViewById(R.id.wheeze_rate);
    peakFlow = (LinearLayout) findViewById(R.id.peak_flow);

    Display display = getWindowManager().getDefaultDisplay();
    mWidth = display.getWidth(); // deprecated
    viewWidth = mWidth / 3;
    layouts = new ArrayList<LinearLayout>();
    params = new LayoutParams(viewWidth, LayoutParams.WRAP_CONTENT);

    asthmaActionPlan.setLayoutParams(params);
    controlledMedication.setLayoutParams(params);
    asNeededMedication.setLayoutParams(params);
    rescueMedication.setLayoutParams(params);
    yourSymtoms.setLayoutParams(params);
    yourTriggers.setLayoutParams(params);
    wheezeRate.setLayoutParams(params);
    peakFlow.setLayoutParams(params);

    layouts.add(asthmaActionPlan);
    layouts.add(controlledMedication);
    layouts.add(asNeededMedication);
    layouts.add(rescueMedication);
    layouts.add(yourSymtoms);
    layouts.add(yourTriggers);
    layouts.add(wheezeRate);
    layouts.add(peakFlow);

    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    horizontalScrollView.smoothScrollTo(
                            (int) horizontalScrollView.getScrollX()
                                    + viewWidth,
                            (int) horizontalScrollView.getScrollY());
                }
            }, 100L);
        }
    });

    prev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    horizontalScrollView.smoothScrollTo(
                            (int) horizontalScrollView.getScrollX()
                                    - viewWidth,
                            (int) horizontalScrollView.getScrollY());
                }
            }, 100L);
        }
    });

    horizontalScrollView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            }
            return false;
        }
    });
}

class MyGestureDetector extends SimpleOnGestureListener {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        if (e1.getX() < e2.getX()) {
            currPosition = getVisibleViews("left");
        } else {
            currPosition = getVisibleViews("right");
        }

        horizontalScrollView.smoothScrollTo(layouts.get(currPosition)
                .getLeft(), 0);
        return true;
    }
}

public int getVisibleViews(String direction) {
    Rect hitRect = new Rect();
    int position = 0;
    int rightCounter = 0;
    for (int i = 0; i < layouts.size(); i++) {
        if (layouts.get(i).getLocalVisibleRect(hitRect)) {
            if (direction.equals("left")) {
                position = i;
                break;
            } else if (direction.equals("right")) {
                rightCounter++;
                position = i;
                if (rightCounter == 2)
                    break;
            }
        }
    }
    return position;
}
}

Let me know if any issue enjoy...

HorizontalScrollView within ScrollView Touch Handling

This finally became a part of support v4 library, NestedScrollView. So, no longer local hacks is needed for most of cases I'd guess.

Ansible: create a user with sudo privileges

Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.

Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.

The answer to my question is at Ansible: best practice for maintaining list of sudoers.

The Ansible playbook code fragment looks like this from my problem:

- name: Make sure we have a 'wheel' group
  group:
    name: wheel
    state: present

- name: Allow 'wheel' group to have passwordless sudo
  lineinfile:
    dest: /etc/sudoers
    state: present
    regexp: '^%wheel'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'
    validate: 'visudo -cf %s'

- name: Add sudoers users to wheel group
  user:
    name=deployer
    groups=wheel
    append=yes
    state=present
    createhome=yes

- name: Set up authorized keys for the deployer user
  authorized_key: user=deployer key="{{item}}"
  with_file:
    - /home/railsdev/.ssh/id_rsa.pub

And the best part is that the solution is idempotent. It doesn't add the line

%wheel ALL=(ALL) NOPASSWD: ALL

to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.

error: function returns address of local variable

a is defined locally in the function, and can't be used outside the function. If you want to return a char array from the function, you'll need to allocate it dynamically:

char *a = malloc(1000);

And at some point call free on the returned pointer.

You should also see a warning at this line: char b = "blah";: you're trying to assign a string literal to a char.

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

It may be because of the installation of Cors nuget packages.

If you facing the problem after installing and enabaling cors from nuget , then you may try reinstalling web Api.

From the package manager, run Update-Package Microsoft.AspNet.WebApi -reinstall

Why is document.body null in my javascript?

Or add this part

<script type="text/javascript">

    var mySpan = document.createElement("span");
    mySpan.innerHTML = "This is my span!";

    mySpan.style.color = "red";
    document.body.appendChild(mySpan);

    alert("Why does the span change after this alert? Not before?");

</script>

after the HTML, like:

    <html>
    <head>...</head>
    <body>...</body>
   <script type="text/javascript">
        var mySpan = document.createElement("span");
        mySpan.innerHTML = "This is my span!";

        mySpan.style.color = "red";
        document.body.appendChild(mySpan);

        alert("Why does the span change after this alert? Not before?");

    </script>

    </html>

Java Refuses to Start - Could not reserve enough space for object heap

I upgraded the memory of a machine from 2GB to 4GB, and started to get the error straight away:

$ java -version
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

The problem was the ulimit, which I had set at 1GB for the addressable space. Increasing it to 2GB solved the issue.

-Xms and -Xmx had no effect.

Looks like java tries to get memory in proportion to the available memory, and fails if it can't.

IF a == true OR b == true statement

Comparison expressions should each be in their own brackets:

{% if (a == 'foo') or (b == 'bar') %}
    ...
{% endif %}

Alternative if you are inspecting a single variable and a number of possible values:

{% if a in ['foo', 'bar', 'qux'] %}
    ...
{% endif %}

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

To diagnose this problem, run the service under the Visual Studio debugger. Use the menu: Debug|Exceptions and indicate that you want to break when an Exception is thrown.

The original exception thrown will have a much better error message than "..it is in the Faulted state."

For example I was getting this exception from ServiceHost.Open(), but when I caught the original exception at the time it was thrown, the error message was:

Service 'MyServiceName' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.

Fixing the spelling error in App.config solved the problem.

Adding text to a cell in Excel using VBA

You could do

[A1].Value = "'O1/01/13 00:00"

if you really mean to add it as text (note the apostrophe as the first character).

The [A1].Value is VBA shorthand for Range("A1").Value.

If you want to enter a date, you could instead do (edited order with thanks to @SiddharthRout):

[A1].NumberFormat = "mm/dd/yyyy hh:mm;@"
[A1].Value = DateValue("01/01/2013 00:00")

Fetching distinct values on a column using Spark DataFrame

Well to obtain all different values in a Dataframe you can use distinct. As you can see in the documentation that method returns another DataFrame. After that you can create a UDF in order to transform each record.

For example:

val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")

// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct

// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)

// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

Remember to install AccessDatabaseEngine on server for web application.

What are some uses of template template parameters?

I use it for versioned types.

If you have a type versioned through a template such as MyType<version>, you can write a function in which you can capture the version number:

template<template<uint8_t> T, uint8_t Version>
Foo(const T<Version>& obj)
{
    assert(Version > 2 && "Versions older than 2 are no longer handled");
    ...
    switch (Version)
    {
    ...
    }
}

So you can do different things depending on the version of the type being passed in instead of having an overload for each type. You can also have conversion functions which take in MyType<Version> and return MyType<Version+1>, in a generic way, and even recurse them to have a ToNewest() function which returns the latest version of a type from any older version (very useful for logs that might have been stored a while back but need to be processed with today's newest tool).

how to put focus on TextBox when the form load?

it's worked for me set tabindex to 0 this.yourtextbox.TabIndex = 0;

Replace spaces with dashes and make all letters lower-case

Above answer can be considered to be confusing a little. String methods are not modifying original object. They return new object. It must be:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase(); //new object assigned to var str

How to make circular background using css?

You can use the :before and :after pseudo-classes to put a multi-layered background on a element.

#divID : before {
    background: url(someImage);
}

#div : after {
    background : url(someotherImage) -10% no-repeat;
}

how to change text box value with jQuery?

<style>
    .form-cus {
        width: 200px;
        margin: auto;
        position: relative;
    }
        .form-cus .putval, .form-cus .getval {
            width: 100%;
        }
        .form-cus .putval {
            position: absolute;
            left: 0px;
            top: 0;
            color: transparent !important;
            box-shadow: 0 0 0 0 !important;
            background-color: transparent !important;
            border: 0px;
            outline: 0 none;
        }
            .form-cus .putval::selection {
                color: transparent;
                background: lightblue;
            }
</style>

<link href="css/bootstrap.min.css" rel="stylesheet" />
<script src="js/jquery.min.js"></script>
<div class="form-group form-cus">
    <input class="putval form-control" type="text" id="input" maxlength="16" oninput="xText();">
    <input class="getval form-control" type="text" id="output" maxlength="16">
</div>

<script type="text/javascript">
    function xText() {
        var x = $("#input").val();
        var x_length = x.length;
        var a = '';
        for (var i = 0; i < x_length; i++) {
            a += "x";
        }
        $("#output").val(a);
     }
    $("#input").click(function(){
     $("#output").trigger("click");
    })

</script>

Telling gcc directly to link a library statically

You can add .a file in the linking command:

  gcc yourfiles /path/to/library/libLIBRARY.a

But this is not talking with gcc driver, but with ld linker as options like -Wl,anything are.

When you tell gcc or ld -Ldir -lLIBRARY, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose). To change order of library types checked you can use -Wl,-Bstatic and -Wl,-Bdynamic. Here is a man page of gnu LD: http://linux.die.net/man/1/ld

To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:

gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3

Assuming that default setting of ld is to use dynamic libraries (it is on Linux).

When to use Common Table Expression (CTE)

It is very useful when you want to perform an "ordered update".

MS SQL does not allow you to use ORDER BY with UPDATE, but with help of CTE you can do it that way:

WITH cte AS
(
    SELECT TOP(5000) message_compressed, message, exception_compressed, exception
    FROM logs
    WHERE Id >= 5519694 
    ORDER BY Id
)
UPDATE  cte
SET     message_compressed = COMPRESS(message), exception_compressed = COMPRESS(exception)

Look here for more info: How to update and order by using ms sql

Nested jQuery.each() - continue/break

Unfortunately no. The problem here is that the iteration happens inside functions, so they aren't like normal loops. The only way you can "break" out of a function is by returning or by throwing an exception. So yes, using a boolean flag seems to be the only reasonable way to "break" out of the outer "loop".

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

In my case I had 2 projects A and B. And I upgraded to gradle 4.5.

A was dependent on B but both had references of my 3rd party jar

I was getting this error

com.android.tools.r8.errors.CompilationError: Program type already present: com.mnox.webservice.globals.WebServiceLightErrorHashCode

Program type already present: com.mnox.webservice.globals.WebServiceLightErrorHashCode

To fix it

  1. I removed the duplicate jar's
  2. I used api in the B build.gradle file so that it gets referred to in A.

The other root cause can be if you have upgraded to gradle 4.5 and used implementation instead of api in your commons build.gradle

Change windows hostname from command line

Why be easy when it can be complicated? Why use third-party applications like netdom.exe when correct interogations is the way? Try 2 interogations:

wmic computersystem where caption='%computername%' get caption, UserName, Domain /format:value

wmic computersystem where "caption like '%%%computername%%%'" get caption, UserName, Domain /format:value

or in a batch file use loop

for /f "tokens=2 delims==" %%i in ('wmic computersystem where "Caption like '%%%currentname%%%'" get UserName /format:value') do (echo. UserName- %%i)

How to asynchronously call a method in Java

You may wish to also consider the class java.util.concurrent.FutureTask.

If you are using Java 5 or later, FutureTask is a turnkey implementation of "A cancellable asynchronous computation."

There are even richer asynchronous execution scheduling behaviors available in the java.util.concurrent package (for example, ScheduledExecutorService), but FutureTask may have all the functionality you require.

I would even go so far as to say that it is no longer advisable to use the first code pattern you gave as an example ever since FutureTask became available. (Assuming you are on Java 5 or later.)

jQuery ajax call to REST service

From the use of 8080 I'm assuming you are using a tomcat servlet container to serve your rest api. If this is the case you can also consider to have your webserver proxy the requests to the servlet container.

With apache you would typically use mod_jk (although there are other alternatives) to serve the api trough the web server behind port 80 instead of 8080 which would solve the cross domain issue.

This is common practice, have the 'static' content in the webserver and dynamic content in the container, but both served from behind the same domain.

The url for the rest api would be http://localhost/restws/json/product/get

Here a description on how to use mod_jk to connect apache to tomcat: http://tomcat.apache.org/connectors-doc/webserver_howto/apache.html

Get ID of element that called a function

I know you don't want a jQuery solution but including javascript inside HTML is a big no no.

I mean you can do it but there are lots of reasons why you shouldn't (read up on unobtrusive javascript if you want the details).

So in the interest of other people who may see this question, here is the jQuery solution:

$(document).ready(function() {
  $('area').mouseover(function(event) {
    $('#preview').attr('src', 'images/' + $(event.srcElement).attr('id'));
  });
});

The major benefit is you don't mix javascript code with HTML. Further more, you only need to write this once and it will work for all tags as opposed to having to specify the handler for each separately.

Additional benefit is that every jQuery handler receives an event object that contains a lot of useful data - such as the source of the event, type of the event and so on making it much easier to write the kind of code you are after.

Finally since it's jQuery you don't need to think about cross-browser stuff - a major benefit especially when dealing with events.

Replace all occurrences of a string in a data frame

Equivalent to "find and replace." Don't overthink it.

Try it with one:

library(tidyverse)
df <- data.frame(name = rep(letters[1:3], each = 3), var1 = rep('< 2', 9), var2 = rep('<3', 9))

df %>% 
  mutate(var1 = str_replace(var1, " ", ""))
#>   name var1 var2
#> 1    a   <2   <3
#> 2    a   <2   <3
#> 3    a   <2   <3
#> 4    b   <2   <3
#> 5    b   <2   <3
#> 6    b   <2   <3
#> 7    c   <2   <3
#> 8    c   <2   <3
#> 9    c   <2   <3

Apply to all

df %>% 
  mutate_all(funs(str_replace(., " ", "")))
#>   name var1 var2
#> 1    a   <2   <3
#> 2    a   <2   <3
#> 3    a   <2   <3
#> 4    b   <2   <3
#> 5    b   <2   <3
#> 6    b   <2   <3
#> 7    c   <2   <3
#> 8    c   <2   <3
#> 9    c   <2   <3

If the extra space was produced by uniting columns, think about making str_trim part of your workflow.

Created on 2018-03-11 by the reprex package (v0.2.0).

When to use static keyword before global variables?

You should not define global variables in header files. You should define them in .c source file.

  • If global variable is to be visible within only one .c file, you should declare it static.

  • If global variable is to be used across multiple .c files, you should not declare it static. Instead you should declare it extern in header file included by all .c files that need it.

Example:

  • example.h

    extern int global_foo;
    
  • foo.c

    #include "example.h"
    
    int global_foo = 0;
    static int local_foo = 0;
    
    int foo_function()
    {
       /* sees: global_foo and local_foo
          cannot see: local_bar  */
       return 0;
    }
    
  • bar.c

    #include "example.h"
    
    static int local_bar = 0;
    static int local_foo = 0;
    
    int bar_function()
    {
        /* sees: global_foo, local_bar */
        /* sees also local_foo, but it's not the same local_foo as in foo.c
           it's another variable which happen to have the same name.
           this function cannot access local_foo defined in foo.c
        */
        return 0;
    }
    

How can I make a float top with CSS?

The only way to do this with CSS only is by using CSS 3 which is not going to work on every browser (only the latest generation like FF 3.5, Opera, Safari, Chrome).

Indeed with CSS 3 there's this awesome property : column-count that you can use like so :

#myContent{
  column-count: 2;
  column-gap: 20px;
  height: 350px;
}

If #myContent is wrapping your other divs.

More info here : http://www.quirksmode.org/css/multicolumn.html

As you can read there, there are serious limitations in using this. In the example above, it will only add up to one another column if the content overflows. in mozilla you can use the column-width property that allows you to divide the content in as many columns as needed.

Otherwise you'll have to distribute the content between different divs in Javascript or in the backend.

How to make the window full screen with Javascript (stretching all over the screen)

Try screenfull.js. It's a nice cross-browser solution that should work for Opera browser as well.

Simple wrapper for cross-browser usage of the JavaScript Fullscreen API, which lets you bring the page or any element into fullscreen. Smoothens out the browser implementation differences, so you don't have to.

Demo.

Print all properties of a Python Class

Another way is to call the dir() function (see https://docs.python.org/2/library/functions.html#dir).

a = Animal()
dir(a)   
>>>
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__',
 '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', 
 '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
 '__weakref__', 'age', 'color', 'kids', 'legs', 'name', 'smell']

Note, that dir() tries to reach any attribute that is possible to reach.

Then you can access the attributes e.g. by filtering with double underscores:

attributes = [attr for attr in dir(a) 
              if not attr.startswith('__')]

This is just an example of what is possible to do with dir(), please check the other answers for proper way of doing this.

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

I honestly suggest that you use moment.js. Just download moment.min.js and then use this snippet to get your date in whatever format you want:

<script>
$(document).ready(function() {

     // set an element
     $("#date").val( moment().format('MMM D, YYYY') );

     // set a variable
     var today = moment().format('D MMM, YYYY');

});
</script>

Use following chart for date formats:

enter image description here

Batch command date and time in file name

From the answer above, I have made a ready-to-use function.

Validated with french local settings.

:::::::: PROGRAM ::::::::::

call:genname "my file 1.txt"
echo "%newname%"
call:genname "my file 2.doc"
echo "%newname%"

echo.&pause&goto:eof
:::::::: FUNCTIONS :::::::::

:genname
    set d1=%date:~-4,4%
    set d2=%date:~-10,2%
    set d3=%date:~-7,2%
    set t1=%time:~0,2%
    ::if "%t1:~0,1%" equ " " set t1=0%t1:~1,1%
    set t1=%t1: =0%
    set t2=%time:~3,2%
    set t3=%time:~6,2%
    set filename=%~1
    set newname=%d1%%d2%%d3%_%t1%%t2%%t3%-%filename%
goto:eof

Loop through all nested dictionary values?

Here is pythonic way to do it. This function will allow you to loop through key-value pair in all the levels. It does not save the whole thing to the memory but rather walks through the dict as you loop through it

def recursive_items(dictionary):
    for key, value in dictionary.items():
        if type(value) is dict:
            yield (key, value)
            yield from recursive_items(value)
        else:
            yield (key, value)

a = {'a': {1: {1: 2, 3: 4}, 2: {5: 6}}}

for key, value in recursive_items(a):
    print(key, value)

Prints

a {1: {1: 2, 3: 4}, 2: {5: 6}}
1 {1: 2, 3: 4}
1 2
3 4
2 {5: 6}
5 6

How to set the font style to bold, italic and underlined in an Android TextView?

This should make your TextView bold, underlined and italic at the same time.

strings.xml

<resources>
    <string name="register"><u><b><i>Copyright</i></b></u></string>
</resources>

To set this String to your TextView, do this in your main.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/register" />

or In JAVA,

TextView textView = new TextView(this);
textView.setText(R.string.register);

Sometimes the above approach will not be helpful when you might have to use Dynamic Text. So in that case SpannableString comes into action.

String tempString="Copyright";
TextView text=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.ITALIC), 0, spanString.length(), 0);
text.setText(spanString);

OUTPUT

enter image description here

What is pipe() function in Angular

You have to look to official ReactiveX documentation: https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md.

This is a good article about piping in RxJS: https://blog.hackages.io/rxjs-5-5-piping-all-the-things-9d469d1b3f44.

In short .pipe() allows chaining multiple pipeable operators.

Starting in version 5.5 RxJS has shipped "pipeable operators" and renamed some operators:

do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize

Using IF ELSE in Oracle

You can use Decode as well:

SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
      AND A.ITEM_KEY = b.item_key
      AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
                         and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item

How to plot a histogram using Matplotlib in Python with a list of data?

If you haven't installed matplotlib yet just try the command.

> pip install matplotlib

Library import

import matplotlib.pyplot as plot

The histogram data:

plot.hist(weightList,density=1, bins=20) 
plot.axis([50, 110, 0, 0.06]) 
#axis([xmin,xmax,ymin,ymax])
plot.xlabel('Weight')
plot.ylabel('Probability')

Display histogram

plot.show()

And the output is like :

enter image description here

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

How to implement __iter__(self) for a container object (Python)

If your object contains a set of data you want to bind your object's iter to, you can cheat and do this:

>>> class foo:
    def __init__(self, *params):
           self.data = params
    def __iter__(self):
        if hasattr(self.data[0], "__iter__"):
            return self.data[0].__iter__()
        return self.data.__iter__()
>>> d=foo(6,7,3,8, "ads", 6)
>>> for i in d:
    print i
6
7
3
8
ads
6

How To have Dynamic SQL in MySQL Stored Procedure

I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

Here is an example:

mysql> PREPARE stmt FROM 
    -> 'select count(*) 
    -> from information_schema.schemata 
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt 
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;

The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

Here is a good link about this:

Don't forget to deallocate the stmt using the last line!

Good Luck!

Push commits to another branch

That will almost work.

When pushing to a non-default branch, you need to specify the source ref and the target ref:

git push origin branch1:branch2

Or

git push <remote> <branch with new changes>:<branch you are pushing to> 

How to draw a circle with text in the middle?

If it's only one line of text you could use the line-height property, with the same value as the element height:

height:100px;
line-height:100px;

If the text has multiple lines, or if the content is variable, you could use the padding-top:

padding-top:30px;
height:70px;

Example: http://jsfiddle.net/2GUFL/

Create a function with optional call variables

Not sure I understand the question correctly.

From what I gather, you want to be able to assign a value to Domain if it is null and also what to check if $args2 is supplied and according to the value, execute a certain code?

I changed the code to reassemble the assumptions made above.

Function DoStuff($computername, $arg2, $domain)
{
    if($domain -ne $null)
    {
        $domain = "Domain1"
    }

    if($arg2 -eq $null)
    {
    }
    else
    {
    }
}

DoStuff -computername "Test" -arg2 "" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Test"  -domain ""
DoStuff -computername "Test" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Domain2"

Did that help?

C# Macro definitions in Preprocessor

Turn the C Macro into a C# static method in a class.

Close application and launch home screen on Android

It's actually quiet easy.

The way I do this is by saving a flag in a static variable available to all. Then, when I exit, I set this flag and all my activities check this flag onResume. If the flag is set then I issue the System.exit on that activity.

That way all activities will check for the flag and will close gracefully if the flag is set.

Remove characters from C# string

Comparing various suggestions (as well as comparing in the context of single-character replacements with various sizes and positions of the target).

In this particular case, splitting on the targets and joining on the replacements (in this case, empty string) is the fastest by at least a factor of 3. Ultimately, performance is different depending on the number of replacements, where the replacements are in the source, and the size of the source. #ymmv

Results

(full results here)

| Test                      | Compare | Elapsed                                                            |
|---------------------------|---------|--------------------------------------------------------------------|
| SplitJoin                 | 1.00x   | 29023 ticks elapsed (2.9023 ms) [in 10K reps, 0.00029023 ms per]   |
| Replace                   | 2.77x   | 80295 ticks elapsed (8.0295 ms) [in 10K reps, 0.00080295 ms per]   |
| RegexCompiled             | 5.27x   | 152869 ticks elapsed (15.2869 ms) [in 10K reps, 0.00152869 ms per] |
| LinqSplit                 | 5.43x   | 157580 ticks elapsed (15.758 ms) [in 10K reps, 0.0015758 ms per]   |
| Regex, Uncompiled         | 5.85x   | 169667 ticks elapsed (16.9667 ms) [in 10K reps, 0.00169667 ms per] |
| Regex                     | 6.81x   | 197551 ticks elapsed (19.7551 ms) [in 10K reps, 0.00197551 ms per] |
| RegexCompiled Insensitive | 7.33x   | 212789 ticks elapsed (21.2789 ms) [in 10K reps, 0.00212789 ms per] |
| Regex Insentive           | 7.52x   | 218164 ticks elapsed (21.8164 ms) [in 10K reps, 0.00218164 ms per] |

Test Harness (LinqPad)

(note: the Perf and Vs are timing extensions I wrote)

void test(string title, string sample, string target, string replacement) {
    var targets = target.ToCharArray();

    var tox = "[" + target + "]";
    var x = new Regex(tox);
    var xc = new Regex(tox, RegexOptions.Compiled);
    var xci = new Regex(tox, RegexOptions.Compiled | RegexOptions.IgnoreCase);

    // no, don't dump the results
    var p = new Perf/*<string>*/();
        p.Add(string.Join(" ", title, "Replace"), n => targets.Aggregate(sample, (res, curr) => res.Replace(new string(curr, 1), replacement)));
        p.Add(string.Join(" ", title, "SplitJoin"), n => String.Join(replacement, sample.Split(targets)));
        p.Add(string.Join(" ", title, "LinqSplit"), n => String.Concat(sample.Select(c => targets.Contains(c) ? replacement : new string(c, 1))));
        p.Add(string.Join(" ", title, "Regex"), n => Regex.Replace(sample, tox, replacement));
        p.Add(string.Join(" ", title, "Regex Insentive"), n => Regex.Replace(sample, tox, replacement, RegexOptions.IgnoreCase));
        p.Add(string.Join(" ", title, "Regex, Uncompiled"), n => x.Replace(sample, replacement));
        p.Add(string.Join(" ", title, "RegexCompiled"), n => xc.Replace(sample, replacement));
        p.Add(string.Join(" ", title, "RegexCompiled Insensitive"), n => xci.Replace(sample, replacement));

    var trunc = 40;
    var header = sample.Length > trunc ? sample.Substring(0, trunc) + "..." : sample;

    p.Vs(header);
}

void Main()
{
    // also see https://stackoverflow.com/questions/7411438/remove-characters-from-c-sharp-string

    "Control".Perf(n => { var s = "*"; });


    var text = "My name @is ,Wan.;'; Wan";
    var clean = new[] { '@', ',', '.', ';', '\'' };

    test("stackoverflow", text, string.Concat(clean), string.Empty);


    var target = "o";
    var f = "x";
    var replacement = "1";

    var fillers = new Dictionary<string, string> {
        { "short", new String(f[0], 10) },
        { "med", new String(f[0], 300) },
        { "long", new String(f[0], 1000) },
        { "huge", new String(f[0], 10000) }
    };

    var formats = new Dictionary<string, string> {
        { "start", "{0}{1}{1}" },
        { "middle", "{1}{0}{1}" },
        { "end", "{1}{1}{0}" }
    };

    foreach(var filler in fillers)
    foreach(var format in formats) {
        var title = string.Join("-", filler.Key, format.Key);
        var sample = string.Format(format.Value, target, filler.Value);

        test(title, sample, target, replacement);
    }
}

ASP.NET MVC get textbox input value

Another way by using ajax method:

View:

@Html.TextBox("txtValue", null, new { placeholder = "Input value" })
<input type="button" value="Start" id="btnStart"  />

<script>
    $(function () {
        $('#btnStart').unbind('click');
        $('#btnStart').on('click', function () {
            $.ajax({
                url: "/yourControllerName/yourMethod",
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: JSON.stringify({
                    txtValue: $("#txtValue").val()
                }),
                async: false
            });
       });
   });
</script>

Controller:

[HttpPost]
public EmptyResult YourMethod(string txtValue)
{
    // do what you want with txtValue
    ...
}

What is the best way to extract the first word from a string in Java?

You can use String.split with a limit of 2.

    String s = "Hello World, I'm the rest.";
    String[] result = s.split(" ", 2);
    String first = result[0];
    String rest = result[1];
    System.out.println("First: " + first);
    System.out.println("Rest: " + rest);

    // prints =>
    // First: Hello
    // Rest: World, I'm the rest.

Running code after Spring Boot starts

you can use @Component

@RequiredArgsConstructor
@Component
@Slf4j
public class BeerLoader implements CommandLineRunner {
    //declare 

    @Override
    public void run(String... args) throws Exception {
        //some code here 

    }

How do I resolve "Run-time error '429': ActiveX component can't create object"?

You say it works once you install the VB6 IDE so the problem is likely to be that the components you are trying to use depend on the VB6 runtime being installed.

The VB6 runtime isn't installed on Windows by default.

Installing the IDE is one way to get the runtime. For non-developer machines, a "redistributable" installer package from Microsoft should be used instead.

Here is one VB6 runtime installer from Microsoft. I'm not sure if it will be the right version for your components:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=7b9ba261-7a9c-43e7-9117-f673077ffb3c

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

Implement runtime permission for running your app on Android 6.0 Marshmallow (API 23) or later.

or you can manually enable the storage permission-

goto settings>apps> "your_app_name" >click on it >then click permissions> then enable the storage. Thats it.

But i suggest go the for first one which is, Implement runtime permissions in your code.

What is the best way to get the count/length/size of an iterator?

Using Guava library, another option is to convert the Iterable to a List.

List list = Lists.newArrayList(some_iterator);
int count = list.size();

Use this if you need also to access the elements of the iterator after getting its size. By using Iterators.size() you no longer can access the iterated elements.

Two constructors

The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();

android set button background programmatically

button.setBackgroundColor(getResources().getColor(R.color.red);

Sets the background color for this view. Parameters: color the color of the background

R.color.red is a reference generated at the compilation in gen.

How to continue the code on the next line in VBA

In VBA (and VB.NET) the line terminator (carriage return) is used to signal the end of a statement. To break long statements into several lines, you need to

Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).

(From How to: Break and Combine Statements in Code)

In other words: Whenever the interpreter encounters the sequence <space>_<line terminator>, it is ignored and parsing continues on the next line. Note, that even when ignored, the line continuation still acts as a token separator, so it cannot be used in the middle of a variable name, for example. You also cannot continue a comment by using a line-continuation character.

To break the statement in your question into several lines you could do the following:

U_matrix(i, j, n + 1) = _
     k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
     (k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

(Leading whitespaces are ignored.)

How to write std::string to file?

remove the ios::binary from your modes in your ofstream and use studentPassword.c_str() instead of (char *)&studentPassword in your write.write()

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

An alternative way of sending a large number of repeating characters to a text field (for instance to test the maximum number of characters the field will allow) is to type a few characters and then repeatedly copy and paste them:

inputField.sendKeys('0123456789');
for(int i = 0; i < 100; i++) {
    inputField.sendKeys(Key.chord(Key.CONTROL, 'a'));
    inputField.sendKeys(Key.chord(Key.CONTROL, 'c'));
    for(int i = 0; i < 10; i++) {
        inputField.sendKeys(Key.chord(Key.CONTROL, 'v'));
    }
}

Unfortunately pressing CTRL doesn't seem to work for IE unless REQUIRE_WINDOW_FOCUS is enabled (which can cause other issues), but it works fine for Firefox and Chrome.

How to restart remote MySQL server running on Ubuntu linux?

sudo service mysql stop;
sudo service mysql start;

If the above process will not work let's check one the given code above you can stop Mysql server and again start server

PostgreSQL delete with inner join

Another form that works with Postgres 9.1+ is combining a Common Table Expression with the USING statement for the join.

WITH prod AS (select m_product_id, upc from m_product where upc='7094')
DELETE FROM m_productprice B
USING prod C
WHERE B.m_product_id = C.m_product_id 
AND B.m_pricelist_version_id = '1000020';

Entity Framework - Code First - Can't Store List<String>

JSON.NET to the rescue.

You serialize it to JSON to persist in the Database and Deserialize it to reconstitute the .NET collection. This seems to perform better than I expected it to with Entity Framework 6 & SQLite. I know you asked for List<string> but here's an example of an even more complex collection that works just fine.

I tagged the persisted property with [Obsolete] so it would be very obvious to me that "this is not the property you are looking for" in the normal course of coding. The "real" property is tagged with [NotMapped] so Entity framework ignores it.

(unrelated tangent): You could do the same with more complex types but you need to ask yourself did you just make querying that object's properties too hard for yourself? (yes, in my case).

using Newtonsoft.Json;
....
[NotMapped]
public Dictionary<string, string> MetaData { get; set; } = new Dictionary<string, string>();

/// <summary> <see cref="MetaData"/> for database persistence. </summary>
[Obsolete("Only for Persistence by EntityFramework")]
public string MetaDataJsonForDb
{
    get
    {
        return MetaData == null || !MetaData.Any()
                   ? null
                   : JsonConvert.SerializeObject(MetaData);
    }

    set
    {
        if (string.IsNullOrWhiteSpace(value))
           MetaData.Clear();
        else
           MetaData = JsonConvert.DeserializeObject<Dictionary<string, string>>(value);
    }
}

WHERE Clause to find all records in a specific month

Using the MONTH and YEAR functions as suggested in most of the responses has the disadvantage that SQL Server will not be able to use any index there may be on your date column. This can kill performance on a large table.

I would be inclined to pass a DATETIME value (e.g. @StartDate) to the stored procedure which represents the first day of the month you are interested in.

You can then use

SELECT ... FROM ...
WHERE DateColumn >= @StartDate 
AND DateColumn < DATEADD(month, 1, @StartDate)

If you must pass the month and year as separate parameters to the stored procedure, you can generate a DATETIME representing the first day of the month using CAST and CONVERT then proceed as above. If you do this I would recommend writing a function that generates a DATETIME from integer year, month, day values, e.g. the following from a SQL Server blog.

create function Date(@Year int, @Month int, @Day int)
returns datetime
as
    begin
    return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
    end
go

The query then becomes:

SELECT ... FROM ...
WHERE DateColumn >= Date(@Year,@Month,1)
AND DateColumn < DATEADD(month, 1, Date(@Year,@Month,1))

How can I create a dynamically sized array of structs?

If you want to grow the array dynamically, you should use malloc() to dynamically allocate some fixed amount of memory, and then use realloc() whenever you run out. A common technique is to use an exponential growth function such that you allocate some small fixed amount and then make the array grow by duplicating the allocated amount.

Some example code would be:

size = 64; i = 0;
x = malloc(sizeof(words)*size); /* enough space for 64 words */
while (read_words()) {
    if (++i > size) {
        size *= 2;
        x = realloc(sizeof(words) * size);
    }
}
/* done with x */
free(x);

Writing List of Strings to Excel CSV File in Python

Very simple to fix, you just need to turn the parameter to writerow into a list.

for item in RESULTS:
     wr.writerow([item,])

Adding git branch on the Bash command prompt

At first, open your Bash Profile in your home directory. The easiest way to open & edit your bash_profile using your default editor.

For example, I open it using the VS Code using this command: code .bash_profile.

Then just paste the following codes to your Bash.

parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

The function

parse_git_branch()

will fetch the branch name & then through PS1 you can show it in your terminal.

Here,

\u = Username

@ = Static Text

\h = Computer Name

\w = Current Directory

$ = Static Text

You can change or remove these variables for more customization.


If you use Git for the first time in terminal or instantly after configuration, maybe sometimes you can not see the branch name.

If you get this problem, don't worry. In that case, just make a sample repository and commit it after some changes. When the commit command will execute once, the terminal will find git branch from then.


Screenshot: Git Branch in Terminal

Squash the first two commits in Git?

You could use rebase interactive to modify the last two commits before they've been pushed to a remote

git rebase HEAD^^ -i

How do you use bcrypt for hashing passwords in PHP?

You can create a one-way hash with bcrypt using PHP's crypt() function and passing in an appropriate Blowfish salt. The most important of the whole equation is that A) the algorithm hasn't been compromised and B) you properly salt each password. Don't use an application-wide salt; that opens up your entire application to attack from a single set of Rainbow tables.

PHP - Crypt Function

REST API error return good practices

There are two sorts of errors. Application errors and HTTP errors. The HTTP errors are just to let your AJAX handler know that things went fine and should not be used for anything else.

5xx Server Error

500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported
506 Variant Also Negotiates (RFC 2295 )
507 Insufficient Storage (WebDAV) (RFC 4918 )
509 Bandwidth Limit Exceeded (Apache bw/limited extension)
510 Not Extended (RFC 2774 )

2xx Success

200 OK
201 Created
202 Accepted
203 Non-Authoritative Information (since HTTP/1.1)
204 No Content
205 Reset Content
206 Partial Content
207 Multi-Status (WebDAV)

However, how you design your application errors is really up to you. Stack Overflow for example sends out an object with response, data and message properties. The response I believe contains true or false to indicate if the operation was successful (usually for write operations). The data contains the payload (usually for read operations) and the message contains any additional metadata or useful messages (such as error messages when the response is false).

exceeds the list view threshold 5000 items in Sharepoint 2010

SharePoint lists V: Techniques for managing large lists :

Tutorial By Microsoft

Level: Advanced

Length: 40 - 50 minutes

When a SharePoint list gets large, you might see warnings such as, “This list exceeds the list view threshold,” or “Displaying the newest results below.” Find out why these warnings occur, and learn ways to configure your large list so that it still provides useful information.

After completing this course you will be able to:

  • Learn what the List View Threshold is, and understand its benefits.
  • Create an index so that you can see more information in a view.
  • Create folders to better organize your large list.
  • Use Datasheet view for fast filtering and sorting of a large list.
  • Learn what the Daily Time Window for Large Queries is.
  • Use Key Filters for fast filtering within Standard view.
  • Sync a large list to SharePoint Workspace.
  • Export a large list to Excel. Link a large list in Access.

How can I select the row with the highest ID in MySQL?

SELECT * FROM permlog ORDER BY id DESC LIMIT 0, 1

How to print the contents of RDD?

You can convert your RDD to a DataFrame then show() it.

// For implicit conversion from RDD to DataFrame
import spark.implicits._

fruits = sc.parallelize([("apple", 1), ("banana", 2), ("orange", 17)])

// convert to DF then show it
fruits.toDF().show()

This will show the top 20 lines of your data, so the size of your data should not be an issue.

+------+---+                                                                    
|    _1| _2|
+------+---+
| apple|  1|
|banana|  2|
|orange| 17|
+------+---+

How to get the squared symbol (²) to display in a string

No need to get too complicated. If all you need is ² then use the unicode representation.

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

(which is how I assume you got the ² to appear in your question. )

How to input a path with a white space?

SOME_PATH=/mnt/someProject/some\ path

should work

How do you get assembler output from C/C++ source in gcc?

Use "-S" as an option. It displays the assembly output in the terminal.

checking if a number is divisible by 6 PHP

$num += (6-$num%6)%6;

no need for a while loop! Modulo (%) returns the remainder of a division. IE 20%6 = 2. 6-2 = 4. 20+4 = 24. 24 is divisible by 6.

error: expected class-name before ‘{’ token

I know it is a bit late to answer this question, but it is the first entry in google, so I think it is worth to answer it.

The problem is not a coding problem, it is an architecture problem.

You have created an interface class Event: public Item to define the methods which all events should implement. Then you have defined two types of events which inherits from class Event: public Item; Arrival and Landing and then, you have added a method Landing* createNewLanding(Arrival* arrival); from the landing functionality in the class Event: public Item interface. You should move this method to the class Landing: public Event class because it only has sense for a landing. class Landing: public Event and class Arrival: public Event class should know class Event: public Item but event should not know class Landing: public Event nor class Arrival: public Event.

I hope this helps, regards, Alberto

Check if a div does NOT exist with javascript

I do below and check if id exist and execute function if exist.

var divIDVar = $('#divID').length;
if (divIDVar === 0){ 
    console.log('No DIV Exist'); 
} else{  
    FNCsomefunction(); 
}   

AngularJS - get element attributes values

_x000D_
_x000D_
function onContentLoad() {_x000D_
  var item = document.getElementById("id1");_x000D_
  var x = item.dataset.x;_x000D_
  var data = item.dataset.myData;_x000D_
_x000D_
  var resX = document.getElementById("resX");_x000D_
  var resData = document.getElementById("resData");_x000D_
_x000D_
  resX.innerText = x;_x000D_
  resData.innerText = data;_x000D_
_x000D_
  console.log(x);_x000D_
  console.log(data);_x000D_
}
_x000D_
<body onload="onContentLoad()">_x000D_
  <div id="id1" data-x="a" data-my-data="b"></div>_x000D_
_x000D_
  Read 'x':_x000D_
  <label id="resX"></label>_x000D_
  <br/>Read 'my-data':_x000D_
  <label id="resData"></label>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Intro to GPU programming

Take a look at the ATI Stream Computing SDK. It is based on BrookGPU developed at Stanford.

In the future all GPU work will be standardized using OpenCL. It's an Apple-sponsored initiative that will be graphics card vendor neutral.

dropping infinite values from dataframes in pandas?

Use (fast and simple):

df = df[np.isfinite(df).all(1)]

This answer is based on DougR's answer in an other question. Here an example code:

import pandas as pd
import numpy as np
df=pd.DataFrame([1,2,3,np.nan,4,np.inf,5,-np.inf,6])
print('Input:\n',df,sep='')
df = df[np.isfinite(df).all(1)]
print('\nDropped:\n',df,sep='')

Result:

Input:
    0
0  1.0000
1  2.0000
2  3.0000
3     NaN
4  4.0000
5     inf
6  5.0000
7    -inf
8  6.0000

Dropped:
     0
0  1.0
1  2.0
2  3.0
4  4.0
6  5.0
8  6.0

Setting Camera Parameters in OpenCV/Python

Not all parameters are supported by all cameras - actually, they are one of the most troublesome part of the OpenCV library. Each camera type - from android cameras to USB cameras to professional ones offer a different interface to modify its parameters. There are many branches in OpenCV code to support as many of them, but of course not all possibilities are covered.

What you can do is to investigate your camera driver, write a patch for OpenCV and send it to code.opencv.org. This way others will enjoy your work, the same way you enjoy others'.

There is also a possibility that your camera does not support your request - most USB cams are cheap and simple. Maybe that parameter is just not available for modifications.

If you are sure the camera supports a given param (you say the camera manufacturer provides some code) and do not want to mess with OpenCV, you can wrap that sample code in C++ with boost::python, to make it available in Python. Then, enjoy using it.

Merging two arrays in .NET

Easier would just be using LINQ:

var array = new string[] { "test" }.ToList();
var array1 = new string[] { "test" }.ToList();
array.AddRange(array1);
var result = array.ToArray();

First convert the arrays to lists and merge them... After that just convert the list back to an array :)

JavaScript: How do I print a message to the error console?

The simplest way to do this is:

console.warn("Text to print on console");

How to set the java.library.path from Eclipse

Another solution would be to open the 'run configuration' and then in the 'Environment' tab, set the couple {Path,Value}.

For instance to add a 'lib' directory located at the root of the project,

    Path  <-  ${workspace_loc:name_of_the_project}\lib

How to figure out the SMTP server host?

You could send yourself an email an look in the email header (In Outlook: Open the mail, View->Options, there is 'Internet headers)

What does "make oldconfig" do exactly in the Linux kernel makefile?

From this page:

Make oldconfig takes the .config and runs it through the rules of the Kconfig files and produces a .config which is consistant with the Kconfig rules. If there are CONFIG values which are missing, the make oldconfig will ask for them.

If the .config is already consistant with the rules found in Kconfig, then make oldconfig is essentially a no-op.

If you were to run make oldconfig, and then run make oldconfig a second time, the second time won't cause any additional changes to be made.

Is there an easy way to convert jquery code to javascript?

I can see a reason, unrelated to the original post, to automatically compile jQuery code into standard JavaScript:

16k -- or whatever the gzipped, minified jQuery library is -- might be too much for your website that is intended for a mobile browser. The w3c is recommending that all HTTP requests for mobile websites should be a maximum of 20k.

w3c specs for mobile

So I enjoy coding in my nice, terse, chained jQuery. But now I need to optimize for mobile. Should I really go back and do the difficult, tedious work of rewriting all the helper functions I used in the jQuery library? Or is there some kind of convenient app that will help me recompile?

That would be very sweet. Sadly, I don't think such a thing exists.

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

Easiest Way To install PDT

  1. Run eclipse
  2. Click on "Help", "Install New Software"
  3. “Choose all available sites”, in search box type "php"(takes a while to load)
  4. => “programming languages” => "PHP Development Tools", => PhP Development Tools (PDT) SDK Feature.
  5. Restart eclipse
  6. File new => other => php .
  7. Should be able to follow from their

Pass array to where in Codeigniter Active Record

From the Active Record docs:

$this->db->where_in();

Generates a WHERE field IN ('item', 'item') SQL query joined with AND if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')

How to set and reference a variable in a Jenkinsfile

A complete example for scripted pipepline:

       stage('Build'){
            withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
                sh 'bash build.sh'
            }
        }

How can I redirect a php page to another php page?

<?php header('Location: /login.php'); ?>

The above php script redirects the user to login.php within the same site

Function to calculate distance between two coordinates

I implemeneted this algorithm in typescript and ES6

export type Coordinate = {
  lat: number;
  lon: number;
};

get the distance between two points:

function getDistanceBetweenTwoPoints(cord1: Coordinate, cord2: Coordinate) {
  if (cord1.lat == cord2.lat && cord1.lon == cord2.lon) {
    return 0;
  }

  const radlat1 = (Math.PI * cord1.lat) / 180;
  const radlat2 = (Math.PI * cord2.lat) / 180;

  const theta = cord1.lon - cord2.lon;
  const radtheta = (Math.PI * theta) / 180;

  let dist =
    Math.sin(radlat1) * Math.sin(radlat2) +
    Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);

  if (dist > 1) {
    dist = 1;
  }

  dist = Math.acos(dist);
  dist = (dist * 180) / Math.PI;
  dist = dist * 60 * 1.1515;
  dist = dist * 1.609344; //convert miles to km
  
  return dist;
}

get the distance between an array of coordinates

export function getTotalDistance(coordinates: Coordinate[]) {
  coordinates = coordinates.filter((cord) => {
    if (cord.lat && cord.lon) {
      return true;
    }
  });
  
  let totalDistance = 0;

  if (!coordinates) {
    return 0;
  }

  if (coordinates.length < 2) {
    return 0;
  }

  for (let i = 0; i < coordinates.length - 2; i++) {
    if (
      !coordinates[i].lon ||
      !coordinates[i].lat ||
      !coordinates[i + 1].lon ||
      !coordinates[i + 1].lat
    ) {
      totalDistance = totalDistance;
    }
    totalDistance =
      totalDistance +
      getDistanceBetweenTwoPoints(coordinates[i], coordinates[i + 1]);
  }

  return totalDistance.toFixed(2);
}

Forcing label to flow inline with input that they label

Put the input in the label, and ditch the for attribute

<label>
  label1:
  <input type="text" id="id1" name="whatever" />
</label>

But of course, what if you want to style the text? Just use a span.

<label id="id1">
  <span>label1:</span>
  <input type="text" name="whatever" />
</label>

Change mysql user password using command line

In windows 10, just exit out of current login and run this on command line

--> mysqladmin -u root password “newpassword”

where instead of root could be any user.

Issue in installing php7.2-mcrypt

Mcrypt PECL extenstion

 sudo apt-get -y install gcc make autoconf libc-dev pkg-config
 sudo apt-get -y install libmcrypt-dev
 sudo pecl install mcrypt-1.0.1

When you are shown the prompt

 libmcrypt prefix? [autodetect] :

Press [Enter] to autodetect.

After success installing mcrypt trought pecl, you should add mcrypt.so extension to php.ini.

The output will look like this:

...
Build process completed successfully
Installing '/usr/lib/php/20170718/mcrypt.so'    ---->   this is our path to mcrypt extension lib
install ok: channel://pecl.php.net/mcrypt-1.0.1
configuration option "php_ini" is not set to php.ini location
You should add "extension=mcrypt.so" to php.ini

Grab installing path and add to cli and apache2 php.ini configuration.

sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/cli/conf.d/mcrypt.ini"
sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/apache2/conf.d/mcrypt.ini"

Verify that the extension was installed

Run command:

php -i | grep "mcrypt"

The output will look like this:

/etc/php/7.2/cli/conf.d/mcrypt.ini
Registered Stream Filters => zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, convert.iconv.*, mcrypt.*, mdecrypt.*
mcrypt
mcrypt support => enabled
mcrypt_filter support => enabled
mcrypt.algorithms_dir => no value => no value
mcrypt.modes_dir => no value => no value

ImportError: No module named 'selenium'

For python3, on a Mac you must use pip3 to install selenium.

sudo pip3 install selenium

What are forward declarations in C++?

One problem is, that the compiler does not know, which kind of value is delivered by your function; is assumes, that the function returns an int in this case, but this can be as correct as it can be wrong. Another problem is, that the compiler does not know, which kind of arguments your function expects, and cannot warn you, if you are passing values of the wrong kind. There are special "promotion" rules, which apply when passing, say floating point values to an undeclared function (the compiler has to widen them to type double), which is often not, what the function actually expects, leading to hard to find bugs at run-time.

Page scroll when soft keyboard popped up

You can try using the following code to solve your problem:

 <activity
     android:name=".DonateNow"
     android:label="@string/title_activity_donate_now"
     android:screenOrientation="portrait"
     android:theme="@style/AppTheme"
     android:windowSoftInputMode="stateVisible|adjustPan">
 </activity>

How to know the git username and email saved during configuration?

Sometimes above solutions doesn't work in macbook to get username n password.

IDK why?, here i got another solution.

$ git credential-osxkeychain get
host=github.com
protocol=https

this will revert username and password

Groovy - How to compare the string?

This should be an answer

str2.equals( str )

If you want to ignore case

str2.equalsIgnoreCase( str )

CSS, Images, JS not loading in IIS

I had the same problem, an unauthenticated page would not load the CSS, JS and Images when I installed my web application in ASP.Net 4.5 in IIS 8.5 on Windows Server 2012 R2.

  1. I had the static content role installed
  2. My Web Application was in the wwwroot folder of IIS and all the Windows Folder permissions were intact (the default ones, including IIS_IUSRS)
  3. I added authorization for all the folders that contained the CSS, JS and images.
  4. I had the web application folder on a windows share, so I removed the sharing as suggested by @imran-rashid

Yet, nothing seemed to solved the problem. Then finally I tried setting the identity of the anonymous user to the App Pool Identity and it started working.

Click on the Authentication Feature Edit the Anonymous Authentication Change to App Pool Identity

I banged my head for a few hours and hope that this response will save the agony for my fellow developers.

I would really like to know why this is working. Any thoughts?

sed command with -i option failing on Mac, but works on Linux

sed -ie 's/old_link/new_link/g' *

Works on both BSD & Linux with gnu sed

Default behavior of "git push" without a branch specified

You can push current branch with command

git push origin HEAD

(took from here)

How to pass parameters or arguments into a gradle task

I think you probably want to view the minification of each set of css as a separate task

task minifyBrandACss(type: com.eriwen.gradle.css.tasks.MinifyCssTask) {
     source = "src/main/webapp/css/brandA/styles.css"
     dest = "${buildDir}/brandA/styles.css"
}

etc etc

BTW executing your minify tasks in an action of the war task seems odd to me - wouldn't it make more sense to make them a dependency of the war task?

hash function for string

First, is 40 collisions for 130 words hashed to 0..99 bad? You can't expect perfect hashing if you are not taking steps specifically for it to happen. An ordinary hash function won't have fewer collisions than a random generator most of the time.

A hash function with a good reputation is MurmurHash3.

Finally, regarding the size of the hash table, it really depends what kind of hash table you have in mind, especially, whether buckets are extensible or one-slot. If buckets are extensible, again there is a choice: you choose the average bucket length for the memory/speed constraints that you have.

How do you get the selected value of a Spinner?

Simply use this:

spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();

This will give you the String of the selected item in the Spinner.

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

I had a similar problem but I fixed it with by doing some changes in firewall setting.

You can follow the below steps

  1. Go to "Start" --> "Control Panel"
  2. Click on "Windows Firewall" enter image description here

  3. Inside Windows Firewall, click on "Allow a program or feature through Windows Firewall" enter image description here

  4. Now inside of Allow Programs, Click on "Change Settings" button. Once you clicked on Change Settings button, the "Allow another program..." button gets enabled. enter image description here

  5. Click on "Allow another program..." button , a new dialog box will be opened. Choose the programs or application for which you are getting the socket exception and click on "Add" button. enter image description here

  6. Click OK, and restart your machine.

  7. Try to run your application (which has an exception) with administrative rights.

I hope this helps.

Peace,

Sunny Makode

How to search for a part of a word with ElasticSearch

Nevermind.

I had to look at the Lucene documentation. Seems I can use wildcards! :-)

curl http://localhost:9200/my_idx/my_type/_search?q=*Doe*

does the trick!

How do I set a checkbox in razor view?

You can do this with @Html.CheckBoxFor():

@Html.CheckBoxFor(m => m.AllowRating, new{@checked=true });

or you can also do this with a simple @Html.CheckBox():

@Html.CheckBox("AllowRating", true) ;

Python how to plot graph sine wave

  • Setting the x-axis with np.arange(0, 1, 0.001) gives an array from 0 to 1 in 0.001 increments.
    • x = np.arange(0, 1, 0.001) returns an array of 1000 points from 0 to 1, and y = np.sin(2*np.pi*x) you will get the sin wave from 0 to 1 sampled 1000 times

I hope this will help:

import matplotlib.pyplot as plt
import numpy as np


Fs = 8000
f = 5
sample = 8000
x = np.arange(sample)
y = np.sin(2 * np.pi * f * x / Fs)
plt.plot(x, y)
plt.xlabel('sample(n)')
plt.ylabel('voltage(V)')
plt.show()

enter image description here

P.S.: For comfortable work you can use The Jupyter Notebook.

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

To reset all the input fields in a modal use the following.

$(".modal-body input").val("")

Creating a chart in Excel that ignores #N/A or blank cells

just wanted to put my 2cents in about this issue...

I had a similar need where i was pulling data from another table via INDEX/MATCH, and it was difficult to distinguish between a real 0 value vs. a 0 value because of no match (for example for a column chart that shows the progress of values over the 12 months and where we are only in february but the rest of the months data is not available yet and the column chart still showed 0's everywhere for Mar to Dec)

What i ended up doing is create a new series and plot this new series on the graph as a line chart and then i hid the line chart by choosing not to display the line in the options and i put the data labels on top, the formula for the values for this new series was something like :

=IF(LEN([@[column1]])=0,NA(),[@[column1]])

I used LEN as a validation because ISEMPTY/ISBLANK didn't work because the result of the INDEX/MATCH always returned something other than a blank even though i had put a "" after the IFERROR...

On the line chart the error value NA() makes it so that the value isn't displayed ...so this worked out for me...

I guess it's a bit difficult to follow this procedure without pictures, but i hope it paints some kind of picture to allow you to use a workaround if you have a similar case like mine

<embed> vs. <object>

You could also use the iframe method, although this is not cross browser compatible (eg. not working in chromium or android and probably others -> instead prompts to download). It works with dataURL's and normal URLS, not sure if the other examples work with dataURLS (please let me know if the other examples work with dataURLS?)

 <iframe class="page-icon preview-pane" frameborder="0" height="352" width="396" src="data:application/pdf;base64, ..DATAURLHERE!... "></iframe>

Get img thumbnails from Vimeo?

It seems like api/v2 is dead.
In order to use the new API, you need to register your application, and base64 encode the client_id and client_secret as an Authorization header.

$.ajax({
    type:'GET',
    url: 'https://api.vimeo.com/videos/' + video_id,
    dataType: 'json',
    headers: {
        'Authorization': 'Basic ' + window.btoa(client_id + ":" + client_secret);
    },
    success: function(data) {
        var thumbnail_src = data.pictures.sizes[2].link;
        $('#thumbImg').attr('src', thumbnail_src);
    }
});

For security, you can return the client_id and client_secret already encoded from the server.

What's the difference between Cache-Control: max-age=0 and no-cache?

In my recent tests with IE8 and Firefox 3.5, it seems that both are RFC-compliant. However, they differ in their "friendliness" to the origin server. IE8 treats no-cache responses with the same semantics as max-age=0,must-revalidate. Firefox 3.5, however, seems to treat no-cache as equivalent to no-store, which sucks for performance and bandwidth usage.

Squid Cache, by default, seems to never store anything with a no-cache header, just like Firefox.

My advice would be to set public,max-age=0 for non-sensitive resources you want to have checked for freshness on every request, but still allow the performance and bandwidth benefits of caching. For per-user items with the same consideration, use private,max-age=0.

I would avoid the use of no-cache entirely, as it seems it has been bastardized by some browsers and popular caches to the functional equivalent of no-store.

Additionally, do not emulate Akamai and Limelight. While they essentially run massive caching arrays as their primary business, and should be experts, they actually have a vested interest in causing more data to be downloaded from their networks. Google might not be a good choice for emulation, either. They seem to use max-age=0 or no-cache randomly depending on the resource.

Finding the length of an integer in C

This goes for both negative and positive intigers

    int get_len(int n)
    {
        if(n == 0)
        return 1;

        if(n < 0)    
        {
           n = n * (-1); // if negative
        }

        return  log10(n) + 1;
    }

Same logic goes for loop

  int get_len(int n)
  {
       if(n == 0)
       return 1;

       int len = 0;
       if(n < 0)
       n = n * (-1);

       while(n > 1)
       {
          n /= 10;
          len++;
       }

       return len;
  }

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

For people using boto3 (Python SDK) use the below code

from botocore.client import Config


s3 = boto3.resource(
    's3',
    aws_access_key_id='xxxxxx',
    aws_secret_access_key='xxxxxx',
    config=Config(signature_version='s3v4')
)

Calling a parent window function from an iframe

I have posted this as a separate answer as it is unrelated to my existing answer.

This issue recently cropped up again for accessing a parent from an iframe referencing a subdomain and the existing fixes did not work.

This time the answer was to modify the document.domain of the parent page and the iframe to be the same. This will fool the same origin policy checks into thinking they co-exist on exactly the same domain (subdomains are considered a different host and fail the same origin policy check).

Insert the following to the <head> of the page in the iframe to match the parent domain (adjust for your doctype).

<script>
    document.domain = "mydomain.com";
</script>

Please note that this will throw an error on localhost development, so use a check like the following to avoid the error:

if (!window.location.href.match(/localhost/gi)) {
    document.domain = "mydomain.com";
} 

What is the meaning of @_ in Perl?

All Perl's "special variables" are listed in the perlvar documentation page.

A Generic error occurred in GDI+ in Bitmap.Save method

For me it was a permission problem. Somebody removed write permissions on the folder for the user account under which the application was running.

What is the size of column of int(11) in mysql in bytes?

A good explanation for this can be found here

To summarize : The number N in int(N) is often confused by the maximum size allowed for the column, as it does in the case of varchar(N).

But this is not the case with Integer data types- the number N in the parentheses is not the maximum size for the column, but simply a parameter to tell MySQL what width to display the column at when the table's data is being viewed via the MySQL console (when you're using the ZEROFILL attribute).

The number in brackets will tell MySQL how many zeros to pad incoming integers with. For example: If you're using ZEROFILL on a column that is set to INT(5) and the number 78 is inserted, MySQL will pad that value with zeros until the number satisfies the number in brackets. i.e. 78 will become 00078 and 127 will become 00127. To sum it up: The number in brackets is used for display purposes.
In a way, the number in brackets is kind of usless unless you're using the ZEROFILL attribute.

So the size for the int would remain same i.e., -2147483648 to 2147483648 for signed and 0 to 4294967295 for unsigned (~ 2.15 billions and 4.2 billions, which is one of the reasons why developers remain unaware of the story behind the Number N in parentheses, as it hardly affects the database unless it contains over 2 billions of rows), and in terms of bytes it would be 4 bytes.

For more information on Integer Types size/range, refer to MySQL Manual

Save array in mysql database

To convert any array (or any object) into a string using PHP, call the serialize():

$array = array( 1, 2, 3 );
$string = serialize( $array );
echo $string;

$string will now hold a string version of the array. The output of the above code is as follows:

a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}

To convert back from the string to the array, use unserialize():

// $array will contain ( 1, 2, 3 )
$array = unserialize( $string );

Entity framework self referencing loop detected

I just had the same issue on my .net core site. The accepted answer didn't work for me but i found that a combination of ReferenceLoopHandling.Ignore and PreserveReferencesHandling.Objects fixed it.

//serialize item
var serializedItem = JsonConvert.SerializeObject(data, Formatting.Indented, 
new JsonSerializerSettings
{
     PreserveReferencesHandling = PreserveReferencesHandling.Objects,
     ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});

How to create nonexistent subdirectories recursively using Bash?

You can use the -p parameter, which is documented as:

-p, --parents

no error if existing, make parent directories as needed

So:

mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"

Changing the color of an hr element

hr
{
  background-color: #123455;
}

the background is the one you should try to change

You can also work with the borders color. i am not sure i think there are crossbrowser issues with this. you should test it in differrent browsers

Create random list of integers in Python

All the random methods end up calling random.random() so the best way is to call it directly:

[int(1000*random.random()) for i in xrange(10000)]

For example,

  • random.randint calls random.randrange.
  • random.randrange has a bunch of overhead to check the range before returning istart + istep*int(self.random() * n).

NumPy is much faster still of course.

Checking password match while typing

Probably invalid syntax in your onChange event, I avoid using like this (within the html) as I think it is messy and it is hard enough keeping JavaScript tidy at the best of times.

I would rather register the event on the document ready event in javascript. You will also definitely want to use keyup event too if you want the validation as the user is typing:

$(document).ready(function () {
   $("#txtConfirmPassword").keyup(checkPasswordMatch);
});

Here is a working example


Personally I would prefer to do the check when either password field changes, that way if they re-type the original password then you still get the same validation check:

$(document).ready(function () {
   $("#txtNewPassword, #txtConfirmPassword").keyup(checkPasswordMatch);
});

Here is a working example

Using CSS how to change only the 2nd column of a table

Try this:

.countTable table tr td:first-child + td

You could also reiterate in order to style the others columns:

.countTable table tr td:first-child + td + td {...} /* third column */
.countTable table tr td:first-child + td + td + td {...} /* fourth column */
.countTable table tr td:first-child + td + td + td +td {...} /* fifth column */

Get client IP address via third party web service

Checking your linked site, you may include a script tag passing a ?var=desiredVarName parameter which will be set as a global variable containing the IP address:

<script type="text/javascript" src="http://l2.io/ip.js?var=myip"></script>
                                                      <!-- ^^^^ -->
<script>alert(myip);</script>

Demo

I believe I don't have to say that this can be easily spoofed (through either use of proxies or spoofed request headers), but it is worth noting in any case.


HTTPS support

In case your page is served using the https protocol, most browsers will block content in the same page served using the http protocol (that includes scripts and images), so the options are rather limited. If you have < 5k hits/day, the Smart IP API can be used. For instance:

<script>
var myip;
function ip_callback(o) {
    myip = o.host;
}
</script>
<script src="https://smart-ip.net/geoip-json?callback=ip_callback"></script>
<script>alert(myip);</script>

Demo

Edit: Apparently, this https service's certificate has expired so the user would have to add an exception manually. Open its API directly to check the certificate state: https://smart-ip.net/geoip-json


With back-end logic

The most resilient and simple way, in case you have back-end server logic, would be to simply output the requester's IP inside a <script> tag, this way you don't need to rely on external resources. For example:

PHP:

<script>var myip = '<?php echo $_SERVER['REMOTE_ADDR']; ?>';</script>

There's also a more sturdy PHP solution (accounting for headers that are sometimes set by proxies) in this related answer.

C#:

<script>var myip = '<%= Request.UserHostAddress %>';</script>

How can I perform a reverse string search in Excel without using VBA?

I found this on google, tested in Excel 2003 & it works for me:

=IF(COUNTIF(A1,"* *"),RIGHT(A1,LEN(A1)-LOOKUP(LEN(A1),FIND(" ",A1,ROW(INDEX($A:$A,1,1):INDEX($A:$A,LEN(A1),1))))),A1)

[edit] I don't have enough rep to comment, so this seems the best place...BradC's answer also doesn't work with trailing spaces or empty cells...
[2nd edit] actually, it doesn't work for single words either...

Should I use pt or px?

Here you've got a very detailed explanation of their differences

http://kyleschaeffer.com/development/css-font-size-em-vs-px-vs-pt-vs/

The jist of it (from source)

Pixels are fixed-size units that are used in screen media (i.e. to be read on the computer screen). Pixel stands for "picture element" and as you know, one pixel is one little "square" on your screen. Points are traditionally used in print media (anything that is to be printed on paper, etc.). One point is equal to 1/72 of an inch. Points are much like pixels, in that they are fixed-size units and cannot scale in size.

Microsoft.ACE.OLEDB.12.0 provider is not registered

Basically, if you're on a 64-bit machine, IIS 7 is not (by default) serving 32-bit apps, which the database engine operates on. So here is exactly what you do:

1) ensure that the 2007 database engine is installed, this can be downloaded at: http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en

2) open IIS7 manager, and open the Application Pools area. On the right sidebar, you will see an option that says "Set application pool defaults". Click it, and a window will pop up with the options.

3) the second field down, which says 'Enable 32-bit applications' is probably set to FALSE by default. Simply click where it says 'false' to change it to 'true'.

4) Restart your app pool (you can do this by hitting RECYCLE instead of STOP then START, which will also work).

5) done, and your error message will go away.

node.js execute system command synchronously

you can do synchronous shell operations in nodejs like so:

var execSync = function(cmd) {

    var exec  = require('child_process').exec;
    var fs = require('fs');

    //for linux use ; instead of &&
    //execute your command followed by a simple echo 
    //to file to indicate process is finished
    exec(cmd + " > c:\\stdout.txt && echo done > c:\\sync.txt");

    while (true) {
        //consider a timeout option to prevent infinite loop
        //NOTE: this will max out your cpu too!
        try {
            var status = fs.readFileSync('c:\\sync.txt', 'utf8');

            if (status.trim() == "done") {
                var res = fs.readFileSync("c:\\stdout.txt", 'utf8');
                fs.unlinkSync("c:\\stdout.txt"); //cleanup temp files
                fs.unlinkSync("c:\\sync.txt");
                return res;
            }
        } catch(e) { } //readFileSync will fail until file exists
    }

};

//won't return anything, but will take 10 seconds to run
console.log(execSync("sleep 10")); 

//assuming there are a lot of files and subdirectories, 
//this too may take a while, use your own applicable file path
console.log(execSync("dir /s c:\\usr\\docs\\"));

EDIT - this example is meant for windows environments, adjust for your own linux needs if necessary

How to determine the version of android SDK installed in computer?

While some responses have shown how to get the versions of the installed Android SDKs and various Android SDK related tools using the Android SDK Manager GUI, here's a way to get the same information from the command line:

%ANDROID_HOME%\tools\bin\sdkmanager.bat --list

You can redirect the output to a file to ease review and sharing.

Note: In my corporate environment, I also had to use the --proxy, --proxy_host, and --proxy_port command line options. You may need to use them as well.

How exactly does the python any() function work?

>>> names = ['King', 'Queen', 'Joker']
>>> any(n in 'King and john' for n in names)
True

>>> all(n in 'King and Queen' for n in names)
False

It just reduce several line of code into one. You don't have to write lengthy code like:

for n in names:
    if n in 'King and john':
       print True
    else:
       print False

Bind class toggle to window scroll event

Why do you all suggest heavy scope operations? I don't see why this is not an "angular" solution:

.directive('changeClassOnScroll', function ($window) {
  return {
    restrict: 'A',
    scope: {
        offset: "@",
        scrollClass: "@"
    },
    link: function(scope, element) {
        angular.element($window).bind("scroll", function() {
            if (this.pageYOffset >= parseInt(scope.offset)) {
                element.addClass(scope.scrollClass);
            } else {
                element.removeClass(scope.scrollClass);
            }
        });
    }
  };
})

So you can use it like this:

<navbar change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></navbar>

or

<div change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></div>

How to read data from a zip file without having to unzip the entire file

With .Net Framework 4.5 (using ZipArchive):

using (ZipArchive zip = ZipFile.Open(zipfile, ZipArchiveMode.Read))
    foreach (ZipArchiveEntry entry in zip.Entries)
        if(entry.Name == "myfile")
            entry.ExtractToFile("myfile");

Find "myfile" in zipfile and extract it.

Practical uses for the "internal" keyword in C#

Keep in mind that any class defined as public will automatically show up in the intellisense when someone looks at your project namespace. From an API perspective, it is important to only show users of your project the classes that they can use. Use the internal keyword to hide things they shouldn't see.

If your Big_Important_Class for Project A is intended for use outside your project, then you should not mark it internal.

However, in many projects, you'll often have classes that are really only intended for use inside a project. For example, you may have a class that holds the arguments to a parameterized thread invocation. In these cases, you should mark them as internal if for no other reason than to protect yourself from an unintended API change down the road.

Can't access to HttpContext.Current

Have you included the System.Web assembly in the application?

using System.Web;

If not, try specifying the System.Web namespace, for example:

 System.Web.HttpContext.Current

Importing json file in TypeScript

Enable "resolveJsonModule": true in tsconfig.json file and implement as below code, it's work for me:

const config = require('./config.json');

Reading/writing an INI file

The creators of the .NET framework want you to use XML-based config files, rather than INI files. So no, there is no built-in mechanism for reading them.

There are third party solutions available, though.

WooCommerce - get category for product page

<?php
   $terms = get_the_terms($product->ID, 'product_cat');
      foreach ($terms as $term) {

        $product_cat = $term->name;
           echo $product_cat;
             break;
  }
 ?>

Cast Double to Integer in Java

Memory efficient, as it will share the already created instance of Double.

Double.valueOf(Math.floor(54644546464/60*60*24*365)).intValue()

How can I show figures separately in matplotlib?

Perhaps you need to read about interactive usage of Matplotlib. However, if you are going to build an app, you should be using the API and embedding the figures in the windows of your chosen GUI toolkit (see examples/embedding_in_tk.py, etc).

Parsing JSON giving "unexpected token o" error

Try parse so:

var yourval = jQuery.parseJSON(JSON.stringify(data));

If (Array.Length == 0)

Yeah, for safety I would probably do:

if(array == null || array.Length == 0)

How can I make directory writable?

To make the parent directory as well as all other sub-directories writable, just add -R

chmod -R a+w <directory>

ORA-01031: insufficient privileges when selecting view

To use a view, the user must have the appropriate privileges but only for the view itself, not its underlying objects. However, if access privileges for the underlying objects of the view are removed, then the user no longer has access. This behavior occurs because the security domain that is used when a user queries the view is that of the definer of the view. If the privileges on the underlying objects are revoked from the view's definer, then the view becomes invalid, and no one can use the view. Therefore, even if a user has been granted access to the view, the user may not be able to use the view if the definer's rights have been revoked from the view's underlying objects.

Oracle Documentation http://docs.oracle.com/cd/B28359_01/network.111/b28531/authorization.htm#DBSEG98017

Sending email with PHP from an SMTP server

Here is a way to do it with PHP PEAR

// Pear Mail Library
require_once "Mail.php";

$from = '<[email protected]>'; //change this to your email address
$to = '<[email protected]>'; // change to address
$subject = 'Insert subject here'; // subject of mail
$body = "Hello world! this is the content of the email"; //content of mail

$headers = array(
    'From' => $from,
    'To' => $to,
    'Subject' => $subject
);

$smtp = Mail::factory('smtp', array(
        'host' => 'ssl://smtp.gmail.com',
        'port' => '465',
        'auth' => true,
        'username' => '[email protected]', //your gmail account
        'password' => 'snip' // your password
    ));

// Send the mail
$mail = $smtp->send($to, $headers, $body);

//check mail sent or not
if (PEAR::isError($mail)) {
    echo '<p>'.$mail->getMessage().'</p>';
} else {
    echo '<p>Message successfully sent!</p>';
}

If you use Gmail SMTP remember to enable SMTP in your Gmail account, under settings

EDIT: If you can't find Mail.php on debian/ubuntu you can install php-pear with

sudo apt install php-pear

Then install the mail extention:

sudo pear install mail
sudo pear install Net_SMTP
sudo pear install Auth_SASL
sudo pear install mail_mime

Then you should be able to load it by simply require_once "Mail.php" else it is located here: /usr/share/php/Mail.php

Serialize an object to string

[VB]

Public Function XmlSerializeObject(ByVal obj As Object) As String

    Dim xmlStr As String = String.Empty

    Dim settings As New XmlWriterSettings()
    settings.Indent = False
    settings.OmitXmlDeclaration = True
    settings.NewLineChars = String.Empty
    settings.NewLineHandling = NewLineHandling.None

    Using stringWriter As New StringWriter()
        Using xmlWriter__1 As XmlWriter = XmlWriter.Create(stringWriter, settings)

            Dim serializer As New XmlSerializer(obj.[GetType]())
            serializer.Serialize(xmlWriter__1, obj)

            xmlStr = stringWriter.ToString()
            xmlWriter__1.Close()
        End Using

        stringWriter.Close()
    End Using

    Return xmlStr.ToString
End Function

Public Function XmlDeserializeObject(ByVal data As [String], ByVal objType As Type) As Object

    Dim xmlSer As New System.Xml.Serialization.XmlSerializer(objType)
    Dim reader As TextReader = New StringReader(data)

    Dim obj As New Object
    obj = DirectCast(xmlSer.Deserialize(reader), Object)
    Return obj
End Function

[C#]

public string XmlSerializeObject(object obj)
{
    string xmlStr = String.Empty;
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = false;
    settings.OmitXmlDeclaration = true;
    settings.NewLineChars = String.Empty;
    settings.NewLineHandling = NewLineHandling.None;

    using (StringWriter stringWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings))
        {
            XmlSerializer serializer = new XmlSerializer( obj.GetType());
            serializer.Serialize(xmlWriter, obj);
            xmlStr = stringWriter.ToString();
            xmlWriter.Close();
        }
    }
    return xmlStr.ToString(); 
}

public object XmlDeserializeObject(string data, Type objType)
{
    XmlSerializer xmlSer = new XmlSerializer(objType);
    StringReader reader = new StringReader(data);

    object obj = new object();
    obj = (object)(xmlSer.Deserialize(reader));
    return obj;
}

Calling Objective-C method from C++ member function?

You can mix C++ with Objective-C if you do it carefully. There are a few caveats but generally speaking they can be mixed. If you want to keep them separate, you can set up a standard C wrapper function that gives the Objective-C object a usable C-style interface from non-Objective-C code (pick better names for your files, I have picked these names for verbosity):

MyObject-C-Interface.h

#ifndef __MYOBJECT_C_INTERFACE_H__
#define __MYOBJECT_C_INTERFACE_H__

// This is the C "trampoline" function that will be used
// to invoke a specific Objective-C method FROM C++
int MyObjectDoSomethingWith (void *myObjectInstance, void *parameter);
#endif

MyObject.h

#import "MyObject-C-Interface.h"

// An Objective-C class that needs to be accessed from C++
@interface MyObject : NSObject
{
    int someVar;
}

// The Objective-C member function you want to call from C++
- (int) doSomethingWith:(void *) aParameter;
@end

MyObject.mm

#import "MyObject.h"

@implementation MyObject

// C "trampoline" function to invoke Objective-C method
int MyObjectDoSomethingWith (void *self, void *aParameter)
{
    // Call the Objective-C method using Objective-C syntax
    return [(id) self doSomethingWith:aParameter];
}

- (int) doSomethingWith:(void *) aParameter
{
    // The Objective-C function you wanted to call from C++.
    // do work here..
    return 21 ; // half of 42
}
@end

MyCPPClass.cpp

#include "MyCPPClass.h"
#include "MyObject-C-Interface.h"

int MyCPPClass::someMethod (void *objectiveCObject, void *aParameter)
{
    // To invoke an Objective-C method from C++, use
    // the C trampoline function
    return MyObjectDoSomethingWith (objectiveCObject, aParameter);
}

The wrapper function does not need to be in the same .m file as the Objective-C class, but the file that it does exist in needs to be compiled as Objective-C code. The header that declares the wrapper function needs to be included in both CPP and Objective-C code.

(NOTE: if the Objective-C implementation file is given the extension ".m" it will not link under Xcode. The ".mm" extension tells Xcode to expect a combination of Objective-C and C++, i.e., Objective-C++.)


You can implement the above in an Object-Orientented manner by using the PIMPL idiom. The implementation is only slightly different. In short, you place the wrapper functions (declared in "MyObject-C-Interface.h") inside a class with a (private) void pointer to an instance of MyClass.

MyObject-C-Interface.h (PIMPL)

#ifndef __MYOBJECT_C_INTERFACE_H__
#define __MYOBJECT_C_INTERFACE_H__

class MyClassImpl
{
public:
    MyClassImpl ( void );
    ~MyClassImpl( void );

    void init( void );
    int  doSomethingWith( void * aParameter );
    void logMyMessage( char * aCStr );

private:
    void * self;
};

#endif

Notice the wrapper methods no longer require the void pointer to an instance of MyClass; it is now a private member of MyClassImpl. The init method is used to instantiate a MyClass instance;

MyObject.h (PIMPL)

#import "MyObject-C-Interface.h"

@interface MyObject : NSObject
{
    int someVar;
}

- (int)  doSomethingWith:(void *) aParameter;
- (void) logMyMessage:(char *) aCStr;

@end

MyObject.mm (PIMPL)

#import "MyObject.h"

@implementation MyObject

MyClassImpl::MyClassImpl( void )
    : self( NULL )
{   }

MyClassImpl::~MyClassImpl( void )
{
    [(id)self dealloc];
}

void MyClassImpl::init( void )
{    
    self = [[MyObject alloc] init];
}

int MyClassImpl::doSomethingWith( void *aParameter )
{
    return [(id)self doSomethingWith:aParameter];
}

void MyClassImpl::logMyMessage( char *aCStr )
{
    [(id)self doLogMessage:aCStr];
}

- (int) doSomethingWith:(void *) aParameter
{
    int result;

    // ... some code to calculate the result

    return result;
}

- (void) logMyMessage:(char *) aCStr
{
    NSLog( aCStr );
}

@end

Notice that MyClass is instantiated with a call to MyClassImpl::init. You could instantiate MyClass in MyClassImpl's constructor, but that generally isn't a good idea. The MyClass instance is destructed from MyClassImpl's destructor. As with the C-style implementation, the wrapper methods simply defer to the respective methods of MyClass.

MyCPPClass.h (PIMPL)

#ifndef __MYCPP_CLASS_H__
#define __MYCPP_CLASS_H__

class MyClassImpl;

class MyCPPClass
{
    enum { cANSWER_TO_LIFE_THE_UNIVERSE_AND_EVERYTHING = 42 };
public:
    MyCPPClass ( void );
    ~MyCPPClass( void );

    void init( void );
    void doSomethingWithMyClass( void );

private:
    MyClassImpl * _impl;
    int           _myValue;
};

#endif

MyCPPClass.cpp (PIMPL)

#include "MyCPPClass.h"
#include "MyObject-C-Interface.h"

MyCPPClass::MyCPPClass( void )
    : _impl ( NULL )
{   }

void MyCPPClass::init( void )
{
    _impl = new MyClassImpl();
}

MyCPPClass::~MyCPPClass( void )
{
    if ( _impl ) { delete _impl; _impl = NULL; }
}

void MyCPPClass::doSomethingWithMyClass( void )
{
    int result = _impl->doSomethingWith( _myValue );
    if ( result == cANSWER_TO_LIFE_THE_UNIVERSE_AND_EVERYTHING )
    {
        _impl->logMyMessage( "Hello, Arthur!" );
    }
    else
    {
        _impl->logMyMessage( "Don't worry." );
    }
}

You now access calls to MyClass through a private implementation of MyClassImpl. This approach can be advantageous if you were developing a portable application; you could simply swap out the implementation of MyClass with one specific to the other platform ... but honestly, whether this is a better implementation is more a matter of taste and needs.

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

ImportError: No module named Image

The PIL distribution is mispackaged for egg installation.

Install Pillow instead, the friendly PIL fork.

How do you post data with a link

You cannot make POST HTTP Requests by <a href="some_script.php">some_script</a>

Just open your house.php, find in it where you have $house = $_POST['houseVar'] and change it to:

isset($_POST['houseVar']) ? $house = $_POST['houseVar'] : $house = $_GET['houseVar']

And in the streeview.php make links like that:

<a href="house.php?houseVar=$houseNum"></a>

Or something else. I just don't know your files and what inside it.

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

Data variables ($email, $subject) seems to be global. And globals cannot be read inside functions. You must pass them as parameters (the recommended way) or declare them as global.

Try this way:

Mail::send('emails.activation', $data, function($message, $email, $subject){
        $message->to($email)->subject($subject);
    });
            ->with('title', "Registered Successfully.");

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

Sometimes you can just do 'Window -> Reset Window Layout', and that'll work :)

How to get past the login page with Wget?

I had the same problem. My solution was to do the login via Chrome and save the cookies data to a text file. This is easily done with this Chrome extension: Chrome cookie.txt export extension.

When you get the cookies data, there is also an example on how to use them with wget. A simple copy-paste command line is provided to you.

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

How to set a header in an HTTP response?

First of all you have to understand the nature of

response.sendRedirect(newUrl);

It is giving the client (browser) 302 http code response with an URL. The browser then makes a separate GET request on that URL. And that request has no knowledge of headers in the first one.

So sendRedirect won't work if you need to pass a header from Servlet A to Servlet B.

If you want this code to work - use RequestDispatcher in Servlet A (instead of sendRedirect). Also, it is always better to use relative path.

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
    String userName=request.getParameter("userName");
    String newUrl = "ServletB";
    response.addHeader("REMOTE_USER", userName);
    RequestDispatcher view = request.getRequestDispatcher(newUrl);
    view.forward(request, response);
}

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

public void doPost(HttpServletRequest request, HttpServletResponse response)
{
    String sss = response.getHeader("REMOTE_USER");
}

syntaxerror: unexpected character after line continuation character in python

You need to quote that filename:

f = open("D\\python\\HW\\2_1 - Copy.cp", "r")

Otherwise the bare backslash after the D is interpreted as a line-continuation character, and should be followed by a newline. This is used to extend long expressions over multiple lines, for readability:

print "This is a long",\
      "line of text",\
      "that I'm printing."

Also, you shouldn't have semicolons (;) at the end of your statements in Python.

How to specify the default error page in web.xml?

You can also do something like that:

<error-page>
    <error-code>403</error-code>
    <location>/403.html</location>
</error-page>

<error-page>
    <location>/error.html</location>
</error-page>

For error code 403 it will return the page 403.html, and for any other error code it will return the page error.html.

OpenCV error: the function is not implemented

Don't waste your time trying to resolve this issue, this was made clear by the makers themselves. Instead of cv2.imshow() use this:

img = cv2.imread('path_to_image')
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
plt.show()

Call an activity method from a fragment

You should probably try to decouple the fragment from the activity in case you want to use it somewhere else. You can do this by creating a interface that your activity implements.

So you would define an interface like the following:

Suppose for example you wanted to give the activity a String and have it return a Integer:

public interface MyStringListener{
    public Integer computeSomething(String myString);
}

This can be defined in the fragment or a separate file.

Then you would have your activity implement the interface.

public class MyActivity extends FragmentActivity implements MyStringListener{

  @Override
  public Integer computeSomething(String myString){
   /** Do something with the string and return your Integer instead of 0 **/ 
   return 0;
  }

}

Then in your fragment you would have a MyStringListener variable and you would set the listener in fragment onAttach(Activity activity) method.

public class MyFragment {

        private MyStringListener listener;

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            try {
                listener = (MyStringListener) context;
            } catch (ClassCastException castException) {
                /** The activity does not implement the listener. */
            }
        }

    }

edit(17.12.2015):onAttach(Activity activity) is deprecated, use onAttach(Context context) instead, it works as intended

The first answer definitely works but it couples your current fragment with the host activity. Its good practice to keep the fragment decoupled from the host activity in case you want to use it in another acitivity.

Can we add div inside table above every <tr>?

In the html tables, <table> tag expect <tr> tag right after itself and <tr> tag expect <td> tag right after itself. So if you want to put a div in table, you can put it in between <td> and </td> tags as data.

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div>_x000D_
        <p>It works well</p>_x000D_
      </div>_x000D_
     </td>_x000D_
  </tr>_x000D_
<table>
_x000D_
_x000D_
_x000D_

Find specific string in a text file with VBS script

Try to change like this ..

firstStr = "<?xml version" 'my file always starts like this

Do until objInputFile.AtEndOfStream  

    strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"  

   substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))

   tmpStr = objInputFile.ReadLine

   If InStr(tmpStr, substrToFind) <= 0 Then
       If Instr(tmpStr, firstStr) > 0 Then
          text = tmpStr 'to avoid the first empty line
       Else
          text = text & vbCrLf & tmpStr
       End If
   Else
      text = text & vbCrLf & strToAdd & vbCrLf & tmpStr

   End If
   index = index + 1
Loop

Wait until all promises complete even if some rejected

Promise.all with using modern async/await approach

const promise1 = //...
const promise2 = //...

const data = await Promise.all([promise1, promise2])

const dataFromPromise1 = data[0]
const dataFromPromise2 = data[1]

How to run stored procedures in Entity Framework Core?

I'm using Entity Framework Core with my ASP.Net Core 3.x WebAPI. I wanted one of my end points just to execute a particular Stored Procedure, and this is the code I needed:

namespace MikesBank.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ResetController : ControllerBase
    {
        private readonly MikesBankContext _context;

        public ResetController(MikesBankContext context)
        {
            _context = context;
        }

        [HttpGet]
        public async Task<ActionResult> Get()
        {
            try
            {
                using (DbConnection conn = _context.Database.GetDbConnection())
                {
                    if (conn.State != System.Data.ConnectionState.Open)
                        conn.Open();
                    var cmd = conn.CreateCommand();
                    cmd.CommandText = "Reset_Data";
                    await cmd.ExecuteNonQueryAsync();
                }
                return new OkObjectResult(1);
            }
            catch (Exception ex)
            {
                return new BadRequestObjectResult(ex.Message);
            }
        }
    }
}

Notice how I need to get my DbContext which has been injected, but I also need to Open() this connection.

Responsive background image in div full width

Here is one way of getting the design that you want.

Start with the following HTML:

<div class="container">
    <div class="row-fluid">
        <div class="span12">
            <div class="nav">nav area</div>
            <div class="bg-image">
                <img src="http://unplugged.ee/wp-content/uploads/2013/03/frank2.jpg">
                 <h1>This is centered text.</h1>
            </div>
            <div class="main">main area</div>
        </div>
    </div>
</div>

Note that the background image is now part of the regular flow of the document.

Apply the following CSS:

.bg-image {
    position: relative;
}
.bg-image img {
    display: block;
    width: 100%;
    max-width: 1200px; /* corresponds to max height of 450px */
    margin: 0 auto;
}
.bg-image h1 {
    position: absolute;
    text-align: center;
    bottom: 0;
    left: 0;
    right: 0;
    color: white;
}
.nav, .main {
    background-color: #f6f6f6;
    text-align: center;
}

How This Works

The image is set an regular flow content with a width of 100%, so it will adjust itself responsively to the width of the parent container. However, you want the height to be no more than 450px, which corresponds to the image width of 1200px, so set the maximum width of the image to 1200px. You can keep the image centered by using display: block and margin: 0 auto.

The text is painted over the image by using absolute positioning. In the simplest case, I stretch the h1 element to be the full width of the parent and use text-align: center to center the text. Use the top or bottom offsets to place the text where it is needed.

If your banner images are going to vary in aspect ratio, you will need to adjust the maximum width value for .bg-image img dynamically using jQuery/Javascript, but otherwise, this approach has a lot to offer.

See demo at: http://jsfiddle.net/audetwebdesign/EGgaN/

How does paintComponent work?

The (very) short answer to your question is that paintComponent is called "when it needs to be." Sometimes it's easier to think of the Java Swing GUI system as a "black-box," where much of the internals are handled without too much visibility.

There are a number of factors that determine when a component needs to be re-painted, ranging from moving, re-sizing, changing focus, being hidden by other frames, and so on and so forth. Many of these events are detected auto-magically, and paintComponent is called internally when it is determined that that operation is necessary.

I've worked with Swing for many years, and I don't think I've ever called paintComponent directly, or even seen it called directly from something else. The closest I've come is using the repaint() methods to programmatically trigger a repaint of certain components (which I assume calls the correct paintComponent methods downstream.

In my experience, paintComponent is rarely directly overridden. I admit that there are custom rendering tasks that require such granularity, but Java Swing does offer a (fairly) robust set of JComponents and Layouts that can be used to do much of the heavy lifting without having to directly override paintComponent. I guess my point here is to make sure that you can't do something with native JComponents and Layouts before you go off trying to roll your own custom-rendered components.

Mac OS X and multiple Java versions

Here's a more DRY version for bash (Based on Vegard's answer)

Replace 1.7 and 1.8 with whatever versions you are interested with and you'll get an alias called 'javaX'; where 'X' is the java version (7 / 8 in the snippet below) that will allow you to easily switch versions

for version in 1.7 1.8; do
    v="${version: -1}"
    h=JAVA_"$v"_HOME

    export "$h"=$(/usr/libexec/java_home -v $version)

    alias "java$v"="export JAVA_HOME=\$$h"
done

How does "cat << EOF" work in bash?

Worth noting that here docs work in bash loops too. This example shows how-to get the column list of table:

export postgres_db_name='my_db'
export table_name='my_table_name'

# start copy 
while read -r c; do test -z "$c" || echo $table_name.$c , ; done < <(cat << EOF | psql -t -q -d $postgres_db_name -v table_name="${table_name:-}"
SELECT column_name
FROM information_schema.columns
WHERE 1=1
AND table_schema = 'public'
AND table_name   =:'table_name'  ;
EOF
)
# stop copy , now paste straight into the bash shell ...

output: 
my_table_name.guid ,
my_table_name.id ,
my_table_name.level ,
my_table_name.seq ,

or even without the new line

while read -r c; do test -z "$c" || echo $table_name.$c , | perl -ne 
's/\n//gm;print' ; done < <(cat << EOF | psql -t -q -d $postgres_db_name -v table_name="${table_name:-}"
 SELECT column_name
 FROM information_schema.columns
 WHERE 1=1
 AND table_schema = 'public'
 AND table_name   =:'table_name'  ;
 EOF
 )

 # output: daily_issues.guid ,daily_issues.id ,daily_issues.level ,daily_issues.seq ,daily_issues.prio ,daily_issues.weight ,daily_issues.status ,daily_issues.category ,daily_issues.name ,daily_issues.description ,daily_issues.type ,daily_issues.owner

AngularJS ngClass conditional

Angular JS provide this functionality in ng-class Directive. In which you can put condition and also assign conditional class. You can achieve this in two different ways.

Type 1

<div ng-class="{0:'one', 1:'two',2:'three'}[status]"></div>

In this code class will be apply according to value of status value

if status value is 0 then apply class one

if status value is 1 then apply class two

if status value is 2 then apply class three


Type 2

<div ng-class="{1:'test_yes', 0:'test_no'}[status]"></div>

In which class will be apply by value of status

if status value is 1 or true then it will add class test_yes

if status value is 0 or false then it will add class test_no

Checking oracle sid and database name

As has been mentioned above,

select global_name from global_name;

is the way to go.

You couldn't query v$database/v$instance/v$thread because your user does not have the required permissions. You can grant them (via a DBA account) with:

grant select on v$database to <username here>;

How organize uploaded media in WP?

You can use the Media Library Folders plugin. It allows you to create folders, move or copy images to a folder and even includes a sync function to bulk add images uploaded by FTP to the server to the Wordpress media library.

Media Library Folders example

SQL Server - In clause with a declared variable

This is an example where I use the table variable to list multiple values in an IN clause. The obvious reason is to be able to change the list of values only one place in a long procedure.

To make it even more dynamic and alowing user input, I suggest declaring a varchar variable for the input, and then using a WHILE to loop trough the data in the variable and insert it into the table variable.

Replace @your_list, Your_table and the values with real stuff.

DECLARE @your_list TABLE (list varchar(25)) 
INSERT into @your_list
VALUES ('value1'),('value2376')

SELECT *  
FROM your_table 
WHERE your_column in ( select list from @your_list )

The select statement abowe will do the same as:

SELECT *  
FROM your_table 
WHERE your_column in ('value','value2376' )

How to maximize a plt.show() window using Python

I am on a Windows (WIN7), running Python 2.7.5 & Matplotlib 1.3.1.

I was able to maximize Figure windows for TkAgg, QT4Agg, and wxAgg using the following lines:

from matplotlib import pyplot as plt

### for 'TkAgg' backend
plt.figure(1)
plt.switch_backend('TkAgg') #TkAgg (instead Qt4Agg)
print '#1 Backend:',plt.get_backend()
plt.plot([1,2,6,4])
mng = plt.get_current_fig_manager()
### works on Ubuntu??? >> did NOT working on windows
# mng.resize(*mng.window.maxsize())
mng.window.state('zoomed') #works fine on Windows!
plt.show() #close the figure to run the next section

### for 'wxAgg' backend
plt.figure(2)
plt.switch_backend('wxAgg')
print '#2 Backend:',plt.get_backend()
plt.plot([1,2,6,4])
mng = plt.get_current_fig_manager()
mng.frame.Maximize(True)
plt.show() #close the figure to run the next section

### for 'Qt4Agg' backend
plt.figure(3)
plt.switch_backend('QT4Agg') #default on my system
print '#3 Backend:',plt.get_backend()
plt.plot([1,2,6,4])
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
plt.show()

if you want to maximize multiple figures you can use

for fig in figs:
    mng = fig.canvas.manager
    # ...

Hope this summary of the previous answers (and some additions) combined in a working example (at least for windows) helps. Cheers

How to provide shadow to Button

Use this approach to get your desired look.
button_selector.xml :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <layer-list>
        <item android:right="5dp" android:top="5dp">
            <shape>
                <corners android:radius="3dp" />
                <solid android:color="#D6D6D6" />
            </shape>
        </item>
        <item android:bottom="2dp" android:left="2dp">
            <shape>
                <gradient android:angle="270" 
                    android:endColor="#E2E2E2" android:startColor="#BABABA" />
                <stroke android:width="1dp" android:color="#BABABA" />
                <corners android:radius="4dp" />
                <padding android:bottom="10dp" android:left="10dp" 
                    android:right="10dp" android:top="10dp" />
            </shape>
        </item>
    </layer-list>
</item>

</selector>

And in your xml layout:

<Button
   android:background="@drawable/button_selector"
   ...
   ..
/>

Disable sorting on last column when using jQuery DataTables

This would be useful for v1.10+ of datatables. Set column number for which you want to remove sorting for e.g 1st column would be like:

columnDefs: [
   { orderable: false, targets: 0 }
]

For multiple columns(1st,second and third):

columnDefs: [
   { orderable: false, targets: [0,1,2] }
]

Strings and character with printf

%c

is designed for a single character a char, so it print only one element.Passing the char array as a pointer you are passing the address of the first element of the array(that is a single char) and then will be printed :

s

printf("%c\n",*name++);

will print

i

and so on ...

Pointer is not needed for the %s because it can work directly with String of characters.

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

Post values from a multiple select

try this : here select is your select element

let select = document.getElementsByClassName('lstSelected')[0],
    options = select.options,
    len = options.length,
    data='',
    i=0;
while (i<len){
    if (options[i].selected)
        data+= "&" + select.name + '=' + options[i].value;
    i++;
}
return data;

Data is in the form of query string i.e.name=value&name=anotherValue

Total memory used by Python process?

Below is my function decorator which allows to track how much memory this process consumed before the function call, how much memory it uses after the function call, and how long the function is executed.

import time
import os
import psutil


def elapsed_since(start):
    return time.strftime("%H:%M:%S", time.gmtime(time.time() - start))


def get_process_memory():
    process = psutil.Process(os.getpid())
    return process.memory_info().rss


def track(func):
    def wrapper(*args, **kwargs):
        mem_before = get_process_memory()
        start = time.time()
        result = func(*args, **kwargs)
        elapsed_time = elapsed_since(start)
        mem_after = get_process_memory()
        print("{}: memory before: {:,}, after: {:,}, consumed: {:,}; exec time: {}".format(
            func.__name__,
            mem_before, mem_after, mem_after - mem_before,
            elapsed_time))
        return result
    return wrapper

So, when you have some function decorated with it

from utils import track

@track
def list_create(n):
    print("inside list create")
    return [1] * n

You will be able to see this output:

inside list create
list_create: memory before: 45,928,448, after: 46,211,072, consumed: 282,624; exec time: 00:00:00

Angular 2 - Setting selected value on dropdown list

Thanks for the tip Günter, it got me moving in the right direction. There was a mis-matched spelling of 'color' in my solution which was causing issues and I needed to use 'ngValue' not 'value' in the template html.

Here is the complete solution using objects for the ngModel and select list options and avoiding use of the [selected] attribute.

I have updated the Plunker to show the full working solution. https://plnkr.co/edit/yIVEeLK7PUY4VQFrR48g?p=preview

Component template

 <div>
        <label>Colour</label>
        <div *ngIf="car != null">
            <select [(ngModel)]="car.colour">
                <option *ngFor="let x of colours" [ngValue]="x" >{{x.name}}</option>
            </select>
        </div>
    </div>

Component

import { Component, OnInit } from '@angular/core';
import {AbstractControl,FORM_DIRECTIVES } from '@angular/common';

@Component({
    selector:'dropdown',
    templateUrl:'app/components/dropdown/dropdown.component.html',
    directives:[FORM_DIRECTIVES]
})
export class DropdownComponent implements OnInit
{
    car:Car;
    colours: Array<Colour>;

    ngOnInit(): void {

        this.colours = Array<Colour>();
        this.colours.push(new Colour(-1, 'Please select'));
        this.colours.push(new Colour(1, 'Green'));
        this.colours.push(new Colour(2, 'Pink'));

        this.car = new Car();
        this.car.colour = this.colours[1];        
    }
}

export class Car  
{
    colour:Colour;
}

export class Colour
{
    constructor(id:number, name:string) {
        this.id=id;
        this.name=name;
    }

    id:number;
    name:string;
}

What is :: (double colon) in Python when subscripting sequences?

Python sequence slice addresses can be written as a[start:end:step] and any of start, stop or end can be dropped. a[::3] is every third element of the sequence.

How can I easily convert DataReader to List<T>?

I would suggest writing an extension method for this:

public static IEnumerable<T> Select<T>(this IDataReader reader,
                                       Func<IDataReader, T> projection)
{
    while (reader.Read())
    {
        yield return projection(reader);
    }
}

You can then use LINQ's ToList() method to convert that into a List<T> if you want, like this:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select(r => new Customer {
        CustomerId = r["id"] is DBNull ? null : r["id"].ToString(),
        CustomerName = r["name"] is DBNull ? null : r["name"].ToString() 
    }).ToList();
}

I would actually suggest putting a FromDataReader method in Customer (or somewhere else):

public static Customer FromDataReader(IDataReader reader) { ... }

That would leave:

using (IDataReader reader = ...)
{
    List<Customer> customers = reader.Select<Customer>(Customer.FromDataReader)
                                     .ToList();
}

(I don't think type inference would work in this case, but I could be wrong...)

Run script with rc.local: script works, but not at boot

In this example of a rc.local script I use io redirection at the very first line of execution to my own log file:

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

exec 2> /tmp/rc.local.log  # send stderr from rc.local to a log file
exec 1>&2                      # send stdout to the same log file
set -x                         # tell sh to display commands before execution

/opt/stuff/somefancy.error.script.sh

exit 0

how to bold words within a paragraph in HTML/CSS?

Although your answer has many solutions I think this is a great way to save lines of code. Try using spans which is great for situations like yours.

  1. Create a class for making any item bold. So for paragraph text it would be
span.bold(This name can be anything do not include parenthesis) {
   font-weight: bold;
}
  1. In your html you can access that class like by using the span tags and adding a class of bold or whatever name you have chosen

Get selected key/value of a combo box using jQuery

<select name="foo" id="foo">
 <option value="1">a</option>
 <option value="2">b</option>
 <option value="3">c</option>
  </select>
  <input type="button" id="button" value="Button" />
  });
  <script> ("#foo").val() </script>

which returns 1 if you have selected a and so on..

How to convert JSON object to JavaScript array?

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [];

for(var i in json_data)
    result.push([i, json_data [i]]);


var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(result);

http://jsfiddle.net/MV5rj/

Get human readable version of file size?

The following works in Python 3.6+, is, in my opinion, the easiest to understand answer on here, and lets you customize the amount of decimal places used.

def human_readable_size(size, decimal_places=2):
    for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']:
        if size < 1024.0 or unit == 'PiB':
            break
        size /= 1024.0
    return f"{size:.{decimal_places}f} {unit}"

Loop X number of times

Use:

1..10 | % { write "loop $_" }

Output:

PS D:\temp> 1..10 | % { write "loop $_" }
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
loop 10

Java: Reading integers from a file into an array

It looks like Java is trying to convert an empty string into a number. Do you have an empty line at the end of the series of numbers?

You could probably fix the code like this

String s = in.readLine();
int i = 0;

while (s != null) {
    // Skip empty lines.
    s = s.trim();
    if (s.length() == 0) {
        continue;
    }

    tall[i] = Integer.parseInt(s); // This is line 19.
    System.out.println(tall[i]);
    s = in.readLine();
    i++;
}

in.close();

CSS last-child(-1)

Unless you can get PHP to label that element with a class you are better to use jQuery.

jQuery(document).ready(function () {
  $count =  jQuery("ul li").size() - 1;
  alert($count);
  jQuery("ul li:nth-child("+$count+")").css("color","red");
});

Removing rounded corners from a <select> element in Chrome/Webkit

While the top answer removes the border, it also removes the arrow which makes it extremely difficult if not impossible for the user to identify the element as a select.

My solution was to just stick a white div (with border-radius:0px) behind the select. Set its position to absolute, its height to the height of the select, and you should be good to go!

How to get maximum value from the Collection (for example ArrayList)?

We can simply use Collections.max() and Collections.min() method.

public class MaxList {
    public static void main(String[] args) {
        List l = new ArrayList();
        l.add(1);
        l.add(2);
        l.add(3);
        l.add(4);
        l.add(5);
        System.out.println(Collections.max(l)); // 5
        System.out.println(Collections.min(l)); // 1
    }
}

How to move a marker in Google Maps API

use panTo(x,y).This will help u

How do I group Windows Form radio buttons?

Put all radio buttons for a group in a container object like a Panel or a GroupBox. That will automatically group them together in Windows Forms.

jQuery - find child with a specific class

Based on your comment, moddify this:

$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV

to:

$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV

More about selectors: https://api.jquery.com/category/selectors/

Vertical divider doesn't work in Bootstrap 3

I think this will bring it back using 3.0

.navbar .divider-vertical {
    height: 50px;
    margin: 0 9px;
    border-right: 1px solid #ffffff;
    border-left: 1px solid #f2f2f2;
}

.navbar-inverse .divider-vertical {
    border-right-color: #222222;
    border-left-color: #111111;
}

@media (max-width: 767px) {
    .navbar-collapse .nav > .divider-vertical {
        display: none;
     }
}

PHP is_numeric or preg_match 0-9 validation

is_numeric() allows any form of number. so 1, 3.14159265, 2.71828e10 are all "numeric", while your regex boils down to the equivalent of is_int()