Programs & Examples On #Subscription

An arrangement to receive something, typically a publication, regularly.

Angular/RxJs When should I unsubscribe from `Subscription`

Some of the best practices regarding observables unsubscriptions inside Angular components:

A quote from Routing & Navigation

When subscribing to an observable in a component, you almost always arrange to unsubscribe when the component is destroyed.

There are a few exceptional observables where this is not necessary. The ActivatedRoute observables are among the exceptions.

The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

Feel free to unsubscribe anyway. It is harmless and never a bad practice.

And in responding to the following links:

I collected some of the best practices regarding observables unsubscriptions inside Angular components to share with you:

  • http observable unsubscription is conditional and we should consider the effects of the 'subscribe callback' being run after the component is destroyed on a case by case basis. We know that angular unsubscribes and cleans the http observable itself (1), (2). While this is true from the perspective of resources it only tells half the story. Let's say we're talking about directly calling http from within a component, and the http response took longer than needed so the user closed the component. The subscribe() handler will still be called even if the component is closed and destroyed. This can have unwanted side effects and in the worse scenarios leave the application state broken. It can also cause exceptions if the code in the callback tries to call something that has just been disposed of. However at the same time occasionally they are desired. Like, let's say you're creating an email client and you trigger a sound when the email is done sending - well you'd still want that to occur even if the component is closed (8).
  • No need to unsubscribe from observables that complete or error. However, there is no harm in doing so(7).
  • Use AsyncPipe as much as possible because it automatically unsubscribes from the observable on component destruction.
  • Unsubscribe from the ActivatedRoute observables like route.params if they are subscribed inside a nested (Added inside tpl with the component selector) or dynamic component as they may be subscribed many times as long as the parent/host component exists. No need to unsubscribe from them in other scenarios as mentioned in the quote above from Routing & Navigation docs.
  • Unsubscribe from global observables shared between components that are exposed through an Angular service for example as they may be subscribed multiple times as long as the component is initialized.
  • No need to unsubscribe from internal observables of an application scoped service since this service never get's destroyed, unless your entire application get's destroyed, there is no real reason to unsubscribe from it and there is no chance of memory leaks. (6).

    Note: Regarding scoped services, i.e component providers, they are destroyed when the component is destroyed. In this case, if we subscribe to any observable inside this provider, we should consider unsubscribing from it using the OnDestroy lifecycle hook which will be called when the service is destroyed, according to the docs.
  • Use an abstract technique to avoid any code mess that may be resulted from unsubscriptions. You can manage your subscriptions with takeUntil (3) or you can use this npm package mentioned at (4) The easiest way to unsubscribe from Observables in Angular.
  • Always unsubscribe from FormGroup observables like form.valueChanges and form.statusChanges
  • Always unsubscribe from observables of Renderer2 service like renderer2.listen
  • Unsubscribe from every observable else as a memory-leak guard step until Angular Docs explicitly tells us which observables are unnecessary to be unsubscribed (Check issue: (5) Documentation for RxJS Unsubscribing (Open)).
  • Bonus: Always use the Angular ways to bind events like HostListener as angular cares well about removing the event listeners if needed and prevents any potential memory leak due to event bindings.

A nice final tip: If you don't know if an observable is being automatically unsubscribed/completed or not, add a complete callback to subscribe(...) and check if it gets called when the component is destroyed.

Returning Arrays in Java

You have a couple of basic misconceptions about Java:

I want it to return the array without having to explicitly tell the console to print.

1) Java does not work that way. Nothing ever gets printed implicitly. (Java does not support an interactive interpreter with a "repl" loop ... like Python, Ruby, etc.)

2) The "main" doesn't "return" anything. The method signature is:

  public static void main(String[] args)

and the void means "no value is returned". (And, sorry, no you can't replace the void with something else. If you do then the java command won't recognize the "main" method.)

3) If (hypothetically) you did want your "main" method to return something, and you altered the declaration to allow that, then you still would need to use a return statement to tell it what value to return. Unlike some language, Java does not treat the value of the last statement of a method as the return value for the method. You have to use a return statement ...

Utils to read resource text file to String (Java)

Use Apache commons's FileUtils. It has a method readFileToString

Finding whether a point lies inside a rectangle or not

bool pointInRectangle(Point A, Point B, Point C, Point D, Point m ) {
    Point AB = vect2d(A, B);  float C1 = -1 * (AB.y*A.x + AB.x*A.y); float  D1 = (AB.y*m.x + AB.x*m.y) + C1;
    Point AD = vect2d(A, D);  float C2 = -1 * (AD.y*A.x + AD.x*A.y); float D2 = (AD.y*m.x + AD.x*m.y) + C2;
    Point BC = vect2d(B, C);  float C3 = -1 * (BC.y*B.x + BC.x*B.y); float D3 = (BC.y*m.x + BC.x*m.y) + C3;
    Point CD = vect2d(C, D);  float C4 = -1 * (CD.y*C.x + CD.x*C.y); float D4 = (CD.y*m.x + CD.x*m.y) + C4;
    return     0 >= D1 && 0 >= D4 && 0 <= D2 && 0 >= D3;}





Point vect2d(Point p1, Point p2) {
    Point temp;
    temp.x = (p2.x - p1.x);
    temp.y = -1 * (p2.y - p1.y);
    return temp;}

Points inside polygon

I just implemented AnT's Answer using c++. I used this code to check whether the pixel's coordination(X,Y) lies inside the shape or not.

What is the use of a private static variable in Java?

Of course it can be accessed as ClassName.var_name, but only from inside the class in which it is defined - that's because it is defined as private.

public static or private static variables are often used for constants. For example, many people don't like to "hard-code" constants in their code; they like to make a public static or private static variable with a meaningful name and use that in their code, which should make the code more readable. (You should also make such constants final).

For example:

public class Example {
    private final static String JDBC_URL = "jdbc:mysql://localhost/shopdb";
    private final static String JDBC_USERNAME = "username";
    private final static String JDBC_PASSWORD = "password";

    public static void main(String[] args) {
        Connection conn = DriverManager.getConnection(JDBC_URL,
                                         JDBC_USERNAME, JDBC_PASSWORD);

        // ...
    }
}

Whether you make it public or private depends on whether you want the variables to be visible outside the class or not.

How to represent a fix number of repeats in regular expression?

^\w{14}$ in Perl and any Perl-style regex.

If you want to learn more about regular expressions - or just need a handy reference - the Wikipedia Entry on Regular Expressions is actually pretty good.

CakePHP find method with JOIN

Otro example, custom Data Pagination for JOIN

CODE in Controller CakePHP 2.6 is OK:

$this->SenasaPedidosFacturadosSds->recursive = -1;
    // Filtro
    $where = array(
        'joins' => array(
            array(
                'table' => 'usuarios',
                'alias' => 'Usuarios',
                'type' => 'INNER',
                'conditions' => array(
                    'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
                )
            ),
            array(
                'table' => 'senasa_pedidos',
                'alias' => 'SenasaPedidos',
                'type' => 'INNER',
                'conditions' => array(
                    'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
                )
            ),
            array(
                'table' => 'clientes',
                'alias' => 'Clientes',
                'type' => 'INNER',
                'conditions' => array(
                    'Clientes.id_cliente = SenasaPedidos.clientes_id'
                )
            ),
        ),
        'fields'=>array(
            'SenasaPedidosFacturadosSds.*',
            'Usuarios.usuario_id',
            'Usuarios.apellido_nombre',
            'Usuarios.senasa_establecimientos_id',
            'Clientes.id_cliente',
            'Clientes.consolida_doc_sanitaria',
            'Clientes.requiere_senasa',
            'Clientes.razon_social',
            'SenasaPedidos.id',
            'SenasaPedidos.domicilio_entrega',
            'SenasaPedidos.sds',
            'SenasaPedidos.pt_ptr'
        ),
        'conditions'=>array(
            'Clientes.requiere_senasa'=>1
        ),
        'order' => 'SenasaPedidosFacturadosSds.created DESC',
        'limit'=>100
    );
    $this->paginate = $where;
    // Get datos
    $data = $this->Paginator->paginate();
    exit(debug($data));

OR Example 2, NOT active conditions:

$this->SenasaPedidosFacturadosSds->recursive = -1;
    // Filtro
    $where = array(
        'joins' => array(
            array(
                'table' => 'usuarios',
                'alias' => 'Usuarios',
                'type' => 'INNER',
                'conditions' => array(
                    'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
                )
            ),
            array(
                'table' => 'senasa_pedidos',
                'alias' => 'SenasaPedidos',
                'type' => 'INNER',
                'conditions' => array(
                    'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
                )
            ),
            array(
                'table' => 'clientes',
                'alias' => 'Clientes',
                'type' => 'INNER',
                'conditions' => array(
                    'Clientes.id_cliente = SenasaPedidos.clientes_id',
                    'Clientes.requiere_senasa = 1'
                )
            ),
        ),
        'fields'=>array(
            'SenasaPedidosFacturadosSds.*',
            'Usuarios.usuario_id',
            'Usuarios.apellido_nombre',
            'Usuarios.senasa_establecimientos_id',
            'Clientes.id_cliente',
            'Clientes.consolida_doc_sanitaria',
            'Clientes.requiere_senasa',
            'Clientes.razon_social',
            'SenasaPedidos.id',
            'SenasaPedidos.domicilio_entrega',
            'SenasaPedidos.sds',
            'SenasaPedidos.pt_ptr'
        ),
        //'conditions'=>array(
        //    'Clientes.requiere_senasa'=>1
        //),
        'order' => 'SenasaPedidosFacturadosSds.created DESC',
        'limit'=>100
    );
    $this->paginate = $where;
    // Get datos
    $data = $this->Paginator->paginate();
    exit(debug($data));

How does "make" app know default target to build if no target is specified?

To save others a few seconds, and to save them from having to read the manual, here's the short answer. Add this to the top of your make file:

.DEFAULT_GOAL := mytarget

mytarget will now be the target that is run if "make" is executed and no target is specified.

If you have an older version of make (<= 3.80), this won't work. If this is the case, then you can do what anon mentions, simply add this to the top of your make file:

.PHONY: default
default: mytarget ;

References: https://www.gnu.org/software/make/manual/html_node/How-Make-Works.html

Get position/offset of element relative to a parent container?

I did it like this in Internet Explorer.

function getWindowRelativeOffset(parentWindow, elem) {
    var offset = {
        left : 0,
        top : 0
    };
    // relative to the target field's document
    offset.left = elem.getBoundingClientRect().left;
    offset.top = elem.getBoundingClientRect().top;
    // now we will calculate according to the current document, this current
    // document might be same as the document of target field or it may be
    // parent of the document of the target field
    var childWindow = elem.document.frames.window;
    while (childWindow != parentWindow) {
        offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
        offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
        childWindow = childWindow.parent;
    }

    return offset;
};

=================== you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus on IE only as per my focus but similar things can be done for other browsers.

how to convert 2d list to 2d numpy array?

just use following code

c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix([[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]])

Then it will give you

you can check shape and dimension of matrix by using following code

c.shape

c.ndim

Swift Beta performance: sorting arrays

TL;DR: Yes, the only Swift language implementation is slow, right now. If you need fast, numeric (and other types of code, presumably) code, just go with another one. In the future, you should re-evaluate your choice. It might be good enough for most application code that is written at a higher level, though.

From what I'm seeing in SIL and LLVM IR, it seems like they need a bunch of optimizations for removing retains and releases, which might be implemented in Clang (for Objective-C), but they haven't ported them yet. That's the theory I'm going with (for now… I still need to confirm that Clang does something about it), since a profiler run on the last test-case of this question yields this “pretty” result:

Time profiling on -O3 Time profiling on -Ofast

As was said by many others, -Ofast is totally unsafe and changes language semantics. For me, it's at the “If you're going to use that, just use another language” stage. I'll re-evaluate that choice later, if it changes.

-O3 gets us a bunch of swift_retain and swift_release calls that, honestly, don't look like they should be there for this example. The optimizer should have elided (most of) them AFAICT, since it knows most of the information about the array, and knows that it has (at least) a strong reference to it.

It shouldn't emit more retains when it's not even calling functions which might release the objects. I don't think an array constructor can return an array which is smaller than what was asked for, which means that a lot of checks that were emitted are useless. It also knows that the integer will never be above 10k, so the overflow checks can be optimized (not because of -Ofast weirdness, but because of the semantics of the language (nothing else is changing that var nor can access it, and adding up to 10k is safe for the type Int).

The compiler might not be able to unbox the array or the array elements, though, since they're getting passed to sort(), which is an external function and has to get the arguments it's expecting. This will make us have to use the Int values indirectly, which would make it go a bit slower. This could change if the sort() generic function (not in the multi-method way) was available to the compiler and got inlined.

This is a very new (publicly) language, and it is going through what I assume are lots of changes, since there are people (heavily) involved with the Swift language asking for feedback and they all say the language isn't finished and will change.

Code used:

import Cocoa

let swift_start = NSDate.timeIntervalSinceReferenceDate();
let n: Int = 10000
let x = Int[](count: n, repeatedValue: 1)
for i in 0..n {
    for j in 0..n {
        let tmp: Int = x[j]
        x[i] = tmp
    }
}
let y: Int[] = sort(x)
let swift_stop = NSDate.timeIntervalSinceReferenceDate();

println("\(swift_stop - swift_start)s")

P.S: I'm not an expert on Objective-C nor all the facilities from Cocoa, Objective-C, or the Swift runtimes. I might also be assuming some things that I didn't write.

Simplest code for array intersection in javascript

Hope this Helps for all versions.

function diffArray(arr1, arr2) {
  var newArr = [];

  var large = arr1.length>=arr2.length?arr1:arr2;
  var small = JSON.stringify(large) == JSON.stringify(arr1)?arr2:arr1;
  for(var i=0;i<large.length;i++){
    var copyExists = false; 
    for(var j =0;j<small.length;j++){
      if(large[i]==small[j]){
        copyExists= true;
        break;
      }
    }
    if(!copyExists)
      {
        newArr.push(large[i]);
      }
  }

  for(var i=0;i<small.length;i++){
    var copyExists = false; 
    for(var j =0;j<large.length;j++){
      if(large[j]==small[i]){
        copyExists= true;
        break;
      }
    }
    if(!copyExists)
      {
        newArr.push(small[i]);
      }
  }


  return newArr;
}

How to create separate AngularJS controller files?

Not so graceful, but the very much simple in implementation solution - using global variable.

In the "first" file:


window.myApp = angular.module("myApp", [])
....

in the "second" , "third", etc:


myApp.controller('MyController', function($scope) {
    .... 
    }); 

Show history of a file?

Have you tried this:

gitk path/to/file

Singletons vs. Application Context in Android?

They're actually the same. There's one difference I can see. With Application class you can initialize your variables in Application.onCreate() and destroy them in Application.onTerminate(). With singleton you have to rely VM initializing and destroying statics.

How can I tell if a VARCHAR variable contains a substring?

CONTAINS is for a Full Text Indexed field - if not, then use LIKE

Select distinct values from a large DataTable column

Method 1:

   DataView view = new DataView(table);
   DataTable distinctValues = view.ToTable(true, "id");

Method 2: You will have to create a class matching your datatable column names and then you can use the following extension method to convert Datatable to List

    public static List<T> ToList<T>(this DataTable table) where T : new()
    {
        List<PropertyInfo> properties = typeof(T).GetProperties().ToList();
        List<T> result = new List<T>();

        foreach (var row in table.Rows)
        {
            var item = CreateItemFromRow<T>((DataRow)row, properties);
            result.Add(item);
        }

        return result;
    }

    private static T CreateItemFromRow<T>(DataRow row, List<PropertyInfo> properties) where T : new()
    {
        T item = new T();
        foreach (var property in properties)
        {
            if (row.Table.Columns.Contains(property.Name))
            {
                if (row[property.Name] != DBNull.Value)
                    property.SetValue(item, row[property.Name], null);
            }
        }
        return item;
    }

and then you can get distinct from list using

      YourList.Select(x => x.Id).Distinct();

Please note that this will return you complete Records and not just ids.

PHPExcel Make first row bold

$objPHPExcel->getActiveSheet()->getStyle('1:1')->getFont()->setBold(true);

That way you get the complete first row

Python socket receive - incoming packets always have a different size

You can alternatively use recv(x_bytes, socket.MSG_WAITALL), which seems to work only on Unix, and will return exactly x_bytes.

Why doesn't margin:auto center an image?

I've found that I must define a specific width for the object or nothing else will make it center. A relative width doesn't work.

download csv file from web api in angular js

I think the best way to download any file generated by REST call is to use window.location example :

_x000D_
_x000D_
    $http({_x000D_
        url: url,_x000D_
        method: 'GET'_x000D_
    })_x000D_
    .then(function scb(response) {_x000D_
        var dataResponse = response.data;_x000D_
        //if response.data for example is : localhost/export/data.csv_x000D_
        _x000D_
        //the following will download the file without changing the current page location_x000D_
        window.location = 'http://'+ response.data_x000D_
    }, function(response) {_x000D_
      showWarningNotification($filter('translate')("global.errorGetDataServer"));_x000D_
    });
_x000D_
_x000D_
_x000D_

anaconda update all possible packages?

Imagine the dependency graph of packages, when the number of packages grows large, the chance of encountering a conflict when upgrading/adding packages is much higher. To avoid this, simply create a new environment in Anaconda.

Be frugal, install only what you need. For me, I installed the following packages in my new environment:

  • pandas
  • scikit-learn
  • matplotlib
  • notebook
  • keras

And I have 84 packages in total.

How to fix 'Notice: Undefined index:' in PHP form action

Simply

if(isset($_POST['filename'])){
 $filename = $_POST['filename'];
 echo $filename;
}
else{
 echo "POST filename is not assigned";
}

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

Sometimes there is some error in the local Maven repo. So please close your eclipse and delete the jar spring-webmvc from your local .m2 then open Eclipse and on the project press Update Maven Dependencies.

Then Eclipse will download the dependency again for you. That how I fixed the same problem.

Dynamically create and submit form

Josepmra example works well for what i need. But i had to add the line

 form.appendTo( document.body )

for it to work.

var form = $(document.createElement('form'));
$(form).attr("action", "reserves.php");
$(form).attr("method", "POST");

var input = $("<input>")
    .attr("type", "hidden")
    .attr("name", "mydata")
    .val("bla" );


$(form).append($(input));

form.appendTo( document.body )

$(form).submit();

Convert Map to JSON using Jackson

You should prefer Object Mapper instead. Here is the link for the same : Object Mapper - Spring MVC way of Obect to JSON

Checkout subdirectories in Git?

git clone --filter from git 2.19 now works on GitHub (tested 2020-09-18, git 2.25.1)

This option was added together with an update to the remote protocol, and it truly prevents objects from being downloaded from the server.

To clone only objects required for d1 of this repository: https://github.com/cirosantilli/test-git-partial-clone I can do:

git clone \
  --depth 1 \
  --filter=blob:none \
  --no-checkout \
  https://github.com/cirosantilli/test-git-partial-clone \
;
cd test-git-partial-clone
git checkout master -- d1

I have covered this in more detail at: Git: How do I clone a subdirectory only of a Git repository?

How does Tomcat find the HOME PAGE of my Web App?

I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 

What is the difference between dim and set in vba


However, I don't think this is what you're really asking.

Sometimes I use:

    Dim r as Range
    r = Range("A1")

This will never work. Without Set you will receive runtime error #91 Object variable or With block variable not set. This is because you must use Set to assign a variables value to an object reference. Then the code above will work.

I think the code below illustrates what you're really asking about. Let's suppose we don't declare a type and let r be a Variant type instead.

Public Sub test()
    Dim r
    debug.print TypeName(r)

    Set r = Range("A1")
    debug.print TypeName(r)

    r = Range("A1")
    debug.print TypeName(r)
End Sub

So, let's break down what happens here.

  1. r is declared as a Variant

    `Dim r` ' TypeName(r) returns "Empty", which is the value for an uninitialized variant
    
  2. r is set to the Range containing cell "A1"

    Set r = Range("A1") ' TypeName(r) returns "Range"
    
  3. r is set to the value of the default property of Range("A1").

    r = Range("A1") ' TypeName(r) returns "String"
    

In this case, the default property of a Range is .Value, so the following two lines of code are equivalent.

r = Range("A1")
r = Range("A1").Value

For more about default object properties, please see Chip Pearson's "Default Member of a Class".


As for your Set example:

Other times I use

Set r = Range("A1")

This wouldn't work without first declaring that r is a Range or Variant object... using the Dim statement - unless you don't have Option Explicit enabled, which you should. Always. Otherwise, you're using identifiers that you haven't declared and they are all implicitly declared as Variants.

How to prevent custom views from losing state across screen orientation changes

You do this by implementing View#onSaveInstanceState and View#onRestoreInstanceState and extending the View.BaseSavedState class.

public class CustomView extends View {

  private int stateToSave;

  ...

  @Override
  public Parcelable onSaveInstanceState() {
    //begin boilerplate code that allows parent classes to save state
    Parcelable superState = super.onSaveInstanceState();

    SavedState ss = new SavedState(superState);
    //end

    ss.stateToSave = this.stateToSave;

    return ss;
  }

  @Override
  public void onRestoreInstanceState(Parcelable state) {
    //begin boilerplate code so parent classes can restore state
    if(!(state instanceof SavedState)) {
      super.onRestoreInstanceState(state);
      return;
    }

    SavedState ss = (SavedState)state;
    super.onRestoreInstanceState(ss.getSuperState());
    //end

    this.stateToSave = ss.stateToSave;
  }

  static class SavedState extends BaseSavedState {
    int stateToSave;

    SavedState(Parcelable superState) {
      super(superState);
    }

    private SavedState(Parcel in) {
      super(in);
      this.stateToSave = in.readInt();
    }

    @Override
    public void writeToParcel(Parcel out, int flags) {
      super.writeToParcel(out, flags);
      out.writeInt(this.stateToSave);
    }

    //required field that makes Parcelables from a Parcel
    public static final Parcelable.Creator<SavedState> CREATOR =
        new Parcelable.Creator<SavedState>() {
          public SavedState createFromParcel(Parcel in) {
            return new SavedState(in);
          }
          public SavedState[] newArray(int size) {
            return new SavedState[size];
          }
    };
  }
}

The work is split between the View and the View's SavedState class. You should do all the work of reading and writing to and from the Parcel in the SavedState class. Then your View class can do the work of extracting the state members and doing the work necessary to get the class back to a valid state.

Notes: View#onSavedInstanceState and View#onRestoreInstanceState are called automatically for you if View#getId returns a value >= 0. This happens when you give it an id in xml or call setId manually. Otherwise you have to call View#onSaveInstanceState and write the Parcelable returned to the parcel you get in Activity#onSaveInstanceState to save the state and subsequently read it and pass it to View#onRestoreInstanceState from Activity#onRestoreInstanceState.

Another simple example of this is the CompoundButton

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

Why does corrcoef return a matrix?

The function Correlate of numpy works with 2 1D arrays that you want to correlate and returns one correlation value.

What does the @ symbol before a variable name mean in C#?

An important point that the other answers forgot, is that "@keyword" is compiled into "keyword" in the CIL.

So if you have a framework that was made in, say, F#, which requires you to define a class with a property named "class", you can actually do it.

It is not that useful in practice, but not having it would prevent C# from some forms of language interop.

I usually see it used not for interop, but to avoid the keyword restrictions (usually on local variable names, where this is the only effect) ie.

private void Foo(){
   int @this = 2;
}

but I would strongly discourage that! Just find another name, even if the 'best' name for the variable is one of the reserved names.

python location on mac osx

I checked a few similar discussions and found out the best way to locate all python2/python3 builds is:

which -a python python3

Convert multidimensional array into single array

Despite that array_column will work nice here, in case you need to flatten any array no matter of it's internal structure you can use this array library to achieve it without ease:

$flattened = Arr::flatten($array);

which will produce exactly the array you want.

How to select the first element in the dropdown using jquery?

if you want to check the text of selected option regardless if its the 1st child.

var a = $("#select_id option:selected").text();
alert(a); //check if the value is correct.
if(a == "value") {-- execute code --}

How to add data via $.ajax ( serialize() + extra data ) like this

You can do it like this:

postData[postData.length] = { name: "variable_name", value: variable_value };

How to apply color in Markdown?

Seems that kramdown supports colors in some form.

Kramdown allows inline html:

This is <span style="color: red">written in red</span>.

Also it has another syntax for including css classes inline:

This is *red*{: style="color: red"}.

This page further explains how GitLab utilizes more compact way to apply css classes in Kramdown:

Applying blue class to text:

This is a paragraph that for some reason we want blue.
{: .blue}

Applying blue class to headings:

#### A blue heading
{: .blue}

Applying two classes:

A blue and bold paragraph.
{: .blue .bold}

Applying ids:

#### A blue heading
{: .blue #blue-h}

This produces:

<h4 class="blue" id="blue-h">A blue heading</h4>

There is a lot of other stuff explained at above link. You may need to check.

Also, as other answer said, Kramdown is also the default markdown renderer behind Jekyll. So if you are authoring anything on github pages, above functionality might be available out of the box.

Examples of good gotos in C or C++

Very common.

do_stuff(thingy) {
    lock(thingy);

    foo;
    if (foo failed) {
        status = -EFOO;
        goto OUT;
    }

    bar;
    if (bar failed) {
        status = -EBAR;
        goto OUT;
    }

    do_stuff_to(thingy);

OUT:
    unlock(thingy);
    return status;
}

The only case I ever use goto is for jumping forwards, usually out of blocks, and never into blocks. This avoids abuse of do{}while(0) and other constructs which increase nesting, while still maintaining readable, structured code.

How to make an array of arrays in Java

there is the class I mentioned in the comment we had with Sean Patrick Floyd : I did it with a peculiar use which needs WeakReference, but you can change it by any object with ease.

Hoping this can help someone someday :)

import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;


/**
 *
 * @author leBenj
 */
public class Array2DWeakRefsBuffered<T>
{
    private final WeakReference<T>[][] _array;
    private final Queue<T> _buffer;

    private final int _width;

    private final int _height;

    private final int _bufferSize;

    @SuppressWarnings( "unchecked" )
    public Array2DWeakRefsBuffered( int w , int h , int bufferSize )
    {
        _width = w;
        _height = h;
        _bufferSize = bufferSize;
        _array = new WeakReference[_width][_height];
        _buffer = new LinkedList<T>();
    }

    /**
     * Tests the existence of the encapsulated object
     * /!\ This DOES NOT ensure that the object will be available on next call !
     * @param x
     * @param y
     * @return
     * @throws IndexOutOfBoundsException
     */public boolean exists( int x , int y ) throws IndexOutOfBoundsException
    {
        if( x >= _width || x < 0 )
        {
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
        }
        if( y >= _height || y < 0 )
        {
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
        }
        if( _array[x][y] != null )
        {
            T elem = _array[x][y].get();
            if( elem != null )
            {
            return true;
            }
        }
        return false;
    }

    /**
     * Gets the encapsulated object
     * @param x
     * @param y
     * @return
     * @throws IndexOutOfBoundsException
     * @throws NoSuchElementException
     */
    public T get( int x , int y ) throws IndexOutOfBoundsException , NoSuchElementException
    {
        T retour = null;
        if( x >= _width || x < 0 )
        {
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
        }
        if( y >= _height || y < 0 )
        {
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
        }
        if( _array[x][y] != null )
        {
            retour = _array[x][y].get();
            if( retour == null )
            {
            throw new NoSuchElementException( "Dereferenced WeakReference element at [ " + x + " ; " + y + "]" );
            }
        }
        else
        {
            throw new NoSuchElementException( "No WeakReference element at [ " + x + " ; " + y + "]" );
        }
        return retour;
    }

    /**
     * Add/replace an object
     * @param o
     * @param x
     * @param y
     * @throws IndexOutOfBoundsException
     */
    public void set( T o , int x , int y ) throws IndexOutOfBoundsException
    {
        if( x >= _width || x < 0 )
        {
            throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ x = " + x + "]" );
        }
        if( y >= _height || y < 0 )
        {
            throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ y = " + y + "]" );
        }
        _array[x][y] = new WeakReference<T>( o );

        // store local "visible" references : avoids deletion, works in FIFO mode
        _buffer.add( o );
        if(_buffer.size() > _bufferSize)
        {
            _buffer.poll();
        }
    }

}

Example of how to use it :

// a 5x5 array, with at most 10 elements "bufferized" -> the last 10 elements will not be taken by GC process
Array2DWeakRefsBuffered<Image> myArray = new Array2DWeakRefsBuffered<Image>(5,5,10);
Image img = myArray.set(anImage,0,0);
if(myArray.exists(3,3))
{
    System.out.println("Image at 3,3 is still in memory");
}

How to set focus to a button widget programmatically?

Yeah it's possible.

Button myBtn = (Button)findViewById(R.id.myButtonId);
myBtn.requestFocus();

or in XML

<Button ...><requestFocus /></Button>

Important Note: The button widget needs to be focusable and focusableInTouchMode. Most widgets are focusable but not focusableInTouchMode by default. So make sure to either set it in code

myBtn.setFocusableInTouchMode(true);

or in XML

android:focusableInTouchMode="true"

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

if you dont use every time use line-height:'..'; property its control the height of textarea and width property for width of textarea.

or you can make use of font-size by following css:

#sbr {
  font-size: 16px;
  line-height:1.4;
  width:100%;
}

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Returning multiple values from a C++ function

std::pair<int, int> divide(int dividend, int divisor)
{
   // :
   return std::make_pair(quotient, remainder);
}

std::pair<int, int> answer = divide(5,2);
 // answer.first == quotient
 // answer.second == remainder

std::pair is essentially your struct solution, but already defined for you, and ready to adapt to any two data types.

How to convert string to integer in UNIX

Any of these will work from the shell command line. bc is probably your most straight forward solution though.

Using bc:

$ echo "$d1 - $d2" | bc

Using awk:

$ echo $d1 $d2 | awk '{print $1 - $2}'

Using perl:

$ perl -E "say $d1 - $d2"

Using Python:

$ python -c "print $d1 - $d2"

all return

4

How do I output the difference between two specific revisions in Subversion?

To compare entire revisions, it's simply:

svn diff -r 8979:11390


If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:

svn diff -r PREV:HEAD

(Note, without anything specified afterwards, all files in the specified revisions are compared.)


You can compare a specific file if you add the file path afterwards:

svn diff -r 8979:HEAD /path/to/my/file.php

C char* to int conversion

Use atoi() from <stdlib.h>

http://linux.die.net/man/3/atoi

Or, write your own atoi() function which will convert char* to int

int a2i(const char *s)
{
  int sign=1;
  if(*s == '-'){
    sign = -1;
    s++;
  }
  int num=0;
  while(*s){
    num=((*s)-'0')+num*10;
    s++;   
  }
  return num*sign;
}

Setting different color for each series in scatter plot on matplotlib

You can always use the plot() function like so:

import matplotlib.pyplot as plt

import numpy as np

x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]
plt.figure()
for y in ys:
    plt.plot(x, y, 'o')
plt.show()

plot as scatter but changes colors

Write-back vs Write-Through caching?

maybe this article can help you link here

Write-through: Write is done synchronously both to the cache and to the backing store.

Write-back (or Write-behind): Writing is done only to the cache. A modified cache block is written back to the store, just before it is replaced.

Write-through: When data is updated, it is written to both the cache and the back-end storage. This mode is easy for operation but is slow in data writing because data has to be written to both the cache and the storage.

Write-back: When data is updated, it is written only to the cache. The modified data is written to the back-end storage only when data is removed from the cache. This mode has fast data write speed but data will be lost if a power failure occurs before the updated data is written to the storage.

Declaring an HTMLElement Typescript

In JavaScript you declare variables or functions by using the keywords var, let or function. In TypeScript classes you declare class members or methods without these keywords followed by a colon and the type or interface of that class member.

It’s just syntax sugar, there is no difference between:

var el: HTMLElement = document.getElementById('content');

and:

var el = document.getElementById('content');

On the other hand, because you specify the type you get all the information of your HTMLElement object.

Convert a Unicode string to a string in Python (containing extra symbols)

Here is an example:

>>> u = u'€€€'
>>> s = u.encode('utf8')
>>> s
'\xe2\x82\xac\xe2\x82\xac\xe2\x82\xac'

How to convert List<Integer> to int[] in Java?

No one mentioned yet streams added in Java 8 so here it goes:

int[] array = list.stream().mapToInt(i->i).toArray();
//OR
//int[] array = list.stream().mapToInt(Integer::intValue).toArray();

Thought process:

  • simple Stream#toArray returns Object[], so it is not what we want. Also Stream#toArray(IntFunction<A[]> generator) doesn't do what we want because generic type A can't represent primitive int

  • so it would be nice to have some stream which could handle primitive type int instead of wrapper Integer, because its toArray method will most likely also return int[] array (returning something else like Object[] or even boxed Integer[] would be unnatural here). And fortunately Java 8 has such stream which is IntStream

  • so now only thing we need to figure out is how to convert our Stream<Integer> (which will be returned from list.stream()) to that shiny IntStream. Here Stream#mapToInt(ToIntFunction<? super T> mapper) method comes to a rescue. All we need to do is pass to it mapping from Integer to int. We could use something like Integer#intValue which returns int like :

      mapToInt( (Integer i) -> i.intValue() )  
    

(or if someone prefers mapToInt(Integer::intValue) )

but similar code can be generated using unboxing, since compiler knows that result of this lambda must be int (lambda in mapToInt is implementation of ToIntFunction interface which expects body for int applyAsInt(T value) method which is expected to return int).

So we can simply write

    mapToInt((Integer i)->i)

Also since Integer type in (Integer i) can be inferred by compiler because List<Integer>#stream() returns Stream<Integer> we can also skip it which leaves us with

    mapToInt(i -> i)

HttpWebRequest-The remote server returned an error: (400) Bad Request

400 Bad request Error will be thrown due to incorrect authentication entries.

  1. Check if your API URL is correct or wrong. Don't append or prepend spaces.
  2. Verify that your username and password are valid. Please check any spelling mistake(s) while entering.

Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.

How to remove white space characters from a string in SQL Server

Looks like the invisible character -

ALT+255

Try this

select REPLACE(ProductAlternateKey, ' ', '@')
--type ALT+255 instead of space for the second expression in REPLACE 
from DimProducts
where ProductAlternateKey  like '46783815%'

Raj

Edit: Based on ASCII() results, try ALT+10 - use numeric keypad

default select option as blank

Try this:

<h2>Favorite color</h2>
<select name="color">
<option value=""></option>
<option>Pink</option>
<option>Red</option>
<option>Blue</option>
</select>

The first option in the drop down would be blank.

Putting -moz-available and -webkit-fill-available in one width (css property)

I needed my ASP.NET drop down list to take up all available space, and this is all I put in the CSS and it is working in Firefox and IE11:

width: 100%

I had to add the CSS class into the asp:DropDownList element

Eclipse Optimize Imports to Include Static Imports

Eclipse 3.4 has a Favourites section under Window->Preferences->Java->Editor->Content Assist

If you use org.junit.Assert a lot, you might find some value to adding it there.

How to cancel an $http request in AngularJS?

For some reason config.timeout doesn't work for me. I used this approach:

_x000D_
_x000D_
let cancelRequest = $q.defer();_x000D_
let cancelPromise = cancelRequest.promise;_x000D_
_x000D_
let httpPromise = $http.get(...);_x000D_
_x000D_
$q.race({ cancelPromise, httpPromise })_x000D_
    .then(function (result) {_x000D_
..._x000D_
});
_x000D_
_x000D_
_x000D_

And cancelRequest.resolve() to cancel. Actually it doesn't not cancel a request but you don't get unnecessary response at least.

Hope this helps.

How to access a dictionary key value present inside a list?

To get all the values from a list of dictionaries, use the following code :

list = [{'text': 1, 'b': 2}, {'text': 3, 'd': 4}, {'text': 5, 'f': 6}]
subtitle=[]
for value in list:
   subtitle.append(value['text'])

Replacing NULL and empty string within Select statement

Sounds like you want a view instead of altering actual table data.

Coalesce(NullIf(rtrim(Address.Country),''),'United States')

This will force your column to be null if it is actually an empty string (or blank string) and then the coalesce will have a null to work with.

C++ - How to append a char to char*?

The specific problem is that you're declaring a new variable instead of assigning to an existing one:

char * ret = new char[strlen(array) + 1 + 1];
^^^^^^ Remove this

and trying to compare string values by comparing pointers:

if (array!="")     // Wrong - compares pointer with address of string literal
if (array[0] == 0) // Better - checks for empty string

although there's no need to make that comparison at all; the first branch will do the right thing whether or not the string is empty.

The more general problem is that you're messing around with nasty, error-prone C-style string manipulation in C++. Use std::string and it will manage all the memory allocation for you:

std::string appendCharToString(std::string const & s, char a) {
    return s + a;
}

Trying to retrieve first 5 characters from string in bash error?

You were so close! Here is the easiest solution: NEWTESTSTRING=$(echo ${TESTSTRINGONE::5})

So for your example:

$ TESTSTRINGONE="MOTEST"
$ NEWTESTSTRING=$(echo ${TESTSTRINGONE::5})
$ echo $NEWTESTSTRING
MOTES

How to get the latest tag name in current branch in Git?

To get the latest tag only on the current branch/tag name that prefixes with current branch, I had to execute the following

BRANCH=`git rev-parse --abbrev-ref HEAD` && git describe --tags --abbrev=0 $BRANCH^ | grep $BRANCH

Branch master:

git checkout master

BRANCH=`git rev-parse --abbrev-ref HEAD` && git describe --tags 
--abbrev=0 $BRANCH^ | grep $BRANCH

master-1448

Branch custom:

git checkout 9.4

BRANCH=`git rev-parse --abbrev-ref HEAD` && git describe --tags 
--abbrev=0 $BRANCH^ | grep $BRANCH

9.4-6

And my final need to increment and get the tag +1 for next tagging.

BRANCH=`git rev-parse --abbrev-ref HEAD` && git describe --tags  --abbrev=0 $BRANCH^ | grep $BRANCH | awk -F- '{print $NF}'

How to position two elements side by side using CSS

You can float the elements (the map wrapper, and the paragraph), or use inline-block on both of them.

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

it means ONLY one byte will be allocated per character - so if you're using multi-byte charsets, your 1 character won't fit

if you know you have to have at least room enough for 1 character, don't use the BYTE syntax unless you know exactly how much room you'll need to store that byte

when in doubt, use VARCHAR2(1 CHAR)

same thing answered here Difference between BYTE and CHAR in column datatypes

Also, in 12c the max for varchar2 is now 32k, not 4000. If you need more than that, use CLOB

in Oracle, don't use VARCHAR

To draw an Underline below the TextView in Android

In Kotlin you can create extension property:

inline var TextView.underline: Boolean
    set(visible) {
        paintFlags = if (visible) paintFlags or Paint.UNDERLINE_TEXT_FLAG
        else paintFlags and Paint.UNDERLINE_TEXT_FLAG.inv()
    }
    get() = paintFlags and Paint.UNDERLINE_TEXT_FLAG == Paint.UNDERLINE_TEXT_FLAG

And use:

textView.underline = true

mysqldump with create database line

The simplest solution is to use option -B or --databases.Then CREATE database command appears in the output file. For example:

mysqldump -uuser -ppassword -d -B --events --routines --triggers database_example > database_example.sql

Here is a dumpfile's header:

-- MySQL dump 10.13  Distrib 5.5.36-34.2, for Linux (x86_64)
--
-- Host: localhost    Database: database_example
-- ------------------------------------------------------
-- Server version       5.5.36-34.2-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Current Database: `database_example`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `database_example` /*!40100 DEFAULT CHARACTER SET utf8 */;

Tuples( or arrays ) as Dictionary keys in C#

The good, clean, fast, easy and readable ways is:

  • generate equality members (Equals() and GetHashCode()) method for the current type. Tools like ReSharper not only creates the methods, but also generates the necessary code for an equality check and/or for calculating hash code. The generated code will be more optimal than Tuple realization.
  • just make a simple key class derived from a tuple.

add something similar like this:

public sealed class myKey : Tuple<TypeA, TypeB, TypeC>
{
    public myKey(TypeA dataA, TypeB dataB, TypeC dataC) : base (dataA, dataB, dataC) { }

    public TypeA DataA => Item1; 

    public TypeB DataB => Item2;

    public TypeC DataC => Item3;
}

So you can use it with dictionary:

var myDictinaryData = new Dictionary<myKey, string>()
{
    {new myKey(1, 2, 3), "data123"},
    {new myKey(4, 5, 6), "data456"},
    {new myKey(7, 8, 9), "data789"}
};
  • You also can use it in contracts
  • as a key for join or groupings in linq
  • going this way you never ever mistype order of Item1, Item2, Item3 ...
  • you no need to remember or look into to code to understand where to go to get something
  • no need to override IStructuralEquatable, IStructuralComparable, IComparable, ITuple they all alredy here

Bootstrap collapse animation not smooth

Adding to @CR Rollyson answer,

In case if you have a collapsible div which has a min-height attribute, it will also cause the jerking. Try removing that attribute from directly collapsible div. Use it in the child div of the collapsible div.

<div class="form-group">
    <a for="collapseOne" data-toggle="collapse" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">+ Not Jerky</a>
    <div class="collapse" id="collapseOne" style="padding: 0;">
        <textarea class="form-control" rows="4" style="padding: 20px;">No padding on animated element. Padding on child.</textarea>
    </div>
</div>

Fiddle

How can I run a program from a batch file without leaving the console open after the program starts?

Look at the START command, you can do this:

START rest-of-your-program-name

For instance, this batch-file will wait until notepad exits:

@echo off
notepad c:\test.txt

However, this won't:

@echo off
start notepad c:\test.txt

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

As other answers mentioned, Docker's default local bridge network only supports 30 different networks (each one of them uniquely identifiable by their name). If you are not using them, then docker network prune will do the trick.

However, you might be interested in establishing more than 30 containers, each with their own network. Were you interested in doing so then you would need to define an overlay network. This is a bit more tricky but extremely well documented here.

EDIT (May 2020): Link has become unavailable, going through the docs there's not an exact replacement, but I would recommend starting from here.

How to implement and do OCR in a C# project?

Here's one: (check out http://hongouru.blogspot.ie/2011/09/c-ocr-optical-character-recognition.html or http://www.codeproject.com/Articles/41709/How-To-Use-Office-2007-OCR-Using-C for more info)

using MODI;
static void Main(string[] args)
{
    DocumentClass myDoc = new DocumentClass();
    myDoc.Create(@"theDocumentName.tiff"); //we work with the .tiff extension
    myDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, true, true);

    foreach (Image anImage in myDoc.Images)
    {
        Console.WriteLine(anImage.Layout.Text); //here we cout to the console.
    }
}

"NoClassDefFoundError: Could not initialize class" error

NoClassDefFound error is a nebulous error and is often hiding a more serious issue. It is not the same as ClassNotFoundException (which is thrown when the class is just plain not there).

NoClassDefFound may indicate the class is not there, as the javadocs indicate, but it is typically thrown when, after the classloader has loaded the bytes for the class and calls "defineClass" on them. Also carefully check your full stack trace for other clues or possible "cause" Exceptions (though your particular backtrace shows none).

The first place to look when you get a NoClassDefFoundError is in the static bits of your class i.e. any initialization that takes place during the defining of the class. If this fails it will throw a NoClassDefFoundError - it's supposed to throw an ExceptionInInitializerError and indicate the details of the problem but in my experience, these are rare. It will only do the ExceptionInInitializerError the first time it tries to define the class, after that it will just throw NoClassDefFound. So look at earlier logs.

I would thus suggest looking at the code in that HibernateTransactionInterceptor line and seeing what it is requiring. It seems that it is unable to define the class SpringFactory. So maybe check the initialization code in that class, that might help. If you can debug it, stop it at the last line above (17) and debug into so you can try find the exact line that is causing the exception. Also check higher up in the log, if you very lucky there might be an ExceptionInInitializerError.

Get file name from a file location in Java

From Apache Commons IO FileNameUtils

String fileName = FilenameUtils.getName(stringNameWithPath);

What is an API key?

Very generally speaking:

An API key simply identifies you.

If there is a public/private distinction, then the public key is one that you can distribute to others, to allow them to get some subset of information about you from the api. The private key is for your use only, and provides access to all of your data.

Run Button is Disabled in Android Studio

If you have changed jdk version then go to File->Project Structure->Select SDK Location from left bar->update JDK Location in editbar in right bar.

How to set String's font size, style in Java using the Font class?

Font myFont = new Font("Serif", Font.BOLD, 12);, then use a setFont method on your components like

JButton b = new JButton("Hello World");
b.setFont(myFont);

How to change fonts in matplotlib (python)?

You can also use rcParams to change the font family globally.

 import matplotlib.pyplot as plt
 plt.rcParams["font.family"] = "cursive"
 # This will change to your computer's default cursive font

The list of matplotlib's font family arguments is here.

jQueryUI modal dialog does not show close button (x)

I had the same issue just add this function to the open dialog options and it worked sharm

open: function(){
            var closeBtn = $('.ui-dialog-titlebar-close');
            closeBtn.append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span>');
        },

and on close event you need to remove that

close: function () {
            var closeBtn = $('.ui-dialog-titlebar-close');
            closeBtn.html('');}

Complete example

<div id="deleteDialog" title="Confirm Delete">
 Can you confirm you want to delete this event?
</div> 

$("#deleteDialog").dialog({
                width: 400, height: 200,
                modal: true,
                open: function () {
                    var closeBtn = $('.ui-dialog-titlebar-close');
                    closeBtn.append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span>');
                },
                close: function () {
                    var closeBtn = $('.ui-dialog-titlebar-close');
                    closeBtn.html('');
                },
                buttons: {
                    "Confirm": function () {
                        calendar.fullCalendar('removeEvents', event._id);
                        $(this).dialog("close");
                    },
                    "Cancel": function () {
                        $(this).dialog("close");
                    }
                }
            });

            $("#dialog").dialog("open");

React Native TextInput that only accepts numeric characters

Only allow numbers using a regular expression

<TextInput 
  keyboardType = 'numeric'
  onChangeText = {(e)=> this.onTextChanged(e)}
  value = {this.state.myNumber}
/> 

onTextChanged(e) {
  if (/^\d+$/.test(e.toString())) { 
    this.setState({ myNumber: e });
  }
}

You might want to have more than one validation


<TextInput 
  keyboardType = 'numeric'
  onChangeText = {(e)=> this.validations(e)}
  value = {this.state.myNumber}
/> 

numbersOnly(e) {
    return /^\d+$/.test(e.toString()) ? true : false
}

notZero(e) {
    return /0/.test(parseInt(e)) ? false : true
}

validations(e) {
    return this.notZero(e) && this.numbersOnly(e)
        ? this.setState({ numColumns: parseInt(e) })
        : false
}

How to install sshpass on mac?

Some years have passed and there is now a proper Homebrew Tap for sshpass, maintained by Aleks Hudochenkov. To install sshpass from this tap, run:

brew install hudochenkov/sshpass/sshpass

String compare in Perl with "eq" vs "=="

First, eq is for comparing strings; == is for comparing numbers.

Even if the "if" condition is satisfied, it doesn't evaluate the "then" block.

I think your problem is that your variables don't contain what you think they do. I think your $str1 or $str2 contains something like "taste\n" or so. Check them by printing before your if: print "str1='$str1'\n";.

The trailing newline can be removed with the chomp($str1); function.

How link to any local file with markdown syntax?

If you have spaces in the filename, try these:

[file](./file%20with%20spaces.md)
[file](<./file with spaces.md>)

First one seems more reliable

How to set text color to a text view programmatically

Use,..

Color.parseColor("#bdbdbd");

like,

mTextView.setTextColor(Color.parseColor("#bdbdbd"));

Or if you have defined color code in resource's color.xml file than

(From API >= 23)

mTextView.setTextColor(ContextCompat.getColor(context, R.color.<name_of_color>));

(For API < 23)

mTextView.setTextColor(getResources().getColor(R.color.<name_of_color>));

How to add hyperlink in JLabel?

You can use this under an

actionListener ->  Runtime.getRuntime().exec("cmd.exe /c start chrome www.google.com")`

or if you want to use Internet Explorer or Firefox replace chrome with iexplore or firefox

Disable automatic sorting on the first column when using jQuery DataTables

Use this simple code for DataTables custom sorting. Its 100% work

<script>
    $(document).ready(function() {
        $('#myTable').DataTable( {
            "order": [[ 0, "desc" ]] // "0" means First column and "desc" is order type; 
        } );
    } );
</script>


See in Datatables website

https://datatables.net/examples/basic_init/table_sorting.html

How to get the function name from within that function?

You could use this, for browsers that support Error.stack (not nearly all, probably)

function WriteSomeShitOut(){ 
  var a = new Error().stack.match(/at (.*?) /);
  console.log(a[1]);
} 
WriteSomeShitOut();

of course this is for the current function, but you get the idea.

happy drooling while you code

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.

HashSet vs LinkedHashSet

All Methods and constructors are same but only one difference is LinkedHashset will maintain insertion order but it will not allow duplicates.

Hashset will not maintain any insertion order. It is combination of List and Set simple :)

Git 'fatal: Unable to write new index file'

I had the same problem. I restarted my computer and the issue was resolved.

Change priorityQueue to max priorityqueue

PriorityQueue<Integer> pq = new PriorityQueue<Integer> (
  new Comparator<Integer> () {
    public int compare(Integer a, Integer b) {
       return b - a;
    }
  }
);

Play local (hard-drive) video file with HTML5 video tag?

That will be possible only if the HTML file is also loaded with the file protocol from the local user's harddisk.

If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src attribute with the file:// protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.

As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.

Resize background image in div using css

With the background-size property in those browsers which support this very new feature of CSS.

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

You can build it manually:

var m = new Date();
var dateString = m.getUTCFullYear() +"/"+ (m.getUTCMonth()+1) +"/"+ m.getUTCDate() + " " + m.getUTCHours() + ":" + m.getUTCMinutes() + ":" + m.getUTCSeconds();

and to force two digits on the values that require it, you can use something like this:

("0000" + 5).slice(-2)

Which would look like this:

_x000D_
_x000D_
var m = new Date();_x000D_
var dateString =_x000D_
    m.getUTCFullYear() + "/" +_x000D_
    ("0" + (m.getUTCMonth()+1)).slice(-2) + "/" +_x000D_
    ("0" + m.getUTCDate()).slice(-2) + " " +_x000D_
    ("0" + m.getUTCHours()).slice(-2) + ":" +_x000D_
    ("0" + m.getUTCMinutes()).slice(-2) + ":" +_x000D_
    ("0" + m.getUTCSeconds()).slice(-2);_x000D_
_x000D_
console.log(dateString);
_x000D_
_x000D_
_x000D_

Automatically open Chrome developer tools when new tab/new window is opened

If you use Visual Studio Code (vscode), using the very popular vscode chrome debug extension (https://github.com/Microsoft/vscode-chrome-debug) you can setup a launch configuration file launch.json and specify to open the developer tool during a debug session.

This the launch.json I use for my React projects :

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "chrome",
      "request": "launch",
      "name": "Launch Chrome against localhost",
      "url": "http://localhost:3000",
      "runtimeArgs": ["--auto-open-devtools-for-tabs"],
      "webRoot": "${workspaceRoot}/src"
    }
  ]
}

The important line is "runtimeArgs": ["--auto-open-devtools-for-tabs"],

From vscode you can now type F5, Chrome opens your app and the console tab as well.

How can I specify the required Node.js version in package.json?

A Mocha test case example:

describe('Check version of node', function () {
    it('Should test version assert', async function () {

            var version = process.version;
            var check = parseFloat(version.substr(1,version.length)) > 12.0;
            console.log("version: "+version);
            console.log("check: " +check);         
            assert.equal(check, true);
    });});

How to install SQL Server Management Studio 2008 component only

If you have the SQL Server 2008 Installation media, you can install just the Client/Workstation Components. You don't have to install the database engine to install the workstation tools, but if you plan to do Integration Services development, you do need to install the Integration Services Engine on the workstation for BIDS to be able to be used for development. Keep in mind that Visual Studio 2010 does not have BI development support currently, so you have to install BIDS from the SQL Installation media and use the Visual Studio 2008 BI Development Studio that installs under the SQL Server 2008 folder in Program Files if you need to do any SSIS, SSRS, or SSAS development from the workstation.

As mentioned in the comments you can download Management Studio Express free from Microsoft, but if you already have the installation media for SQL Server Standard/Enterprise/Developer edition, you'd be better off using what you have.

Download SSMS 2008 Express

Finishing current activity from a fragment

Well actually...

I wouldn't have the Fragment try to finish the Activity. That places too much authority on the Fragment in my opinion. Instead, I would use the guide here: http://developer.android.com/training/basics/fragments/communicating.html

Have the Fragment define an interface which the Activity must implement. Make a call up to the Activity, then let the Activity decide what to do with the information. If the activity wishes to finish itself, then it can.

How to "perfectly" override a dict?

You can write an object that behaves like a dict quite easily with ABCs (Abstract Base Classes) from the collections.abc module. It even tells you if you missed a method, so below is the minimal version that shuts the ABC up.

from collections.abc import MutableMapping


class TransformedDict(MutableMapping):
    """A dictionary that applies an arbitrary key-altering
       function before accessing the keys"""

    def __init__(self, *args, **kwargs):
        self.store = dict()
        self.update(dict(*args, **kwargs))  # use the free update to set keys

    def __getitem__(self, key):
        return self.store[self._keytransform(key)]

    def __setitem__(self, key, value):
        self.store[self._keytransform(key)] = value

    def __delitem__(self, key):
        del self.store[self._keytransform(key)]

    def __iter__(self):
        return iter(self.store)
    
    def __len__(self):
        return len(self.store)

    def _keytransform(self, key):
        return key

You get a few free methods from the ABC:

class MyTransformedDict(TransformedDict):

    def _keytransform(self, key):
        return key.lower()


s = MyTransformedDict([('Test', 'test')])

assert s.get('TEST') is s['test']   # free get
assert 'TeSt' in s                  # free __contains__
                                    # free setdefault, __eq__, and so on

import pickle
# works too since we just use a normal dict
assert pickle.loads(pickle.dumps(s)) == s

I wouldn't subclass dict (or other builtins) directly. It often makes no sense, because what you actually want to do is implement the interface of a dict. And that is exactly what ABCs are for.

Formatting numbers (decimal places, thousands separators, etc) with CSS

No, you have to use javascript once it's in the DOM or format it via your language server-side (PHP/ruby/python etc.)

Formatting struct timespec

I wanted to ask the same question. Here is my current solution to obtain a string like this: 2013-02-07 09:24:40.749355372 I am not sure if there is a more straight forward solution than this, but at least the string format is freely configurable with this approach.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define NANO 1000000000L

// buf needs to store 30 characters
int timespec2str(char *buf, uint len, struct timespec *ts) {
    int ret;
    struct tm t;

    tzset();
    if (localtime_r(&(ts->tv_sec), &t) == NULL)
        return 1;

    ret = strftime(buf, len, "%F %T", &t);
    if (ret == 0)
        return 2;
    len -= ret - 1;

    ret = snprintf(&buf[strlen(buf)], len, ".%09ld", ts->tv_nsec);
    if (ret >= len)
        return 3;

    return 0;
}

int main(int argc, char **argv) {
    clockid_t clk_id = CLOCK_REALTIME;
    const uint TIME_FMT = strlen("2012-12-31 12:59:59.123456789") + 1;
    char timestr[TIME_FMT];

    struct timespec ts, res;
    clock_getres(clk_id, &res);
    clock_gettime(clk_id, &ts);

    if (timespec2str(timestr, sizeof(timestr), &ts) != 0) {
        printf("timespec2str failed!\n");
        return EXIT_FAILURE;
    } else {
        unsigned long resol = res.tv_sec * NANO + res.tv_nsec;
        printf("CLOCK_REALTIME: res=%ld ns, time=%s\n", resol, timestr);
        return EXIT_SUCCESS;
    }
}

output:

gcc mwe.c -lrt 
$ ./a.out 
CLOCK_REALTIME: res=1 ns, time=2013-02-07 13:41:17.994326501

How to make bootstrap 3 fluid layout without horizontal scrollbar

It's already fluid by default. If you want to be fluid for less width instead of col-md-6 use col-sm-6 or col-xs-6.

How can I use a DLL file from Python?

For ease of use, ctypes is the way to go.

The following example of ctypes is from actual code I've written (in Python 2.5). This has been, by far, the easiest way I've found for doing what you ask.

import ctypes

# Load DLL into memory.

hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll")

# Set up prototype and parameters for the desired function call.
# HLLAPI

hllApiProto = ctypes.WINFUNCTYPE (
    ctypes.c_int,      # Return type.
    ctypes.c_void_p,   # Parameters 1 ...
    ctypes.c_void_p,
    ctypes.c_void_p,
    ctypes.c_void_p)   # ... thru 4.
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0),

# Actually map the call ("HLLAPI(...)") to a Python name.

hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)

# This is how you can actually call the DLL function.
# Set up the variables and call the Python name with them.

p1 = ctypes.c_int (1)
p2 = ctypes.c_char_p (sessionVar)
p3 = ctypes.c_int (1)
p4 = ctypes.c_int (0)
hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))

The ctypes stuff has all the C-type data types (int, char, short, void*, and so on) and can pass by value or reference. It can also return specific data types although my example doesn't do that (the HLL API returns values by modifying a variable passed by reference).


In terms of the specific example shown above, IBM's EHLLAPI is a fairly consistent interface.

All calls pass four void pointers (EHLLAPI sends the return code back through the fourth parameter, a pointer to an int so, while I specify int as the return type, I can safely ignore it) as per IBM's documentation here. In other words, the C variant of the function would be:

int hllApi (void *p1, void *p2, void *p3, void *p4)

This makes for a single, simple ctypes function able to do anything the EHLLAPI library provides, but it's likely that other libraries will need a separate ctypes function set up per library function.

The return value from WINFUNCTYPE is a function prototype but you still have to set up more parameter information (over and above the types). Each tuple in hllApiParams has a parameter "direction" (1 = input, 2 = output and so on), a parameter name and a default value - see the ctypes doco for details

Once you have the prototype and parameter information, you can create a Python "callable" hllApi with which to call the function. You simply create the needed variable (p1 through p4 in my case) and call the function with them.

How to increase the vertical split window size in Vim

CTRL-W >

and

CTRL-W <

to make the window wider or narrower.

How can I remove specific rules from iptables?

Execute the same commands but replace the "-A" with "-D". For example:

iptables -A ...

becomes

iptables -D ...

How to get String Array from arrays.xml file

Your array.xml is not right. change it to like this

Here is array.xml file

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <string-array name="testArray">  
        <item>first</item>  
        <item>second</item>  
        <item>third</item>  
        <item>fourth</item>  
        <item>fifth</item>  
   </string-array>
</resources>

MVVM: Tutorial from start to finish?

Some blogs/websites to check out:

Currently, Josh Smith has a "From Russia With Love" article that can be of some use to you.

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

If you need to write line by line from string builder

StringBuilder sb = new StringBuilder();
sb.AppendLine("New Line!");

using (var sw = new StreamWriter(@"C:\MyDir\MyNewTextFile.txt", true))
{
   sw.Write(sb.ToString());
}

If you need to write all text as single line from string builder

StringBuilder sb = new StringBuilder();
sb.Append("New Text line!");

using (var sw = new StreamWriter(@"C:\MyDir\MyNewTextFile.txt", true))
{
   sw.Write(sb.ToString());
}

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

function converToLocalTime(serverDate) {

    var dt = new Date(Date.parse(serverDate));
    var localDate = dt;
    
    var gmt = localDate;
        var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
        var localNow = new Date().getTimezoneOffset(); // get the timezone
        // offset in minutes
        var localTime = min - localNow; // get the local time

    var dateStr = new Date(localTime * 1000 * 60);
    // dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
    dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    return dateStr;
}

jquery .on() method with load event

To run function onLoad

jQuery(window).on("load", function(){
    ..code..
});

To run code onDOMContentLoaded (also called onready)

jQuery(document).ready(function(){
    ..code..
});

or the recommended shorthand for onready

jQuery(function($){
    ..code.. ($ is the jQuery object)
});

onready fires when the document has loaded

onload fires when the document and all the associated content, like the images on the page have loaded.

Difference between Hashing a Password and Encrypting it

I've always thought that Encryption can be converted both ways, in a way that the end value can bring you to original value and with Hashing you'll not be able to revert from the end result to the original value.

[ :Unexpected operator in shell programming

you can use case/esac instead of if/else

case "$choose" in
  [yY]) echo "Yes" && exit;;
  [nN]) echo "No" && exit;;
  * ) echo "wrong input" && exit;;
esac

How do you divide each element in a list by an int?

myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [i/myInt for i in myList]

What's the difference between ngOnInit and ngAfterViewInit of Angular2?

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

ngAfterViewInit() is called after a component's view, and its children's views, are created. Its a lifecycle hook that is called after a component's view has been fully initialized.

Bootstrap with jQuery Validation Plugin

this is the solution you need, you can use the errorPlacement method to override where to put the error message

$('form').validate({
    rules: {
        firstname: {
            minlength: 3,
            maxlength: 15,
            required: true
        },
        lastname: {
            minlength: 3,
            maxlength: 15,
            required: true
        }
    },
    errorPlacement: function(error, element) {
        error.insertAfter('.form-group'); //So i putted it after the .form-group so it will not include to your append/prepend group.
    }, 
    highlight: function(element) {
        $(element).closest('.form-group').addClass('has-error');
    },
    unhighlight: function(element) {
        $(element).closest('.form-group').removeClass('has-error');
    }
});

it's works for me like magic. Cheers

Update only specific fields in a models.Model

To update a subset of fields, you can use update_fields:

survey.save(update_fields=["active"]) 

The update_fields argument was added in Django 1.5. In earlier versions, you could use the update() method instead:

Survey.objects.filter(pk=survey.pk).update(active=True)

How to capitalize the first letter of word in a string using Java?

If you only want to capitalize the first letter of a string named input and leave the rest alone:

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

Now output will have what you want. Check that your input is at least one character long before using this, otherwise you'll get an exception.

Use a URL to link to a Google map with a marker on it

This format works, but it doesn't seem to be an official way of doing so

http://maps.google.com/maps?q=loc:36.26577,-92.54324

Also you may want to take a look at this. They have a few answers and seem to indicate that this is the new method:

http://maps.google.com/maps?&z=10&q=36.26577+-92.54324&ll=36.26577+-92.54324

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

As mentioned in the comments, the Starting Guide is the place to start with Java 11 and JavaFX 11.

The key to work as you did before Java 11 is to understand that:

  • JavaFX 11 is not part of the JDK anymore
  • You can get it in different flavors, either as an SDK or as regular dependencies (maven/gradle).
  • You will need to include it to the module path of your project, even if your project is not modular.

JavaFX project

If you create a regular JavaFX default project in IntelliJ (without Maven or Gradle) I'd suggest you download the SDK from here. Note that there are jmods as well, but for a non modular project the SDK is preferred.

These are the easy steps to run the default project:

  1. Create a JavaFX project
  2. Set JDK 11 (point to your local Java 11 version)
  3. Add the JavaFX 11 SDK as a library. The URL could be something like /Users/<user>/Downloads/javafx-sdk-11/lib/. Once you do this you will notice that the JavaFX classes are now recognized in the editor.

JavaFX 11 Project

  1. Before you run the default project, you just need to add these to the VM options:

    --module-path /Users/<user>/Downloads/javafx-sdk-11/lib --add-modules=javafx.controls,javafx.fxml

  2. Run

Maven

If you use Maven to build your project, follow these steps:

  1. Create a Maven project with JavaFX archetype
  2. Set JDK 11 (point to your local Java 11 version)
  3. Add the JavaFX 11 dependencies.

    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>11</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>11</version>
        </dependency>
    </dependencies>
    

Once you do this you will notice that the JavaFX classes are now recognized in the editor.

JavaFX 11 Maven project

You will notice that Maven manages the required dependencies for you: it will add javafx.base and javafx.graphics for javafx.controls, but most important, it will add the required classifier based on your platform. In my case, Mac.

This is why your jars org.openjfx:javafx-controls:11 are empty, because there are three possible classifiers (windows, linux and mac platforms), that contain all the classes and the native implementation.

In case you still want to go to your .m2 repo and take the dependencies from there manually, make sure you pick the right one (for instance .m2/repository/org/openjfx/javafx-controls/11/javafx-controls-11-mac.jar)

  1. Replace default maven plugins with those from here.

  2. Run mvn compile javafx:run, and it should work.

Similar works as well for Gradle projects, as explained in detail here.

EDIT

The mentioned Getting Started guide contains updated documentation and sample projects for IntelliJ:

hash function for string

One thing I've used with good results is the following (I don't know if its mentioned already because I can't remember its name).

You precompute a table T with a random number for each character in your key's alphabet [0,255]. You hash your key 'k0 k1 k2 ... kN' by taking T[k0] xor T[k1] xor ... xor T[kN]. You can easily show that this is as random as your random number generator and its computationally very feasible and if you really run into a very bad instance with lots of collisions you can just repeat the whole thing using a fresh batch of random numbers.

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

Just like to contribute that the above answers of :not() can be very effective in angular forms, rather than creating effects or adjusting the view/DOM,

input.ng-invalid:not(.ng-pristine) { ... your css here i.e. border-color: red; ...}

Ensures that on loading your page, the input fields will only show the invalid (red borders or backgrounds, etc) if they have data added (i.e. no longer pristine) but are invalid.

C++, copy set to vector

I think the most efficient way is to preallocate and then emplace elements:

template <typename T>
std::vector<T> VectorFromSet(const std::set<T>& from)
{
    std::vector<T> to;
    to.reserve(from.size());

    for (auto const& value : from)
        to.emplace_back(value);

    return to;
}

That way we will only invoke copy constructor for every element as opposed to calling default constructor first and then copy assignment operator for other solutions listed above. More clarifications below.

  1. back_inserter may be used but it will invoke push_back() on the vector (https://en.cppreference.com/w/cpp/iterator/back_insert_iterator). emplace_back() is more efficient because it avoids creating a temporary when using push_back(). It is not a problem with trivially constructed types but will be a performance implication for non-trivially constructed types (e.g. std::string).

  2. We need to avoid constructing a vector with the size argument which causes all elements default constructed (for nothing). Like with solution using std::copy(), for instance.

  3. And, finally, vector::assign() method or the constructor taking the iterator range are not good options because they will invoke std::distance() (to know number of elements) on set iterators. This will cause unwanted additional iteration through the all set elements because the set is Binary Search Tree data structure and it does not implement random access iterators.

Hope that helps.

How to upgrade Git on Windows to the latest version?

Update Git Through Command Prompt

  1. Check Version git --version

  2. If your git version is 2.27.0.windows.1 or earlier

  3. If the version is equal to or greater than Git 2.27.0.windows.1

  4. Use command git update-git-for-windows

if you want to video tutorial click here

A Simple AJAX with JSP example

You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:

var config=document.getElementsByName('configselect').value;

because you have declared only the name attribute in your <select> tag. So you should get this element by name.

After correcting this, it will run without any JavaScript error

plot data from CSV file with matplotlib

According to the docs numpy.loadtxt is

a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.

so there are only a few options to handle more complicated files. As mentioned numpy.genfromtxt has more options. So as an example you could use

import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
                     skip_footer=10, names=['x', 'y', 'z'])

to read the data and assign names to the columns (or read a header line from the file with names=True) and than plot it with

ax1.plot(data['x'], data['y'], color='r', label='the data')

I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython or by using an IDE like spider if you prefer to read them rendered as HTML.

Callback when DOM is loaded in react.js

Looks like a combination of componentDidMount and componentDidUpdate will get the job done. The first is called after the initial rendering, when the DOM is available, the second is called after any subsequent renderings, once the updated DOM is available. In my case, I both have them delegate to a common function to do the same thing.

load json into variable

  • this will get JSON file externally to your javascript variable.
  • now this sample_data will contain the values of JSON file.

var sample_data = '';
$.getJSON("sample.json", function (data) {
    sample_data = data;
    $.each(data, function (key, value) {
        console.log(sample_data);
    });
});

Getting the thread ID from a thread

To get the OS ID use:

AppDomain.GetCurrentThreadId()

Regular expression negative lookahead

A negative lookahead says, at this position, the following regex can not match.

Let's take a simplified example:

a(?!b(?!c))

a      Match: (?!b) succeeds
ac     Match: (?!b) succeeds
ab     No match: (?!b(?!c)) fails
abe    No match: (?!b(?!c)) fails
abc    Match: (?!b(?!c)) succeeds

The last example is a double negation: it allows a b followed by c. The nested negative lookahead becomes a positive lookahead: the c should be present.

In each example, only the a is matched. The lookahead is only a condition, and does not add to the matched text.

Attach a file from MemoryStream to a MailMessage in C#

I landed on this question because I needed to attach an Excel file I generate through code and is available as MemoryStream. I could attach it to the mail message but it was sent as 64Bytes file instead of a ~6KB as it was meant. So, the solution that worked for me was this:

MailMessage mailMessage = new MailMessage();
Attachment attachment = new Attachment(myMemorySteam, new ContentType(MediaTypeNames.Application.Octet));

attachment.ContentDisposition.FileName = "myFile.xlsx";
attachment.ContentDisposition.Size = attachment.Length;

mailMessage.Attachments.Add(attachment);

Setting the value of attachment.ContentDisposition.Size let me send messages with the correct size of attachment.

C++ IDE for Macs

Another (albeit non-free) option is to install VMware Fusion or Parallels Desktop on the Mac and run Windows with Visual Studio in a VM.

This works really pretty well. The downsides are:

  • it'll cost money for the virtual machine software and Windows (the school may have some academic licensing that may help here)
  • the Mac needs to be an x86 Mac with a fair bit of memory

The upside is that you and the student don't need to hassle with differences in the IDE that may not be accounted for in your instruction materials.

Print PHP Call Stack

please take a look at this utils class, may be helpful:

Usage:

<?php
/* first caller */
 Who::callme();

/* list the entire list of calls */
Who::followme();

Source class: https://github.com/augustowebd/utils/blob/master/Who.php

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

I had received a similar error message. Think I inadvertently typed "9o" at start of first line of php.ini file. Once I removed that, I no longer received the "fatal error" messages. Hope this helps.

Undefined symbols for architecture x86_64 on Xcode 6.1

Check if that file is included in Build Phases -> Compiled Sources

How do I set a VB.Net ComboBox default value

OR

you can write this down in your program

Private Sub ComboBoxExp_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles MyBase.Load
    AlarmHourSelect.Text = "YOUR DEFAULT VALUE"
    AlarmMinuteSelect.Text = "YOUR DEFAULT VALUE"
End Sub

so when you start your program, the first thing it would do is set it on your assigned default value and later you can easily select your required option from the drop down list. also keeping the DropDownStyle to DropDownList would make it look more cooler.

-Starkternate

Printing all global variables/local variables?

In addition, since info locals does not display the arguments to the function you're in, use

(gdb) info args

For example:

int main(int argc, char *argv[]) {
    argc = 6*7;    //Break here.
    return 0;
}

argc and argv won't be shown by info locals. The message will be "No locals."

Reference: info locals command.

What is the difference between decodeURIComponent and decodeURI?

To explain the difference between these two let me explain the difference between encodeURI and encodeURIComponent.

The main difference is that:

  • The encodeURI function is intended for use on the full URI.
  • The encodeURIComponent function is intended to be used on .. well .. URI components that is any part that lies between separators (; / ? : @ & = + $ , #).

So, in encodeURIComponent these separators are encoded also because they are regarded as text and not special characters.

Now back to the difference between the decode functions, each function decodes strings generated by its corresponding encode counterpart taking care of the semantics of the special characters and their handling.

How to detect duplicate values in PHP array?

A simple method:

$array = array_values(array_unique($array, SORT_REGULAR));

Do fragments really need an empty constructor?

Here is my simple solution:

1 - Define your fragment

public class MyFragment extends Fragment {

    private String parameter;

    public MyFragment() {
    }

    public void setParameter(String parameter) {
        this.parameter = parameter;
    } 
}

2 - Create your new fragment and populate the parameter

    myfragment = new MyFragment();
    myfragment.setParameter("here the value of my parameter");

3 - Enjoy it!

Obviously you can change the type and the number of parameters. Quick and easy.

Differences between Oracle JDK and OpenJDK

Both OpenJDK and Oracle JDK are created and maintained currently by Oracle only.

OpenJDK and Oracle JDK are implementations of the same Java specification passed the TCK (Java Technology Certification Kit).

Most of the vendors of JDK are written on top of OpenJDK by doing a few tweaks to [mostly to replace licensed proprietary parts / replace with more high-performance items that only work on specific OS] components without breaking the TCK compatibility.

Many vendors implemented the Java specification and got TCK passed. For example, IBM J9, Azul Zulu, Azul Zing, and Oracle JDK.

Almost every existing JDK is derived from OpenJDK.

As suggested by many, licensing is a change between JDKs.

Starting with JDK 11 accessing the long time support Oracle JDK/Java SE will now require a commercial license. You should now pay attention to which JDK you're installing as Oracle JDK without subscription could stop working. source

Ref: List of Java virtual machines

Show constraints on tables command

You can use this:

select
    table_name,column_name,referenced_table_name,referenced_column_name
from
    information_schema.key_column_usage
where
    referenced_table_name is not null
    and table_schema = 'my_database' 
    and table_name = 'my_table'

Or for better formatted output use this:

select
    concat(table_name, '.', column_name) as 'foreign key',  
    concat(referenced_table_name, '.', referenced_column_name) as 'references'
from
    information_schema.key_column_usage
where
    referenced_table_name is not null
    and table_schema = 'my_database' 
    and table_name = 'my_table'

How to check if a string "StartsWith" another string?

Also check out underscore.string.js. It comes with a bunch of useful string testing and manipulation methods, including a startsWith method. From the docs:

startsWith _.startsWith(string, starts)

This method checks whether string starts with starts.

_("image.gif").startsWith("image")
=> true

CSS to select/style first word

There isn't a plain CSS method for this. You might have to go with JavaScript + Regex to pop in a span.

Ideally, there would be a pseudo-element for first-word, but you're out of luck as that doesn't appear to work. We do have :first-letter and :first-line.

You might be able to use a combination of :after or :before to get at it without using a span.

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

I try to get in the habit of using HostingEnvironment instead of Server as it works within the context of WCF services too.

 HostingEnvironment.MapPath(@"~/App_Data/PriceModels.xml");

LaTeX Optional Arguments

I had a similar problem, when I wanted to create a command, \dx, to abbreviate \;\mathrm{d}x (i.e. put an extra space before the differential of the integral and have the "d" upright as well). But then I also wanted to make it flexible enough to include the variable of integration as an optional argument. I put the following code in the preamble.

\usepackage{ifthen}

\newcommand{\dx}[1][]{%
   \ifthenelse{ \equal{#1}{} }
      {\ensuremath{\;\mathrm{d}x}}
      {\ensuremath{\;\mathrm{d}#1}}
}

Then

\begin{document}
   $$\int x\dx$$
   $$\int t\dx[t]$$
\end{document}

gives \dx with optional argument

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:

url:   'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',

to this line:

url: '/path/to/phpscript.php',

and then in the php script (if you have permission to use the file_get_contents() function):

<?php

header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

?>

Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.

Edit: If you want to cache the result in php, here's the php file you would use:

<?php

$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
  $contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
  file_put_contents($cacheName, $contents);
}

$xml = simplexml_load_file($cacheName);

header('Content-type: application/xml');
echo $xml;

?>

Caching code take from here.

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Creating .exe distributions isn't typical for Java. While such wrappers do exist, the normal mode of operation is to create a .jar file.

To create a .jar file from a Java project in Eclipse, use file->export->java->Jar file. This will create an archive with all your classes.

On the command prompt, use invocation like the following:

java -cp myapp.jar foo.bar.MyMainClass

Get value from text area

You need to be using .val() not .value

$(document).ready(function () {
  if ($("textarea").val() != "") {
    alert($("textarea").val());
  }
});

What svn command would list all the files modified on a branch?

You can use the following command:

svn status -q

According to svnbook:

With --quiet (-q), it prints only summary information about locally modified items.

WARNING: The output of this command only shows your modification. So I suggest to do a svn up to get latest version of the file and then use svn status -q to get the files you have modified.

How do I build an import library (.lib) AND a DLL in Visual C++?

By selecting 'Class Library' you were accidentally telling it to make a .Net Library using the CLI (managed) extenstion of C++.

Instead, create a Win32 project, and in the Application Settings on the next page, choose 'DLL'.

You can also make an MFC DLL or ATL DLL from those library choices if you want to go that route, but it sounds like you don't.

jquery UI dialog: how to initialize without a title bar?

This worked for me to hide the dialog box title bar:

$(".ui-dialog-titlebar" ).css("display", "none" );

How to create a template function within a class? (C++)

Your guess is the correct one. The only thing you have to remember is that the member function template definition (in addition to the declaration) should be in the header file, not the cpp, though it does not have to be in the body of the class declaration itself.

xxxxxx.exe is not a valid Win32 application

I got this problem while launching a VS2013 32-bit console application in powershell, launching it in cmd did not issue this problem.

What is the difference between for and foreach?

The major difference between the for and foreach loop in c# we understand by its working:

The for loop:

  1. The for loop's variable always be integer only.
  2. The For Loop executes the statement or block of statements repeatedly until specified expression evaluates to false.
  3. In for loop we have to specify the loop's boundary ( maximum or minimum).-------->We can say this is the limitation of the for loop.

The foreach loop:

  1. In the case of the foreach loop the variable of the loop while be same as the type of values under the array.

  2. The Foreach statement repeats a group of embedded statements for each element in an array or an object collection.

  3. In foreach loop, You do not need to specify the loop bounds minimum or maximum.---> here we can say that this is the advantage of the for each loop.

Count the number occurrences of a character in a string

spam = 'have a nice day'
var = 'd'


def count(spam, var):
    found = 0
    for key in spam:
        if key == var:
            found += 1
    return found
count(spam, var)
print 'count %s is: %s ' %(var, count(spam, var))

Pass entire form as data in jQuery Ajax function

A good jQuery option to do this is through FormData. This method is also suited when sending files through a form!

<form id='test' method='post' enctype='multipart/form-data'>
   <input type='text' name='testinput' id='testinput'>
   <button type='submit'>submit</button>
</form>

Your send function in jQuery would look like this:

$( 'form#test' ).submit( function(){
   var data = new FormData( $( 'form#test' )[ 0 ] );

   $.ajax( {
      processData: false,
      contentType: false,

      data: data,
      dataType: 'json',
      type: $( this ).attr( 'method' );
      url: 'yourapi.php',
      success: function( feedback ){
         console.log( "the feedback from your API: " + feedback );
      }
});

to add data to your form you can either use a hidden input in your form, or you add it on the fly:

var data = new FormData( $( 'form#test' )[ 0 ] );
data.append( 'command', 'value_for_command' );

How to use a findBy method with comparative criteria

$criteria = new \Doctrine\Common\Collections\Criteria();
    $criteria->where($criteria->expr()->gt('id', 'id'))
        ->setMaxResults(1)
        ->orderBy(array("id" => $criteria::DESC));

$results = $articlesRepo->matching($criteria);

Converting any string into camel case

The top answer is terse but it doesn't handle all edge cases. For anyone needing a more robust utility, without any external dependencies:

function camelCase(str) {
    return (str.slice(0, 1).toLowerCase() + str.slice(1))
      .replace(/([-_ ]){1,}/g, ' ')
      .split(/[-_ ]/)
      .reduce((cur, acc) => {
        return cur + acc[0].toUpperCase() + acc.substring(1);
      });
}

function sepCase(str, sep = '-') {
    return str
      .replace(/[A-Z]/g, (letter, index) => {
        const lcLet = letter.toLowerCase();
        return index ? sep + lcLet : lcLet;
      })
      .replace(/([-_ ]){1,}/g, sep)
}

// All will return 'fooBarBaz'
console.log(camelCase('foo_bar_baz'))
console.log(camelCase('foo-bar-baz'))
console.log(camelCase('foo_bar--baz'))
console.log(camelCase('FooBar  Baz'))
console.log(camelCase('FooBarBaz'))
console.log(camelCase('fooBarBaz'))

// All will return 'foo-bar-baz'
console.log(sepCase('fooBarBaz'));
console.log(sepCase('FooBarBaz'));
console.log(sepCase('foo-bar-baz'));
console.log(sepCase('foo_bar_baz'));
console.log(sepCase('foo___ bar -baz'));
console.log(sepCase('foo-bar-baz'));

// All will return 'foo__bar__baz'
console.log(sepCase('fooBarBaz', '__'));
console.log(sepCase('foo-bar-baz', '__'));

Demo here: https://codesandbox.io/embed/admiring-field-dnm4r?fontsize=14&hidenavigation=1&theme=dark

SQLite with encryption/password protection

You can always encrypt data on the client side. Please note that not all of the data have to be encrypted because it has a performance issue.

Change jsp on button click

Just use two forms.

In the first form action attribute will have name of the second jdp page and your 1st button. In the second form there will be 2nd button with action attribute thats giving the name of your 3rd jsp page.

It will be like this :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <form name="main1"  method="get" action="2nd.jsp">
        <input type="submit" name="ter" value="LOGOUT" >
    </form>
    <DIV ALIGN="left"><form name="main0" action="3rd.jsp" method="get">
        <input type="submit" value="FEEDBACK">
    </form></DIV>
</body>
</html>

Difference between CR LF, LF and CR line break types?

CR and LF are control characters, respectively coded 0x0D (13 decimal) and 0x0A (10 decimal).

They are used to mark a line break in a text file. As you indicated, Windows uses two characters the CR LF sequence; Unix only uses LF and the old MacOS ( pre-OSX MacIntosh) used CR.

An apocryphal historical perspective:

As indicated by Peter, CR = Carriage Return and LF = Line Feed, two expressions have their roots in the old typewriters / TTY. LF moved the paper up (but kept the horizontal position identical) and CR brought back the "carriage" so that the next character typed would be at the leftmost position on the paper (but on the same line). CR+LF was doing both, i.e. preparing to type a new line. As time went by the physical semantics of the codes were not applicable, and as memory and floppy disk space were at a premium, some OS designers decided to only use one of the characters, they just didn't communicate very well with one another ;-)

Most modern text editors and text-oriented applications offer options/settings etc. that allow the automatic detection of the file's end-of-line convention and to display it accordingly.

Change <select>'s option and trigger events with JavaScript

Try this:

<select id="sel">
 <option value='1'>One</option>
  <option value='2'>Two</option> 
  <option value='3'>Three</option> 
  </select> 


  <input type="button" value="Change option to 2"  onclick="changeOpt()"/>

  <script>

  function changeOpt(){
  document.getElementById("sel").options[1].selected = true;

alert("changed")
  }

  </script>

AddTransient, AddScoped and AddSingleton Services Differences

This image illustrates this concept well. Unfortunately, I could not find the original source of this image, but someone made it, he has shown this concept very well in the form of an image. enter image description here

jQuery - trapping tab select event

This post shows a complete working HTML file as an example of triggering code to run when a tab is clicked. The .on() method is now the way that jQuery suggests that you handle events.

jQuery development history

To make something happen when the user clicks a tab can be done by giving the list element an id.

<li id="list">

Then referring to the id.

$("#list").on("click", function() {
 alert("Tab Clicked!");
});

Make sure that you are using a current version of the jQuery api. Referencing the jQuery api from Google, you can get the link here:

https://developers.google.com/speed/libraries/devguide#jquery

Here is a complete working copy of a tabbed page that triggers an alert when the horizontal tab 1 is clicked.

<!-- This HTML doc is modified from an example by:  -->
<!-- http://keith-wood.name/uiTabs.html#tabs-nested -->

<head>
<meta charset="utf-8">
<title>TabDemo</title>

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/themes/south-street/jquery-ui.css">

<style>
pre {
clear: none;
}
div.showCode {
margin-left: 8em;
}
.tabs {
margin-top: 0.5em;
}
.ui-tabs { 
padding: 0.2em; 
background: url(http://code.jquery.com/ui/1.8.23/themes/south-street/images/ui-bg_highlight-hard_100_f5f3e5_1x100.png) repeat-x scroll 50% top #F5F3E5; 
border-width: 1px; 
} 
.ui-tabs .ui-tabs-nav { 
padding-left: 0.2em; 
background: url(http://code.jquery.com/ui/1.8.23/themes/south-street/images/ui-bg_gloss-wave_100_ece8da_500x100.png) repeat-x scroll 50% 50% #ECE8DA; 
border: 1px solid #D4CCB0;
-moz-border-radius: 6px; 
-webkit-border-radius: 6px; 
border-radius: 6px; 
} 
.ui-tabs-nav .ui-state-active {
border-color: #D4CCB0;
}
.ui-tabs .ui-tabs-panel { 
background: transparent; 
border-width: 0px; 
}
.ui-tabs-panel p {
margin-top: 0em;
}
#minImage {
margin-left: 6.5em;
}
#minImage img {
padding: 2px;
border: 2px solid #448844;
vertical-align: bottom;
}

#tabs-nested > .ui-tabs-panel {
padding: 0em;
}
#tabs-nested-left {
position: relative;
padding-left: 6.5em;
}
#tabs-nested-left .ui-tabs-nav {
position: absolute;
left: 0.25em;
top: 0.25em;
bottom: 0.25em;
width: 6em;
padding: 0.2em 0 0.2em 0.2em;
}
#tabs-nested-left .ui-tabs-nav li {
right: 1px;
width: 100%;
border-right: none;
border-bottom-width: 1px !important;
-moz-border-radius: 4px 0px 0px 4px;
-webkit-border-radius: 4px 0px 0px 4px;
border-radius: 4px 0px 0px 4px;
overflow: hidden;
}
#tabs-nested-left .ui-tabs-nav li.ui-tabs-selected,
#tabs-nested-left .ui-tabs-nav li.ui-state-active {
border-right: 1px solid transparent;
}
#tabs-nested-left .ui-tabs-nav li a {
float: right;
width: 100%;
text-align: right;
}
#tabs-nested-left > div {
height: 10em;
overflow: auto;
}
</pre>

</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>

<script>
    $(function() {
    $('article.tabs').tabs();
    });
</script>

</head>
<body>
<header role="banner">
    <h1>jQuery UI Tabs Styling</h1>
</header>

<section>

<article id="tabs-nested" class="tabs">
<script>
    $(document).ready(function(){
    $("#ForClick").on("click", function() {
        alert("Tab Clicked!");
    });
    });
</script>
<ul>
    <li id="ForClick"><a href="#tabs-nested-1">First</a></li>
    <li><a href="#tabs-nested-2">Second</a></li>
    <li><a href="#tabs-nested-3">Third</a></li>
</ul>
<div id="tabs-nested-1">
    <article id="tabs-nested-left" class="tabs">
        <ul>
            <li><a href="#tabs-nested-left-1">First</a></li>
            <li><a href="#tabs-nested-left-2">Second</a></li>
            <li><a href="#tabs-nested-left-3">Third</a></li>
        </ul>
        <div id="tabs-nested-left-1">
            <p>Nested tabs, horizontal then vertical.</p>


<form action="/sign" method="post">
  <div><textarea name="content" rows="5" cols="100"></textarea></div>
  <div><input type="submit" value="Sign Guestbook"></div>
</form>
        </div>
        <div id="tabs-nested-left-2">
            <p>Nested Left Two</p>
        </div>
        <div id="tabs-nested-left-3">
            <p>Nested Left Three</p>
        </div>
    </article>
</div>
<div id="tabs-nested-2">
    <p>Tab Two Main</p>
</div>
<div id="tabs-nested-3">
    <p>Tab Three Main</p>
</div>
</article>

</section>

</body>
</html>

Run text file as commands in Bash

cat /path/* | bash

OR

cat commands.txt | bash

Sorting an IList in C#

This looks MUCH MORE SIMPLE if you ask me. This works PERFECTLY for me.

You could use Cast() to change it to IList then use OrderBy():

    var ordered = theIList.Cast<T>().OrderBy(e => e);

WHERE T is the type eg. Model.Employee or Plugin.ContactService.Shared.Contact

Then you can use a for loop and its DONE.

  ObservableCollection<Plugin.ContactService.Shared.Contact> ContactItems= new ObservableCollection<Contact>();

    foreach (var item in ordered)
    {
       ContactItems.Add(item);
    }

Remove folder and its contents from git/GitHub's history

I removed the bin and obj folders from old C# projects using git on windows. Be careful with

git filter-branch --tree-filter "rm -rf bin" --prune-empty HEAD

It destroys the integrity of the git installation by deleting the usr/bin folder in the git install folder.

How do I change the hover over color for a hover over table in Bootstrap?

This worked for me:

.table tbody tr:hover td, .table tbody tr:hover th {
    background-color: #eeeeea;
}

How to make a div have a fixed size?

<div class="ai">a b c d e f</div> // something like ~100px
<div class="ai">a b c d e</div> // ~80
<div class="ai">a b c d</div> // ~60 

<script>

function _reWidthAll_div(classname) {

var _maxwidth = 0;

    $(classname).each(function(){

    var _width = $(this).width();

    _maxwidth = (_width >= _maxwidth) ? _width : _maxwidth; // define max width
    });    

$(classname).width(_maxwidth); // return all div same width

}

_reWidthAll_div('.ai');

</script>

Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js

Remove the first / in the path. Also you don't need type="text/javascript" anymore in HTML5.

TypeError: expected string or buffer

readlines() will return a list of all the lines in the file, so lines is a list. You probably want something like this:

for line in f.readlines(): # Iterates through every line and looks for a match
#or
#for line in f:
    match = re.findall('[A-Z]+', line)
    print match

Or, if the file isn't too large you can grab it as as single string:

lines = f.read() # Warning: reads the FULL FILE into memory. This can be bad.
match = re.findall('[A-Z]+', lines)
print match

Compile Views in ASP.NET MVC

Next release of ASP.NET MVC (available in January or so) should have MSBuild task that compiles views, so you might want to wait.

See announcement

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Best way to call a JSON WebService from a .NET Console

WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:

using (var client = new WebClient())
{
    var json = client.DownloadString("http://example.com/json");
    var serializer = new JavaScriptSerializer();
    SomeModel model = serializer.Deserialize<SomeModel>(json);
    // TODO: do something with the model
}

There are also some REST client frameworks you may checkout such as RestSharp.

Prevent double submission of forms in jQuery

Use simple counter on submit.

    var submitCounter = 0;
    function monitor() {
        submitCounter++;
        if (submitCounter < 2) {
            console.log('Submitted. Attempt: ' + submitCounter);
            return true;
        }
        console.log('Not Submitted. Attempt: ' + submitCounter);
        return false;
    }

And call monitor() function on submit the form.

    <form action="/someAction.go" onsubmit="return monitor();" method="POST">
        ....
        <input type="submit" value="Save Data">
    </form>

How to use global variable in node.js?

If your app is written in TypeScript, try

(global as any).logger = // ...

or

Object.assign(global, { logger: // ... })

However, I will do it only when React Native's __DEV__ in testing environment.

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

As per Oracle Glossary :

SID is a unique name for an Oracle database instance. ---> To switch between Oracle databases, users must specify the desired SID <---. The SID is included in the CONNECT DATA parts of the connect descriptors in a TNSNAMES.ORA file, and in the definition of the network listener in the LISTENER.ORA file. Also known as System ID. Oracle Service Name may be anything descriptive like "MyOracleServiceORCL". In Windows, You can your Service Name running as a service under Windows Services.

You should use SID in TNSNAMES.ORA as a better approach.

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

If you remove [DataType(DataType.Date)] from your model, the input field in Chrome is rendered as type="datetime" and won't show the datepicker either.

Count the number of all words in a string

Also from stringi package, the straight forward function stri_count_words

stringi::stri_count_words(str1)
#[1] 7

Convert int to a bit array in .NET

    public static bool[] Convert(int[] input, int length)
    {
        var ret = new bool[length];
        var siz = sizeof(int) * 8;
        var pow = 0;
        var cur = 0;

        for (var a = 0; a < input.Length && cur < length; ++a)
        {
            var inp = input[a];

            pow = 1;

            if (inp > 0)
            {
                for (var i = 0; i < siz && cur < length; ++i)
                {
                    ret[cur++] = (inp & pow) == pow;

                    pow *= 2;
                }
            }
            else
            {
                for (var i = 0; i < siz && cur < length; ++i)
                {
                    ret[cur++] = (inp & pow) != pow;

                    pow *= 2;
                }
            }
        }

        return ret;
    }

Python sys.argv lists and indexes

In a nutshell, sys.argv is a list of the words that appear in the command used to run the program. The first word (first element of the list) is the name of the program, and the rest of the elements of the list are any arguments provided. In most computer languages (including Python), lists are indexed from zero, meaning that the first element in the list (in this case, the program name) is sys.argv[0], and the second element (first argument, if there is one) is sys.argv[1], etc.

The test len(sys.argv) >= 2 simply checks wither the list has a length greater than or equal to 2, which will be the case if there was at least one argument provided to the program.

How can a LEFT OUTER JOIN return more records than exist in the left table?

It isn't impossible. The number of records in the left table is the minimum number of records it will return. If the right table has two records that match to one record in the left table, it will return two records.

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

Object Dump JavaScript

Just use:

console.dir(object);

you will get a nice clickable object representation. Works in Chrome and Firefox

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

I have tested this on EF core 2.1

Here you cannot use either Conventions or Data Annotations. You must use the Fluent API.

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Property(b => b.Created)
            .HasDefaultValueSql("getdate()");
    }
}

Official doc

How to remove line breaks (no characters!) from the string?

You can also use PHP trim

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

How many parameters are too many?

I generally agree with 5, however, if there is a situation where I need more and it's the clearest way to solve the problem, then I would use more.

ASP.NET custom error page - Server.GetLastError() is null

Looking more closely at my web.config set up, one of the comments in this post is very helpful

in asp.net 3.5 sp1 there is a new parameter redirectMode

So we can amend customErrors to add this parameter:

<customErrors mode="RemoteOnly" defaultRedirect="~/errors/GeneralError.aspx" redirectMode="ResponseRewrite" />

the ResponseRewrite mode allows us to load the «Error Page» without redirecting the browser, so the URL stays the same, and importantly for me, exception information is not lost.

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

I found this error occurred when I was using the wrong version of Java. When I changed my environment from Java 7 down to Java 6 the error no longer appeared.

(The MSVCR71.DLL file is in the JDK 6 bin directory, where JDK 7 has MSVCR100.DLL.)

What do 3 dots next to a parameter type mean in Java?

Also to shed some light, it is important to know that var-arg parameters are limited to one and you can't have several var-art params. For example this is illigal:

public void myMethod(String... strings, int ... ints){
// method body
}

Move the mouse pointer to a specific position?

So, I know this is an old topic, but I'll first say it isn't possible. The closest thing currently is locking the mouse to a single position, and tracking change in its x and y. This concept has been adopted by - it looks like - Chrome and Firefox. It's managed by what's called Mouse Lock, and hitting escape will break it. From my brief read-up, I think the idea is that it locks the mouse to one location, and reports motion events similar to click-and-drag events.

Here's the release documentation:
FireFox: https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API
Chrome: http://www.chromium.org/developers/design-documents/mouse-lock

And here's a pretty neat demonstration: http://media.tojicode.com/q3bsp/

HTML: Image won't display?

Just to expand niko's answer:

You can reference any image via its URL. No matter where it is, as long as it's accesible you can use it as the src. Example:

Relative location:

<img src="images/image.png">

The image is sought relative to the document's location. If your document is at http://example.com/site/document.html, then your images folder should be on the same directory where your document.html file is.

Absolute location:

<img src="/site/images/image.png">
<img src="http://example.com/site/images/image.png">

or

<img src="http://another-example.com/images/image.png">

In this case, your image will be sought from the document site's root, so, if your document.html is at http://example.com/site/document.html, the root would be at http://example.com/ (or it's respective directory on the server's filesystem, commonly www/). The first two examples are the same, since both point to the same host, Think of the first / as an alias for your server's root. In the second case, the image is located in another host, so you'd have to specify the complete URL of the image.

Regarding /, . and ..:

The / symbol will always return the root of a filesystem or site.

The single point ./ points to the same directory where you are.

And the double point ../ will point to the upper directory, or the one that contains the actual working directory.

So you can build relative routes using them.

Examples given the route http://example.com/dir/one/two/three/ and your calling document being inside three/:

"./pictures/image.png"

or just

"pictures/image.png"

Will try to find a directory named pictures inside http://example.com/dir/one/two/three/.

"../pictures/image.png"

Will try to find a directory named pictures inside http://example.com/dir/one/two/.

"/pictures/image.png"

Will try to find a directory named pictures directly at / or example.com (which are the same), on the same level as directory.

Java Serializable Object to Byte Array

code example with java 8+:

public class Person implements Serializable {

private String lastName;
private String firstName;

public Person() {
}

public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getFirstName() {
    return firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

@Override
public String toString() {
    return "firstName: " + firstName + ", lastName: " + lastName;
}
}


public interface PersonMarshaller {
default Person fromStream(InputStream inputStream) {
    try (ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
        Person person= (Person) objectInputStream.readObject();
        return person;
    } catch (IOException | ClassNotFoundException e) {
        System.err.println(e.getMessage());
        return null;
    }
}

default OutputStream toStream(Person person) {
    try (OutputStream outputStream = new ByteArrayOutputStream()) {
        ObjectOutput objectOutput = new ObjectOutputStream(outputStream);
        objectOutput.writeObject(person);
        objectOutput.flush();
        return outputStream;
    } catch (IOException e) {
        System.err.println(e.getMessage());
        return null;
    }

}

}

Generic type conversion FROM string

public class TypedProperty<T> : Property
{
    public T TypedValue
    {
        get { return (T)(object)base.Value; }
        set { base.Value = value.ToString();}
    }
}

I using converting via an object. It is a little bit simpler.

MySQL string replace

The replace function should work for you.

REPLACE(str,from_str,to_str)

Returns the string str with all occurrences of the string from_str replaced by the string to_str. REPLACE() performs a case-sensitive match when searching for from_str.

Jenkins: Is there any way to cleanup Jenkins workspace?

There is an option to do it. Configure -> Post-build Actions
The option comes by default at least in Jenkins version 2.236

Disable scrolling on `<input type=number>`

For anyone working with React and looking for solution. I’ve found out that easiest way is to use onWheelCapture prop in Input component like this:

onWheelCapture={e => { e.target.blur() }}

make *** no targets specified and no makefile found. stop

If after ./configure Makefile.in and Makefile.am are generated and make fail (by showing this following make: *** No targets specified and no makefile found. Stop.) so there is something not configured well, to solve it, first run "autoconf" commande to solve wrong configuration then re-run "./configure" commande and finally "make"

No connection string named 'MyEntities' could be found in the application config file

There is a comment on the top answer by @RyanMann that suggests:

Store your connection strings in one config file, then reference them in other projects by <connectionString configSource="../ProjectDir/SharedConnections.config" />

This is a fantastic suggestion!

It also works to share connection strings between App.config and Web.config files!

Anyone wanting to follow this suggestion, should head on over to this SO answer. It has a really great step-by-step guide on sharing connection strings among multiple projects in a solution.

The only caveat is that configSource must exist in the same directory or a sub-directory. The link above explains how to use "Add as Link" to get around this.