Programs & Examples On #Accumulate

How to find the cumulative sum of numbers in a list?

In [42]: a = [4, 6, 12]

In [43]: [sum(a[:i+1]) for i in xrange(len(a))]
Out[43]: [4, 10, 22]

This is slighlty faster than the generator method above by @Ashwini for small lists

In [48]: %timeit list(accumu([4,6,12]))
  100000 loops, best of 3: 2.63 us per loop

In [49]: %timeit [sum(a[:i+1]) for i in xrange(len(a))]
  100000 loops, best of 3: 2.46 us per loop

For larger lists, the generator is the way to go for sure. . .

In [50]: a = range(1000)

In [51]: %timeit [sum(a[:i+1]) for i in xrange(len(a))]
  100 loops, best of 3: 6.04 ms per loop

In [52]: %timeit list(accumu(a))
  10000 loops, best of 3: 162 us per loop

Efficiently sorting a numpy array in descending order?

i suggest using this ...

np.arange(start_index, end_index, intervals)[::-1]

for example:

np.arange(10, 20, 0.5)
np.arange(10, 20, 0.5)[::-1]

Then your resault:

[ 19.5,  19. ,  18.5,  18. ,  17.5,  17. ,  16.5,  16. ,  15.5,
    15. ,  14.5,  14. ,  13.5,  13. ,  12.5,  12. ,  11.5,  11. ,
    10.5,  10. ]

Initializing multiple variables to the same value in Java

No, it's not possible in java.

You can do this way .. But try to avoid it.

String one, two, three;
one = two = three = "";

Javascript call() & apply() vs bind()?

TL;DR:

In simple words, bind creates the function, call and apply executes the function whereas apply expects the parameters in array

Full Explanation

Assume we have multiplication function

function multiplication(a,b){
console.log(a*b);
}

Lets create some standard functions using bind

var multiby2 = multiplication.bind(this,2);

Now multiby2(b) is equal to multiplication(2,b);

multiby2(3); //6
multiby2(4); //8

What if I pass both the parameters in bind

var getSixAlways = multiplication.bind(this,3,2);

Now getSixAlways() is equal to multiplication(3,2);

getSixAlways();//6

even passing parameter returns 6; getSixAlways(12); //6

var magicMultiplication = multiplication.bind(this);

This create a new multiplication function and assigns it to magicMultiplication.

Oh no, we are hiding the multiplication functionality into magicMultiplication.

calling magicMultiplication returns a blank function b()

on execution it works fine magicMultiplication(6,5); //30

How about call and apply?

magicMultiplication.call(this,3,2); //6

magicMultiplication.apply(this,[5,2]); //10

Domain Account keeping locking out with correct password every few minutes

We just had a similar issue, looks like the user reset his password on Friday and over the weekend and on Monday he kept getting locked out.

Turned out to be he forgot to update his password on his mobile phone.

Adding Only Untracked Files

Not exactly what you're looking for, but I've found this quite helpful:

git add -AN

Will add all files to the index, but without their content. Files that were untracked now behave as if they were tracked. Their content will be displayed in git diff, and you can add then interactively with git add -p.

What are invalid characters in XML

This is a C# code to remove the XML invalid characters from a string and return a new valid string.

public static string CleanInvalidXmlChars(string text) 
{ 
    // From xml spec valid chars: 
    // #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]     
    // any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. 
    string re = @"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]"; 
    return Regex.Replace(text, re, ""); 
}

postgres: upgrade a user to be a superuser?

Run this Command

alter user myuser with superuser;

If you want to see the permission to a user run following command

\du

Iterate through the fields of a struct in Go

After you've retrieved the reflect.Value of the field by using Field(i) you can get a interface value from it by calling Interface(). Said interface value then represents the value of the field.

There is no function to convert the value of the field to a concrete type as there are, as you may know, no generics in go. Thus, there is no function with the signature GetValue() T with T being the type of that field (which changes of course, depending on the field).

The closest you can achieve in go is GetValue() interface{} and this is exactly what reflect.Value.Interface() offers.

The following code illustrates how to get the values of each exported field in a struct using reflection (play):

import (
    "fmt"
    "reflect"
)

func main() {
    x := struct{Foo string; Bar int }{"foo", 2}

    v := reflect.ValueOf(x)

    values := make([]interface{}, v.NumField())

    for i := 0; i < v.NumField(); i++ {
        values[i] = v.Field(i).Interface()
    }

    fmt.Println(values)
}

Importing images from a directory (Python) to list or dictionary

from PIL import Image
import os, os.path

imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
    ext = os.path.splitext(f)[1]
    if ext.lower() not in valid_images:
        continue
    imgs.append(Image.open(os.path.join(path,f)))
   

what does numpy ndarray shape do?

yourarray.shape or np.shape() or np.ma.shape() returns the shape of your ndarray as a tuple; And you can get the (number of) dimensions of your array using yourarray.ndim or np.ndim(). (i.e. it gives the n of the ndarray since all arrays in NumPy are just n-dimensional arrays (shortly called as ndarrays))

For a 1D array, the shape would be (n,) where n is the number of elements in your array.

For a 2D array, the shape would be (n,m) where n is the number of rows and m is the number of columns in your array.

Please note that in 1D case, the shape would simply be (n, ) instead of what you said as either (1, n) or (n, 1) for row and column vectors respectively.

This is to follow the convention that:

For 1D array, return a shape tuple with only 1 element   (i.e. (n,))
For 2D array, return a shape tuple with only 2 elements (i.e. (n,m))
For 3D array, return a shape tuple with only 3 elements (i.e. (n,m,k))
For 4D array, return a shape tuple with only 4 elements (i.e. (n,m,k,j))

and so on.

Also, please see the example below to see how np.shape() or np.ma.shape() behaves with 1D arrays and scalars:

# sample array
In [10]: u = np.arange(10)

# get its shape
In [11]: np.shape(u)    # u.shape
Out[11]: (10,)

# get array dimension using `np.ndim`
In [12]: np.ndim(u)
Out[12]: 1

In [13]: np.shape(np.mean(u))
Out[13]: ()       # empty tuple (to indicate that a scalar is a 0D array).

# check using `numpy.ndim`
In [14]: np.ndim(np.mean(u))
Out[14]: 0

P.S.: So, the shape tuple is consistent with our understanding of dimensions of space, at least mathematically.

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

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.

Padding In bootstrap

I have not used Bootstrap but I worked on Zurb Foundation. On that I used to add space like this.

<div id="main" class="container" role="main">
    <div class="row">

        <div class="span5 offset1">
            <h2>Welcome</h2>
            <p>Hello and welcome to my website.</p>
        </div>
        <div class="span6">
            Image Here (TODO)
        </div>
    </div>

Visit this link: http://getbootstrap.com/2.3.2/scaffolding.html and read the section: Offsetting columns.

I think I know what you are doing wrong. If you are applying padding to the span6 like this:

<div class="span6" style="padding-left:5px;">
    <h2>Welcome</h2>
    <p>Hello and welcome to my website.</p>
</div>

It is wrong. What you have to do is add padding to the elements inside:

<div class="span6">
    <h2 style="padding-left:5px;">Welcome</h2>
    <p  style="padding-left:5px;">Hello and welcome to my website.</p>
</div>

How do I update a GitHub forked repository?

I update my forked repos with this one line:

git pull https://github.com/forkuser/forkedrepo.git branch

Use this if you dont want to add another remote endpoint to your project, as other solutions posted here.

How do I remove the space between inline/inline-block elements?

Why not something like this... a bit hacky, and depends on your code for the css units, but:

.my-span {
    position: relative;
    left: -1em;
    width: 1em;
}
<span>...</span><span class="my-span"></span>

How to identify object types in java

You want instanceof:

if (value instanceof Integer)

This will be true even for subclasses, which is usually what you want, and it is also null-safe. If you really need the exact same class, you could do

if (value.getClass() == Integer.class)

or

if (Integer.class.equals(value.getClass())

Translating touch events from Javascript to jQuery

$(window).on("touchstart", function(ev) {
    var e = ev.originalEvent;
    console.log(e.touches);
});

I know it been asked a long time ago, but I thought a concrete example might help.

Pass array to ajax request in $.ajax()

NOTE: Doesn't work on newer versions of jQuery.

Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:

info[0] = 'hi';
info[1] = 'hello';

var data_to_send = $.serialize(info);

$.ajax({
    type: "POST",
    url: "index.php",
    data: data_to_send,
    success: function(msg){
        $('.answer').html(msg);
    }
});

C# constructors overloading

You can factor out your common logic to a private method, for example called Initialize that gets called from both constructors.

Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.

Example:

public Point2D(double x, double y)
{
    // Contracts

    Initialize(x, y);
}

public Point2D(Point2D point)
{
    if (point == null)
        throw new ArgumentNullException("point");

    // Contracts

    Initialize(point.X, point.Y);
}

private void Initialize(double x, double y)
{
    X = x;
    Y = y;
}

How to convert enum value to int?

Maybe it's better to use a String representation than an integer, because the String is still valid if values are added to the enum. You can use the enum's name() method to convert the enum value to a String an the enum's valueOf() method to create an enum representation from the String again. The following example shows how to convert the enum value to String and back (ValueType is an enum):

ValueType expected = ValueType.FLOAT;
String value = expected.name();

System.out.println("Name value: " + value);

ValueType actual = ValueType.valueOf(value);

if(expected.equals(actual)) System.out.println("Values are equal");

Google Chrome redirecting localhost to https

I believe this is caused by HSTS - see http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security

If you have (developed) any other localhost sites which send a HSTS header...

eg. Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

...then depending on the value of max-age, future requests to localhost will be required to be served over HTTPS.

To get around this, I did the following.

  • In the Chrome address bar type "chrome://net-internals/#hsts"
  • At the very bottom of a page is QUERY domain textbox - verify that localhost is known to the browser. If it says "Not found" then this is not the answer you are looking for.
  • If it is, DELETE the localhost domain using the textbox above
  • Your site should now work using plain old HTTP

This is not a permanent solution, but will at least get it working between projects. If anyone knows how to permanently exclude localhost from the HSTS list please let me know :)

UPDATE - November 2017

Chrome has recently moved this setting to sit under Delete domain security policies

enter image description here

UPDATE - December 2017 If you are using .dev domain see other answers below as Chrome (and others) force HTTPS via preloaded HSTS.

Converting String to "Character" array in Java

String#toCharArray returns an array of char, what you have is an array of Character. In most cases it doesn't matter if you use char or Character as there is autoboxing. The problem in your case is that arrays are not autoboxed, I suggest you use an array of char (char[]).

Displaying a Table in Django from Database

$ pip install django-tables2

settings.py

INSTALLED_APPS , 'django_tables2'
TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'

models.py

class hotel(models.Model):
     name = models.CharField(max_length=20)

views.py

from django.shortcuts import render

def people(request):
    istekler = hotel.objects.all()
    return render(request, 'list.html', locals())

list.html

{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="{% static 
'ticket/static/css/screen.css' %}" />
    </head>
    <body>
        {% render_table istekler %}
    </body>
</html>

Using python map and other functional tools

The easiest way would be not to pass bars through the different functions, but to access it directly from maptest:

foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]

def maptest(foo):
    print foo, bars

map(maptest, foos)

With your original maptest function you could also use a lambda function in map:

map((lambda foo: maptest(foo, bars)), foos)

Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

Browser scrollbars don't work at all on iPhone/iPad. At work we are using custom JavaScript scrollbars like jScrollPane to provide a consistent cross-browser UI: http://jscrollpane.kelvinluck.com/

It works very well for me - you can make some really beautiful custom scrollbars that fit the design of your site.

PHP preg_match - only allow alphanumeric strings and - _ characters

if(!preg_match('/^[\w-]+$/', $string1)) {
   echo "String 1 not acceptable acceptable";
   // String2 acceptable
}

How can I access an internal class from an external assembly?

I would like to argue one point - that you cannot augment the original assembly - using Mono.Cecil you can inject [InternalsVisibleTo(...)] to the 3pty assembly. Note there might be legal implications - you're messing with 3pty assembly and technical implications - if the assembly has strong name you either need to strip it or re-sign it with different key.

 Install-Package Mono.Cecil

And the code like:

static readonly string[] s_toInject = {
  // alternatively "MyAssembly, PublicKey=0024000004800000... etc."
  "MyAssembly"
};

static void Main(string[] args) {
  const string THIRD_PARTY_ASSEMBLY_PATH = @"c:\folder\ThirdPartyAssembly.dll";

   var parameters = new ReaderParameters();
   var asm = ModuleDefinition.ReadModule(INPUT_PATH, parameters);
   foreach (var toInject in s_toInject) {
     var ca = new CustomAttribute(
       asm.Import(typeof(InternalsVisibleToAttribute).GetConstructor(new[] {
                      typeof(string)})));
     ca.ConstructorArguments.Add(new CustomAttributeArgument(asm.TypeSystem.String, toInject));
     asm.Assembly.CustomAttributes.Add(ca);
   }
   asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll");
   // note if the assembly is strongly-signed you need to resign it like
   // asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll", new WriterParameters {
   //   StrongNameKeyPair = new StrongNameKeyPair(File.ReadAllBytes(@"c:\MyKey.snk"))
   // });
}

How to set some xlim and ylim in Seaborn lmplot facetgrid

You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)

Then you can get hold of the axes objects (an array of axes):

axes = lm.axes

After that you can tweak the axes properties

axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)

creates:

enter image description here

Why should you use strncpy instead of strcpy?

strncpy is NOT safer than strcpy, it just trades one type of bugs with another. In C, when handling C strings, you need to know the size of your buffers, there is no way around it. strncpy was justified for the directory thing mentioned by others, but otherwise, you should never use it:

  • if you know the length of your string and buffer, why using strncpy ? It is a waste of computing power at best (adding useless 0)
  • if you don't know the lengths, then you risk silently truncating your strings, which is not much better than a buffer overflow

Call a stored procedure with another in Oracle

Your stored procedures work as coded. The problem is with the last line, it is unable to invoke either of your stored procedures.

Three choices in SQL*Plus are: call, exec, and an anoymous PL/SQL block.

call appears to be a SQL keyword, and is documented in the SQL Reference. http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_4008.htm#BABDEHHG The syntax diagram indicates that parentesis are required, even when no arguments are passed to the call routine.

CALL test_sp_1();

An anonymous PL/SQL block is PL/SQL that is not inside a named procedure, function, trigger, etc. It can be used to call your procedure.

BEGIN
    test_sp_1;
END;
/

Exec is a SQL*Plus command that is a shortcut for the above anonymous block. EXEC <procedure_name> will be passed to the DB server as BEGIN <procedure_name>; END;

Full example:

SQL> SET SERVEROUTPUT ON
SQL> CREATE OR REPLACE PROCEDURE test_sp 
  2  AS 
  3  BEGIN 
  4      DBMS_OUTPUT.PUT_LINE('Test works'); 
  5  END;
  6  /

Procedure created.

SQL> CREATE OR REPLACE PROCEDURE test_sp_1 
  2  AS
  3  BEGIN
  4      DBMS_OUTPUT.PUT_LINE('Testing'); 
  5      test_sp; 
  6  END;
  7  /

Procedure created.

SQL> CALL test_sp_1();
Testing
Test works

Call completed.

SQL> exec test_sp_1
Testing
Test works

PL/SQL procedure successfully completed.

SQL> begin
  2      test_sp_1;
  3  end;
  4  /
Testing
Test works

PL/SQL procedure successfully completed.

SQL> 

Add a list item through javascript

I was recently presented with this same challenge and stumbled on this thread but found a simpler solution using append...

var firstname = $('#firstname').val();

$('ol').append( '<li>' + firstname + '</li>' );

Store the firstname value and then use append to add that value as an li to the ol. I hope this helps :)

MySQL SELECT LIKE or REGEXP to match multiple words in one record

SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus % 2100%'

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

Some good solutions here but this one doesn't need SVG, preserves the border via outline and sets it flush on the button.

_x000D_
_x000D_
select {_x000D_
  height: 20px;_x000D_
  -webkit-border-radius: 0;_x000D_
  border: 0;_x000D_
  outline: 1px solid #ccc;_x000D_
  outline-offset: -1px;_x000D_
}
_x000D_
<select>_x000D_
 <option>Apple</option>_x000D_
 <option>Ball</option>_x000D_
 <option>Cat</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Text to speech(TTS)-Android

public class Texttovoice extends ActionBarActivity implements OnInitListener {
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_texttovoice);
    tts = new TextToSpeech(this, this);

    // Refer 'Speak' button
    btnSpeak = (Button) findViewById(R.id.btnSpeak);
    // Refer 'Text' control
    txtText = (EditText) findViewById(R.id.txtText);
    // Handle onClick event for button 'Speak'
    btnSpeak.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // Method yet to be defined
            speakOut();
        }

    });

}

private void speakOut() {
    // Get the text typed
    String text = txtText.getText().toString();
    // If no text is typed, tts will read out 'You haven't typed text'
    // else it reads out the text you typed
    if (text.length() == 0) {
        tts.speak("You haven't typed text", TextToSpeech.QUEUE_FLUSH, null);
    } else {
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

    }

}

public void onDestroy() {
    // Don't forget to shutdown!
    if (tts != null) {
        tts.stop();
        tts.shutdown();
    }
    super.onDestroy();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.texttovoice, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void onInit(int status) {
    // TODO Auto-generated method stub
    // TTS is successfully initialized
    if (status == TextToSpeech.SUCCESS) {
        // Setting speech language
        int result = tts.setLanguage(Locale.US);
        // If your device doesn't support language you set above
        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            // Cook simple toast message with message
            Toast.makeText(getApplicationContext(), "Language not supported",
                    Toast.LENGTH_LONG).show();
            Log.e("TTS", "Language is not supported");
        }
        // Enable the button - It was disabled in main.xml (Go back and
        // Check it)
        else {
            btnSpeak.setEnabled(true);
        }
        // TTS is not initialized properly
    } else {
        Toast.makeText(this, "TTS Initilization Failed", Toast.LENGTH_LONG)
                .show();
        Log.e("TTS", "Initilization Failed");
    }
}
   //-------------------------------XML---------------

  <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:orientation="vertical"
tools:ignore="HardcodedText" >

    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="15dip"
    android:text="listen your text"
    android:textColor="#0587d9"
    android:textSize="26dip"
    android:textStyle="bold" />

<EditText
    android:id="@+id/txtText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dip"
    android:layout_marginTop="20dip"
    android:hint="Enter text to speak" />

<Button
    android:id="@+id/btnSpeak"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dip"
    android:enabled="false"
    android:text="Speak" 
    android:onClick="speakout"/>

GenyMotion Unable to start the Genymotion virtual device

This problem occured for me one time when I had already opened the built-in Android Emulator (AVD). Check if you turned off it before start changing anything in settings.

What is the difference between Sublime text and Github's Atom

I'm working in little extreme environment; edit files on remote filesystem (external network, surely) that is mounted on my Laptop thru ssh(aka. sshfs). Regardless why I'm doing like this, also though its cumbersome responsiveness, it's fairly edible when I'm using Sublime Text 2.

I tried on Atom after reading this post, but it turned out to be somewhat painful to me; Atom seems that it doesn't cache directory structure so efficiently. Every time I expand a folder on Tree View, the UI froze for a short time, 2~3 seconds, maybe fetching file system info. Yes, it's because I'm using remote filesystem. But Sublime handles this more efficient, at least it doesn't freeze every time I expand a folder, so less painful.

I think Atom is hell nice for free, and my story is trivial that might be enhanced someday, but it would be helpful to someone at this time.

--

added on 8/26/2014

Recently, I changed my laptop from Macbook Air 2010 late to Macbook Pro 13" 2013 late. It has likely 4 times faster CPU and much enhancements in performance. I want to mention my opinion is about in the case WHEN YOU MOUNT REMOTE FILE SYSTEM. (using OS X Mavericks, most recent version of Atom, FUSE 2.7.3 / OSXFUSE 2.6.4 / sshfs 2.5.0, and remote system is Ubuntu server) Eventually, UI freeze gets pretty shorter, but it is still there. Specifically, to open a folder with many folder/files in it and index it is requires certain amount of time. Also, if you expand a folder full of files, it just falters. (when collapsing the folder, it doesn't)

According to @EliDuenisch , it seems not happen on Linux Mint. I'm not sure but it might be from difference between OSes. Surely, if you work on local file system, you don't have to care about this issue at all.

Complex JSON nesting of objects and arrays

The first code is an example of Javascript code, which is similar, however not JSON. JSON would not have 1) comments and 2) the var keyword

You don't have any comments in your JSON, but you should remove the var and start like this:

orders: {

The [{}] notation means "object in an array" and is not what you need everywhere. It is not an error, but it's too complicated for some purposes. AssociatedDrug should work well as an object:

"associatedDrug": {
                "name":"asprin",
                "dose":"",
                "strength":"500 mg"
          }

Also, the empty object labs should be filled with something.

Other than that, your code is okay. You can either paste it into javascript, or use the JSON.parse() method, or any other parsing method (please don't use eval)

Update 2 answered:

obj.problems[0].Diabetes[0].medications[0].medicationsClasses[0].className[0].associatedDrug[0].name

returns 'aspirin'. It is however better suited for foreaches everywhere

How can I loop over entries in JSON?

To decode json, you have to pass the json string. Currently you're trying to pass an object:

>>> response = urlopen(url)
>>> response
<addinfourl at 2146100812 whose fp = <socket._fileobject object at 0x7fe8cc2c>>

You can fetch the data with response.read().

Defining a `required` field in Bootstrap

Use 'needs-validation' apart from form-group, it will work.

Search all of Git history for a string?

Try the following commands to search the string inside all previous tracked files:

git log --patch  | less +/searching_string

or

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

which needs to be run from the parent directory where you'd like to do the searching.

ProgressDialog is deprecated.What is the alternate one to use?

I use DelayedProgressDialog from https://github.com/Q115/DelayedProgressDialog It does the same as ProgressDialog with the added benefit of a delay if necessary.

Using it is similar to ProgressDialog before Android O:

DelayedProgressDialog progressDialog = new DelayedProgressDialog();
progressDialog.show(getSupportFragmentManager(), "tag");

Use of contains in Java ArrayList<String>

Your question is not very clear.

  • What's your code exactly doing? Give more code.
  • What's the error you're getting?

You say you get a null-pointer. You cannot get a null pointer as a value returned by contains().

However you can get a NullPointerException if your list has not been initialized. By reading your question now, I'd say that what you show here is correct, but maybe you just didn't instantiate the list.

For this to work (to add a feed URL if it isn't already in the list):

if (!this.rssFeedURLs.contains(rssFeedURL)) {
    this.rssFeedURLs.add(rssFeedUrl);
}

then this declaration would do:

private ArrayList<String> rssFeedURLs = new ArrayList<String>();

or initialize your list later on, but before trying to access its methods:

rssFeedUrls = new ArrayList<String>();

Finally... Do you really need a List? Maybe a Set would be better if you don't want duplicates. Use a LinkedHashSet if preserving the ordering matters.

Insert null/empty value in sql datetime column by default

you can use like this:

string Log_In_Val = (Convert.ToString(attenObj.Log_In) == "" ? "Null" + "," : "'" + Convert.ToString(attenObj.Log_In) + "',");

html div onclick event

You need to read up on event bubbling and for sure remove inline event handling if you have jQuery anyway

Test the click on the div and examine the target

Live Demo

$(".expandable-panel-heading").on("click",function (e) {
    if (e.target.id =="ancherComplaint") { // or test the tag
        e.preventDefault(); // or e.stopPropagation()
        markActiveLink(e.target);
    }    
    else alert('123');
});
function markActiveLink(el) {   
    alert(el.id);
} 

Protect image download

As other answers said, if you can see it you can copy/download it.

To add up to the other answers, just for your information, you can add invisible or tricky watermarks to your images: http://www.cgrats.com/create-an-invisible-watermark-in-photoshop.html (just an example, there are more techniques, just google for invisible watermarks)

Anyway if you want to prove the ownership of your image a good way is to have a bigger resolution copy for yourself, and always publish a lower resolution / size one. Or publish it also on a "public" media like ... deviantart or flickr or something where people can't change the upload date. This way you can prove you had that image before anybody else

How to preview selected image in input type="file" in popup using jQuery?

You can use URL.createObjectURL

_x000D_
_x000D_
    function img_pathUrl(input){
        $('#img_url')[0].src = (window.URL ? URL : webkitURL).createObjectURL(input.files[0]);
    }
_x000D_
#img_url {
  background: #ddd;
  width:100px;
  height: 90px;
  display: block;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="" id="img_url" alt="your image">
<br>
<input type="file" id="img_file" onChange="img_pathUrl(this);">
_x000D_
_x000D_
_x000D_

How do I check if a string contains another string in Swift?

Extension way

Swift 4

extension String {
    func contains(find: String) -> Bool{
        return self.range(of: find) != nil
    }
    func containsIgnoringCase(find: String) -> Bool{
        return self.range(of: find, options: .caseInsensitive) != nil
    }
}

var value = "Hello world"

print(value.contains("Hello")) // true
print(value.contains("bo"))    // false

print(value.containsIgnoringCase(find: "hello"))    // true
print(value.containsIgnoringCase(find: "Hello"))    // true
print(value.containsIgnoringCase(find: "bo"))       // false

Generally Swift 4 has contains method however it available from iOS 8.0+


Swift 3.1

You can write extension contains: and containsIgnoringCase for String

extension String { 

   func contains(_ find: String) -> Bool{
     return self.range(of: find) != nil
   }

   func containsIgnoringCase(_ find: String) -> Bool{
     return self.range(of: find, options: .caseInsensitive) != nil 
   }
 }

Older Swift version

extension String {

    func contains(find: String) -> Bool{
       return self.rangeOfString(find) != nil
     }

    func containsIgnoringCase(find: String) -> Bool{
       return self.rangeOfString(find, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil
     }
}

Example:

var value = "Hello world"

print(value.contains("Hello")) // true
print(value.contains("bo"))    // false

print(value.containsIgnoringCase("hello"))    // true
print(value.containsIgnoringCase("Hello"))    // true
print(value.containsIgnoringCase("bo"))       // false

ExecuteNonQuery: Connection property has not been initialized.

Actually this error occurs when server makes connection but can't build due to failure in identifying connection function identifier. This problem can be solved by typing connection function in code. For this I take a simple example. In this case function is con your may be different.

SqlCommand cmd = new SqlCommand("insert into ptb(pword,rpword) values(@a,@b)",con);

A simple algorithm for polygon intersection

I have no very simple solution, but here are the main steps for the real algorithm:

  1. Do a custom double linked list for the polygon vertices and edges. Using std::list won't do because you must swap next and previous pointers/offsets yourself for a special operation on the nodes. This is the only way to have simple code, and this will give good performance.
  2. Find the intersection points by comparing each pair of edges. Note that comparing each pair of edge will give O(N²) time, but improving the algorithm to O(N·logN) will be easy afterwards. For some pair of edges (say a?b and c?d), the intersection point is found by using the parameter (from 0 to 1) on edge a?b, which is given by t?=d0/(d0-d1), where d0 is (c-a)×(b-a) and d1 is (d-a)×(b-a). × is the 2D cross product such as p×q=p?·q?-p?·q?. After having found t?, finding the intersection point is using it as a linear interpolation parameter on segment a?b: P=a+t?(b-a)
  3. Split each edge adding vertices (and nodes in your linked list) where the segments intersect.
  4. Then you must cross the nodes at the intersection points. This is the operation for which you needed to do a custom double linked list. You must swap some pair of next pointers (and update the previous pointers accordingly).

Then you have the raw result of the polygon intersection resolving algorithm. Normally, you will want to select some region according to the winding number of each region. Search for polygon winding number for an explanation on this.

If you want to make a O(N·logN) algorithm out of this O(N²) one, you must do exactly the same thing except that you do it inside of a line sweep algorithm. Look for Bentley Ottman algorithm. The inner algorithm will be the same, with the only difference that you will have a reduced number of edges to compare, inside of the loop.

Generating Fibonacci Sequence

My 2 cents:

_x000D_
_x000D_
function fibonacci(num) {_x000D_
  return Array.apply(null, Array(num)).reduce(function(acc, curr, idx) {_x000D_
    return idx > 2 ? acc.concat(acc[idx-1] + acc[idx-2]) : acc;_x000D_
  }, [0, 1, 1]);_x000D_
}_x000D_
_x000D_
console.log(fibonacci(10));
_x000D_
_x000D_
_x000D_

Get month name from number

import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B")

Returns: December

Some more info on the Python doc website


[EDIT : great comment from @GiriB] You can also use %b which returns the short notation for month name.

mydate.strftime("%b")

For the example above, it would return Dec.

How to parse Excel (XLS) file in Javascript/HTML5

Upload an excel file here and you can get the data in JSON format in console:

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>_x000D_
<script>_x000D_
    var ExcelToJSON = function() {_x000D_
_x000D_
      this.parseExcel = function(file) {_x000D_
        var reader = new FileReader();_x000D_
_x000D_
        reader.onload = function(e) {_x000D_
          var data = e.target.result;_x000D_
          var workbook = XLSX.read(data, {_x000D_
            type: 'binary'_x000D_
          });_x000D_
          workbook.SheetNames.forEach(function(sheetName) {_x000D_
            // Here is your object_x000D_
            var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);_x000D_
            var json_object = JSON.stringify(XL_row_object);_x000D_
            console.log(JSON.parse(json_object));_x000D_
            jQuery( '#xlx_json' ).val( json_object );_x000D_
          })_x000D_
        };_x000D_
_x000D_
        reader.onerror = function(ex) {_x000D_
          console.log(ex);_x000D_
        };_x000D_
_x000D_
        reader.readAsBinaryString(file);_x000D_
      };_x000D_
  };_x000D_
_x000D_
  function handleFileSelect(evt) {_x000D_
    _x000D_
    var files = evt.target.files; // FileList object_x000D_
    var xl2json = new ExcelToJSON();_x000D_
    xl2json.parseExcel(files[0]);_x000D_
  }_x000D_
_x000D_
_x000D_
 _x000D_
</script>_x000D_
_x000D_
<form enctype="multipart/form-data">_x000D_
    <input id="upload" type=file  name="files[]">_x000D_
</form>_x000D_
_x000D_
    <textarea class="form-control" rows=35 cols=120 id="xlx_json"></textarea>_x000D_
_x000D_
    <script>_x000D_
        document.getElementById('upload').addEventListener('change', handleFileSelect, false);_x000D_
_x000D_
    </script>
_x000D_
_x000D_
_x000D_

This is a combination of the following Stackoverflow posts:

  1. https://stackoverflow.com/a/37083658/4742733
  2. https://stackoverflow.com/a/39515846/4742733

Good Luck...

Conda: Installing / upgrading directly from github

I found a reference to this in condas issues. The following should now work.

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - git+https://github.com/pythonforfacebook/facebook-sdk.git

Git clone particular version of remote repository

You could "reset" your repository to any commit you want (e.g. 1 month ago).

Use git-reset for that:

git clone [remote_address_here] my_repo
cd my_repo
git reset --hard [ENTER HERE THE COMMIT HASH YOU WANT]

What is the most efficient way to deep clone an object in JavaScript?

AngularJS

Well if you're using angular you could do this too

var newObject = angular.copy(oldObject);

Remove or adapt border of frame of legend using matplotlib

When plotting a plot using matplotlib:

How to remove the box of the legend?

plt.legend(frameon=False)

How to change the color of the border of the legend box?

leg = plt.legend()
leg.get_frame().set_edgecolor('b')

How to remove only the border of the box of the legend?

leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

How to plot a subset of a data frame in R?

with(dfr[dfr$var3 < 155,], plot(var1, var2)) should do the trick.

Edit regarding multiple conditions:

with(dfr[(dfr$var3 < 155) & (dfr$var4 > 27),], plot(var1, var2))

Apache won't run in xampp

just disable "world wide web publishing service" , it solve my problem.

Getting vertical gridlines to appear in line plot in matplotlib

Short answer (read below for more info):

ax.grid(axis='both', which='both')

enter image description here

What you do is correct and it should work.

However, since the X axis in your example is a DateTime axis the Major tick-marks (most probably) are appearing only at the both ends of the X axis. The other visible tick-marks are Minor tick-marks.

The ax.grid() method, by default, draws grid lines on Major tick-marks. Therefore, nothing appears in your plot.

Use the code below to highlight the tick-marks. Majors will be Blue while Minors are Red.

ax.tick_params(which='both', width=3)
ax.tick_params(which='major', length=20, color='b')
ax.tick_params(which='minor', length=10, color='r')

Now to force the grid lines to be appear also on the Minor tick-marks, pass the which='minor' to the method:

ax.grid(b=True, which='minor', axis='x', color='#000000', linestyle='--')

or simply use which='both' to draw both Major and Minor grid lines. And this a more elegant grid line:

ax.grid(b=True, which='minor', axis='both', color='#888888', linestyle='--')
ax.grid(b=True, which='major', axis='both', color='#000000', linestyle='-')

Using jQuery to see if a div has a child with a certain class

You can use the find function:

if($('#popup').find('p.filled-text').length !== 0)
   // Do Stuff

What is the maximum number of edges in a directed graph with n nodes?

In addition to the intuitive explanation Chris Smith has provided, we can consider why this is the case from a different perspective: considering undirected graphs.

To see why in a DIRECTED graph the answer is n*(n-1), consider an undirected graph (which simply means that if there is a link between two nodes (A and B) then you can go in both ways: from A to B and from B to A). The maximum number of edges in an undirected graph is n(n-1)/2 and obviously in a directed graph there are twice as many.

Good, you might ask, but why are there a maximum of n(n-1)/2 edges in an undirected graph? For that, Consider n points (nodes) and ask how many edges can one make from the first point. Obviously, n-1 edges. Now how many edges can one draw from the second point, given that you connected the first point? Since the first and the second point are already connected, there are n-2 edges that can be done. And so on. So the sum of all edges is:

Sum = (n-1)+(n-2)+(n-3)+...+3+2+1 

Since there are (n-1) terms in the Sum, and the average of Sum in such a series is ((n-1)+1)/2 {(last + first)/2}, Sum = n(n-1)/2

Setting default values to null fields when mapping with Jackson

You can create your own JsonDeserializer and annotate that property with @JsonDeserialize(as = DefaultZero.class)

For example: To configure BigDecimal to default to ZERO:

public static class DefaultZero extends JsonDeserializer<BigDecimal> {
    private final JsonDeserializer<BigDecimal> delegate;

    public DefaultZero(JsonDeserializer<BigDecimal> delegate) {
        this.delegate = delegate;
    }

    @Override
    public BigDecimal deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        return jsonParser.getDecimalValue();
    }

    @Override
    public BigDecimal getNullValue(DeserializationContext ctxt) throws JsonMappingException {
        return BigDecimal.ZERO;
    }
}

And usage:

class Sth {

   @JsonDeserialize(as = DefaultZero.class)
   BigDecimal property;
 }

Difference between Convert.ToString() and .ToString()

Convert.Tostring() function handles the NULL whereas the .ToString() method does not. visit here.

JavaScript to scroll long page to DIV

Correct me if I'm wrong but I'm reading the question again and again and still think that Angus McCoteup was asking how to set an element to be position: fixed.

Angus McCoteup, check out http://www.cssplay.co.uk/layouts/fixed.html - if you want your DIV to behave like a menu there, have a look at a CSS there

Changing color of Twitter bootstrap Nav-Pills

Step 1: Define a class named applycolor which can be used to apply the color you choose.

Step 2: Define what actions happens to it when it hovers. If your form background is white, then you must make sure that on hover the tab does not turn white. To achieve this use the !important clause to force this feature on hover property. We are doing this to override Bootstrap's default behavior.

Step 3: Apply the class to the Tabs which you are targetting.

CSS section:

<style>
    .nav-pills > li.active > a, .nav-pills > li.active > a:hover, .nav-pills > li.active > a:focus {
        color: #fff;
        background-color: #337ab7 !important;
    }

    .nav > li > a:hover, .nav > li > a:focus {
        text-decoration: none;
        background-color: none !important;
    }

    .applycolor {
        background-color: #efefef;
        text-decoration: none;
        color: #fff;
    }

    .applycolor:hover {
        background-color: #337ab7;
        text-decoration: none;
        color: #fff;
    }
</style>

Tab Section :

<section class="form-toolbar row">
    <div class="form-title col-sm-12" id="tabs">
        <ul class="nav nav-pills nav-justified">
            <li class="applycolor"><a data-toggle="pill" href="#instance" style="font-size: 1.8rem; font-weight: 800;">My Apps</a></li>
            <li class="active applycolor"><a data-toggle="pill" href="#application" style="font-size: 1.8rem; font-weight: 800;">Apps Collection</a></li>
        </ul>
    </div>
</section>

C# loop - break vs. continue

Please let me state the obvious: note that adding neither break nor continue, will resume your program; i.e. I trapped for a certain error, then after logging it, I wanted to resume processing, and there were more code tasks in between the next row, so I just let it fall through.

How to clear form after submit in Angular 2?

To angular version 4, you can use this:

this.heroForm.reset();

But, you could need a initial value like:

ngOnChanges() {
 this.heroForm.reset({
  name: this.hero.name, //Or '' to empty initial value. 
  address: this.hero.addresses[0] || new Address()
 });
}

It is important to resolve null problem in your object reference.

reference link, Search for "reset the form flags".

How do I start Mongo DB from Windows?

Clearly many people have answered upon your query of how to make mongoDb work, I'd answer the second part: Regarding an appropriate GUI for mongoDB

My suggestion is, go for MongoChef (now Studio 3T)

You can easily install and use it.

You might want want to refer to (from 03:10- to 08:50): https://www.youtube.com/watch?v=0ws3oIyqieY&index=2&list=PLS1QulWo1RIZtR6bncmSaH8fB81oRl6MP

For a step by step guide to the GUI tool.

Class is inaccessible due to its protection level

your class should be public

public class FBlock : IDesignRegionInserts, IFormRegionInserts, IAPIRegionInserts, IConfigurationInserts, ISoapProxyClientInserts, ISoapProxyServiceInserts

The system cannot find the file specified in java

When you run a jar, your Main class itself becomes args[0] and your filename comes immediately after.

I had the same issue: I could locate my file when provided the absolute path from eclipse (because I was referring to the file as args[0]). Yet when I run the same from jar, it was trying to locate my main class - which is when I got the idea that I should be reading my file from args[1].

Copy multiple files from one directory to another from Linux shell

You can use brace expansion in bash:

cp /home/ankur/folder/{file1,abc,xyz} /path/to/target

Correct way to push into state array

Here you can not push the object to a state array like this. You can push like your way in normal array. Here you have to set the state,

this.setState({ 
     myArray: [...this.state.myArray, 'new value'] 
})

Oracle SqlDeveloper JDK path

I cannot believe Oracle's documentation is SO LAME! In some documents it is misleading people to point to the JDK by specifying the path to the JDK root, e.g. on a Mac:

/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/

Reviewing /Applications/SQLDeveloper.app/Contents/MacOS/sqldeveloper.sh revealed the method they use to set up the path:

TMP_PATH=/usr/libexec/java_home -F -v 9 if [ -z "$TMP_PATH" ] ; then TMP_PATH=/usr/libexec/java_home -F -v 1.8 if [ -z "$TMP_PATH" ] ; then osascript -e 'tell app "System Events" to display dialog "SQL Developer requires a minimum of Java 8. \nJava 8 can be downloaded from:\n http://www.oracle.com/technetwork/java/javase/downloads/"' exit 1 fi fi

Executing this manually from Terminal:

/usr/libexec/java_home -F -v 1.8

Lists the path as:

/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home

And this is what you need to specify as the value for

SetJavaHome /Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home

Thank you Oracle for wasting half a day on your "product" that does NOT even support your latest Java version, also released by you.

How to state in requirements.txt a direct github source

Since pip v1.5, (released Jan 1 2014: CHANGELOG, PR) you may also specify a subdirectory of a git repo to contain your module. The syntax looks like this:

pip install -e git+https://git.repo/some_repo.git#egg=my_subdir_pkg&subdirectory=my_subdir_pkg # install a python package from a repo subdirectory

Note: As a pip module author, ideally you'd probably want to publish your module in it's own top-level repo if you can. Yet this feature is helpful for some pre-existing repos that contain python modules in subdirectories. You might be forced to install them this way if they are not published to pypi too.

How do I compare a value to a backslash?

When you only need to check for equality, you can also simply use the in operator to do a membership test in a sequence of accepted elements:

if message.value[0] in ('/', '\\'):
    do_stuff()

jquery change class name

So you want to change it WHEN it's clicked...let me go through the whole process. Let's assume that your "External DOM Object" is an input, like a select:

Let's start with this HTML:

<body>
  <div>
    <select id="test">
      <option>Bob</option>
      <option>Sam</option>
      <option>Sue</option>
      <option>Jen</option>
    </select>
  </div>

  <table id="theTable">
    <tr><td id="cellToChange">Bob</td><td>Sam</td></tr>
    <tr><td>Sue</td><td>Jen</td></tr>
  </table>
</body>

Some very basic CSS:

?#theTable td {
    border:1px solid #555;
}
.activeCell {
    background-color:#F00;
}

And set up a jQuery event:

function highlightCell(useVal){
  $("#theTable td").removeClass("activeCell")
      .filter(":contains('"+useVal+"')").addClass("activeCell");
}

$(document).ready(function(){
    $("#test").change(function(e){highlightCell($(this).val())});
});

Now, whenever you pick something from the select, it will automatically find a cell with the matching text, allowing you to subvert the whole id-based process. Of course, if you wanted to do it that way, you could easily modify the script to use IDs rather than values by saying

.filter("#"+useVal)

and make sure to add the ids appropriately. Hope this helps!

submit a form in a new tab

I have a [submit] and a [preview] button, I want the preview to show the print view of the submitted form data, without persisting it to database. Therefore I want [preview] to open in a new tab, and submit to submit the data in the same window/tab.

<button type="submit" id="liquidacion_save"          name="liquidacion[save]"          onclick="$('form').attr('target', '');"      >Save</button></div>    <div>
<button type="submit" id="liquidacion_Previsualizar" name="liquidacion[Previsualizar]" onclick="$('form').attr('target', '_blank');">Preview</button></div>  

figure of imshow() is too small

I'm new to python too. Here is something that looks like will do what you want to

axes([0.08, 0.08, 0.94-0.08, 0.94-0.08]) #[left, bottom, width, height]
axis('scaled')`

I believe this decides the size of the canvas.

How to select the row with the maximum value in each group

Another data.table solution:

library(data.table)
setDT(group)[, head(.SD[order(-pt)], 1), by = .(Subject)]

boundingRectWithSize for NSAttributedString returning wrong size

@warrenm Sorry to say that framesetter method didn't work for me.

I got this.This function can help us to determine the frame size needed for a string range of an NSAttributedString in iphone/Ipad SDK for a given Width :

It can be used for a dynamic height of UITableView Cells

- (CGSize)frameSizeForAttributedString:(NSAttributedString *)attributedString
{
    CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);
    CGFloat width = YOUR_FIXED_WIDTH;

    CFIndex offset = 0, length;
    CGFloat y = 0;
    do {
        length = CTTypesetterSuggestLineBreak(typesetter, offset, width);
        CTLineRef line = CTTypesetterCreateLine(typesetter, CFRangeMake(offset, length));

        CGFloat ascent, descent, leading;
        CTLineGetTypographicBounds(line, &ascent, &descent, &leading);

        CFRelease(line);

        offset += length;
        y += ascent + descent + leading;
    } while (offset < [attributedString length]);

    CFRelease(typesetter);

    return CGSizeMake(width, ceil(y));
}

Thanks to HADDAD ISSA >>> http://haddadissa.blogspot.in/2010/09/compute-needed-heigh-for-fixed-width-of.html

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

I believe I have encountered the same quandary. I started encountering the problem when I changed to:

</system.web>
<httpRuntime targetFramework="4.5"/>

Which gives the error message you describe above.

adding:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />

Solves the issue, but then it makes your validation controls/scripts throw Javascript runtime errors. If you change to:

</system.web>
<httpRuntime targetFramework="4.0"/>

You should be OK, but you’ll have to make sure the rest of your code does/ behaves as desired. You might also have to forgo some new features only available in 4.5 onward.

P.S. It is highly recommended that you read the following before implementing this solution. Especially, if you use Async functionality:

https://blogs.msdn.microsoft.com/webdev/2012/11/19/all-about-httpruntime-targetframework/

UPDATE April 2017: After some some experimentation and testing I have come up with a combination that works:

<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
<httpRuntime targetFramework="4.5.1" />

with:

jQuery version 1.11.3

Delete ActionLink with confirm dialog

those are routes you're passing in

<%= Html.ActionLink("Delete", "Delete",
    new { id = item.storyId }, 
    new { onclick = "return confirm('Are you sure you wish to delete this article?');" })     %>

The overloaded method you're looking for is this one:

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    Object routeValues,
    Object htmlAttributes
)

http://msdn.microsoft.com/en-us/library/dd492124.aspx

Concat scripts in order with Gulp

Another thing that helps if you need some files to come after a blob of files, is to exclude specific files from your glob, like so:

[
  '/src/**/!(foobar)*.js', // all files that end in .js EXCEPT foobar*.js
  '/src/js/foobar.js',
]

You can combine this with specifying files that need to come first as explained in Chad Johnson's answer.

Escaping regex string

Use the re.escape() function for this:

4.2.3 re Module Contents

escape(string)

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.

def simplistic_plural(word, text):
    word_or_plural = re.escape(word) + 's?'
    return re.match(word_or_plural, text)

Close dialog on click (anywhere)

Facing the same problem, I have created a small plugin that enables to close a dialog when clicking outside of it whether it a modal or non-modal dialog. It supports one or multiple dialogs on the same page.

More information on my website here: http://www.coheractio.com/blog/closing-jquery-ui-dialog-widget-when-clicking-outside

Laurent

Adding Table rows Dynamically in Android

public Boolean addArtist(String artistName){

        SQLiteDatabase db= getWritableDatabase();

        ContentValues data=new ContentValues();
        data.put(ArtistMaster.ArtistDetails.COLUMN_ARTIST_NAME,artistName);
        long id = db.insert(ArtistMaster.ArtistDetails.TABLE_NAME,null,data);

        if(id>0){
            return true;
        }else{
            return false;
        }
    }

Difference between Console.Read() and Console.ReadLine()?

Console.Read() basically reads a character so if you are on a console and you press a key then the console will close, meanwhile Console.Readline() will read the whole string.

Convert Xml to DataTable

You can use this code(Recommended)

 MemoryStream objMS = new MemoryStream();
 DataTable oDT = new DataTable();//Your DataTable which you want to convert
 oDT.WriteXml(objMS);
 objMS.Position = 0;
 XPathDocument result = new XPathDocument(objMS);

This is another way but first ex. is recommended

StringWriter objSW = new StringWriter();
DataTable oDt = new DataTable();//Your DataTable which you want to convert
oDt.WriteXml(objSW);
string result = objSW.ToString();

How to change content on hover

This little and simple trick I just learnt may help someone trying to avoid :before or :after pseudo elements altogether (for whatever reason) in changing text on hover. You can add both texts in the HTML, but vary the CSS 'display' property based on hover. Assuming the second text 'Add' has a class named 'add-label'; here is a little modification:

span.add-label{
 display:none;
}
.item:hover span.align{
 display:none;
}
.item:hover span.add-label{
 display:block;
}

Here is a demonstration on codepen: https://codepen.io/ifekt/pen/zBaEVJ

PHP: Calling another class' method

If they are separate classes you can do something like the following:

class A
{
    private $name;

    public function __construct()
    {
        $this->name = 'Some Name';
    }

    public function getName()
    {
        return $this->name;
    }
}

class B
{
    private $a;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    function getNameOfA()
    {
        return $this->a->getName();
    }
}

$a = new A();
$b = new B($a);

$b->getNameOfA();

What I have done in this example is first create a new instance of the A class. And after that I have created a new instance of the B class to which I pass the instance of A into the constructor. Now B can access all the public members of the A class using $this->a.

Also note that I don't instantiate the A class inside the B class because that would mean I tighly couple the two classes. This makes it hard to:

  1. unit test your B class
  2. swap out the A class for another class

Converting a string to a date in a cell

Have you tried the =DateValue() function?

To include time value, just add the functions together:

=DateValue(A1)+TimeValue(A1)

Add number of days to a date

$today=date('d-m-Y');
$next_date= date('d-m-Y', strtotime($today. ' + 90 days'));
echo $next_date;

I want to truncate a text or line with ellipsis using JavaScript

This will limit it to however many lines you want it limited to and is responsive

An idea that nobody has suggested, doing it based on the height of the element and then stripping it back from there.

Fiddle - https://jsfiddle.net/hutber/u5mtLznf/ <- ES6 version

But basically you want to grab the line height of the element, loop through all the text and stop when its at a certain lines height:

'use strict';

var linesElement = 3; //it will truncate at 3 lines.
var truncateElement = document.getElementById('truncateme');
var truncateText = truncateElement.textContent;

var getLineHeight = function getLineHeight(element) {
  var lineHeight = window.getComputedStyle(truncateElement)['line-height'];
  if (lineHeight === 'normal') {
    // sucky chrome
    return 1.16 * parseFloat(window.getComputedStyle(truncateElement)['font-size']);
  } else {
    return parseFloat(lineHeight);
  }
};

linesElement.addEventListener('change', function () {
  truncateElement.innerHTML = truncateText;
  var truncateTextParts = truncateText.split(' ');
  var lineHeight = getLineHeight(truncateElement);
  var lines = parseInt(linesElement.value);

  while (lines * lineHeight < truncateElement.clientHeight) {
    console.log(truncateTextParts.length, lines * lineHeight, truncateElement.clientHeight);
    truncateTextParts.pop();
    truncateElement.innerHTML = truncateTextParts.join(' ') + '...';
  }
});

CSS

#truncateme {
   width: auto; This will be completely dynamic to the height of the element, its just restricted by how many lines you want it to clip to
}

Inheritance and init method in Python

Since you don't call Num.__init__ , the field "n1" never gets created. Call it and then it will be there.

Using C# regular expressions to remove HTML tags

Regex regex = new Regex(@"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline);

Source

jQuery UI DatePicker to show year only

**NOTE : **If anyone have objection that "why i have answered this Question now !" Because i tried all the answers of this post and got no any solution.So i tried my way and got Solution So i am Sharing to next comers****

HTML

<label for="startYear"> Start Year: </label>
  <input name="startYear" id="startYear" class="date-picker-year" />   

jQuery

 <script type="text/javascript">
        $(function() {
            $('.date-picker-year').datepicker({
                changeYear: true,
                showButtonPanel: true,
                dateFormat: 'yy',
                onClose: function(dateText, inst) { 
                    var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                    $(this).datepicker('setDate', new Date(year, 1));
                }
            });
        $(".date-picker-year").focus(function () {
                $(".ui-datepicker-month").hide();
            });
        });

</script>

How can I simulate a print statement in MySQL?

This is an old post, but thanks to this post I have found this:

\! echo 'some text';

Tested with MySQL 8 and working correctly. Cool right? :)

Accessing localhost:port from Android emulator

you need to set URL as 10.0.2.2:portNr

portNr = the given port by ASP.NET Development Server my current service is running on localhost:3229/Service.svc

so my url is 10.0.2.2:3229

i'd fixed my problem this way

i hope it helps...

Passing properties by reference in C#

The accepted answer is good if that function is in your code and you can modify it. But sometimes you have to use an object and a function from some external library and you can't change the property and function definition. Then you can just use a temporary variable.

var phone = Client.WorkPhone;
GetString(input, ref phone);
Client.WorkPhone = phone;

How do I create an Android Spinner as a popup?

MODE_DIALOG and MODE_DROPDOWN are defined in API 11 (Honeycomb). MODE_DIALOG describes the usual behaviour in previous platform versions.

Loop in Jade (currently known as "Pug") template engine

Using node I have a collection of stuff @stuff and access it like this:

- each stuff in stuffs
  p
    = stuff.sentence

How to edit incorrect commit message in Mercurial?

Good news: hg 2.2 just added git like --amend option.

and in tortoiseHg, you can use "Amend current revision" by select black arrow on the right of commit button

a

Deleting multiple elements from a list

I put it all together into a list_diff function that simply takes two lists as inputs and returns their difference, while preserving the original order of the first list.

def list_diff(list_a, list_b, verbose=False):

    # returns a difference of list_a and list_b,
    # preserving the original order, unlike set-based solutions

    # get indices of elements to be excluded from list_a
    excl_ind = [i for i, x in enumerate(list_a) if x in list_b]
    if verbose:
        print(excl_ind)

    # filter out the excluded indices, producing a new list 
    new_list = [i for i in list_a if list_a.index(i) not in excl_ind]
    if verbose:
        print(new_list)

    return(new_list)

Sample usage:

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'woof']
# index = [0, 3, 6]

# define excluded names list
excl_names_list = ['woof', 'c']

list_diff(my_list, excl_names_list)
>> ['a', 'b', 'd', 'e', 'f']

"Correct" way to specifiy optional arguments in R functions

There are several options and none of them are the official correct way and none of them are really incorrect, though they can convey different information to the computer and to others reading your code.

For the given example I think the clearest option would be to supply an identity default value, in this case do something like:

fooBar <- function(x, y=0) {
  x + y
}

This is the shortest of the options shown so far and shortness can help readability (and sometimes even speed in execution). It is clear that what is being returned is the sum of x and y and you can see that y is not given a value that it will be 0 which when added to x will just result in x. Obviously if something more complicated than addition is used then a different identity value will be needed (if one exists).

One thing I really like about this approach is that it is clear what the default value is when using the args function, or even looking at the help file (you don't need to scroll down to the details, it is right there in the usage).

The drawback to this method is when the default value is complex (requiring multiple lines of code), then it would probably reduce readability to try to put all that into the default value and the missing or NULL approaches become much more reasonable.

Some of the other differences between the methods will appear when the parameter is being passed down to another function, or when using the match.call or sys.call functions.

So I guess the "correct" method depends on what you plan to do with that particular argument and what information you want to convey to readers of your code.

Update query PHP MySQL

You have to have single quotes around any VARCHAR content in your queries. So your update query should be:

mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = $id");

Also, it is bad form to update your database directly with the content from a POST. You should sanitize your incoming data with the mysql_real_escape_string function.

Create listview in fragment android

Instead:

public class PhotosFragment extends Fragment

You can use:

public class PhotosFragment extends ListFragment

It change the methods

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ArrayList<ListviewContactItem> listContact = GetlistContact();
        setAdapter(new ListviewContactAdapter(getActivity(), listContact));
    }

onActivityCreated is void and you didn't need to return a view like in onCreateView

You can see an example here

Maven Error: Could not find or load main class

The first thing i would suggest is to use the correct configuration for predefined descriptors.

<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.5.3</version>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
        [...]
</project>

To configure the main class you need to know the package and name of the class you would like to use which should be given into <mainClass>...</mainClass> parameter.

Furthermore i recommend to stop using Maven 2 and move to Maven 3 instead.

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

How can I trigger the click event of another element in ng-click using angularjs?

I think you are over complicated things a bit. Do you really need to trigger a click on the input from your button ?

I suggest you just apply a proper style to your input and the ngFileSelect directive will do the rest and call your onFileSelect function whenever a file is submitted :

input.file {
    cursor: pointer;
    direction: ltr;
    font-size: 23px;
    margin: 0;
    opacity: 0;
    position: absolute;
    right: 0;
    top: 0;
    transform: translate(-300px, 0px) scale(4);
}

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The error tells you that there is an error but you don´t catch it. This is how you can catch it:

getAllPosts().then(response => {
    console.log(response);
}).catch(e => {
    console.log(e);
});

You can also just put a console.log(reponse) at the beginning of your API callback function, there is definitely an error message from the Graph API in it.

More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

Or with async/await:

//some async function
try {
    let response = await getAllPosts();
} catch(e) {
    console.log(e);
}

Printing a java map Map<String, Object> - How?

You may use Map.entrySet() method:

for (Map.Entry entry : objectSet.entrySet())
{
    System.out.println("key: " + entry.getKey() + "; value: " + entry.getValue());
}

How do I compare version numbers in Python?

What's wrong with transforming the version string into a tuple and going from there? Seems elegant enough for me

>>> (2,3,1) < (10,1,1)
True
>>> (2,3,1) < (10,1,1,1)
True
>>> (2,3,1,10) < (10,1,1,1)
True
>>> (10,3,1,10) < (10,1,1,1)
False
>>> (10,3,1,10) < (10,4,1,1)
True

@kindall's solution is a quick example of how good the code would look.

Adding an external directory to Tomcat classpath

Just specify it in shared.loader or common.loader property of /conf/catalina.properties.

Maximum number of threads per process in Linux?

In practical terms, the limit is usually determined by stack space. If each thread gets a 1MB stack (I can't remember if that is the default on Linux), then you a 32-bit system will run out of address space after 3000 threads (assuming that the last gb is reserved to the kernel).

However, you'll most likely experience terrible performance if you use more than a few dozen threads. Sooner or later, you get too much context-switching overhead, too much overhead in the scheduler, and so on. (Creating a large number of threads does little more than eat a lot of memory. But a lot of threads with actual work to do is going to slow you down as they're fighting for the available CPU time)

What are you doing where this limit is even relevant?

How to embed images in html email

I'm using this function that find all images in my letter and attaches it to the message.

Parameters: Takes your HTML (which you want to send);
Return: The necessary HTML and headers, which you can use in mail();

Example usage:

define("DEFCALLBACKMAIL", "[email protected]"); // WIll be shown as "from".
$final_msg = preparehtmlmail($html); // give a function your html*

mail('[email protected]', 'your subject', $final_msg['multipart'], $final_msg['headers']); 
// send email with all images from html attached to letter


function preparehtmlmail($html) {

  preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
  $i = 0;
  $paths = array();

  foreach ($matches[1] as $img) {
    $img_old = $img;

    if(strpos($img, "http://") == false) {
      $uri = parse_url($img);
      $paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
      $content_id = md5($img);
      $html = str_replace($img_old,'cid:'.$content_id,$html);
      $paths[$i++]['cid'] = $content_id;
    }
  }

  $boundary = "--".md5(uniqid(time()));
  $headers .= "MIME-Version: 1.0\n";
  $headers .="Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
  $headers .= "From: ".DEFCALLBACKMAIL."\r\n";
  $multipart = '';
  $multipart .= "--$boundary\n";
  $kod = 'utf-8';
  $multipart .= "Content-Type: text/html; charset=$kod\n";
  $multipart .= "Content-Transfer-Encoding: Quot-Printed\n\n";
  $multipart .= "$html\n\n";

  foreach ($paths as $path) {
    if(file_exists($path['path']))
      $fp = fopen($path['path'],"r");
      if (!$fp)  {
        return false;
      }

    $imagetype = substr(strrchr($path['path'], '.' ),1);
    $file = fread($fp, filesize($path['path']));
    fclose($fp);

    $message_part = "";

    switch ($imagetype) {
      case 'png':
      case 'PNG':
            $message_part .= "Content-Type: image/png";
            break;
      case 'jpg':
      case 'jpeg':
      case 'JPG':
      case 'JPEG':
            $message_part .= "Content-Type: image/jpeg";
            break;
      case 'gif':
      case 'GIF':
            $message_part .= "Content-Type: image/gif";
            break;
    }

    $message_part .= "; file_name = \"$path\"\n";
    $message_part .= 'Content-ID: <'.$path['cid'].">\n";
    $message_part .= "Content-Transfer-Encoding: base64\n";
    $message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
    $message_part .= chunk_split(base64_encode($file))."\n";
    $multipart .= "--$boundary\n".$message_part."\n";

  }

  $multipart .= "--$boundary--\n";
  return array('multipart' => $multipart, 'headers' => $headers);  
}

Regex pattern to match at least 1 number and 1 character in a string

This RE will do:

/^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i

Explanation of RE:

  • Match either of the following:
    1. At least one number, then one letter or
    2. At least one letter, then one number plus
  • Any remaining numbers and letters

  • (?:...) creates an unreferenced group
  • /i is the ignore-case flag, so that a-z == a-zA-Z.

ASP MVC href to a controller/view

There are a couple of ways that you can accomplish this. You can do the following:

<li>
     @Html.ActionLink("Clients", "Index", "User", new { @class = "elements" }, null)
</li>

or this:

<li>
     <a href="@Url.Action("Index", "Users")" class="elements">
          <span>Clients</span>
     </a>
</li>

Lately I do the following:

<a href="@Url.Action("Index", null, new { area = string.Empty, controller = "User" }, Request.Url.Scheme)">
     <span>Clients</span>
</a>

The result would have http://localhost/10000 (or with whatever port you are using) to be appended to the URL structure like:

http://localhost:10000/Users

I hope this helps.

What are best practices for REST nested resources?

I disagree with this kind of path

GET /companies/{companyId}/departments

If you want to get departments, I think it's better to use a /departments resource

GET /departments?companyId=123

I suppose you have a companies table and a departments table then classes to map them in the programming language you use. I also assume that departments could be attached to other entities than companies, so a /departments resource is straightforward, it's convenient to have resources mapped to tables and also you don't need as many endpoints since you can reuse

GET /departments?companyId=123

for any kind of search, for instance

GET /departments?name=xxx
GET /departments?companyId=123&name=xxx
etc.

If you want to create a department, the

POST /departments

resource should be used and the request body should contain the company ID (if the department can be linked to only one company).

Efficient way to update all rows in a table

Might not work you for, but a technique I've used a couple times in the past for similar circumstances.

created updated_{table_name}, then select insert into this table in batches. Once finished, and this hinges on Oracle ( which I don't know or use ) supporting the ability to rename tables in an atomic fashion. updated_{table_name} becomes {table_name} while {table_name} becomes original_{table_name}.

Last time I had to do this was for a heavily indexed table with several million rows that absolutely positively could not be locked for the duration needed to make some serious changes to it.

What is the difference between the kernel space and the user space?

IN short kernel space is the portion of memory where linux kernel runs (top 1 GB virtual space in case of linux) and user space is the portion of memory where user application runs( bottom 3 GB of virtual memory in case of Linux. If you wanna know more the see the link given below :)

http://learnlinuxconcepts.blogspot.in/2014/02/kernel-space-and-user-space.html

Multiple line comment in Python

Try this

'''
This is a multiline
comment. I can type here whatever I want.
'''

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.

Java - Writing strings to a CSV file

Answer for this question is good if you want to overwrite your file everytime you rerun your program, but if you want your records to not be lost at rerunning your program, you may want to try this

public void writeAudit(String actionName) {
    String whereWrite = "./csvFiles/audit.csv";

    try {
        FileWriter fw = new FileWriter(whereWrite, true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter pw = new PrintWriter(bw);

        Date date = new Date();

        pw.println(actionName + "," + date.toString());
        pw.flush();
        pw.close();

    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

XPath Query: get attribute href from a tag

For the following HTML document:

<html>
  <body>
    <a href="http://www.example.com">Example</a> 
    <a href="http://www.stackoverflow.com">SO</a> 
  </body>
</html>

The xpath query /html/body//a/@href (or simply //a/@href) will return:

    http://www.example.com
    http://www.stackoverflow.com

To select a specific instance use /html/body//a[N]/@href,

    $ /html/body//a[2]/@href
    http://www.stackoverflow.com

To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:

    $ /html/body//a[contains(@href,'example')]/@href
    http://www.example.com

Mixing the two:

    $ /html/body//a[contains(@href,'com')][2]/@href
    http://www.stackoverflow.com

Java: how to add image to Jlabel?

Simple code that you can write in main(String[] args) function

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//application will be closed when you close frame
    frame.setSize(800,600);
    frame.setLocation(200,200);

    JFileChooser fc = new JFileChooser();
    if(fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION){
        BufferedImage img = ImageIO.read(fc.getSelectedFile());//it must be an image file, otherwise you'll get an exception
        JLabel label = new JLabel();
        label.setIcon(new ImageIcon(img));
        frame.getContentPane().add(label);
    }

    frame.setVisible(true);//showing up the frame

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

=LEFT(A1,FIND(IF(
 ISERROR(
  FIND("_",A1)
 ),A1,RIGHT(A1,
  LEN(A1)-FIND("~",
   SUBSTITUTE(A1,"_","~",
    LEN(A1)-LEN(SUBSTITUTE(A1,"_",""))
   )
  )
 )
),A1,1)-2)

How to shift a column in Pandas DataFrame

If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:

    offset = 5
    DF = DF.append([np.nan for x in range(offset)])
    DF = DF.shift(periods=offset)
    DF = DF.reset_index() #Only works if sequential index

Adding images to an HTML document with javascript

or you can just

<script> 
document.write('<img src="/*picture_location_(you can just copy the picture and paste   it into the script)*\"')
document.getElementById('pic')
</script>
<div id="pic">
</div>

How to see full absolute path of a symlink

realpath <path to the symlink file> should do the trick.

What's the difference between `raw_input()` and `input()` in Python 3?

Python 2:

  • raw_input() takes exactly what the user typed and passes it back as a string.

  • input() first takes the raw_input() and then performs an eval() on it as well.

The main difference is that input() expects a syntactically correct python statement where raw_input() does not.

Python 3:

  • raw_input() was renamed to input() so now input() returns the exact string.
  • Old input() was removed.

If you want to use the old input(), meaning you need to evaluate a user input as a python statement, you have to do it manually by using eval(input()).

Auto refresh page every 30 seconds

If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.

javascript:

<script language="javascript">
setTimeout(function(){
   window.location.reload(1);
}, 30000);
</script>

What are the various "Build action" settings in Visual Studio project properties and what do they do?

VS2010 has a property for 'Build Action', and also for 'Copy to Output Directory'. So an action of 'None' will still copy over to the build directory if the copy property is set to 'Copy if Newer' or 'Copy Always'.

So a Build Action of 'Content' should be reserved to indicate content you will access via 'Application.GetContentStream'

I used the 'Build Action' setting of 'None' and the 'Copy to Output Direcotry' setting of 'Copy if Newer' for some externally linked .config includes.

G.

HTTP Basic Authentication credentials passed in URL and encryption

Not necessarily true. It will be encrypted on the wire however it still lands in the logs plain text

javascript compare strings without being case sensitive

Try this...

if(string1.toLowerCase() == string2.toLowerCase()){
    return true;
}

Also, it's not a loop, it's a block of code. Loops are generally repeated (although they can possibly execute only once), whereas a block of code never repeats.

I read your note about not using toLowerCase, but can't see why it would be a problem.

How to create a file on Android Internal Storage?

I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/ or /mnt/sdcard/. Let me explain.

If you execute the following statement:

File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
resolveMe.createNewFile();

It will resolve the path to the root /data/ somewhere higher up in Android.

I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/ without me translating anything on my own.

File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
resolveMeSDCard.createNewFile();

A quick fix would be to change your following code:

File f = new File(getLocalPath().replace("/data/data/", "/"));

Hope this helps

SQL Server - Create a copy of a database table and place it in the same database?

use sql server manegement studio or netcat and that will be easier to manipulate sql

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.

Layout

Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here


For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

How can I get the last 7 characters of a PHP string?

for last 7 characters

$newstring = substr($dynamicstring, -7);

$newstring : 5409els

for first 7 characters

$newstring = substr($dynamicstring, 0, 7);

$newstring : 2490slk

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

A simple solution of error is that you first need to change the folder directory in command prompt. By default in command prompt or in terminal(Inside Android studio in the bottom)tab the path is set to C:\Users#Name of your PC that you selected\AndroidStudioProjects#app name\flutter_app> Change accordingly:- C:\Users#Name of your PC that you selected\AndroidStudioProjects#app name\flutter_app>cd\

type **cd** (#after flutter_app>), type only cd\ not comma's

then type cd Program Files\Java\jre1.8.0_251\bin (#remember to check the file name of jre properly)

now type keytool -list -v -keystore "%USERPROFILE%.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android (without anyspace type the command).

screenshot of the codes to run

How to get the string size in bytes?

You can use strlen. Size is determined by the terminating null-character, so passed string should be valid.

If you want to get size of memory buffer, that contains your string, and you have pointer to it:

  • If it is dynamic array(created with malloc), it is impossible to get it size, since compiler doesn't know what pointer is pointing at. (check this)
  • If it is static array, you can use sizeof to get its size.

If you are confused about difference between dynamic and static arrays, check this.

Why doesn't Java offer operator overloading?

Alternatives to Native Support of Java Operator Overloading

Since Java doesn't have operator overloading, here are some alternatives you can look into:

  1. Use another language. Both Groovy and Scala have operator overloading, and are based on Java.
  2. Use java-oo, a plugin that enables operator overloading in Java. Note that it is NOT platform independent. Also, it has many issues, and is not compatible with the latest releases of Java (i.e. Java 10). (Original StackOverflow Source)
  3. Use JNI, Java Native Interface, or alternatives. This allows you to write C or C++ (maybe others?) methods for use in Java. Of course this is also NOT platform independent.

If anyone is aware of others, please comment, and I will add it to this list.

Finding rows that don't contain numeric data in Oracle

enter image description hereI tray order by with problematic column and i find rows with column.

SELECT 
 D.UNIT_CODE,
         D.CUATM,
         D.CAPITOL,
          D.RIND,
          D.COL1  AS COL1


FROM
  VW_DATA_ALL_GC  D
  
  WHERE
  
   (D.PERIOADA IN (:pPERIOADA))  AND   
   (D.FORM = 62) 
   AND D.COL1 IS NOT NULL
 --  AND REGEXP_LIKE (D.COL1, '\[\[:alpha:\]\]')
 
-- AND REGEXP_LIKE(D.COL1, '\[\[:digit:\]\]')
 
 --AND REGEXP_LIKE(TO_CHAR(D.COL1), '\[^0-9\]+')
 
 
   GROUP BY 
    D.UNIT_CODE,
         D.CUATM,
         D.CAPITOL,
          D.RIND ,
          D.COL1  
         
         
        ORDER BY 
        D.COL1

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

I encountered the same issue even though the ca-certificates package is up-to-date. The mirror https://mirrors.fedoraproject.org/ is currently signed by DigiCert High Assurance EV Root CA which is included in my ca-bundle

$ grep -A 3 "DigiCert High" /etc/ssl/certs/ca-bundle.crt 
# DigiCert High Assurance EV Root CA
-----BEGIN CERTIFICATE-----
MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3

The reason why https connections failed in my case, was that system date was set to the year 2002 in which the DigiCert High Assurance EV Root CA is not (yet) valid.

$ date
Di 1. Jan 11:10:35 CET 2002

Changing the system time fixed the issue.

How do you stop MySQL on a Mac OS install?

Use:

sudo mysqladmin shutdown --user=*user* --password=*password*

One could probably get away with not using sudo. The user could be root for example (that is, the MySQL root user).

Your password does not satisfy the current policy requirements

didn't work for me on ubuntu fresh install of mysqld, had to add this: to /etc/mysql/mysql.conf.d/mysqld.cnf or the server wouldn't start (guess the plugin didn't load at the right time when I simply added it without the plugin-load-add directive)

plugin-load-add=validate_password.so
validate_password_policy=LOW
validate_password_length=8
validate_password_mixed_case_count=0
validate_password_number_count=0
validate_password_special_char_count=0

How do I get JSON data from RESTful service using Python?

Something like this should work unless I'm missing the point:

import json
import urllib2
json.load(urllib2.urlopen("url"))

How to add an element to the beginning of an OrderedDict?

If you need functionality that isn't there, just extend the class with whatever you want:

from collections import OrderedDict

class OrderedDictWithPrepend(OrderedDict):
    def prepend(self, other):
        ins = []
        if hasattr(other, 'viewitems'):
            other = other.viewitems()
        for key, val in other:
            if key in self:
                self[key] = val
            else:
                ins.append((key, val))
        if ins:
            items = self.items()
            self.clear()
            self.update(ins)
            self.update(items)

Not terribly efficient, but works:

o = OrderedDictWithPrepend()

o['a'] = 1
o['b'] = 2
print o
# OrderedDictWithPrepend([('a', 1), ('b', 2)])

o.prepend({'c': 3})
print o
# OrderedDictWithPrepend([('c', 3), ('a', 1), ('b', 2)])

o.prepend([('a',11),('d',55),('e',66)])
print o
# OrderedDictWithPrepend([('d', 55), ('e', 66), ('c', 3), ('a', 11), ('b', 2)])

Change Volley timeout duration

req.setRetryPolicy(new DefaultRetryPolicy(
    MY_SOCKET_TIMEOUT_MS, 
    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

You can set MY_SOCKET_TIMEOUT_MS as 100. Whatever you want to set this to is in milliseconds. DEFAULT_MAX_RETRIES can be 0 default is 1.

Printing image with PrintDocument. how to adjust the image to fit paper size

Not to trample on BBoy's already decent answer, but I've done the code that maintains aspect ratio. I took his suggestion, so he should get partial credit here!

PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PrinterSettings.PrinterName = "Printer Name";
pd.DefaultPageSettings.Landscape = true; //or false!
pd.PrintPage += (sender, args) =>
{
    Image i = Image.FromFile(@"C:\...\...\image.jpg");
    Rectangle m = args.MarginBounds;

    if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
    {
        m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
    }
    else
    {
        m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
    }
    args.Graphics.DrawImage(i, m);
};
pd.Print();

ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

Pickle uses different protocols to convert your data to a binary stream.

You must specify in python 3 a protocol lower than 3 in order to be able to load the data in python 2. You can specify the protocol parameter when invoking pickle.dump.

How to properly URL encode a string in PHP?

For the URI query use urlencode/urldecode; for anything else use rawurlencode/rawurldecode.

The difference between urlencode and rawurlencode is that

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?

INNER JOIN gets all records that are common between both tables based on the supplied ON clause.

LEFT JOIN gets all records from the LEFT linked and the related record from the right table ,but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL.

RIGHT JOIN is like the above but gets all records in the RIGHT table.

FULL JOIN gets all records from both tables and puts NULL in the columns where related records do not exist in the opposite table.

How to convert URL parameters to a JavaScript object?

Here's my quick and dirty version, basically its splitting up the URL parameters separated by '&' into array elements, and then iterates over that array adding key/value pairs separated by '=' into an object. I'm using decodeURIComponent() to translate the encoded characters to their normal string equivalents (so %20 becomes a space, %26 becomes '&', etc):

function deparam(paramStr) {
    let paramArr = paramStr.split('&');     
    let paramObj = {};
    paramArr.forEach(e=>{
        let param = e.split('=');
        paramObj[param[0]] = decodeURIComponent(param[1]);
    });
    return paramObj;
}

example:

deparam('abc=foo&def=%5Basf%5D&xyz=5')

returns

{
    abc: "foo"
    def:"[asf]"
    xyz :"5"
}

The only issue is that xyz is a string and not a number (due to using decodeURIComponent()), but beyond that its not a bad starting point.

executing a function in sql plus

One option would be:

SET SERVEROUTPUT ON

EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));

How do I get interactive plots again in Spyder/IPython/matplotlib?

You can quickly control this by typing built-in magic commands in Spyder's IPython console, which I find faster than picking these from the preferences menu. Changes take immediate effect, without needing to restart Spyder or the kernel.

To switch to "automatic" (i.e. interactive) plots, type:

%matplotlib auto

then if you want to switch back to "inline", type this:

%matplotlib inline

(Note: these commands don't work in non-IPython consoles)

See more background on this topic: Purpose of "%matplotlib inline"

Difference between agile and iterative and incremental development

Some important and successfully executed software projects like Google Chrome and Mozilla Firefox are fine examples of both iterative and incremental software development.

I will quote fine ars technica article which describes this approach: http://arstechnica.com/information-technology/2010/07/chrome-team-sets-six-week-cadence-for-new-major-versions/

According to Chrome program manager Anthony Laforge, the increased pace is designed to address three main goals. One is to get new features out to users faster. The second is make the release schedule predictable and therefore easier to plan which features will be included and which features will be targeted for later releases. Third, and most counterintuitive, is to cut the level of stress for Chrome developers. Laforge explains that the shorter, predictable time periods between releases are more like "trains leaving Grand Central Station." New features that are ready don't have to wait for others that are taking longer to complete—they can just hop on the current release "train." This can in turn take the pressure off developers to rush to get other features done, since another release train will be coming in six weeks. And they can rest easy knowing their work isn't holding the train from leaving the station.<<

How to insert data using wpdb

Try this

I recently leaned about $wpdb->prepare HERE and added into our Free Class Booking plugin, plugin approved on wordpress.org and will live soon:

global $wpdb;
$tablename = $wpdb->prefix . "submitted_form";

$name     = "Kumkum"; //string value use: %s
$email    = "[email protected]"; //string value use: %s
$phone    = "3456734567"; //numeric value use: %d
$country  = "India"; //string value use: %s
$course   = "Database"; //string value use: %s
$message  = "hello i want to read db"; //string value use: %s
$now      = new DateTime(); //string value use: %s
$datesent = $now->format('Y-m-d H:i:s'); //string value use: %s

$sql = $wpdb->prepare("INSERT INTO `$tablename` (`name`, `email`, `phone`, `country`, `course`, `message`, `datesent`) values (%s, %s, %d, %s, %s, %s, %s)", $name, $email, $phone, $country, $course, $message, $datesent);

$wpdb->query($sql);

Thanks -Frank

Apache: client denied by server configuration

I had this issue using Vesta CP and for me, the trick was remove .htaccess and try to access to any file again.

That resulted on regeneration of .htaccess file and then I was able to access to my files.

ImportError: DLL load failed: %1 is not a valid Win32 application

All you have to do is copy the cv2.pyd file from the x86 folder (C:\opencv\build\python\2.7\x86\ for example) to C:\Python27\Lib\site-packages\ , not from the x64 folder.

Hope that help you.

TypeError: 'dict_keys' object does not support indexing

Why you need to implement shuffle when it already exists? Stay on the shoulders of giants.

import random

d1 = {0:'zero', 1:'one', 2:'two', 3:'three', 4:'four',
     5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine'}

keys = list(d1)
random.shuffle(keys)

d2 = {}
for key in keys: d2[key] = d1[key]

print(d1)
print(d2)

round a single column in pandas

You are very close. You applied the round to the series of values given by df.value1. The return type is thus a Series. You need to assign that series back to the dataframe (or another dataframe with the same Index).

Also, there is a pandas.Series.round method which is basically a short hand for pandas.Series.apply(np.round).

In[2]: 
    df.value1 = df.value1.round()
    print df

Out[2]:
    item  value1  value2
    0    a       1     1.3
    1    a       2     2.5
    2    a       0     0.0
    3    b       3    -1.0
    4    b       5    -1.0

Using os.walk() to recursively traverse directories in Python

Given a folder name, walk through its entire hierarchy recursively.

#! /usr/local/bin/python3
# findLargeFiles.py - given a folder name, walk through its entire hierarchy
#                   - print folders and files within each folder

import os

def recursive_walk(folder):
    for folderName, subfolders, filenames in os.walk(folder):
        if subfolders:
            for subfolder in subfolders:
                recursive_walk(subfolder)
        print('\nFolder: ' + folderName + '\n')
        for filename in filenames:
            print(filename + '\n')

recursive_walk('/name/of/folder')

UTF-8 byte[] to String

String has a constructor that takes byte[] and charsetname as parameters :)

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

In C++, Replace:

char *str = "hello";

with:

std::string str ("hello");

And if you want to compare it:

str.compare("HALLO");

What is the official name for a credit card's 3 digit code?

It's got a number of names. Most likely you've heard it as either Card Security Code (CSC) or Card Verification Value (CVV).

Card Security Code

How to convert POJO to JSON and vice versa?

Take below reference to convert a JSON into POJO and vice-versa

Let's suppose your JSON schema looks like:

{
  "type":"object",
  "properties": {
    "dataOne": {
      "type": "string"
    },
    "dataTwo": {
      "type": "integer"
    },
    "dataThree": {
      "type": "boolean"
    }
  }
}

Then to covert into POJO, your need to decleare some classes as explained in below style:

==================================
package ;
public class DataOne
{
    private String type;

    public void setType(String type){
        this.type = type;
    }
    public String getType(){
        return this.type;
    }
}

==================================
package ;
public class DataTwo
{
    private String type;

    public void setType(String type){
        this.type = type;
    }
    public String getType(){
        return this.type;
    }
}

==================================
package ;
public class DataThree
{
    private String type;

    public void setType(String type){
        this.type = type;
    }
    public String getType(){
        return this.type;
    }
}

==================================
package ;
public class Properties
{
    private DataOne dataOne;

    private DataTwo dataTwo;

    private DataThree dataThree;

    public void setDataOne(DataOne dataOne){
        this.dataOne = dataOne;
    }
    public DataOne getDataOne(){
        return this.dataOne;
    }
    public void setDataTwo(DataTwo dataTwo){
        this.dataTwo = dataTwo;
    }
    public DataTwo getDataTwo(){
        return this.dataTwo;
    }
    public void setDataThree(DataThree dataThree){
        this.dataThree = dataThree;
    }
    public DataThree getDataThree(){
        return this.dataThree;
    }
}

==================================
package ;
public class Root
{
    private String type;

    private Properties properties;

    public void setType(String type){
        this.type = type;
    }
    public String getType(){
        return this.type;
    }
    public void setProperties(Properties properties){
        this.properties = properties;
    }
    public Properties getProperties(){
        return this.properties;
    }
}

What's the difference between "git reset" and "git checkout"?

  • git reset is specifically about updating the index, moving the HEAD.
  • git checkout is about updating the working tree (to the index or the specified tree). It will update the HEAD only if you checkout a branch (if not, you end up with a detached HEAD).
    (actually, with Git 2.23 Q3 2019, this will be git restore, not necessarily git checkout)

By comparison, since svn has no index, only a working tree, svn checkout will copy a given revision on a separate directory.
The closer equivalent for git checkout would:

  • svn update (if you are in the same branch, meaning the same SVN URL)
  • svn switch (if you checkout for instance the same branch, but from another SVN repo URL)

All those three working tree modifications (svn checkout, update, switch) have only one command in git: git checkout.
But since git has also the notion of index (that "staging area" between the repo and the working tree), you also have git reset.


Thinkeye mentions in the comments the article "Reset Demystified ".

For instance, if we have two branches, 'master' and 'develop' pointing at different commits, and we're currently on 'develop' (so HEAD points to it) and we run git reset master, 'develop' itself will now point to the same commit that 'master' does.

On the other hand, if we instead run git checkout master, 'develop' will not move, HEAD itself will. HEAD will now point to 'master'.

So, in both cases we're moving HEAD to point to commit A, but how we do so is very different. reset will move the branch HEAD points to, checkout moves HEAD itself to point to another branch.

http://git-scm.com/images/reset/reset-checkout.png

On those points, though:

LarsH adds in the comments:

The first paragraph of this answer, though, is misleading: "git checkout ... will update the HEAD only if you checkout a branch (if not, you end up with a detached HEAD)".
Not true: git checkout will update the HEAD even if you checkout a commit that's not a branch (and yes, you end up with a detached HEAD, but it still got updated).

git checkout a839e8f updates HEAD to point to commit a839e8f.

De Novo concurs in the comments:

@LarsH is correct.
The second bullet has a misconception about what HEAD is in will update the HEAD only if you checkout a branch.
HEAD goes wherever you are, like a shadow.
Checking out some non-branch ref (e.g., a tag), or a commit directly, will move HEAD. Detached head doesn't mean you've detached from the HEAD, it means the head is detached from a branch ref, which you can see from, e.g., git log --pretty=format:"%d" -1.

  • Attached head states will start with (HEAD ->,
  • detached will still show (HEAD, but will not have an arrow to a branch ref.

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

My Resolution,

In my case, I have created a model file and kept it blank,

so when I imported it to other model, It gives me error. so write the definition when you create a model typescript file.

CSS image overlay with color and transparency

If you want to make the reverse of what you showed consider doing this:

.tint:hover:before {
    background: rgba(0,0,250, 0.5);

  }

  .t2:before {
    background: none;
  }

and look at the effect on the 2nd picture.

Is it supposed to look like this?

How do I set hostname in docker-compose?

I needed to spin freeipa container to have a working kdc and had to give it a hostname otherwise it wouldn't run. What eventually did work for me is setting the HOSTNAME env variable in compose:

version: 2
services:
  freeipa:
    environment:
      - HOSTNAME=ipa.example.test

Now its working:

docker exec -it freeipa_freeipa_1 hostname
ipa.example.test

Copy file or directories recursively in Python

Unix cp doesn't 'support both directories and files':

betelgeuse:tmp james$ cp source/ dest/
cp: source/ is a directory (not copied).

To make cp copy a directory, you have to manually tell cp that it's a directory, by using the '-r' flag.

There is some disconnect here though - cp -r when passed a filename as the source will happily copy just the single file; copytree won't.

Finish an activity from another activity

There is one approach that you can use in your case.

Step1: Start Activity B from Activity A

startActivity(new Intent(A.this, B.class));

Step2: If the user clicks on modify button start Activity A using the FLAG_ACTIVITY_CLEAR_TOP.Also, pass the flag in extra.

Intent i = new Intent(B.this, A.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("flag", "modify");
startActivity(i);
finish();

Step3: If the user clicks on Add button start Activity A using the FLAG_ACTIVITY_CLEAR_TOP.Also, pass the flag in extra. FLAG_ACTIVITY_CLEAR_TOP will clear all the opened activities up to the target and restart if no launch mode is defined in the target activity

Intent i = new Intent(B.this, A.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("flag", "add");
startActivity(i);
finish();

Step4: Now onCreate() method of the Activity A, need to retrieve that flag.

String flag = getIntent().getStringExtra("flag");
if(flag.equals("add")) {
    //Write a code for add
}else {
    //Write a code for modifying
}

How can I install a CPAN module into a local directory?

Other answers already on Stackoverflow:

From perlfaq8:


How do I keep my own module/library directory?

When you build modules, tell Perl where to install the modules.

For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:

perl Makefile.PL INSTALL_BASE=/mydir/perl

You can set this in your CPAN.pm configuration so modules automatically install in your private library directory when you use the CPAN.pm shell:

% cpan
cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
cpan> o conf commit

For Build.PL-based distributions, use the --install_base option:

perl Build.PL --install_base /mydir/perl

You can configure CPAN.pm to automatically use this option too:

% cpan
cpan> o conf mbuildpl_arg '--install_base /mydir/perl'
cpan> o conf commit

Setting Custom ActionBar Title from Fragment

if you are using android studio 1.4 stable template provided by google than simple you had to write following code in onNavigationItemSelected methode in which your related fragment calling if condition.

 setTitle("YOUR FRAGMENT TITLE");

What would be the Unicode character for big bullet in the middle of the character?

http://www.unicode.org is the place to look for symbol names.

? BLACK CIRCLE        25CF
? MEDIUM BLACK CIRCLE 26AB
? BLACK LARGE CIRCLE  2B24

or even:

 NEW MOON SYMBOL   1F311

Good luck finding a font that supports them all. Only one shows up in Windows 7 with Chrome.

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

How to read/process command line arguments?

I like getopt from stdlib, eg:

try:
    opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err: 
    usage(err)

for opt, arg in opts:
    if opt in ('-h', '--help'): 
        usage()

if len(args) != 1:
    usage("specify thing...")

Lately I have been wrapping something similiar to this to make things less verbose (eg; making "-h" implicit).

Problems with jQuery getJSON using local files in Chrome

This is a known issue with Chrome.

Here's the link in the bug tracker:

Issue 40787: Local files doesn't load with Ajax

Normalize numpy array columns in python

You can use sklearn.preprocessing:

from sklearn.preprocessing import normalize
data = np.array([
    [1000, 10, 0.5],
    [765, 5, 0.35],
    [800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1.     1.     1.   ]
[ 0.765  0.5    0.7  ]
[ 0.8    0.7    0.18 ]]

Xcode couldn't find any provisioning profiles matching

I am now able to successfully build. Not sure exactly which step "fixed" things, but this was the sequence:

  • Tried automatic signing again. No go, so reverted to manual.
  • After reverting, I had no Eligible Profiles, all were ineligible. Strange.
  • I created a new certificate and profile, imported both. This too was "ineligible".
  • Removed the iOS platform and re-added it. I had tried this previously without luck.
  • After doing this, Xcode on its own defaulted to automatic signing. And this worked! Success!

While I am not sure exactly which parts were necessary, I think the previous certificates were the problem. I hate Xcode :(

Thanks for help.

Find all paths between two graph nodes

There's a nice article which may answer your question /only it prints the paths instead of collecting them/. Please note that you can experiment with the C++/Python samples in the online IDE.

http://www.geeksforgeeks.org/find-paths-given-source-destination/

CSS to prevent child element from inheriting parent styles

Can't you style the forms themselves? Then, style the divs accordingly.

form
{
    /* styles */
}

You can always overrule inherited styles by making it important:

form
{
    /* styles */ !important
}

How to play ringtone/alarm sound in Android

For the future googlers: use RingtoneManager.getActualDefaultRingtoneUri() instead of RingtoneManager.getDefaultUri(). According to its name, it would return the actual uri, so you can freely use it. From documentation of getActualDefaultRingtoneUri():

Gets the current default sound's Uri. This will give the actual sound Uri, instead of using this, most clients can use DEFAULT_RINGTONE_URI.

Meanwhile getDefaultUri() says this:

Returns the Uri for the default ringtone of a particular type. Rather than returning the actual ringtone's sound Uri, this will return the symbolic Uri which will resolved to the actual sound when played.

JQuery create new select option

What about

var option = $('<option/>');
option.attr({ 'value': 'myValue' }).text('myText');
$('#county').append(option);

How to specify a port to run a create-react-app based project?

It would be nice to be able to specify a port other than 3000, either as a command line parameter or an environment variable.

Right now, the process is pretty involved:

  1. Run npm run eject
  2. Wait for that to finish
  3. Edit scripts/start.js and find/replace 3000 with whatever port you want to use
  4. Edit config/webpack.config.dev.js and do the same
  5. npm start

PHP If Statement with Multiple Conditions

An elegant way is building an array on the fly and using in_array():

if (in_array($var, array("abc", "def", "ghi")))

The switch statement is also an alternative:

switch ($var) {
case "abc":
case "def":
case "hij":
    echo "yes";
    break;
default:
    echo "no";
}

Declaring static constants in ES6 classes?

In this document it states:

There is (intentionally) no direct declarative way to define either prototype data properties (other than methods) class properties, or instance property

This means that it is intentionally like this.

Maybe you can define a variable in the constructor?

constructor(){
    this.key = value
}

Is there a template engine for Node.js?

Did you try PURE ?
If you give it a try, feel free to post any trouble you may face at the forum

While it was primarly designed for the browser, it works well with Jaxer and Rhino.

I don't know node.js yet but if you can cache some JS and functions in memory, the speed should be even more impressive.

powershell - list local users and their groups

Expanding on mjswensen's answer, the command without the filter could take minutes, but the filtered command is almost instant.

PowerShell - List local user accounts

Fast way

Get-WmiObject -Class Win32_UserAccount -Filter  "LocalAccount='True'" | select name, fullname

Slow way

Get-WmiObject -Class Win32_UserAccount |? {$_.localaccount -eq $true} | select name, fullname

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.

Try as follows:

  1. Format > Conditional Formating...
  2. Select 'Formula Is' from drop down menu
  3. Enter the following formula:

    =ISERROR(MATCH(A1,$B$1:$B$10,0))

  4. Now select the format you want to highlight the values in col A that do not appear in col B

This will highlight any value in Col A that does not appear in Col B.

Put icon inside input element in a form

This works for me for more or less standard forms:

  <button type="submit" value="Submit" name="ButtonType" id="whateveristheId" class="button-class">Submit<img src="/img/selectedImage.png" alt=""></button>

How do I generate sourcemaps when using babel and webpack?

Even same issue I faced, in browser it was showing compiled code. I have made below changes in webpack config file and it is working fine now.

 devtool: '#inline-source-map',
 debug: true,

and in loaders I kept babel-loader as first option

loaders: [
  {
    loader: "babel-loader",
    include: [path.resolve(__dirname, "src")]
  },
  { test: /\.js$/, exclude: [/app\/lib/, /node_modules/], loader: 'ng-annotate!babel' },
  { test: /\.html$/, loader: 'raw' },
  {
    test: /\.(jpe?g|png|gif|svg)$/i,
    loaders: [
      'file?hash=sha512&digest=hex&name=[hash].[ext]',
      'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
    ]
  },
  {test: /\.less$/, loader: "style!css!less"},
  { test: /\.styl$/, loader: 'style!css!stylus' },
  { test: /\.css$/, loader: 'style!css' }
]

How to redirect the output of the time command to a file in Linux?

#!/bin/bash

set -e

_onexit() {
    [[ $TMPD ]] && rm -rf "$TMPD"
}

TMPD="$(mktemp -d)"
trap _onexit EXIT

_time_2() {
    "$@" 2>&3
}

_time_1() {
    time _time_2 "$@"
}

_time() {
    declare time_label="$1"
    shift
    exec 3>&2
    _time_1 "$@" 2>"$TMPD/timing.$time_label"
    echo "time[$time_label]"
    cat "$TMPD/timing.$time_label"
}

_time a _do_something
_time b _do_another_thing
_time c _finish_up

This has the benefit of not spawning sub shells, and the final pipeline has it's stderr restored to the real stderr.

How to check if variable's type matches Type stored in a variable

GetType() exists on every single framework type, because it is defined on the base object type. So, regardless of the type itself, you can use it to return the underlying Type

So, all you need to do is:

u.GetType() == t