Programs & Examples On #Airplane

Airplane is a setting to disable the device's signal transmitting functions on mobile devices.

TypeError: argument of type 'NoneType' is not iterable

The python error says that wordInput is not an iterable -> it is of NoneType.

If you print wordInput before the offending line, you will see that wordInput is None.

Since wordInput is None, that means that the argument passed to the function is also None. In this case word. You assign the result of pickEasy to word.

The problem is that your pickEasy function does not return anything. In Python, a method that didn't return anything returns a NoneType.

I think you wanted to return a word, so this will suffice:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

How to easily initialize a list of Tuples?

One technique I think is a little easier and that hasn't been mentioned before here:

var asdf = new [] { 
    (Age: 1, Name: "cow"), 
    (Age: 2, Name: "bird")
}.ToList();

I think that's a little cleaner than:

var asdf = new List<Tuple<int, string>> { 
    (Age: 1, Name: "cow"), 
    (Age: 2, Name: "bird")
};

Python 2.6: Class inside a Class?

class Second:
    def __init__(self, data):
        self.data = data

class First:
    def SecondClass(self, data):
        return Second(data)

FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data

How to refresh a Page using react-route Link

I ended up keeping Link and adding the reload to the Link's onClick event with a timeout like this:

function refreshPage() {
    setTimeout(()=>{
        window.location.reload(false);
    }, 500);
    console.log('page to reload')
}

<Link to={{pathname:"/"}} onClick={refreshPage}>Home</Link>

without the timeout, the refresh function would run first

Missing Push Notification Entitlement

I had the same problem and my solution was to add the push notification entitlement from Target -> Capabilities.

Transform only one axis to log10 scale with ggplot2

I had a similar problem and this scale worked for me like a charm:

breaks = 10**(1:10)
scale_y_log10(breaks = breaks, labels = comma(breaks))

as you want the intermediate levels, too (10^3.5), you need to tweak the formatting:

breaks = 10**(1:10 * 0.5)
m <- ggplot(diamonds, aes(y = price, x = color)) + geom_boxplot()
m + scale_y_log10(breaks = breaks, labels = comma(breaks, digits = 1))

After executing::

enter image description here

htaccess Access-Control-Allow-Origin

BTW: the .htaccess config must be done on the server hosting the API. For example you create an AngularJS app on x.com domain and create a Rest API on y.com, you should set Access-Control-Allow-Origin "*" in the .htaccess file on the root folder of y.com not x.com :)

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

Also as Lukas mentioned make sure you have enabled mod_headers if you use Apache

Add object to ArrayList at specified index

You need to populate the empty indexes with nulls.

while (arraylist.size() < position)
{
     arraylist.add(null);
}

arraylist.add(position, object);

How to check if a div is visible state or not?

Add your li to a class, and do $(".myclass").hide(); at the start to hide it instead of the visibility style attribute.

As far as I know, jquery uses the display style attribute to show/hide elements instead of visibility (may be wrong on that one, in either case the above is worth trying)

How do I write a RGB color value in JavaScript?

dec2hex = function (d) {
  if (d > 15)
    { return d.toString(16) } else
    { return "0" + d.toString(16) }
}
rgb = function (r, g, b) { return "#" + dec2hex(r) + dec2hex(g) + dec2hex(b) };

and:

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

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

expand/collapse table rows with JQuery

The easiest way to achieve this, without changing the HTML table-based structure, is to use a class-name on the tr elements containing a header, such as .header, to give:

<table border="0">
  <tr class="header">
    <td colspan="2">Header</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr class="header">
    <td colspan="2">Header</td>
  </tr>
  <tr>
    <td>date</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
</table>

And the jQuery:

// bind a click-handler to the 'tr' elements with the 'header' class-name:
$('tr.header').click(function(){
    /* get all the subsequent 'tr' elements until the next 'tr.header',
       set the 'display' property to 'none' (if they're visible), to 'table-row'
       if they're not: */
    $(this).nextUntil('tr.header').css('display', function(i,v){
        return this.style.display === 'table-row' ? 'none' : 'table-row';
    });
});

JS Fiddle demo.

In the linked demo I've used CSS to hide the tr elements that don't have the header class-name; in practice though (despite the relative rarity of users with JavaScript disabled) I'd suggest using JavaScript to add the relevant class-names, hiding and showing as appropriate:

// hide all 'tr' elements, then filter them to find...
$('tr').hide().filter(function () {
    // only those 'tr' elements that have 'td' elements with a 'colspan' attribute:
    return $(this).find('td[colspan]').length;
    // add the 'header' class to those found 'tr' elements
}).addClass('header')
    // set the display of those elements to 'table-row':
  .css('display', 'table-row')
    // bind the click-handler (as above)
  .click(function () {
    $(this).nextUntil('tr.header').css('display', function (i, v) {
        return this.style.display === 'table-row' ? 'none' : 'table-row';
    });
});

JS Fiddle demo.

References:

Check if table exists

Adding to Gaby's post, my jdbc getTables() for Oracle 10g requires all caps to work:

"employee" -> "EMPLOYEE"

Otherwise I would get an exception:

java.sql.SqlExcepcion exhausted resultset

(even though "employee" is in the schema)

How to convert jsonString to JSONObject in Java

String to JSON using Jackson with com.fasterxml.jackson.databind:

Assuming your json-string represents as this: jsonString = {"phonetype":"N95","cat":"WP"}

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * Simple code exmpl
 */
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString);
String phoneType = node.get("phonetype").asText();
String cat = node.get("cat").asText();

How to set a default value with Html.TextBoxFor?

Using @Value is a hack, because it outputs two attributes, e.g.:

<input type="..." Value="foo" value=""/>

You should do this instead:

@Html.TextBox(Html.NameFor(p => p.FirstName).ToString(), "foo")

Is it possible to use global variables in Rust?

Heap allocations are possible for static variables if you use the lazy_static macro as seen in the docs

Using this macro, it is possible to have statics that require code to be executed at runtime in order to be initialized. This includes anything requiring heap allocations, like vectors or hash maps, as well as anything that requires function calls to be computed.

// Declares a lazily evaluated constant HashMap. The HashMap will be evaluated once and
// stored behind a global static reference.

use lazy_static::lazy_static;
use std::collections::HashMap;

lazy_static! {
    static ref PRIVILEGES: HashMap<&'static str, Vec<&'static str>> = {
        let mut map = HashMap::new();
        map.insert("James", vec!["user", "admin"]);
        map.insert("Jim", vec!["user"]);
        map
    };
}

fn show_access(name: &str) {
    let access = PRIVILEGES.get(name);
    println!("{}: {:?}", name, access);
}

fn main() {
    let access = PRIVILEGES.get("James");
    println!("James: {:?}", access);

    show_access("Jim");
}

What is the path for the startup folder in windows 2008 server

SHGetKnownFolderPath:

Retrieves the full path of a known folder identified by the folder's KNOWNFOLDERID.

And, FOLDERID_CommonStartup:

Default Path %ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\StartUp

There are also managed equivalents, but you haven't told us what you're programming in.

How to Change color of Button in Android when Clicked?

1-make 1 shape for Button right click on drawable nd new drawable resource file . change Root element to shape and make your shape.

enter image description here

2-now make 1 copy from your shape and change name and change solid color. enter image description here

3-right click on drawable and new drawable resource file just set root element to selector.

go to file and set "state_pressed"

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

<item android:state_pressed="true"android:drawable="@drawable/YourShape1"/>
<item android:state_pressed="false" android:drawable="@drawable/YourShape2"/>

</selector>

4-the end go to xml layout and set your Button background "your selector"

(sorry for my english weak)

How to generate serial version UID in Intellij

Easiest method: Alt+Enter on

private static final long serialVersionUID = ;

IntelliJ will underline the space after the =. put your cursor on it and hit alt+Enter (Option+Enter on Mac). You'll get a popover that says "Randomly Change serialVersionUID Initializer". Just hit enter, and it'll populate that space with a random long.

how does multiplication differ for NumPy Matrix vs Array classes?

The main reason to avoid using the matrix class is that a) it's inherently 2-dimensional, and b) there's additional overhead compared to a "normal" numpy array. If all you're doing is linear algebra, then by all means, feel free to use the matrix class... Personally I find it more trouble than it's worth, though.

For arrays (prior to Python 3.5), use dot instead of matrixmultiply.

E.g.

import numpy as np
x = np.arange(9).reshape((3,3))
y = np.arange(3)

print np.dot(x,y)

Or in newer versions of numpy, simply use x.dot(y)

Personally, I find it much more readable than the * operator implying matrix multiplication...

For arrays in Python 3.5, use x @ y.

Moment.js - how do I get the number of years since a date, not rounded up?

This method is easy and powerful.

Value is a date and "DD-MM-YYYY" is the mask of the date.

moment().diff(moment(value, "DD-MM-YYYY"), 'years');

Ruby class instance variable vs. class variable

While it may immediately seem useful to utilize class instance variables, since class instance variable are shared among subclasses and they can be referred to within both singleton and instance methods, there is a singificant drawback. They are shared and so subclasses can change the value of the class instance variable, and the base class will also be affected by the change, which is usually undesirable behavior:

class C
  @@c = 'c'
  def self.c_val
    @@c
  end
end

C.c_val
 => "c" 

class D < C
end

D.instance_eval do 
  def change_c_val
    @@c = 'd'
  end
end
 => :change_c_val 

D.change_c_val
(irb):12: warning: class variable access from toplevel
 => "d" 

C.c_val
 => "d" 

Rails introduces a handy method called class_attribute. As the name implies, it declares a class-level attribute whose value is inheritable by subclasses. The class_attribute value can be accessed in both singleton and instance methods, as is the case with the class instance variable. However, the huge benefit with class_attribute in Rails is subclasses can change their own value and it will not impact parent class.

class C
  class_attribute :c
  self.c = 'c'
end

 C.c
 => "c" 

class D < C
end

D.c = 'd'
 => "d" 

 C.c
 => "c" 

JQuery: dynamic height() with window resize()

I feel like there should be a no javascript solution, but how is this?

http://jsfiddle.net/NfmX3/2/

$(window).resize(function() {
    $('#content').height($(window).height() - 46);
});

$(window).trigger('resize');

Passing data to components in vue.js

-------------Following is applicable only to Vue 1 --------------

Passing data can be done in multiple ways. The method depends on the type of use.


If you want to pass data from your html while you add a new component. That is done using props.

<my-component prop-name="value"></my-component>

This prop value will be available to your component only if you add the prop name prop-name to your props attribute.


When data is passed from a component to another component because of some dynamic or static event. That is done by using event dispatchers and broadcasters. So for example if you have a component structure like this:

<my-parent>
    <my-child-A></my-child-A>
    <my-child-B></my-child-B>
</my-parent>

And you want to send data from <my-child-A> to <my-child-B> then in <my-child-A> you will have to dispatch an event:

this.$dispatch('event_name', data);

This event will travel all the way up the parent chain. And from whichever parent you have a branch toward <my-child-B> you broadcast the event along with the data. So in the parent:

events:{
    'event_name' : function(data){
        this.$broadcast('event_name', data);
    },

Now this broadcast will travel down the child chain. And at whichever child you want to grab the event, in our case <my-child-B> we will add another event:

events: {
    'event_name' : function(data){
        // Your code. 
    },
},

The third way to pass data is through parameters in v-links. This method is used when components chains are completely destroyed or in cases when the URI changes. And i can see you already understand them.


Decide what type of data communication you want, and choose appropriately.

Saving numpy array to txt file row wise

The numpy.savetxt() method has several parameters which are worth noting:

fmt : str or sequence of strs, optional
    it is used to format the numbers in the array, see the doc for details on formating

delimiter : str, optional
    String or character separating columns

newline : str, optional
    String or character separating lines.

Let's take an example. I have an array of size (M, N), which consists of integer numbers in the range (0, 255). To save the array row-wise and show it nicely, we can use the following code:

import numpy as np

np.savetxt("my_array.txt", my_array, fmt="%4d", delimiter=",", newline="\n")

Semi-transparent color layer over background-image?

I've used this as a way to both apply colour tints as well as gradients to images to make dynamic overlaying text easier to style for legibility when you can't control image colour profiles. You don't have to worry about z-index.

HTML

<div class="background-image"></div>

SASS

.background-image {
  background: url('../img/bg/diagonalnoise.png') repeat;
  &:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(248, 247, 216, 0.7);
  }
}

CSS

.background-image {
  background: url('../img/bg/diagonalnoise.png') repeat;
}

.background-image:before {
    content: '';
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    background: rgba(248, 247, 216, 0.7);
  }

Hope it helps

Difference Between Schema / Database in MySQL

PostgreSQL supports schemas, which is a subset of a database: https://www.postgresql.org/docs/current/static/ddl-schemas.html

A database contains one or more named schemas, which in turn contain tables. Schemas also contain other kinds of named objects, including data types, functions, and operators. The same object name can be used in different schemas without conflict; for example, both schema1 and myschema can contain tables named mytable. Unlike databases, schemas are not rigidly separated: a user can access objects in any of the schemas in the database they are connected to, if they have privileges to do so.

Schemas are analogous to directories at the operating system level, except that schemas cannot be nested.

In my humble opinion, MySQL is not a reference database. You should never quote MySQL for an explanation. MySQL implements non-standard SQL and sometimes claims features that it does not support. For example, in MySQL, CREATE schema will only create a DATABASE. It is truely misleading users.

This kind of vocabulary is called "MySQLism" by DBAs.

How exactly does binary code get converted into letters?

http://www.roubaixinteractive.com/PlayGround/Binary_Conversion/The_Characters.asp it just looks here... (not HERE but it has a table).

There are 8 bits in a byte. One byte can be one symbol. One bit is either on or off.

How to access data/data folder in Android device?

The question is: how-to-access-data-data-folder-in-android-device?


If android-device is Bluestacks * Root Browser APK shows data/data/..


Try to download Root Browser from https://apkpure.com/root-browser/com.jrummy.root.browserfree


If the file is a text file you need to click on "Open as", "Text file", "Open as", "RB Text Editor"

jquery <a> tag click event

All the hidden fields in your fieldset are using the same id, so jquery is only returning the first one. One way to fix this is to create a counter variable and concatenate it to each hidden field id.

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

Difference between InvariantCulture and Ordinal string comparison

Here is an example where string equality comparison using InvariantCultureIgnoreCase and OrdinalIgnoreCase will not give the same results:

string str = "\xC4"; //A with umlaut, Ä
string A = str.Normalize(NormalizationForm.FormC);
//Length is 1, this will contain the single A with umlaut character (Ä)
string B = str.Normalize(NormalizationForm.FormD);
//Length is 2, this will contain an uppercase A followed by an umlaut combining character
bool equals1 = A.Equals(B, StringComparison.OrdinalIgnoreCase);
bool equals2 = A.Equals(B, StringComparison.InvariantCultureIgnoreCase);

If you run this, equals1 will be false, and equals2 will be true.

PHP list of specific files in a directory

Simplest answer is to put another condition '.xml' == strtolower(substr($file, -3)).

But I'd recommend using glob instead too.

Copy values from one column to another in the same table

Following worked for me..

  1. Ensure you are not using Safe-mode in your query editor application. If you are, disable it!
  2. Then run following sql command

for a table say, 'test_update_cmd', source value column col2, target value column col1 and condition column col3: -

UPDATE  test_update_cmd SET col1=col2 WHERE col3='value';

Good Luck!

JQuery, Spring MVC @RequestBody and JSON - making it work together

If you do not want to configure the message converters yourself, you can use either @EnableWebMvc or <mvc:annotation-driven />, add Jackson to the classpath and Spring will give you both JSON, XML (and a few other converters) by default. Additionally, you will get some other commonly used features for conversion, formatting and validation.

array.select() in javascript

yo can extend your JS with a select method like this

Array.prototype.select = function(closure){
    for(var n = 0; n < this.length; n++) {
        if(closure(this[n])){
            return this[n];
        }
    }

    return null;
};

now you can use this:

var x = [1,2,3,4];

var a = x.select(function(v) {
    return v == 2;
});

console.log(a);

or for objects in a array

var x = [{id: 1, a: true},
    {id: 2, a: true},
    {id: 3, a: true},
    {id: 4, a: true}];

var a = x.select(function(obj) {
    return obj.id = 2;
});

console.log(a);

Table scroll with HTML and CSS

Late answer, another idea, but very short.

  1. put the contents of header cells into div
  2. fix the header contents, see CSS
table  { margin-top:  20px; display: inline-block; overflow: auto; }
th div { margin-top: -20px; position: absolute; }

Note that it is possible to display table as inline-block due to anonymous table objects:

"missing" [in HTML table tree structure] elements must be assumed in order for the table model to work. Any table element will automatically generate necessary anonymous table objects around itself.

_x000D_
_x000D_
/* scrolltable rules */_x000D_
table  { margin-top:  20px; display: inline-block; overflow: auto; }_x000D_
th div { margin-top: -20px; position: absolute; }_x000D_
_x000D_
/* design */_x000D_
table { border-collapse: collapse; }_x000D_
tr:nth-child(even) { background: #EEE; }
_x000D_
<table style="height: 150px">_x000D_
  <tr> <th><div>first</div> <th><div>second</div>_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo foo foo foo foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar bar bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
  <tr> <td>foo <td>bar_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to check status of PostgreSQL server Mac OS X

The pg_ctl status command suggested in other answers checks that the postmaster process exists and if so reports that it's running. That doesn't necessarily mean it is ready to accept connections or execute queries.

It is better to use another method like using psql to run a simple query and checking the exit code, e.g. psql -c 'SELECT 1', or use pg_isready to check the connection status.

How to change a <select> value from JavaScript

Once you have done your processing in the selectFunction() you could do the following

document.getElementById('select').selectedIndex = 0;
document.getElementById('select').value = 'Default';

Find index of last occurrence of a substring in a string

If you don't wanna use rfind then this will do the trick/

def find_last(s, t):
    last_pos = -1
    while True:
        pos = s.find(t, last_pos + 1)
        if pos == -1:
            return last_pos
        else:
            last_pos = pos

How to center icon and text in a android button with width set to "fill parent"

Other possibility to keep Button theme.

<Button
            android:id="@+id/pf_bt_edit"
            android:layout_height="@dimen/standard_height"
            android:layout_width="match_parent"
            />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_alignBottom="@id/pf_bt_edit"
            android:layout_alignLeft="@id/pf_bt_edit"
            android:layout_alignRight="@id/pf_bt_edit"
            android:layout_alignTop="@id/pf_bt_edit"
            android:layout_margin="@dimen/margin_10"
            android:clickable="false"
            android:elevation="20dp"
            android:gravity="center"
            android:orientation="horizontal"
            >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:adjustViewBounds="true"
                android:clickable="false"
                android:src="@drawable/ic_edit_white_48dp"/>

            <TextView
                android:id="@+id/pf_tv_edit"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_marginLeft="@dimen/margin_5"
                android:clickable="false"
                android:gravity="center"
                android:text="@string/pf_bt_edit"/>

        </LinearLayout>

With this solution if your add @color/your_color @color/your_highlight_color in your activity theme, you can have Matherial theme on Lollipop whith shadow and ripple, and for previous version flat button with your color and highlight coor when you press it.

Moreover, with this solution autoresize of picture

Result : First on Lollipop device Second : On pre lollipop device 3th : Pre lollipop device press button

enter image description here

How to rotate a 3D object on axis three.js?

I needed the rotateAroundWorldAxis function but the above code doesn't work with the newest release (r52). It looks like getRotationFromMatrix() was replaced by setEulerFromRotationMatrix()

function rotateAroundWorldAxis( object, axis, radians ) {

    var rotationMatrix = new THREE.Matrix4();

    rotationMatrix.makeRotationAxis( axis.normalize(), radians );
    rotationMatrix.multiplySelf( object.matrix );                       // pre-multiply
    object.matrix = rotationMatrix;
    object.rotation.setEulerFromRotationMatrix( object.matrix );
}

How to get the Facebook user id using the access token

Check out this answer, which describes, how to get ID response. First, you need to create method get data:

const https = require('https');
getFbData = (accessToken, apiPath, callback) => {
    const options = {
        host: 'graph.facebook.com',
        port: 443,
        path: `${apiPath}access_token=${accessToken}`, // apiPath example: '/me/friends'
        method: 'GET'
    };

    let buffer = ''; // this buffer will be populated with the chunks of the data received from facebook
    const request = https.get(options, (result) => {
        result.setEncoding('utf8');
        result.on('data', (chunk) => {
            buffer += chunk;
        });

        result.on('end', () => {
            callback(buffer);
        });
    });

    request.on('error', (e) => {
        console.log(`error from facebook.getFbData: ${e.message}`)
    });

    request.end();
}

Then simply use your method whenever you want, like this:

getFbData(access_token, '/me?fields=id&', (result) => {
      console.log(result);
});

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

Get div to take up 100% body height, minus fixed-height header and footer

The new, modern way to do this is to calculate the vertical height by subtracting the height of both the header and the footer from the vertical-height of the viewport.

//CSS
header { 
  height: 50px;
}
footer { 
  height: 50px;
}
#content { 
  height: calc(100vh - 50px - 50px);
}

How to use the TextWatcher class in Android?

A little bigger perspective of the solution:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.yourlayout, container, false);
        View tv = v.findViewById(R.id.et1);
        ((TextView) tv).addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                 SpannableString contentText = new SpannableString(((TextView) tv).getText());
                 String contents = Html.toHtml(contentText).toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {

                // TODO Auto-generated method stub
            }
        });
        return v;
    }

This works for me, doing it my first time.

How to check queue length in Python

Use queue.rear+1 to get the length of the queue

How to uninstall mini conda? python

To update @Sunil answer: Under Windows, Miniconda has a regular uninstaller. Go to the menu "Settings/Apps/Apps&Features", or click the Start button, type "uninstall", then click on "Add or Remove Programs" and finally on the Miniconda uninstaller.

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I experienced this issue when calling my web api endpoint and solved it.

In my case it was an issue in the way the client was encoding the body content. I was not specifying the encoding or media type. Specifying them solved it.

Not specifying encoding type, caused 415 error:

var content = new StringContent(postData);
httpClient.PostAsync(uri, content);

Specifying the encoding and media type, success:

var content = new StringContent(postData, Encoding.UTF8, "application/json");
httpClient.PostAsync(uri, content);

How do I download NLTK data?

you can't have a saved python file called nltk.py because the interpreter is reading from that and not from the actual file.

Change the name of your file that the python shell is reading from and try what you were doing originally:

import nltk and then nltk.download()

Create boolean column in MySQL with false as default value?

You have to specify 0 (meaning false) or 1 (meaning true) as the default. Here is an example:

create table mytable (
     mybool boolean not null default 0
);

FYI: boolean is an alias for tinyint(1).

Here is the proof:

mysql> create table mytable (
    ->          mybool boolean not null default 0
    ->     );
Query OK, 0 rows affected (0.35 sec)

mysql> insert into mytable () values ();
Query OK, 1 row affected (0.00 sec)

mysql> select * from mytable;
+--------+
| mybool |
+--------+
|      0 |
+--------+
1 row in set (0.00 sec)

FYI: My test was done on the following version of MySQL:

mysql> select version();
+----------------+
| version()      |
+----------------+
| 5.0.18-max-log |
+----------------+
1 row in set (0.00 sec)

How to check for an undefined or null variable in JavaScript?

I think the most efficient way to test for "value is null or undefined" is

if ( some_variable == null ){
  // some_variable is either null or undefined
}

So these two lines are equivalent:

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}

Note 1

As mentioned in the question, the short variant requires that some_variable has been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:

check for optional arguments:

function(foo){
    if( foo == null ) {...}

check for properties on an existing object

if(my_obj.foo == null) {...}

On the other hand typeof can deal with undeclared global variables (simply returns undefined). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.

Note 2

This - even shorter - variant is not equivalent:

if ( !some_variable ) {
  // some_variable is either null, undefined, 0, NaN, false, or an empty string
}

so

if ( some_variable ) {
  // we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}

Note 3

In general it is recommended to use === instead of ==. The proposed solution is an exception to this rule. The JSHint syntax checker even provides the eqnull option for this reason.

From the jQuery style guide:

Strict equality checks (===) should be used in favor of ==. The only exception is when checking for undefined and null by way of null.

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

Java - Access is denied java.io.FileNotFoundException

When you create a new File, you are supposed to provide the file name, not only the directory you want to put your file in.

Try with something like

File file = new File("D:/Data/" + item.getFileName());

JQuery confirm dialog

Try this one

$('<div></div>').appendTo('body')
  .html('<div><h6>Yes or No?</h6></div>')
  .dialog({
      modal: true, title: 'message', zIndex: 10000, autoOpen: true,
      width: 'auto', resizable: false,
      buttons: {
          Yes: function () {
              doFunctionForYes();
              $(this).dialog("close");
          },
          No: function () {
              doFunctionForNo();
              $(this).dialog("close");
          }
      },
      close: function (event, ui) {
          $(this).remove();
      }
});

Fiddle

Import Script from a Parent Directory

If you want to run the script directly, you can:

  1. Add the FolderA's path to the environment variable (PYTHONPATH).
  2. Add the path to sys.path in the your script.

Then:

import module_you_wanted

How do I delete an item or object from an array using ng-click?

implementation Without a Controller.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>_x000D_
<body>_x000D_
_x000D_
<script>_x000D_
  var app = angular.module("myShoppingList", []); _x000D_
</script>_x000D_
_x000D_
<div ng-app="myShoppingList"  ng-init="products = ['Milk','Bread','Cheese']">_x000D_
  <ul>_x000D_
    <li ng-repeat="x in products track by $index">{{x}}_x000D_
      <span ng-click="products.splice($index,1)">×</span>_x000D_
    </li>_x000D_
  </ul>_x000D_
  <input ng-model="addItem">_x000D_
  <button ng-click="products.push(addItem)">Add</button>_x000D_
</div>_x000D_
_x000D_
<p>Click the little x to remove an item from the shopping list.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The splice() method adds/removes items to/from an array.

array.splice(index, howmanyitem(s), item_1, ....., item_n)

index: Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array.

howmanyitem(s): Optional. The number of items to be removed. If set to 0, no items will be removed.

item_1, ..., item_n: Optional. The new item(s) to be added to the array

Replace "\\" with "\" in a string in C#

in case someone got stuck with this and none of the answers above worked, below is what worked for me. Hope it helps.

var oldString = "\\r|\\n";

// None of these worked for me
// var newString = oldString(@"\\", @"\");
// var newString = oldString.Replace("\\\\", "\\");
// var newString = oldString.Replace("\\u5b89", "\u5b89");
// var newString = Regex.Replace(oldString , @"\\", @"\");

// This is what worked
var newString = Regex.Unescape(oldString);
// newString is now "\r|\n"

How to loop through an array containing objects and access their properties

Here's an example on how you can do it :)

_x000D_
_x000D_
var students = [{_x000D_
    name: "Mike",_x000D_
    track: "track-a",_x000D_
    achievements: 23,_x000D_
    points: 400,_x000D_
  },_x000D_
  {_x000D_
    name: "james",_x000D_
    track: "track-a",_x000D_
    achievements: 2,_x000D_
    points: 21,_x000D_
  },_x000D_
]_x000D_
_x000D_
students.forEach(myFunction);_x000D_
_x000D_
function myFunction(item, index) {_x000D_
  for (var key in item) {_x000D_
    console.log(item[key])_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

How to copy files from host to Docker container?

The following is a fairly ugly way of doing it but it works.

docker run -i ubuntu /bin/bash -c 'cat > file' < file

How to prevent scientific notation in R?

Try format function:

> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

How do I disable and re-enable a button in with javascript?

you can try with

document.getElementById('btn').disabled = !this.checked"

_x000D_
_x000D_
<input type="submit" name="btn"  id="btn" value="submit" disabled/>_x000D_
_x000D_
<input type="checkbox"  onchange="document.getElementById('btn').disabled = !this.checked"/>
_x000D_
_x000D_
_x000D_

Bash scripting missing ']'

Change

if [ -s "p1"];  #line 13

into

if [ -s "p1" ];  #line 13

note the space.

"Can't find Project or Library" for standard VBA functions

I've had this error on and off for around two years in a several XLSM files (which is most annoying as when it occurs there is nothing wrong with the file! - I suspect orphaned Excel processes are part of the problem)

The most efficient solution I had found has been to use Python with oletools https://github.com/decalage2/oletools/wiki/Install and extract the VBA code all the modules and save in a text file.

Then I simply rename the file to zip file (backup just in case!), open up this zip file and delete the xl/vbaProject.bin file. Rename back to XLSX and should be good to go.

Copy in the saved VBA code (which will need cleaning of line breaks, comments and other stuff. Will also need to add in missing libraries.

This has saved me when other methods haven't.

YMMV.

How to set or change the default Java (JDK) version on OS X?

TOO EASY SOLUTION: What a headache - this was a quick easy solution that worked for me.

Mac OS Sierra Version 10.12.13

  1. Use the shortcut keys: CMD+SHIFT+G - type in "/Library/"

  2. Find the JAVA folder

  3. Right Click Java Folder = Move to Trash (Password Required)

  4. Install: Java SE Development Kit 8 jdk-8u131-macosx-x64.dmg | Download Javascript SDK

  5. Make sure the new JAVA folder appears in /LIBRARY/
  6. Install Eclipse | Install Eclipse IDE for Java Developers
  7. Boom Done

Angular expression if array contains

You shouldn't overload the templates with complex logic, it's a bad practice. Remember to always keep it simple!

The better approach would be to extract this logic into reusable function on your $rootScope:

.run(function ($rootScope) {
  $rootScope.inArray = function (item, array) {
    return (-1 !== array.indexOf(item));
  };
})

Then, use it in your template:

<li ng-class="{approved: inArray(jobSet, selectedForApproval)}"></li>

I think everyone will agree that this example is much more readable and maintainable.

How to link 2 cell of excel sheet?

The simplest solution is to select the second cell, and press =. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.

To read up more on different options for referencing see - This Article.

How can I parse a string with a comma thousand separator to a number?

All of these answers fail if you have a number in the millions.

3,456,789 would simply return 3456 with the replace method.

The most correct answer for simply removing the commas would have to be.

var number = '3,456,789.12';
number.split(',').join('');
/* number now equips 3456789.12 */
parseFloat(number);

Or simply written.

number = parseFloat(number.split(',').join(''));

Use of Java's Collections.singletonList()?

If an Immutable/Singleton collections refers to the one which having only one object and which is not further gets modified, then the same functionality can be achieved by making a collection "UnmodifiableCollection" having only one object. Since the same functionality can be achieved by Unmodifiable Collection with one object, then what special purpose the Singleton Collection serves for?

Search for highest key/index in an array

$keys = array_keys($arr);
$keys = rsort($keys);

print $keys[0];

should print "10"

Checking for directory and file write permissions in .NET

The answers by Richard and Jason are sort of in the right direction. However what you should be doing is computing the effective permissions for the user identity running your code. None of the examples above correctly account for group membership for example.

I'm pretty sure Keith Brown had some code to do this in his wiki version (offline at this time) of The .NET Developers Guide to Windows Security. This is also discussed in reasonable detail in his Programming Windows Security book.

Computing effective permissions is not for the faint hearted and your code to attempt creating a file and catching the security exception thrown is probably the path of least resistance.

How to implement a secure REST API with node.js

There are many questions about REST auth patterns here on SO. These are the most relevant for your question:

Basically you need to choose between using API keys (least secure as the key may be discovered by an unauthorized user), an app key and token combo (medium), or a full OAuth implementation (most secure).

Content Type application/soap+xml; charset=utf-8 was not supported by service

As suggested by others this happens due to service client mismatch.

I ran into the same problem, when was debugging got to know that there is a mismatch in the binding. Instead of WSHTTPBinding I was referring to BasicHttpBinding. In my case I am referring both BasicHttp and WsHttp. I was dynamically assigning the binding based on the reference. So check your service constructor as shown below

Refer this image

Extract time from date String

The other answers were good answers when the question was asked. Time moves on, Date and SimpleDateFormat get replaced by newer and better classes and go out of use. In 2017, use the classes in the java.time package:

    String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
            .format(DateTimeFormatter.ofPattern("H:mm"));

The result is the desired, 9:00.

How can I check if a Perl array contains a particular value?

You certainly want a hash here. Place the bad parameters as keys in the hash, then decide whether a particular parameter exists in the hash.

our %bad_params = map { $_ => 1 } qw(badparam1 badparam2 badparam3)

if ($bad_params{$new_param}) {
  print "That is a bad parameter\n";
}

If you are really interested in doing it with an array, look at List::Util or List::MoreUtils

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

NSDate get year/month/day

Here's the solution in Swift:

let todayDate = NSDate()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!

// Use a mask to extract the required components. Extract only the required components, since it'll be expensive to compute all available values.
let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: todayDate)

var (year, month, date) = (components.year, components.month, components.day) 

File upload from <input type="file">

I think that it's not supported. If you have a look at this DefaultValueAccessor directive (see https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/default_value_accessor.ts#L23). You will see that the value used to update the bound element is $event.target.value.

This doesn't apply in the case of inputs with type file since the file object can be reached $event.srcElement.files instead.

For more details, you can have a look at this plunkr: https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" (change)="onChange($event)"/>
    </div>
  `,
  providers: [ UploadService ]
})
export class AppComponent {
  onChange(event) {
    var files = event.srcElement.files;
    console.log(files);
  }
}

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

use property UseSimpleDictionaryFormat on DataContractJsonSerializer and set it to true.

Does the job :)

Converting string to double in C#

You can try this example out. A simple C# progaram to convert string to double

class Calculations{

protected double length;
protected double height;
protected double width;

public void get_data(){

this.length = Convert.ToDouble(Console.ReadLine());
this.width  = Convert.ToDouble(Console.ReadLine());
this.height = Convert.ToDouble(Console.ReadLine());

   }
}

TypeError: 'int' object is not callable

Somewhere else in your code you have something that looks like this:

round = 42

Then when you write

round((a/b)*0.9*c)

that is interpreted as meaning a function call on the object bound to round, which is an int. And that fails.

The problem is whatever code binds an int to the name round. Find that and remove it.

Checking Bash exit status of several commands efficiently

An alternative is simply to join the commands together with && so that the first one to fail prevents the remainder from executing:

command1 &&
  command2 &&
  command3

This isn't the syntax you asked for in the question, but it's a common pattern for the use case you describe. In general the commands should be responsible for printing failures so that you don't have to do so manually (maybe with a -q flag to silence errors when you don't want them). If you have the ability to modify these commands, I'd edit them to yell on failure, rather than wrap them in something else that does so.


Notice also that you don't need to do:

command1
if [ $? -ne 0 ]; then

You can simply say:

if ! command1; then

And when you do need to check return codes use an arithmetic context instead of [ ... -ne:

ret=$?
# do something
if (( ret != 0 )); then

how to run vibrate continuously in iphone?

iOS 5 has implemented Custom Vibrations mode. So in some cases variable vibration is acceptable. The only thing is unknown what library deals with that (pretty sure not CoreTelephony) and if it is open for developers. So keep on searching.

AttributeError: 'datetime' module has no attribute 'strptime'

If I had to guess, you did this:

import datetime

at the top of your code. This means that you have to do this:

datetime.datetime.strptime(date, "%Y-%m-%d")

to access the strptime method. Or, you could change the import statement to this:

from datetime import datetime

and access it as you are.

The people who made the datetime module also named their class datetime:

#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")

How to uninstall Golang?

You might try

rm -rvf /usr/local/go/

then remove any mention of go in e.g. your ~/.bashrc; then you need at least to logout and login.

However, be careful when doing that. You might break your system badly if something is wrong.

PS. I am assuming a Linux or POSIX system.

printf() prints whole array

Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.

Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.

Incase of string literals(character arrays defined at declaration), they are automatically appended by \0.

printf prints using the format specifier and the address provided. Since, you use %s it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'

What is the difference between __init__ and __call__?

We can use call method to use other class methods as static methods.

class _Callable:
    def __init__(self, anycallable):
        self.__call__ = anycallable

class Model:

    def get_instance(conn, table_name):

        """ do something"""

    get_instance = _Callable(get_instance)

provs_fac = Model.get_instance(connection, "users")  

How to create a DataFrame from a text file in Spark

A txt File with PIPE (|) delimited file can be read as :


df = spark.read.option("sep", "|").option("header", "true").csv("s3://bucket_name/folder_path/file_name.txt")

How to listen for a WebView finishing loading a URL?

Use this it should help.`var currentUrl = "google.com" var partOfUrl = currentUrl.substring(0, currentUrl.length-2)

webView.setWebViewClient(object: WebViewClient() {

override fun onLoadResource(WebView view, String url) {
     //call loadUrl() method  here 
     // also check if url contains partOfUrl, if not load it differently.
     if(url.contains(partOfUrl, true)) {
         //it should work if you reach inside this if scope.
     } else if(!(currentUrl.startWith("w", true))) {
         webView.loadurl("www.$currentUrl")

     } else if(!(currentUrl.startWith("h", true))) {
         webView.loadurl("https://$currentUrl")

     } else { ...}


 }

override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
   // you can call again loadUrl from here too if there is any error.
}

//You should also override other override method for error such as onReceiveError to see how all these methods are called one after another and how they behave while debugging with break point. } `

How to navigate a few folders up?

if c:\folder1\folder2\folder3\bin is the path then the following code will return the path base folder of bin folder

//string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString());

string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString();

ie,c:\folder1\folder2\folder3

if you want folder2 path then you can get the directory by

string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();

then you will get path as c:\folder1\folder2\

Are the shift operators (<<, >>) arithmetic or logical in C?

Here are functions to guarantee logical right shift and arithmetic right shift of an int in C:

int logicalRightShift(int x, int n) {
    return (unsigned)x >> n;
}
int arithmeticRightShift(int x, int n) {
    if (x < 0 && n > 0)
        return x >> n | ~(~0U >> n);
    else
        return x >> n;
}

git pull remote branch cannot find remote ref

You need to set your local branch to track the remote branch, which it won't do automatically if they have different capitalizations.

Try:

git branch --set-upstream downloadmanager origin/DownloadManager
git pull

UPDATE:

'--set-upstream' option is no longer supported.

git branch --set-upstream-to downloadmanager origin/DownloadManager
git pull

Android read text raw resource file

@borislemke you can do this by similar way like

TextView  tv ;
findViewById(R.id.idOfTextView);
tv.setText(readNewTxt());
private String readNewTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.yourNewTextFile);
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

 int i;
 try {
 i = inputStream.read();
while (i != -1)
  {
   byteArrayOutputStream.write(i);
   i = inputStream.read();
   }
    inputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
 e.printStackTrace();
 }

 return byteArrayOutputStream.toString();
 }

Writing to a new file if it doesn't exist, and appending to a file if it does

Notice that if the file's parent folder doesn't exist you'll get the same error:

IOError: [Errno 2] No such file or directory:

Below is another solution which handles this case:
(*) I used sys.stdout and print instead of f.write just to show another use case

# Make sure the file's folder exist - Create folder if doesn't exist
folder_path = 'path/to/'+folder_name+'/'
if not os.path.exists(folder_path):
     os.makedirs(folder_path)

print_to_log_file(folder_path, "Some File" ,"Some Content")

Where the internal print_to_log_file just take care of the file level:

# If you're not familiar with sys.stdout - just ignore it below (just a use case example)
def print_to_log_file(folder_path ,file_name ,content_to_write):

   #1) Save a reference to the original standard output       
    original_stdout = sys.stdout   
    
    #2) Choose the mode
    write_append_mode = 'a' #Append mode
    file_path = folder_path + file_name
    if (if not os.path.exists(file_path) ):
       write_append_mode = 'w' # Write mode
     
    #3) Perform action on file
    with open(file_path, write_append_mode) as f:
        sys.stdout = f  # Change the standard output to the file we created.
        print(file_path, content_to_write)
        sys.stdout = original_stdout  # Reset the standard output to its original value

Consider the following states:

'w'  --> Write to existing file
'w+' --> Write to file, Create it if doesn't exist
'a'  --> Append to file
'a+' --> Append to file, Create it if doesn't exist

In your case I would use a different approach and just use 'a' and 'a+'.

How can I rename a single column in a table at select?

Also you may omit the AS keyword.
SELECT row1 Price, row2 'Other Price' FROM exampleDB.table1;
in this option readability is a bit degraded but you have desired result.

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

For numerical addressing of cells try to enable S1O1 checkbox in MS Excel settings. It is the second tab from top (i.e. Formulas), somewhere mid-page in my Hungarian version.

If enabled, it handles VBA addressing in both styles, i.e. Range("A1:B10") and Range(Cells(1, 1), Cells(10, 2)). I assume it handles Range("A1:B10") style only, if not enabled.

Good luck!

(Note, that Range("A1:B10") represents a 2x10 square, while Range(Cells(1, 1), Cells(10, 2)) represents 10x2. Using column numbers instead of letters will not affect the order of addresing.)

Custom method names in ASP.NET Web API

Web APi 2 and later versions support a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources.

For example:

[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }

Will perfect and you don't need any extra code for example in WebApiConfig.cs. Just you have to be sure web api routing is enabled or not in WebApiConfig.cs , if not you can activate like below:

        // Web API routes
        config.MapHttpAttributeRoutes();

You don't have to do something more or change something in WebApiConfig.cs. For more details you can have a look this article.

Best cross-browser method to capture CTRL+S with JQuery?

@Eevee: As the browser becomes the home for richer and richer functionality and starts to replace desktop apps, it's just not going to be an option to forgo the use of keyboard shortcuts. Gmail's rich and intuitive set of keyboard commands was instrumental in my willingness to abandon Outlook. The keyboard shortcuts in Todoist, Google Reader, and Google Calendar all make my life much, much easier on a daily basis.

Developers should definitely be careful not to override keystrokes that already have a meaning in the browser. For example, the WMD textbox I'm typing into inexplicably interprets Ctrl+Del as "Blockquote" rather than "delete word forward". I'm curious if there's a standard list somewhere of "browser-safe" shortcuts that site developers can use and that browsers will commit to staying away from in future versions.

How do I get the XML SOAP request of an WCF Web service request?

I think you meant that you want to see the XML at the client, not trace it at the server. In that case, your answer is in the question I linked above, and also at How to Inspect or Modify Messages on the Client. But, since the .NET 4 version of that article is missing its C#, and the .NET 3.5 example has some confusion (if not a bug) in it, here it is expanded for your purpose.

You can intercept the message before it goes out using an IClientMessageInspector:

using System.ServiceModel.Dispatcher;
public class MyMessageInspector : IClientMessageInspector
{ }

The methods in that interface, BeforeSendRequest and AfterReceiveReply, give you access to the request and reply. To use the inspector, you need to add it to an IEndpointBehavior:

using System.ServiceModel.Description;
public class InspectorBehavior : IEndpointBehavior
{
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new MyMessageInspector());
    }
}

You can leave the other methods of that interface as empty implementations, unless you want to use their functionality, too. Read the how-to for more details.

After you instantiate the client, add the behavior to the endpoint. Using default names from the sample WCF project:

ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
client.Endpoint.Behaviors.Add(new InspectorBehavior());
client.GetData(123);

Set a breakpoint in MyMessageInspector.BeforeSendRequest(); request.ToString() is overloaded to show the XML.

If you are going to manipulate the messages at all, you have to work on a copy of the message. See Using the Message Class for details.

Thanks to Zach Bonham's answer at another question for finding these links.

How to verify Facebook access token?

Simply request (HTTP GET):

https://graph.facebook.com/USER_ID/access_token=xxxxxxxxxxxxxxxxx

That's it.

Return array in a function

And why don't "return" the array as a parameter?

fillarr(int source[], size_t dimSource, int dest[], size_t dimDest)
{

    if (dimSource <= dimDest)
    {
        for (size_t i = 0; i < dimSource; i++)
        {   
            //some stuff...
        }
    }
    else 
    {
        //some stuff..
    }
}

or..in a simpler way (but you have to know the dimensions...):

fillarr(int source[], int dest[])
{
    //...
}

Create dataframe from a matrix

If you change your time column into row names, then you can use as.data.frame(as.table(mat)) for simple cases like this.

Example:

data <- c(0.1, 0.2, 0.3, 0.3, 0.4, 0.5)
dimnames <- list(time=c(0, 0.5, 1), name=c("C_0", "C_1"))
mat <- matrix(data, ncol=2, nrow=3, dimnames=dimnames)
as.data.frame(as.table(mat))
  time name Freq
1    0  C_0  0.1
2  0.5  C_0  0.2
3    1  C_0  0.3
4    0  C_1  0.3
5  0.5  C_1  0.4
6    1  C_1  0.5

In this case time and name are both factors. You may want to convert time back to numeric, or it may not matter.

Visual Studio Code: format is not using indent settings

For myself, this problem was caused by using the prettier VSCode plugin without having a prettier config file in the workspace.

Disabling the plugin fixed the problem. It could have also probably been fixed by relying on the prettier config.

How do I search a Perl array for a matching string?

If you will be doing many searches of the array, AND matching always is defined as string equivalence, then you can normalize your data and use a hash.

my @strings = qw( aAa Bbb cCC DDD eee );

my %string_lut;

# Init via slice:
@string_lut{ map uc, @strings } = ();

# or use a for loop:
#    for my $string ( @strings ) {
#        $string_lut{ uc($string) } = undef;
#    }


#Look for a string:

my $search = 'AAa';

print "'$string' ", 
    ( exists $string_lut{ uc $string ? "IS" : "is NOT" ),
    " in the array\n";

Let me emphasize that doing a hash lookup is good if you are planning on doing many lookups on the array. Also, it will only work if matching means that $foo eq $bar, or other requirements that can be met through normalization (like case insensitivity).

How to store values from foreach loop into an array?

Just to save you too much typos:

foreach($group_membership as $username){
        $username->items = array(additional array to add);
    }
    print_r($group_membership);

How do I decrease the size of my sql server log file?

You have to shrink & backup the log a several times to get the log file to reduce in size, this is because the the log file pages cannot be re-organized as data files pages can be, only truncated. For a more detailed explanation check this out.

WARNING : Detaching the db & deleting the log file is dangerous! don't do this unless you'd like data loss

How to iterate over each string in a list of strings and operate on it's elements

The following code outputs the number of words whose first and last letters are equal. Tested and verified using a python online compiler:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']  
count = 0  
for i in words:  
     if i[0]==i[-1]:
        count = count + 1  
print(count)  

Output:

$python main.py
3

Strings and character with printf

You're confusing the dereference operator * with pointer type annotation *. Basically, in C * means different things in different places:

  • In a type, * means a pointer. int is an integer type, int* is a pointer to integer type
  • As a prefix operator, * means 'dereference'. name is a pointer, *name is the result of dereferencing it (i.e. getting the value that the pointer points to)
  • Of course, as an infix operator, * means 'multiply'.

What does it mean if a Python object is "subscriptable" or not?

Off the top of my head, the following are the only built-ins that are subscriptable:

string:  "foobar"[3] == "b"
tuple:   (1,2,3,4)[3] == 4
list:    [1,2,3,4][3] == 4
dict:    {"a":1, "b":2, "c":3}["c"] == 3

But mipadi's answer is correct - any class that implements __getitem__ is subscriptable

Using a PHP variable in a text input value = statement

You need, for example:

<input type="text" name="idtest" value="<?php echo $idtest; ?>" />

The echo function is what actually outputs the value of the variable.

GitHub README.md center image

You can also resize the image to the desired width and height. For example:

<p align="center">
  <img src="https://anyserver.com/image.png" width="750px" height="300px"/></p>

To add a centered caption to the image, just one more line:

<p align="center">This is a centered caption for the image<p align="center">

Fortunately, this works both for README.md and the GitHub Wiki pages.

How can I get argv[] as int?

Basic usage

The "string to long" (strtol) function is standard for this ("long" can hold numbers much larger than "int"). This is how to use it:

#include <stdlib.h>

long arg = strtol(argv[1], NULL, 10);
// string to long(string, endpointer, base)

Since we use the decimal system, base is 10. The endpointer argument will be set to the "first invalid character", i.e. the first non-digit. If you don't care, set the argument to NULL instead of passing a pointer, as shown.

Error checking (1)

If you don't want non-digits to occur, you should make sure it's set to the "null terminator", since a \0 is always the last character of a string in C:

#include <stdlib.h>

char* p;
long arg = strtol(argv[1], &p, 10);
if (*p != '\0') // an invalid character was found before the end of the string

Error checking (2)

As the man page mentions, you can use errno to check that no errors occurred (in this case overflows or underflows).

#include <stdlib.h>
#include <errno.h>

char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
    return 1; // In main(), returning non-zero means failure
}

// Everything went well, print it as 'long decimal'
printf("%ld", arg);

Convert to integer

So now we are stuck with this long, but we often want to work with integers. To convert a long into an int, we should first check that the number is within the limited capacity of an int. To do this, we add a second if-statement, and if it matches, we can just cast it.

#include <stdlib.h>
#include <errno.h>
#include <limits.h>

char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
    return 1; // In main(), returning non-zero means failure
}

if (arg < INT_MIN || arg > INT_MAX) {
    return 1;
}
int arg_int = arg;

// Everything went well, print it as a regular number
printf("%d", arg_int);

To see what happens if you don't do this check, test the code without the INT_MIN/MAX if-statement. You'll see that if you pass a number larger than 2147483647 (231), it will overflow and become negative. Or if you pass a number smaller than -2147483648 (-231-1), it will underflow and become positive. Values beyond those limits are too large to fit in an integer.

Full example

#include <stdio.h>  // for printf()
#include <stdlib.h> // for strtol()
#include <errno.h>  // for errno
#include <limits.h> // for INT_MIN and INT_MAX

int main(int argc, char** argv) {
    char* p;
    errno = 0; // not 'int errno', because the '#include' already defined it
    long arg = strtol(argv[1], &p, 10);
    if (*p != '\0' || errno != 0) {
        return 1; // In main(), returning non-zero means failure
    }

    if (arg < INT_MIN || arg > INT_MAX) {
        return 1;
    }
    int arg_int = arg;

    // Everything went well, print it as a regular number plus a newline
    printf("Your value was: %d\n", arg_int);
    return 0;
}

In Bash, you can test this with:

cc code.c -o example  # Compile, output to 'example'
./example $((2**31-1))  # Run it
echo "exit status: $?"  # Show the return value, also called 'exit status'

Using 2**31-1, it should print the number and 0, because 231-1 is just in range. If you pass 2**31 instead (without -1), it will not print the number and the exit status will be 1.

Beyond this, you can implement custom checks: test whether the user passed an argument at all (check argc), test whether the number is in the range that you want, etc.

Java: Getting a substring from a string starting after a particular character

This can also get the filename

import java.nio.file.Paths;
import java.nio.file.Path;
Path path = Paths.get("/abc/def/ghfj.doc");
System.out.println(path.getFileName().toString());

Will print ghfj.doc

Subtract one day from datetime

To simply subtract one day from todays date:

Select DATEADD(day,-1,GETDATE())

(original post used -7 and was incorrect)

Relative path in HTML

The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.

If the URL of your website is: http://www.example.com/mywebsite/ then starting at the root level starts above the "mywebsite" folder path.

How to convert string to char array in C++?

If you're using C++11 or above, I'd suggest using std::snprintf over std::strcpy or std::strncpy because of its safety (i.e., you determine how many characters can be written to your buffer) and because it null-terminates the string for you (so you don't have to worry about it). It would be like this:

#include <string>
#include <cstdio>

std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, sizeof(tab2), "%s", tmp.c_str());

In C++17, you have this alternative:

#include <string>
#include <cstdio>
#include <iterator>

std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, std::size(tab2), "%s", tmp.c_str());

Archive the artifacts in Jenkins

An artifact can be any result of your build process. The important thing is that it doesn't matter on which client it was built it will be tranfered from the workspace back to the master (server) and stored there with a link to the build. The advantage is that it is versionized this way, you only have to setup backup on your master and that all artifacts are accesible via the web interface even if all build clients are offline.

It is possible to define a regular expression as the artifact name. In my case I zipped all the files I wanted to store in one file with a constant name during the build.

Get Mouse Position

If you're using Swing as your UI layer, you can use a Mouse-Motion Listener for this.

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

All of these are kinds of indices.

primary: must be unique, is an index, is (likely) the physical index, can be only one per table.

unique: as it says. You can't have more than one row with a tuple of this value. Note that since a unique key can be over more than one column, this doesn't necessarily mean that each individual column in the index is unique, but that each combination of values across these columns is unique.

index: if it's not primary or unique, it doesn't constrain values inserted into the table, but it does allow them to be looked up more efficiently.

fulltext: a more specialized form of indexing that allows full text search. Think of it as (essentially) creating an "index" for each "word" in the specified column.

Is there any way to install Composer globally on Windows?

A bit more generic if you put the batch in the same folder as composer.phar:

@ECHO OFF
SET SUBDIR=%~dp0
php %SUBDIR%/composer.phar %*

I'd write it as a comment, but code isn't avail there

"detached entity passed to persist error" with JPA/EJB code

I got the answer, I was using:

em.persist(user);

I used merge in place of persist:

em.merge(user);

But no idea, why persist didn't work. :(

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

C# Lambda expressions: Why should I use them?

The biggest benefit of lambda expressions and anonymous functions is the fact that they allow the client (programmer) of a library/framework to inject functionality by means of code in the given library/framework ( as it is the LINQ, ASP.NET Core and many others ) in a way that the regular methods cannot. However, their strength is not obvious for a single application programmer but to the one that creates libraries that will be later used by others who will want to configure the behaviour of the library code or the one that uses libraries. So the context of effectively using a lambda expression is the usage/creation of a library/framework.

Also since they describe one-time usage code they don't have to be members of a class where that will led to more code complexity. Imagine to have to declare a class with unclear focus every time we wanted to configure the operation of a class object.

How can I fill out a Python string with spaces?

You could do it using list comprehension, this'd give you an idea about the number of spaces too and would be a one liner.

"hello" + " ".join([" " for x in range(1,10)])
output --> 'hello                 '

Scroll to a div using jquery

There is no .scrollTo() method in jQuery, but there is a .scrollTop() one. .scrollTop expects a parameter, that is, the pixel value where the scrollbar should scroll to.

Example:

$(window).scrollTop(200);

will scroll the window (if there is enough content in it).

So you can get this desired value with .offset() or .position().

Example:

$(window).scrollTop($('#contact').offset().top);

This should scroll the #contact element into view.

The non-jQuery alternate method is .scrollIntoView(). You can call that method on any DOM element like:

$('#contact')[0].scrollIntoView(true);

true indicates that the element is positioned at the top whereas false would place it on the bottom of the view. The nice thing with the jQuery method is, you can even use it with fx functions like .animate(). So you might smooth scroll something.

Reference: .scrollTop(), .position(), .offset()

Format XML string to print friendly XML string

I tried:

internal static void IndentedNewWSDLString(string filePath)
{
    var xml = File.ReadAllText(filePath);
    XDocument doc = XDocument.Parse(xml);
    File.WriteAllText(filePath, doc.ToString());
}

it is working fine as expected.

Remove all constraints affecting a UIView

The easier and efficient approach is to remove the view from superView and re add as subview again. this causes all the subview constraints get removed automagically.

The controller for path was not found or does not implement IController

If appropriate to your design, you can make sure the access modifier on your controller class is 'public', not something that could limit access like 'internal' or 'private'.

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

Change .img-responsive inside bootstrap.css to the following:

.img-responsive {
    display: block;
    max-width: 100%;
    width: 100%;
    height: auto;
}

For some reason adding width: 100% to the mix makes img-responsive work.

Allow anonymous authentication for a single folder in web.config?

<location path="ForAll/Demo.aspx">
 <system.web>
  <authorization>
    <allow users="*" />
  </authorization>
 </system.web>
</location>

In Addition: If you want to write something on that folder through website , you have to give IIS_User permission to the folder

Push local Git repo to new remote including all branches and tags

This is the most concise way I have found, provided the destination is empty. Switch to an empty folder and then:

# Note the period for cwd >>>>>>>>>>>>>>>>>>>>>>>> v
git clone --bare https://your-source-repo/repo.git .
git push --mirror https://your-destination-repo/repo.git

Substitute https://... for file:///your/repo etc. as appropriate.

Cannot find module cv2 when using OpenCV

I have come accross same as this problem i installed cv2 by

pip install cv2

However when i import cv2 module it displayed no module named cv2 error.
Then i searched and find cv2.pyd files in my computer and i copy and paste to site-packages directory

C:\Python27\Lib\site-packages

then i closed and reopened existing application, it worked.

EDIT I will tell how to install cv2 correctly.

1. Firstly install numpy on your computer by

pip install numpy


2. Download opencv from internet (almost 266 mb).
I download opencv-2.4.12.exe for python 2.7. Then install this opencv-2.4.12.exe file.
I extracted to C:\Users\harun\Downloads to this folder.
After installation go look for cv2.py into the folders.
For me

C:\Users\harun\Downloads\opencv\build\python\2.7\x64

in this folder take thecv2.pyd and copy it in to the

C:\Python27\Lib\site-packages

now you can able to use cv2 in you python scripts.

How do I create a file at a specific path?

It will be created once you close the file (with or without writing). Use os.path.join() to create your path eg

filepath = os.path.join("c:\\","test.py")

gcc makefile error: "No rule to make target ..."

In my case, the source and/or old object file(s) were locked (read-only) by a semi-crashed IDE or from a backup cloud service that stopped working properly. Restarting all programs and services that were associated with the folder structure solved the problem.

SVN upgrade working copy

from eclipse, you can select on the project, right click->team->upgrade

Writing Unicode text to a text file?

Unicode string handling is already standardized in Python 3.

  1. char's are already stored in Unicode (32-bit) in memory
  2. You only need to open file in utf-8
    (32-bit Unicode to variable-byte-length utf-8 conversion is automatically performed from memory to file.)

    out1 = "(???? ??? ??´ ??` ???` )"
    fobj = open("t1.txt", "w", encoding="utf-8")
    fobj.write(out1)
    fobj.close()
    

Moving up one directory in Python

Well.. I'm not sure how portable os.chdir('..') would actually be. Under Unix those are real filenames. I would prefer the following:

import os
os.chdir(os.path.dirname(os.getcwd()))

That gets the current working directory, steps up one directory, and then changes to that directory.

Elastic Search: how to see the indexed data

Probably the easiest way to explore your ElasticSearch cluster is to use elasticsearch-head.

You can install it by doing:

cd elasticsearch/
./bin/plugin -install mobz/elasticsearch-head

Then (assuming ElasticSearch is already running on your local machine), open a browser window to:

http://localhost:9200/_plugin/head/

Alternatively, you can just use curl from the command line, eg:

Check the mapping for an index:

curl -XGET 'http://127.0.0.1:9200/my_index/_mapping?pretty=1' 

Get some sample docs:

curl -XGET 'http://127.0.0.1:9200/my_index/_search?pretty=1' 

See the actual terms stored in a particular field (ie how that field has been analyzed):

curl -XGET 'http://127.0.0.1:9200/my_index/_search?pretty=1'  -d '
 {
    "facets" : {
       "my_terms" : {
          "terms" : {
             "size" : 50,
             "field" : "foo"
          }
       }
    }
 }

More available here: http://www.elasticsearch.org/guide

UPDATE : Sense plugin in Marvel

By far the easiest way of writing curl-style commands for Elasticsearch is the Sense plugin in Marvel.

It comes with source highlighting, pretty indenting and autocomplete.

Note: Sense was originally a standalone chrome plugin but is now part of the Marvel project.

Didn't Java once have a Pair class?

If you want a pair (not supposedly key-value pair) just to hold two generic data together neither of the solutions above really handy since first (or so called Key) cannot be changed (neither in Apache Commons Lang's Pair nor in AbstractMap.SimpleEntry). They have thier own reasons, but still you may need to be able to change both of the components. Here is a Pair class in which both elements can be set

public class Pair<First, Second> {
    private First first;
    private Second second;

    public Pair(First first, Second second) {
        this.first = first;
        this.second = second;
    }

    public void setFirst(First first) {
        this.first = first;
    }

    public void setSecond(Second second) {
        this.second = second;
    }

    public First getFirst() {
        return first;
    }

    public Second getSecond() {
        return second;
    }

    public void set(First first, Second second) {
        setFirst(first);
        setSecond(second);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Pair pair = (Pair) o;

        if (first != null ? !first.equals(pair.first) : pair.first != null) return false;
        if (second != null ? !second.equals(pair.second) : pair.second != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = first != null ? first.hashCode() : 0;
        result = 31 * result + (second != null ? second.hashCode() : 0);
        return result;
    }
}

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

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

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

Syntax for a for loop in ruby

To iterate a loop a fixed number of times, try:

n.times do
  #Something to be done n times
end

How do I find the location of my Python site-packages directory?

A solution that:

  • outside of virtualenv - provides the path of global site-packages,
  • insidue a virtualenv - provides the virtualenv's site-packages

...is this one-liner:

python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"

Formatted for readability (rather than use as a one-liner), that looks like the following:

from distutils.sysconfig import get_python_lib
print(get_python_lib())


Source: an very old version of "How to Install Django" documentation (though this is useful to more than just Django installation)

jQuery: Uncheck other checkbox on one checked

I think the prop method is more convenient when it comes to boolean attribute. http://api.jquery.com/prop/

How do you make a HTTP request with C++?

Although a little bit late. You may prefer https://github.com/Taymindis/backcurl .

It allows you to do http call on mobile c++ development. Suitable for Mobile game developement

bcl::init(); // init when using

bcl::execute<std::string>([&](bcl::Request *req) {
    bcl::setOpts(req, CURLOPT_URL , "http://www.google.com",
             CURLOPT_FOLLOWLOCATION, 1L,
             CURLOPT_WRITEFUNCTION, &bcl::writeContentCallback,
             CURLOPT_WRITEDATA, req->dataPtr,
             CURLOPT_USERAGENT, "libcurl-agent/1.0",
             CURLOPT_RANGE, "0-200000"
            );
}, [&](bcl::Response * resp) {
    std::string ret =  std::string(resp->getBody<std::string>()->c_str());
    printf("Sync === %s\n", ret.c_str());
});


bcl::cleanUp(); // clean up when no more using

How do I prevent Conda from activating the base environment by default?

So in the end I found that if I commented out the Conda initialisation block like so:

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
# __conda_setup="$('/Users/geoff/anaconda2/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
# if [ $? -eq 0 ]; then
    # eval "$__conda_setup"
# else
if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
    . "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
else
    export PATH="/Users/geoff/anaconda2/bin:$PATH"
fi
# fi
# unset __conda_setup
# <<< conda initialize <<<

It works exactly how I want. That is, Conda is available to activate an environment if I want, but doesn't activate by default.

Display the current time and date in an Android application

To get current Time/Date just use following code snippet:

To use Time:

SimpleDateFormat simpleDateFormatTime = new SimpleDateFormat("HH:mm", Locale.getDefault());
String strTime = simpleDateFormatTime.format(now.getTime());

To use Date:

SimpleDateFormat simpleDateFormatDate = new SimpleDateFormat("E, MMM dd, yyyy", Locale.getDefault());    
String strDate = simpleDateFormatDate.format(now.getTime());

and you are good to go.

How to print like printf in Python3?

print("Name={}, balance={}".format(var-name, var-balance))

Get first day of week in PHP?

<?php
/* PHP 5.3.0 */

date_default_timezone_set('America/Denver'); //Set apprpriate timezone
$start_date = strtotime('2009-12-15'); //Set start date

//Today's date if $start_date is a Sunday, otherwise date of previous Sunday
$today_or_previous_sunday = mktime(0, 0, 0, date('m', $start_date), date('d', $start_date), date('Y', $start_date)) - ((date("w", $start_date) ==0) ? 0 : (86400 * date("w", $start_date)));

//prints 12-13-2009 (month-day-year)
echo date('m-d-Y', $today_or_previous_sunday);

?>

(Note: MM, dd and yyyy in the Question are not standard php date format syntax - I can't be sure what is meant, so I set the $start_date with ISO year-month-day)

SQL Server Format Date DD.MM.YYYY HH:MM:SS

A quick way to do it in sql server 2012 is as follows:

SELECT FORMAT(GETDATE() , 'dd/MM/yyyy HH:mm:ss')

How can I reduce the waiting (ttfb) time

I have met the same problem. My project is running on the local server. I checked my php code.

$db = mysqli_connect('localhost', 'root', 'root', 'smart');

I use localhost to connect to my local database. That maybe the cause of the problem which you're describing. You can modify your HOSTS file. Add the line

127.0.0.1 localhost.

How to access List elements

Recursive solution to print all items in a list:

def printItems(l):
   for i in l:
      if isinstance(i,list):
         printItems(i)
      else:
         print i


l = [['vegas','London'],['US','UK']]
printItems(l)

sendKeys() in Selenium web driver

List<WebElement>itemNames = wd.findElements(By.cssSelector("a strong")); 
System.out.println("No items in Catalog page: " + itemNames.size());
   for (WebElement itemName:itemNames)
    {  
       System.out.println(itemName.getText());
    }

How to sort List of objects by some property

As mentioned you can sort by:

  • Making your object implement Comparable
  • Or pass a Comparator to Collections.sort

If you do both, the Comparable will be ignored and Comparator will be used. This helps that the value objects has their own logical Comparable which is most reasonable sort for your value object, while each individual use case has its own implementation.

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

Also, we can use it following ways

To get only first

 $cat_details = DB::table('an_category')->where('slug', 'people')->first();

To get by limit and offset

$top_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(0)->orderBy('id', 'DESC')->get();
$remaining_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(30)->orderBy('id', 'DESC')->get();

Change the Textbox height?

set the minimum size property

tb_01.MinimumSize = new Size(500, 300);

This is working for me.

How do you Change a Package's Log Level using Log4j?

I encountered the exact same problem today, Ryan.

In my src (or your root) directory, my log4j.properties file now has the following addition

# https://issues.apache.org/jira/browse/AXIS2-4363
log4j.category.org.apache.axiom=WARN

Thanks for the heads up as to how to do this, Benjamin.

How to define servlet filter order of execution using annotations in WAR

The Servlet 3.0 spec doesn't seem to provide a hint on how a container should order filters that have been declared via annotations. It is clear how about how to order filters via their declaration in the web.xml file, though.

Be safe. Use the web.xml file order filters that have interdependencies. Try to make your filters all order independent to minimize the need to use a web.xml file.

How can I create basic timestamps or dates? (Python 3.4)

>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14

Copying a local file from Windows to a remote server using scp

Drive letter can be used in the source like

scp /c/path/to/file.txt user@server:/dir1/file.txt

SQL set values of one column equal to values of another column in the same table

I would do it this way:

UPDATE YourTable SET B = COALESCE(B, A);

COALESCE is a function that returns its first non-null argument.

In this example, if B on a given row is not null, the update is a no-op.

If B is null, the COALESCE skips it and uses A instead.

Maven: best way of linking custom external JAR to my project?

Maven way to add non maven jars to maven project

Maven Project and non maven jars

Add the maven install plugins in your build section

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-install-plugin</artifactId>
        <version>${version.maven-install-plugin}</version>
        <executions>

            <execution>
                <id>install-external-non-maven1-jar</id>
                <phase>clean</phase>
                <configuration>
                    <repositoryLayout>default</repositoryLayout>
                    <groupId>jar1.group</groupId>
                    <artifactId>non-maven1</artifactId>
                    <version>${version.non-maven1}</version>
                    <file>${project.basedir}/libs/non-maven1.jar</file>
                    <packaging>jar</packaging>
                    <generatePom>true</generatePom>
                </configuration>
                <goals>
                    <goal>install-file</goal>
                </goals>
            </execution>
            <execution>
                <id>install-external-non-maven2-jar</id>
                <phase>clean</phase>
                <configuration>
                    <repositoryLayout>default</repositoryLayout>
                    <groupId>jar2.group</groupId>
                    <artifactId>non-maven2</artifactId>
                    <version>${version.non-maven2}</version>
                    <file>${project.basedir}/libs/non-maven2.jar</file>
                    <packaging>jar</packaging>
                    <generatePom>true</generatePom>
                </configuration>
                <goals>
                    <goal>install-file</goal>
                </goals>
            </execution>
            <execution>
                <id>install-external-non-maven3-jar</id>
                <phase>clean</phase>
                <configuration>
                    <repositoryLayout>default</repositoryLayout>
                    <groupId>jar3.group</groupId>
                    <artifactId>non-maven3</artifactId>
                    <version>${version.non-maven3}</version>
                    <file>${project.basedir}/libs/non-maven3.jar</file>
                    <packaging>jar</packaging>
                    <generatePom>true</generatePom>
                </configuration>
                <goals>
                    <goal>install-file</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

Add the dependency

<dependencies>
    <dependency>
        <groupId>jar1.group</groupId>
        <artifactId>non-maven1</artifactId>
        <version>${version.non-maven1}</version>
    </dependency>
    <dependency>
        <groupId>jar2.group</groupId>
        <artifactId>non-maven2</artifactId>
        <version>${version.non-maven2}</version>
    </dependency>
    <dependency>
        <groupId>jar3.group</groupId>
        <artifactId>non-maven3</artifactId>
        <version>${version.non-maven3}</version>
    </dependency>
</dependencies>

References Note I am the owner of the blog

How to remove unused C/C++ symbols with GCC and ld?

strip --strip-unneeded only operates on the symbol table of your executable. It doesn't actually remove any executable code.

The standard libraries achieve the result you're after by splitting all of their functions into seperate object files, which are combined using ar. If you then link the resultant archive as a library (ie. give the option -l your_library to ld) then ld will only include the object files, and therefore the symbols, that are actually used.

You may also find some of the responses to this similar question of use.

How Do I Uninstall Yarn

For Windows:

I need to do these steps to completely remove the yarn from the system.

  1. Go to add or remove programs and then search for yarn and uninstall it(if you installed it with the .msi)
  2. npm uninstall -g yarn (if you installed with npm)
  3. Remove any existing yarn folders from your Program Files (x86) (Program Files (x86)\Yarn).
  4. Also need to delete your Appdata\local\yarn folder ( type %LOCALAPPDATA% in the run dialog box (win+R), it opens a local folder and there you'll find the yarn folder to delete)
  5. Finally,check your user directory and remove all .yarn folder, .yarn.lock file, .yarnrc etc ( from C:\Users\<user>\)

Converting pixels to dp

Kotlin

fun convertDpToPixel(dp: Float, context: Context): Float {
    return dp * (context.resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}

fun convertPixelsToDp(px: Float, context: Context): Float {
    return px / (context.resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}

Java

public static float convertDpToPixel(float dp, Context context) {
    return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}

public static float convertPixelsToDp(float px, Context context) {
    return px / ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}

How to load a resource bundle from a file resource in Java?

For JSF Application

To get resource bundle prop files from a given file path to use them in a JSF app.

  • Set the bundle with URLClassLoader for a class that extends ResourceBundle to load the bundle from the file path.
  • Specify the class at basename property of loadBundle tag. <f:loadBundle basename="Message" var="msg" />

For basic implementation of extended RB please see the sample at Sample Customized Resource Bundle

/* Create this class to make it base class for Loading Bundle for JSF apps */
public class Message extends ResourceBundle {
        public Messages (){
                File file = new File("D:\\properties\\i18n");  
                ClassLoader loader=null;
                   try {
                       URL[] urls = {file.toURI().toURL()};  
                       loader = new URLClassLoader(urls); 
                       ResourceBundle bundle = getBundle("message", FacesContext.getCurrentInstance().getViewRoot().getLocale(), loader);
                       setParent(bundle);
                       } catch (MalformedURLException ex) { }
       }
      .
      .
      .
    }

Otherwise, get the bundle from getBundle method but locale from others source like Locale.getDefault(), the new (RB)class may not require in this case.

What does 'URI has an authority component' mean?

After trying a skeleton project called "jsf-blank", which did not demonstrate this problem with xhtml files; I concluded that there was an unknown problem in my project. My solution may not have been too elegant, but it saved time. I backed up the code and other files I'd already developed, deleted the project, and started over - recreated the project. So far, I've added back most of the files and it looks pretty good.

How to output HTML from JSP <%! ... %> block?

A simple alternative would be the following:

<%!
    String myVariable = "Test";
    pageContext.setAttribute("myVariable", myVariable);
%>

<c:out value="myVariable"/>
<h1>${myVariable}</h1>

The you could simply use the variable in any way within the jsp code

What is the default value for enum variable?

I think it's quite dangerous to rely on the order of the values in a enum and to assume that the first is always the default. This would be good practice if you are concerned about protecting the default value.

enum E
{
    Foo = 0, Bar, Baz, Quux
}

Otherwise, all it takes is a careless refactor of the order and you've got a completely different default.

div inside php echo

Try this,

<?php  if ( ($cart->count_product) > 0) { ?>
         <div class="my_class"><?php print $cart->count_product; ?></div>
<?php } else { 
          print ''; 
}  ?>

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Convert object of any type to JObject with Json.NET

If you have an object and wish to become JObject you can use:

JObject o = (JObject)JToken.FromObject(miObjetoEspecial);

like this :

Pocion pocionDeVida = new Pocion{
tipo = "vida",
duracion = 32,
};

JObject o = (JObject)JToken.FromObject(pocionDeVida);
Console.WriteLine(o.ToString());
// {"tipo": "vida", "duracion": 32,}

htaccess "order" Deny, Allow, Deny

In apache2, linux configuration

Require all granted

How do you find out the type of an object (in Swift)?

Swift 3:

if unknownType is MyClass {
   //unknownType is of class type MyClass
}

Colorplot of 2D array matplotlib

Here is the simplest example that has the key lines of code:

import numpy as np 
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]])

plt.imshow(H, interpolation='none')
plt.show()

enter image description here

POST string to ASP.NET Web Api application - returns null

Web API works very nicely if you accept the fact that you are using HTTP. It's when you start trying to pretend that you are sending objects over the wire that it starts to get messy.

 public class TextController : ApiController
    {
        public HttpResponseMessage Post(HttpRequestMessage request) {

            var someText = request.Content.ReadAsStringAsync().Result;
            return new HttpResponseMessage() {Content = new StringContent(someText)};

        }

    }

This controller will handle a HTTP request, read a string out of the payload and return that string back.

You can use HttpClient to call it by passing an instance of StringContent. StringContent will be default use text/plain as the media type. Which is exactly what you are trying to pass.

    [Fact]
    public void PostAString()
    {

        var client = new HttpClient();

        var content = new StringContent("Some text");
        var response = client.PostAsync("http://oak:9999/api/text", content).Result;

        Assert.Equal("Some text",response.Content.ReadAsStringAsync().Result);

    }

How do you get the contextPath from JavaScript, the right way?

I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:

<html>
    <head>
        <link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
    <body>
        <script src="main.js" type="text/javascript"></script>
    </body>
</html>

main.js

var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});

If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

Just copy-paste the .jar under the "libs" folder (or whole "libs" folder), right click on it and select 'Add as library' option from the list. It will do the rest...

enter image description here

Replace new line/return with space using regex

This should take care of space, tab and newline:

data = data.replaceAll("[ \t\n\r]*", " ");

Is there a way to get the git root directory in one command?

To calculate the absolute path of the current git root directory, say for use in a shell script, use this combination of readlink and git rev-parse:

gitroot=$(readlink -f ./$(git rev-parse --show-cdup))

git-rev-parse --show-cdup gives you the right number of ".."s to get to the root from your cwd, or the empty string if you are at the root. Then prepend "./" to deal with the empty string case and use readlink -f to translate to a full path.

You could also create a git-root command in your PATH as a shell script to apply this technique:

cat > ~/bin/git-root << EOF
#!/bin/sh -e
cdup=$(git rev-parse --show-cdup)
exec readlink -f ./$cdup
EOF
chmod 755 ~/bin/git-root

(The above can be pasted into a terminal to create git-root and set execute bits; the actual script is in lines 2, 3 and 4.)

And then you'd be able to run git root to get the root of your current tree. Note that in the shell script, use "-e" to cause the shell to exit if the rev-parse fails so that you can properly get the exit status and error message if you are not in a git directory.

How do I get the absolute directory of a file in bash?

Try our new Bash library product realpath-lib over at GitHub that we have given to the community for free and unencumbered use. It's clean, simple and well documented so it's great to learn from. You can do:

get_realpath <absolute|relative|symlink|local file path>

This function is the core of the library:

if [[ -f "$1" ]]
then
    # file *must* exist
    if cd "$(echo "${1%/*}")" &>/dev/null
    then
        # file *may* not be local
        # exception is ./file.ext
        # try 'cd .; cd -;' *works!*
        local tmppwd="$PWD"
        cd - &>/dev/null
    else
        # file *must* be local
        local tmppwd="$PWD"
    fi
else
    # file *cannot* exist
    return 1 # failure
fi

# reassemble realpath
echo "$tmppwd"/"${1##*/}"
return 0 # success

}

It's Bash 4+, does not require any dependencies and also provides get_dirname, get_filename, get_stemname and validate_path.

SQL Server ORDER BY date and nulls last

I know this is old but this is what worked for me

Order by Isnull(Date,'12/31/9999')

Android Transparent TextView?

Hi Please try with the below color code as textview's background.

android:background="#20535252"

No module named setuptools

For python3 is:

sudo apt-get install -y python3-setuptools

Hive insert query like SQL

You can't do insert into to insert single record. It's not supported by Hive. You may place all new records that you want to insert in a file and load that file into a temp table in Hive. Then using insert overwrite..select command insert those rows into a new partition of your main Hive table. The constraint here is your main table will have to be pre partitioned. If you don't use partition then your whole table will be replaced with these new records.

Meaning of 'const' last in a function declaration of a class?

https://isocpp.org/wiki/faq/const-correctness#const-member-fns

What is a "const member function"?

A member function that inspects (rather than mutates) its object.

A const member function is indicated by a const suffix just after the member function’s parameter list. Member functions with a const suffix are called “const member functions” or “inspectors.” Member functions without a const suffix are called “non-const member functions” or “mutators.”

class Fred {
public:
  void inspect() const;   // This member promises NOT to change *this
  void mutate();          // This member function might change *this
};
void userCode(Fred& changeable, const Fred& unchangeable)
{
  changeable.inspect();   // Okay: doesn't change a changeable object
  changeable.mutate();    // Okay: changes a changeable object
  unchangeable.inspect(); // Okay: doesn't change an unchangeable object
  unchangeable.mutate();  // ERROR: attempt to change unchangeable object
}

The attempt to call unchangeable.mutate() is an error caught at compile time. There is no runtime space or speed penalty for const, and you don’t need to write test-cases to check it at runtime.

The trailing const on inspect() member function should be used to mean the method won’t change the object’s abstract (client-visible) state. That is slightly different from saying the method won’t change the “raw bits” of the object’s struct. C++ compilers aren’t allowed to take the “bitwise” interpretation unless they can solve the aliasing problem, which normally can’t be solved (i.e., a non-const alias could exist which could modify the state of the object). Another (important) insight from this aliasing issue: pointing at an object with a pointer-to-const doesn’t guarantee that the object won’t change; it merely promises that the object won’t change via that pointer.

How to implement Android Pull-to-Refresh

We should first know what is Pull to refresh layout in android . we can call pull to refresh in android as swipe-to-refresh. when you swipe screen from top to bottom it will do some action based on setOnRefreshListener.

Here's tutorial that demonstrate about how to implement android pull to refresh. I hope this helps.

How to get the EXIF data from a file using C#

Here is a link to another similar SO question, which has an answer pointing to this good article on "Reading, writing and photo metadata" in .Net.

How to define a relative path in java

Try something like this

String filePath = new File("").getAbsolutePath();
filePath.concat("path to the property file");

So your new file points to the path where it is created, usually your project home folder.

[EDIT]

As @cmc said,

    String basePath = new File("").getAbsolutePath();
    System.out.println(basePath);

    String path = new File("src/main/resources/conf.properties")
                                                           .getAbsolutePath();
    System.out.println(path);

Both give the same value.

How to run a PowerShell script

If you want to run a script without modifying the default script execution policy, you can use the bypass switch when launching Windows PowerShell.

powershell [-noexit] -executionpolicy bypass -File <Filename>

How can I change the size of a Bootstrap checkbox?

Following works in bootstrap 4 and displays well in CSS, mobile and has no issues with label spacing.

enter image description here

CSS

.checkbox-lg .custom-control-label::before, 
.checkbox-lg .custom-control-label::after {
  top: .8rem;
  width: 1.55rem;
  height: 1.55rem;
}

.checkbox-lg .custom-control-label {
  padding-top: 13px;
  padding-left: 6px;
}


.checkbox-xl .custom-control-label::before, 
.checkbox-xl .custom-control-label::after {
  top: 1.2rem;
  width: 1.85rem;
  height: 1.85rem;
}

.checkbox-xl .custom-control-label {
  padding-top: 23px;
  padding-left: 10px;
}

HTML

<div class="custom-control custom-checkbox checkbox-lg">
      <input type="checkbox" class="custom-control-input" id="checkbox-3">
      <label class="custom-control-label" for="checkbox-3">Large checkbox</label>
    </div>

You can also make it extra large by declaring checkbox-xl

If anyone from BS team is reading this, it would be really good if you make this available right out of the box, I don't see anything for it in BS 5 either

source

If file exists then delete the file

You're close, you just need to delete the file before trying to over-write it.

dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file: for each file in infolder.Files

    dim name: name = file.name
    dim parts: parts = split(name, ".")

    if UBound(parts) = 2 then

       ' file name like a.c.pdf    

        dim newname: newname = parts(0) & "." & parts(2)
        dim newpath: newpath = fso.BuildPath(OUT_PATH, newname)

        ' warning:
        ' if we have source files C:\IN_PATH\ABC.01.PDF, C:\IN_PATH\ABC.02.PDF, ...
        ' only one of them will be saved as D:\OUT_PATH\ABC.PDF

        if fso.FileExists(newpath) then
            fso.DeleteFile newpath
        end if

        file.Move newpath

    end if

next

How do I install Python OpenCV through Conda?

To install the OpenCV package with conda, run:

conda install -c menpo opencv3=3.1.0

https://anaconda.org/menpo/opencv3

Coarse-grained vs fine-grained

In term of dataset like a text file ,Coarse-grained meaning we can transform the whole dataset but not an individual element on the dataset While fine-grained means we can transform individual element on the dataset.

Is ncurses available for windows?

Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.

ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.

The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).

A better option

Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses (and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.

TortoiseGit-git did not exit cleanly (exit code 1)

Actually, this error message just says that there is some problem but no specifications of the problem. So, in my case, it was a pending pull request. I pulled the changes into my repo, and then pushed it again and it worked. Moreover, if there is an error on tortoisegit, I prefer to do the same on console. Console gives more detail error message

bootstrap multiselect get selected values

Shorter version:

$('#multiselect1').multiselect({
    ...
    onChange: function() {
        console.log($('#multiselect1').val());
    }
}); 

How do I create HTML table using jQuery dynamically?

An example with a little less stringified html:

var container = $('#my-container'),
  table = $('<table>');

users.forEach(function(user) {
  var tr = $('<tr>');
  ['ID', 'Name', 'Address'].forEach(function(attr) {
    tr.append('<td>' + user[attr] + '</td>');
  });
  table.append(tr);
});

container.append(table);

How can I replace a newline (\n) using sed?

Replace newlines with any string, and replace the last newline too

The pure tr solutions can only replace with a single character, and the pure sed solutions don't replace the last newline of the input. The following solution fixes these problems, and seems to be safe for binary data (even with a UTF-8 locale):

printf '1\n2\n3\n' |
  sed 's/%/%p/g;s/@/%a/g' | tr '\n' @ | sed 's/@/<br>/g;s/%a/@/g;s/%p/%/g'

Result:

1<br>2<br>3<br>

jQuery: get data attribute

Change IDs and data attributes as you wish!

  <select id="selectVehicle">
       <option value="1" data-year="2011">Mazda</option>
       <option value="2" data-year="2015">Honda</option>
       <option value="3" data-year="2008">Mercedes</option>
       <option value="4" data-year="2005">Toyota</option>
  </select>

$("#selectVehicle").change(function () {
     alert($(this).find(':selected').data("year"));
});

Here is the working example: https://jsfiddle.net/ed5axgvk/1/