Programs & Examples On #Mvvm light

The MVVM Light Toolkit is a set of components helping people to get started with the Model - View - ViewModel pattern in Silverlight, WPF, Xamarin, .NET Core and Windows Phone. It is a light and pragmatic framework that contains only the essential components needed.

Handling the window closing event with WPF / MVVM Light Toolkit

Here is an answer according to the MVVM-pattern if you don't want to know about the Window (or any of its event) in the ViewModel.

public interface IClosing
{
    /// <summary>
    /// Executes when window is closing
    /// </summary>
    /// <returns>Whether the windows should be closed by the caller</returns>
    bool OnClosing();
}

In the ViewModel add the interface and implementation

public bool OnClosing()
{
    bool close = true;

    //Ask whether to save changes och cancel etc
    //close = false; //If you want to cancel close

    return close;
}

In the Window I add the Closing event. This code behind doesn't break the MVVM pattern. The View can know about the viewmodel!

void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    IClosing context = DataContext as IClosing;
    if (context != null)
    {
        e.Cancel = !context.OnClosing();
    }
}

Java SSL: how to disable hostname verification

The answer from @Nani doesn't work anymore with Java 1.8u181. You still need to use your own TrustManager, but it needs to be a X509ExtendedTrustManager instead of a X509TrustManager:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509ExtendedTrustManager;

public class Test {

   public static void main (String [] args) throws IOException {
      // This URL has a certificate with a wrong name
      URL url = new URL ("https://wrong.host.badssl.com/");

      try {
         // opening a connection will fail
         url.openConnection ().connect ();
      } catch (SSLHandshakeException e) {
         System.out.println ("Couldn't open connection: " + e.getMessage ());
      }

      // Bypassing the SSL verification to execute our code successfully
      disableSSLVerification ();

      // now we can open the connection
      url.openConnection ().connect ();

      System.out.println ("successfully opened connection to " + url + ": " + ((HttpURLConnection) url.openConnection ()).getResponseCode ());
   }

   // Method used for bypassing SSL verification
   public static void disableSSLVerification () {

      TrustManager [] trustAllCerts = new TrustManager [] {new X509ExtendedTrustManager () {
         @Override
         public void checkClientTrusted (X509Certificate [] chain, String authType, Socket socket) {

         }

         @Override
         public void checkServerTrusted (X509Certificate [] chain, String authType, Socket socket) {

         }

         @Override
         public void checkClientTrusted (X509Certificate [] chain, String authType, SSLEngine engine) {

         }

         @Override
         public void checkServerTrusted (X509Certificate [] chain, String authType, SSLEngine engine) {

         }

         @Override
         public java.security.cert.X509Certificate [] getAcceptedIssuers () {
            return null;
         }

         @Override
         public void checkClientTrusted (X509Certificate [] certs, String authType) {
         }

         @Override
         public void checkServerTrusted (X509Certificate [] certs, String authType) {
         }

      }};

      SSLContext sc = null;
      try {
         sc = SSLContext.getInstance ("SSL");
         sc.init (null, trustAllCerts, new java.security.SecureRandom ());
      } catch (KeyManagementException | NoSuchAlgorithmException e) {
         e.printStackTrace ();
      }
      HttpsURLConnection.setDefaultSSLSocketFactory (sc.getSocketFactory ());
   }
}

Programmatic equivalent of default(Type)

Why not call the method that returns default(T) with reflection ? You can use GetDefault of any type with:

    public object GetDefault(Type t)
    {
        return this.GetType().GetMethod("GetDefaultGeneric").MakeGenericMethod(t).Invoke(this, null);
    }

    public T GetDefaultGeneric<T>()
    {
        return default(T);
    }

How to get the difference between two arrays in JavaScript?

You could use a Set in this case. It is optimized for this kind of operation (union, intersection, difference).

Make sure it applies to your case, once it allows no duplicates.

var a = new JS.Set([1,2,3,4,5,6,7,8,9]);
var b = new JS.Set([2,4,6,8]);

a.difference(b)
// -> Set{1,3,5,7,9}

How can I debug my JavaScript code?

There is a debugger keyword in JavaScript to debug the JavaScript code. Put debugger; snippet in your JavaScript code. It will automatically start debugging the JavaScript code at that point.

For example:

Suppose this is your test.js file

function func(){
    //Some stuff
    debugger;  //Debugging is automatically started from here
    //Some stuff
}
func();
  • When the browser runs the web page in developer option with enabled debugger, then it automatically starts debugging from the debugger; point.
  • There should be opened the developer window the browser.

How can I include css files using node, express, and ejs?

Use in your main .js file:

app.use('/css',express.static(__dirname +'/css'));

use in you main .html file:

<link rel="stylesheet" type="text/css" href="css/style.css" />

The reason you getting an error because you are using a comma instead of a concat + after __dirname.

Convert a String to int?

You can directly convert to an int using the str::parse::<T>() method.

let my_string = "27".to_string();  // `parse()` works with `&str` and `String`!
let my_int = my_string.parse::<i32>().unwrap();

You can either specify the type to parse to with the turbofish operator (::<>) as shown above or via explicit type annotation:

let my_int: i32 = my_string.parse().unwrap();

As mentioned in the comments, parse() returns a Result. This result will be an Err if the string couldn't be parsed as the type specified (for example, the string "peter" can't be parsed as i32).

Recover unsaved SQL query scripts

Go to SSMS >> Tools >> Options >> Environment >> AutoRecover

There are two different settings:

1) Save AutoRecover Information Every Minutes

This option will save the SQL Query file at certain interval. Set this option to minimum value possible to avoid loss. If you have set this value to 5, in the worst possible case, you can lose last 5 minutes of the work.

2) Keep AutoRecover Information for Days

This option will preserve the AutoRecovery information for specified days. Though, I suggest in case of accident open SQL Server Management Studio right away and recover your file. Do not procrastinate this important task for future dates.

malloc for struct and pointer in C

In principle you're doing it correct already. For what you want you do need two malloc()s.

Just some comments:

struct Vector y = (struct Vector*)malloc(sizeof(struct Vector));
y->x = (double*)malloc(10*sizeof(double));

should be

struct Vector *y = malloc(sizeof *y); /* Note the pointer */
y->x = calloc(10, sizeof *y->x);

In the first line, you allocate memory for a Vector object. malloc() returns a pointer to the allocated memory, so y must be a Vector pointer. In the second line you allocate memory for an array of 10 doubles.

In C you don't need the explicit casts, and writing sizeof *y instead of sizeof(struct Vector) is better for type safety, and besides, it saves on typing.

You can rearrange your struct and do a single malloc() like so:

struct Vector{    
    int n;
    double x[];
};
struct Vector *y = malloc(sizeof *y + 10 * sizeof(double));

find vs find_by vs where

Model.find

1- Parameter: ID of the object to find.

2- If found: It returns the object (One object only).

3- If not found: raises an ActiveRecord::RecordNotFound exception.

Model.find_by

1- Parameter: key/value

Example:

User.find_by name: 'John', email: '[email protected]'

2- If found: It returns the object.

3- If not found: returns nil.

Note: If you want it to raise ActiveRecord::RecordNotFound use find_by!

Model.where

1- Parameter: same as find_by

2- If found: It returns ActiveRecord::Relation containing one or more records matching the parameters.

3- If not found: It return an Empty ActiveRecord::Relation.

Select mySQL based only on month and year

No one seems to be talking about performance so I tested the two most popular answers on a sample database from Mysql. The table has 2.8M rows with structure

CREATE TABLE `salaries` (
  `emp_no` int(11) NOT NULL,
  `salary` int(11) NOT NULL,
  `from_date` date NOT NULL,
  `to_date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `salaries`
  ADD PRIMARY KEY (`emp_no`,`from_date`);

Here are the tests performed and results

SELECT * FROM `salaries` WHERE YEAR(from_date) = 1992 AND MONTH(from_date) = 6
12339 results
-----------------
11.5 ms 
12.1 ms
09.5 ms
07.5 ms
10.2 ms
-----------------
10.2 ms Avg
-----------------


SELECT * FROM `salaries` WHERE from_date BETWEEN '1992-06-01' AND '1992-06-31'
-----------------
10.0 ms
10.8 ms
09.5 ms
09.0 ms
08.3 ms
-----------------
09.5 ms Avg
-----------------


SELECT * FROM `salaries` WHERE YEAR(to_date) = 1992 AND MONTH(to_date) = 6
10887 results
-----------------
10.2 ms
11.7 ms
11.8 ms
12.4 ms
09.6 ms
-----------------
11.1 ms Avg
-----------------


SELECT * FROM `salaries` WHERE to_date BETWEEN '1992-06-01' AND '1992-06-31'
-----------------
09.0 ms
07.5 ms
10.6 ms
11.7 ms
12.0 ms
-----------------
10.2 ms Avg
-----------------

My Conclusions

  1. BETWEEN was slightly better on both indexed and unindexed column.
  2. The unindexed column was marginally slower than the indexed column.

Serving static web resources in Spring Boot & Spring Security application

  @Override
      public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
             .antMatchers("/resources/**"); // #3
      }

Ignore any request that starts with "/resources/". This is similar to configuring http@security=none when using the XML namespace configuration.

MySQL stored procedure vs function, which would I use when?

The most general difference between procedures and functions is that they are invoked differently and for different purposes:

  1. A procedure does not return a value. Instead, it is invoked with a CALL statement to perform an operation such as modifying a table or processing retrieved records.
  2. A function is invoked within an expression and returns a single value directly to the caller to be used in the expression.
  3. You cannot invoke a function with a CALL statement, nor can you invoke a procedure in an expression.

Syntax for routine creation differs somewhat for procedures and functions:

  1. Procedure parameters can be defined as input-only, output-only, or both. This means that a procedure can pass values back to the caller by using output parameters. These values can be accessed in statements that follow the CALL statement. Functions have only input parameters. As a result, although both procedures and functions can have parameters, procedure parameter declaration differs from that for functions.
  2. Functions return value, so there must be a RETURNS clause in a function definition to indicate the data type of the return value. Also, there must be at least one RETURN statement within the function body to return a value to the caller. RETURNS and RETURN do not appear in procedure definitions.

    • To invoke a stored procedure, use the CALL statement. To invoke a stored function, refer to it in an expression. The function returns a value during expression evaluation.

    • A procedure is invoked using a CALL statement, and can only pass back values using output variables. A function can be called from inside a statement just like any other function (that is, by invoking the function's name), and can return a scalar value.

    • Specifying a parameter as IN, OUT, or INOUT is valid only for a PROCEDURE. For a FUNCTION, parameters are always regarded as IN parameters.

    If no keyword is given before a parameter name, it is an IN parameter by default. Parameters for stored functions are not preceded by IN, OUT, or INOUT. All function parameters are treated as IN parameters.

To define a stored procedure or function, use CREATE PROCEDURE or CREATE FUNCTION respectively:

CREATE PROCEDURE proc_name ([parameters])
 [characteristics]
 routine_body


CREATE FUNCTION func_name ([parameters])
 RETURNS data_type       // diffrent
 [characteristics]
 routine_body

A MySQL extension for stored procedure (not functions) is that a procedure can generate a result set, or even multiple result sets, which the caller processes the same way as the result of a SELECT statement. However, the contents of such result sets cannot be used directly in expression.

Stored routines (referring to both stored procedures and stored functions) are associated with a particular database, just like tables or views. When you drop a database, any stored routines in the database are also dropped.

Stored procedures and functions do not share the same namespace. It is possible to have a procedure and a function with the same name in a database.

In Stored procedures dynamic SQL can be used but not in functions or triggers.

SQL prepared statements (PREPARE, EXECUTE, DEALLOCATE PREPARE) can be used in stored procedures, but not stored functions or triggers. Thus, stored functions and triggers cannot use Dynamic SQL (where you construct statements as strings and then execute them). (Dynamic SQL in MySQL stored routines)

Some more interesting differences between FUNCTION and STORED PROCEDURE:

  1. (This point is copied from a blogpost.) Stored procedure is precompiled execution plan where as functions are not. Function Parsed and compiled at runtime. Stored procedures, Stored as a pseudo-code in database i.e. compiled form.

  2. (I'm not sure for this point.)
    Stored procedure has the security and reduces the network traffic and also we can call stored procedure in any no. of applications at a time. reference

  3. Functions are normally used for computations where as procedures are normally used for executing business logic.

  4. Functions Cannot affect the state of database (Statements that do explicit or implicit commit or rollback are disallowed in function) Whereas Stored procedures Can affect the state of database using commit etc.
    refrence: J.1. Restrictions on Stored Routines and Triggers

  5. Functions can't use FLUSH statements whereas Stored procedures can do.

  6. Stored functions cannot be recursive Whereas Stored procedures can be. Note: Recursive stored procedures are disabled by default, but can be enabled on the server by setting the max_sp_recursion_depth server system variable to a nonzero value. See Section 5.2.3, “System Variables”, for more information.

  7. Within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger. Good Example: How to Update same table on deletion in MYSQL?

Note: that although some restrictions normally apply to stored functions and triggers but not to stored procedures, those restrictions do apply to stored procedures if they are invoked from within a stored function or trigger. For example, although you can use FLUSH in a stored procedure, such a stored procedure cannot be called from a stored function or trigger.

Android Use Done button on Keyboard to click button

max.setOnKeyListener(new OnKeyListener(){
  @Override
  public boolean onKey(View v, int keyCode, KeyEvent event){
    if(keyCode == event.KEYCODE_ENTER){
        //do what you want
    }
  }
});

Didn't Java once have a Pair class?

Map.Entry

Java 1.6 and upper have two implementation of Map.Entry interface pairing a key with a value:

UML diagram of SimpleEntry & SimpleImmutableEntry classes inheriting from Map.Entry interface

For example

Map.Entry < Month, Boolean > pair = 
    new AbstractMap.SimpleImmutableEntry <>( 
        Month.AUGUST , 
        Boolean.TRUE 
    )
;

pair.toString(): AUGUST=true

I use it when need to store pairs (like size and object collection).

This piece from my production code:

public Map<L1Risk, Map.Entry<int[], Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>>>>
        getEventTable(RiskClassifier classifier) {
    Map<L1Risk, Map.Entry<int[], Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>>>> l1s = new HashMap<>();
    Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>> l2s = new HashMap<>();
    Map<L3Risk, List<Event>> l3s = new HashMap<>();
    List<Event> events = new ArrayList<>();
    ...
    map.put(l3s, events);
    map.put(l2s, new AbstractMap.SimpleImmutableEntry<>(l3Size, l3s));
    map.put(l1s, new AbstractMap.SimpleImmutableEntry<>(l2Size, l2s));
}

Code looks complicated but instead of Map.Entry you limited to array of object (with size 2) and lose type checks...

How to list records with date from the last 10 days?

Just generalising the query if you want to work with any given date instead of current date:

SELECT Table.date
  FROM Table 
  WHERE Table.date > '2020-01-01'::date - interval '10 day'

php date validation

You can use some methods of the DateTime class, which might be handy; namely, DateTime::createFromFormat() in conjunction with DateTime::getLastErrors().

$test_date = '03/22/2010';

$date = DateTime::createFromFormat('m/d/Y', $test_date);
$date_errors = DateTime::getLastErrors();
if ($date_errors['warning_count'] + $date_errors['error_count'] > 0) {
    $errors[] = 'Some useful error message goes here.';
}

This even allows us to see what actually caused the date parsing warnings/errors (look at the warnings and errors arrays in $date_errors).

How to convert milliseconds to seconds with precision

I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.

double time_seconds = time_milliseconds / 1000.0;   // add the decimal
System.out.println(time_milliseconds);              // Now this should give you the right value.

git diff between two different files

If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"

how to open a jar file in Eclipse

Since the jar file 'executes' then it contains compiled java files known as .class files. You cannot import it to eclipse and modify the code. You should ask the supplier of the "demo" for the "source code". (or check the page you got the demo from for the source code)

Unless, you want to decompile the .class files and import to Eclipse. That may not be the case for starters.

How to colorize diff on the command line?

Coloured, word-level diff ouput

Here's what you can do with the the below script and diff-highlight:

Coloured diff screenshot

#!/bin/sh -eu

# Use diff-highlight to show word-level differences

diff -U3 --minimal "$@" |
  sed 's/^-/\x1b[1;31m-/;s/^+/\x1b[1;32m+/;s/^@/\x1b[1;34m@/;s/$/\x1b[0m/' |
  diff-highlight

(Credit to @retracile's answer for the sed highlighting)

Python: can't assign to literal

You should use variables to store the names.

Numbers can't store strings.

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

Python 2:

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

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

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

Python 3:

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

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

How can I get onclick event on webview in android?

On Click event On webView works in onTouch like this:

imagewebViewNewsChart.setOnTouchListener(new View.OnTouchListener(){

  @Override   
  public boolean onTouch(View v, MotionEvent event) { 
    if (event.getAction()==MotionEvent.ACTION_MOVE){                        
       return false;     
    }

    if (event.getAction()==MotionEvent.ACTION_UP){    
        startActivity(new Intent(this,Example.class));                

    } 

    return false;                 
  }                       
});

Print list without brackets in a single row

print(*names)

this will work in python 3 if you want them to be printed out as space separated. If you need comma or anything else in between go ahead with .join() solution

Update with two tables?

I was scratching my head, not being able to get John Sansom's Join syntax work, at least in MySQL 5.5.30 InnoDB.

It turns out that this doesn't work.

UPDATE A 
    SET A.x = 1
FROM A INNER JOIN B 
        ON A.name = B.name
WHERE A.x <> B.x

But this works:

UPDATE A INNER JOIN B 
    ON A.name = B.name
SET A.x = 1
WHERE A.x <> B.x

How to set a default Value of a UIPickerView

You have to send - (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated to the picker view before it appears. The documentation states that the method selectedRowInComp... will give -1, thus it is possible that the picker view is in a state with no selected row. It turns out to be in that state when created.

Server did not recognize the value of HTTP Header SOAPAction

I found out that my web reference was out of date and the code was calling a removed web service.

MySQL Event Scheduler on a specific time everyday

The documentation on CREATE EVENT is quite good, but it takes a while to get it right.

You have two problems, first, making the event recur, second, making it run at 13:00 daily.

This example creates a recurring event.

CREATE EVENT e_hourly
    ON SCHEDULE
      EVERY 1 HOUR
    COMMENT 'Clears out sessions table each hour.'
    DO
      DELETE FROM site_activity.sessions;

When in the command-line MySQL client, you can:

SHOW EVENTS;

This lists each event with its metadata, like if it should run once only, or be recurring.

The second problem: pointing the recurring event to a specific schedule item.

By trying out different kinds of expression, we can come up with something like:

CREATE EVENT IF NOT EXISTS `session_cleaner_event`
ON SCHEDULE
  EVERY 13 DAY_HOUR
  COMMENT 'Clean up sessions at 13:00 daily!'
  DO
    DELETE FROM site_activity.sessions;

What's the difference between [ and [[ in Bash?

  • [ is the same as the test builtin, and works like the test binary (man test)
    • works about the same as [ in all the other sh-based shells in many UNIX-like environments
    • only supports a single condition. Multiple tests with the bash && and || operators must be in separate brackets.
    • doesn't natively support a 'not' operator. To invert a condition, use a ! outside the first bracket to use the shell's facility for inverting command return values.
    • == and != are literal string comparisons
  • [[ is a bash
    • is bash-specific, though others shells may have implemented similar constructs. Don't expect it in an old-school UNIX sh.
    • == and != apply bash pattern matching rules, see "Pattern Matching" in man bash
    • has a =~ regex match operator
    • allows use of parentheses and the !, &&, and || logical operators within the brackets to combine subexpressions

Aside from that, they're pretty similar -- most individual tests work identically between them, things only get interesting when you need to combine different tests with logical AND/OR/NOT operations.

Laravel 5.1 API Enable Cors

Here is my CORS middleware:

<?php namespace App\Http\Middleware;

use Closure;

class CORS {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }

}

To use CORS middleware you have to register it first in your app\Http\Kernel.php file like this:

protected $routeMiddleware = [
        //other middlewares
        'cors' => 'App\Http\Middleware\CORS',
    ];

Then you can use it in your routes

Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));

Jquery each - Stop loop and return object

Rather than setting a flag, it could be more elegant to use JavaScript's Array.prototype.find to find the matching item in the array. The loop will end as soon as a truthy value is returned from the callback, and the array value during that iteration will be the .find call's return value:

function findXX(word) {
    return someArray.find((item, i) => {
        $('body').append('-> '+i+'<br />');
        return item === word;
    }); 
}

_x000D_
_x000D_
const someArray = new Array();
someArray[0] = 't5';
someArray[1] = 'z12';
someArray[2] = 'b88';
someArray[3] = 's55';
someArray[4] = 'e51';
someArray[5] = 'o322';
someArray[6] = 'i22';
someArray[7] = 'k954';

var test = findXX('o322');
console.log('found word:', test);

function findXX(word) {
  return someArray.find((item, i) => {
    $('body').append('-> ' + i + '<br />');
    return item === word;
  });
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Throughput and bandwidth difference?

  • Bandwidth - theoretical maximum units of work per unit of time
  • Throughput - actual units of work per unit of time

As opposed to the time per unit of work (speed/latency).

This question in network engineering stack exchange contains good responses: https://networkengineering.stackexchange.com/questions/10504/what-is-the-difference-between-data-rate-and-latency

Google Maps API 3 - Custom marker color for default (dot) marker

You can use color code also.

 const marker: Marker = this.map.addMarkerSync({
    icon: '#008000',
    animation: 'DROP',
    position: {lat: 39.0492127, lng: -111.1435662},
    map: this.map,
 });

ORA-30926: unable to get a stable set of rows in the source tables

A further clarification to the use of DISTINCT to resolve error ORA-30926 in the general case:

You need to ensure that the set of data specified by the USING() clause has no duplicate values of the join columns, i.e. the columns in the ON() clause.

In OP's example where the USING clause only selects a key, it was sufficient to add DISTINCT to the USING clause. However, in the general case the USING clause may select a combination of key columns to match on and attribute columns to be used in the UPDATE ... SET clause. Therefore in the general case, adding DISTINCT to the USING clause will still allow different update rows for the same keys, in which case you will still get the ORA-30926 error.

This is an elaboration of DCookie's answer and point 3.1 in Tagar's answer, which from my experience may not be immediately obvious.

Count number of occurrences of a pattern in a file (even on same line)

Hack grep's color function, and count how many color tags it prints out:

echo -e "a\nb  b b\nc\ndef\nb e brb\nr" \
| GREP_COLOR="033" grep --color=always  b \
| perl -e 'undef $/; $_=<>; s/\n//g; s/\x1b\x5b\x30\x33\x33/\n/g; print $_' \
| wc -l

FFmpeg on Android

To make my FFMPEG application I used this project (https://github.com/hiteshsondhi88/ffmpeg-android-java) so, I don't have to compile anything. I think it's the easy way to use FFMPEG in our Android applications.

More info on http://hiteshsondhi88.github.io/ffmpeg-android-java/

How to return an array from an AJAX call?

Use JSON to transfer data types (arrays and objects) between client and server.

In PHP:

In JavaScript:

PHP:

echo json_encode($id_numbers);

JavaScript:

id_numbers = JSON.parse(msg);

As Wolfgang mentioned, you can give a fourth parameter to jQuery to automatically decode JSON for you.

id_numbers = new Array();
$.ajax({
    url:"Example.php",
    type:"POST",
    success:function(msg){
        id_numbers = msg;
    },
    dataType:"json"
});

Incompatible implicit declaration of built-in function ‘malloc’

The only solution for such warnings is to include stdlib.h in the program.

How to run a python script from IDLE interactive shell?

execFile('helloworld.py') does the job for me. A thing to note is to enter the complete directory name of the .py file if it isnt in the Python folder itself (atleast this is the case on Windows)

For example, execFile('C:/helloworld.py')

Constructor in an Interface?

Here´s an example using this Technic. In this specifik example the code is making a call to Firebase using a mock MyCompletionListener that is an interface masked as an abstract class, an interface with a constructor

private interface Listener {
    void onComplete(databaseError, databaseReference);
}

public abstract class MyCompletionListener implements Listener{
    String id;
    String name;
    public MyCompletionListener(String id, String name) {
        this.id = id;
        this.name = name;
    }
}

private void removeUserPresenceOnCurrentItem() {
    mFirebase.removeValue(child("some_key"), new MyCompletionListener(UUID.randomUUID().toString(), "removeUserPresenceOnCurrentItem") {
        @Override
        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

        }
    });
    }
}

@Override
public void removeValue(DatabaseReference ref, final MyCompletionListener var1) {
    CompletionListener cListener = new CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    if (var1 != null){
                        System.out.println("Im back and my id is: " var1.is + " and my name is: " var1.name);
                        var1.onComplete(databaseError, databaseReference);
                    }
                }
            };
    ref.removeValue(cListener);
}

how to get param in method post spring mvc?

It also works if you change the content type

    <form method="POST"
    action="http://localhost:8080/cms/customer/create_customer"
    id="frmRegister" name="frmRegister"
    enctype="application/x-www-form-urlencoded">

In the controller also add the header value as follows:

    @RequestMapping(value = "/create_customer", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")

What are the date formats available in SimpleDateFormat class?

check the formats here http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

main

System.out.println("date  : " + new classname().getMyDate("2014-01-09 14:06", "dd-MMM-yyyy E hh:mm a z", "yyyy-MM-dd HH:mm"));

method

 public String getMyDate(String myDate, String returnFormat, String myFormat)
            {
                DateFormat dateFormat = new SimpleDateFormat(returnFormat);
                Date date=null;
                String returnValue="";
                try {
                    date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
                    returnValue = dateFormat.format(date);
                } catch (ParseException e) {
                    returnValue= myDate;
                    System.out.println("failed");
                    e.printStackTrace();
                }

            return returnValue;
            }

css width: calc(100% -100px); alternative using jquery

Try jQuery animate() method, ex.

$("#divid").animate({'width':perc+'%'});

How to Export Private / Secret ASC Key to Decrypt GPG Files

All the above replies are correct, but might be missing one crucial step, you need to edit the imported key and "ultimately trust" that key

gpg --edit-key (keyIDNumber)
gpg> trust

Please decide how far you trust this user to correctly verify other users' keys
(by looking at passports, checking fingerprints from different sources, etc.)

  1 = I don't know or won't say
  2 = I do NOT trust
  3 = I trust marginally
  4 = I trust fully
  5 = I trust ultimately
  m = back to the main menu

and select 5 to enable that imported private key as one of your keys

document.getElementById(id).focus() is not working for firefox or chrome

One thing to check that I just found is that it won't work if there are multiple elements with the same ID. It doesn't error if you try to do this, it just fails silently

How can I interrupt a running code in R with a keyboard command?

Self Answer (pretty much summary of other's comments and answers):

  • In RStudio, Esc works, on windows, Mac, and ubuntu (and I would guess on other linux distributions as well).

  • If the process is ran in say ubuntu shell (and this is not R specific), for example using:

    Rscript my_file.R
    

    Ctrl + c kills the process

    Ctrl + z suspends the process

  • Within R shell, Ctrl + C kills helps you escape it

In Subversion can I be a user other than my login name?

I believe you can set the SVN_USER environment variable to change your SVN username.

Describe table structure

In MySQL you can use DESCRIBE <table_name>

JQuery: dynamic height() with window resize()

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

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

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

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

Find maximum value of a column and return the corresponding row values using Pandas

The country and place is the index of the series, if you don't need the index, you can set as_index=False:

df.groupby(['country','place'], as_index=False)['value'].max()

Edit:

It seems that you want the place with max value for every country, following code will do what you want:

df.groupby("country").apply(lambda df:df.irow(df.value.argmax()))

How do I check that multiple keys are in a dict in a single pass?

In case you want to:

  • also get the values for the keys
  • check more than one dictonary

then:

from operator import itemgetter
foo = {'foo':1,'zip':2,'zam':3,'bar':4}
keys = ("foo","bar") 
getter = itemgetter(*keys) # returns all values
try:
    values = getter(foo)
except KeyError:
    # not both keys exist
    pass

how to set font size based on container size?

If you want to set the font-size as a percentage of the viewport width, use the vwunit:

#mydiv { font-size: 5vw; }

The other alternative is to use SVG embedded in the HTML. It will just be a few lines. The font-size attribute to the text element will be interpreted as "user units", for instance those the viewport is defined in terms of. So if you define viewport as 0 0 100 100, then a font-size of 1 will be one one-hundredth of the size of the svg element.

And no, there is no way to do this in CSS using calculations. The problem is that percentages used for font-size, including percentages inside a calculation, are interpreted in terms of the inherited font size, not the size of the container. CSS could use a unit called bw (box-width) for this purpose, so you could say div { font-size: 5bw; }, but I've never heard this proposed.

What is the most useful script you've written for everyday life?

I suppose this depends on how you define useful, but my favorite little script is a variant on the *nix fortune program. See below, and you'll get the idea of what it does:

telemachus ~ $ haiku 

   January--
in other provinces,
   plums blooming.
    Issa

It doesn't really get anything done, but a nice haiku goes a long way. (I like how the colorizer decided to interpret the poem.) (Edit: If I really have to be useful, I'd say a script that allows a user to enter a US zipcode and get current weather and 0-3 days of forecast from Google.)

How can I use ":" as an AWK field separator?

There isn't any need to write this much. Just put your desired field separator with the -F option in the AWK command and the column number you want to print segregated as per your mentioned field separator.

echo "1: " | awk -F: '{print $1}'
1

echo "1#2" | awk -F# '{print $1}'
1

c++ custom compare function for std::sort()

std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K and V.

Also bear in mind that std::sort requires a strict weak ordeing comparison, and <= does not satisfy that. You would need, for example, a less-than comparison < for K and V. With that in place, all you need is

std::vector<pair<K,V>> items; 
std::sort(items.begin(), items.end()); 

If you really need to provide your own comparison function, then you need something along the lines of

template <typename K, typename V>
bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
{
  return lhs.first < rhs.first;
}

Remove Safari/Chrome textinput/textarea glow

Carl W:

This effect can occur on non-input elements, too. I've found the following works as a more general solution

:focus {
  outline-color: transparent;
  outline-style: none;
}

I’ll explain this:

  • :focus means it styles the elements that are in focus. So we are styling the elements in focus.
  • outline-color: transparent; means that the blue glow is transparent.
  • outline-style: none; does the same thing.

What strategies and tools are useful for finding memory leaks in .NET?

From Visual Studio 2015 consider to use out of the box Memory Usage diagnostic tool to collect and analyze memory usage data.

The Memory Usage tool lets you take one or more snapshots of the managed and native memory heap to help understand the memory usage impact of object types.

Play sound file in a web-page in the background

Though this might be too late to comment but here's the working code for problems such as yours.

<div id="player">
    <audio autoplay hidden>
     <source src="link/to/file/file.mp3" type="audio/mpeg">
                If you're reading this, audio isn't supported. 
    </audio>
</div>

libstdc++.so.6: cannot open shared object file: No such file or directory

For Fedora use:

yum install libstdc++44.i686

You can find out which versions are supported by running:

yum list all | grep libstdc | grep i686

Java - How to access an ArrayList of another class?

Two ways

1)instantiate the first class and getter for arrayList

or

2)Make arraylist as static

And finally

Java Basics By Oracle

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

On Android >=6.0, We have to request permission runtime.

Step1: add in AndroidManifest.xml file

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Step2: Request permission.

int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);

if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
} else {
    //TODO
}

Step3: Handle callback when you request permission.

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_READ_PHONE_STATE:
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                //TODO
            }
            break;

        default:
            break;
    }
}

Edit: Read official guide here Requesting Permissions at Run Time

How do I set a ViewModel on a window in XAML using DataContext property?

You might want to try Catel. It allows you to define a DataWindow class (instead of Window), and that class automatically creates the view model for you. This way, you can use the declaration of the ViewModel as you did in your original post, and the view model will still be created and set as DataContext.

See this article for an example.

Python Brute Force algorithm

If you REALLY want to brute force it, try this, but it will take you a ridiculous amount of time:

your_list = 'abcdefghijklmnopqrstuvwxyz'
complete_list = []
for current in xrange(10):
    a = [i for i in your_list]
    for y in xrange(current):
        a = [x+i for i in your_list for x in a]
    complete_list = complete_list+a

On a smaller example, where list = 'ab' and we only go up to 5, this prints the following:

['a', 'b', 'aa', 'ba', 'ab', 'bb', 'aaa', 'baa', 'aba', 'bba', 'aab', 'bab', 'abb', 'bbb', 'aaaa', 'baaa', 'abaa', 'bbaa', 'aaba', 'baba', 'abba', 'bbba', 'aaab', 'baab', 'abab', 'bbab', 'aabb', 'babb', 'abbb', 'bbbb', 'aaaaa', 'baaaa', 'abaaa', 'bbaaa', 'aabaa', 'babaa', 'abbaa', 'bbbaa', 'aaaba','baaba', 'ababa', 'bbaba', 'aabba', 'babba', 'abbba', 'bbbba', 'aaaab', 'baaab', 'abaab', 'bbaab', 'aabab', 'babab', 'abbab', 'bbbab', 'aaabb', 'baabb', 'ababb', 'bbabb', 'aabbb', 'babbb', 'abbbb', 'bbbbb']

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

This will work:

 >>>print(unicodedata.normalize('NFD', re.sub("[\(\[].*?[\)\]]", "", "bats\xc3\xa0")).encode('ascii', 'ignore'))

Output:

>>>bats

Split varchar into separate columns in Oracle

Depends on the consistency of the data - assuming a single space is the separator between what you want to appear in column one vs two:

SELECT SUBSTR(t.column_one, 1, INSTR(t.column_one, ' ')-1) AS col_one,
       SUBSTR(t.column_one, INSTR(t.column_one, ' ')+1) AS col_two
  FROM YOUR_TABLE t

Oracle 10g+ has regex support, allowing more flexibility depending on the situation you need to solve. It also has a regex substring method...

Reference:

How to add color to Github's README.md file

Here is the code you can write color texts

<h3 style="color:#ff0000">Danger</h3>

What does the "map" method do in Ruby?

The map method takes an enumerable object and a block, and runs the block for each element, outputting each returned value from the block (the original object is unchanged unless you use map!):

[1, 2, 3].map { |n| n * n } #=> [1, 4, 9]

Array and Range are enumerable types. map with a block returns an Array. map! mutates the original array.

Where is this helpful, and what is the difference between map! and each? Here is an example:

names = ['danil', 'edmund']

# here we map one array to another, convert each element by some rule
names.map! {|name| name.capitalize } # now names contains ['Danil', 'Edmund']

names.each { |name| puts name + ' is a programmer' } # here we just do something with each element

The output:

Danil is a programmer
Edmund is a programmer

Where can I download Eclipse Android bundle?

You don't actually need the bundle as the ADT can be used with just any latest Eclipse IDE.


1. Make sure you have JDK installed.

  1. Download latest eclipse.

  2. Download latest ADT plugin ADT-XX.X.X.zip. As of this answer the current version is ADT-23.0.7.zip (More versions at http://developer.android.com/tools/sdk/eclipse-adt.html)

  3. Open Eclipse and follow the following steps:

    • Open Help > Install New Software > Add > Archive
    • Navigate to where you downloaded your ADT plugin and select it.
    • Check Developer Tools, click Next, accept any licenses and Finish
  4. After restarting Eclipse, if you are not able to open a layout file go to step 4 but instead of selecting archive add https://dl-ssl.google.com/android/eclipse/ in the Location: textbox. Press Ok, update the ADT and restart Eclipse. Close and reopen the layout files and you'll be good to go.

  5. Run the Android SDK Manager to update its components.


EDIT: The ADT plugin has long since been deprecated. For more information visit this link:

https://developer.android.com/studio/tools/sdk/eclipse-adt.html

Matching exact string with JavaScript

var data =   {"values": [
    {"name":0,"value":0.12791263050161572},
    {"name":1,"value":0.13158780927382124}
]};

//JSON to string conversion
var a = JSON.stringify(data);
// replace all name with "x"- global matching
var t = a.replace(/name/g,"x"); 
// replace exactly the value rather than all values
var d = t.replace(/"value"/g, '"y"');
// String to JSON conversion
var data = JSON.parse(d);

get name of a variable or parameter

Pre C# 6.0 solution

You can use this to get a name of any provided member:

public static class MemberInfoGetting
{
    public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
    {
        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
        return expressionBody.Member.Name;
    }
}

To get name of a variable:

string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);

To get name of a parameter:

public class TestClass
{
    public void TestMethod(string param1, string param2)
    {
        string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
    }
}

C# 6.0 and higher solution

You can use the nameof operator for parameters, variables and properties alike:

string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

Subtracting two lists in Python

I would do it in an easier way:

a_b = [e for e in a if not e in b ]

..as wich wrote, this is wrong - it works only if the items are unique in the lists. And if they are, it's better to use

a_b = list(set(a) - set(b))

Easy way to use variables of enum types as string in C?

// Define your enumeration like this (in say numbers.h);
ENUM_BEGIN( Numbers )
    ENUM(ONE),
    ENUM(TWO),
    ENUM(FOUR)
ENUM_END( Numbers )

// The macros are defined in a more fundamental .h file (say defs.h);
#define ENUM_BEGIN(typ) enum typ {
#define ENUM(nam) nam
#define ENUM_END(typ) };

// Now in one and only one .c file, redefine the ENUM macros and reinclude
//  the numbers.h file to build a string table
#undef ENUM_BEGIN
#undef ENUM
#undef ENUM_END
#define ENUM_BEGIN(typ) const char * typ ## _name_table [] = {
#define ENUM(nam) #nam
#define ENUM_END(typ) };
#undef NUMBERS_H_INCLUDED   // whatever you need to do to enable reinclusion
#include "numbers.h"

// Now you can do exactly what you want to do, with no retyping, and for any
//  number of enumerated types defined with the ENUM macro family
//  Your code follows;
char num_str[10];
int process_numbers_str(Numbers num) {
  switch(num) {
    case ONE:
    case TWO:
    case THREE:
    {
      strcpy(num_str, Numbers_name_table[num]); // eg TWO -> "TWO"
    } break;
    default:
      return 0; //no match
  return 1;
}

// Sweet no ? After being frustrated by this for years, I finally came up
//  with this solution for my most recent project and plan to reuse the idea
//  forever

Converting a number with comma as decimal point to float

Might look excessive but will convert any given format no mater the locale:

function normalizeDecimal($val, int $precision = 4): string
{
    $input = str_replace(' ', '', $val);
    $number = str_replace(',', '.', $input);
    if (strpos($number, '.')) {
        $groups = explode('.', str_replace(',', '.', $number));
        $lastGroup = array_pop($groups);
        $number = implode('', $groups) . '.' . $lastGroup;
    }
    return bcadd($number, 0, $precision);
}

Output:

.12           -> 0.1200
123           -> 123.0000
123.91        -> 12345678.9100
123 456 78.91 -> 12345678.9100
123,456,78.91 -> 12345678.9100
123.456.78,91 -> 12345678.9100
123 456 78,91 -> 12345678.9100

SQL is null and = null

In SQL, a comparison between a null value and any other value (including another null) using a comparison operator (eg =, !=, <, etc) will result in a null, which is considered as false for the purposes of a where clause (strictly speaking, it's "not true", rather than "false", but the effect is the same).

The reasoning is that a null means "unknown", so the result of any comparison to a null is also "unknown". So you'll get no hit on rows by coding where my_column = null.

SQL provides the special syntax for testing if a column is null, via is null and is not null, which is a special condition to test for a null (or not a null).

Here's some SQL showing a variety of conditions and and their effect as per above.

create table t (x int, y int);
insert into t values (null, null), (null, 1), (1, 1);

select 'x = null' as test , x, y from t where x = null
union all
select 'x != null', x, y from t where x != null
union all
select 'not (x = null)', x, y from t where not (x = null)
union all
select 'x = y', x, y from t where x = y
union all
select 'not (x = y)', x, y from t where not (x = y);

returns only 1 row (as expected):

TEST    X   Y
x = y   1   1

See this running on SQLFiddle

How do I change select2 box height

You could do this with some simple css. From what I read, you want to set the Height of the element with the class "select2-choices".

.select2-choices {
  min-height: 150px;
  max-height: 150px;
  overflow-y: auto;
}

That should give you a set height of 150px and it will scroll if needed. Simply adjust the height till your image fits as desired.

You can also use css to set the height of the select2-results (the drop down portion of the select control).

ul.select2-results {
 max-height: 200px;
}

200px is the default height, so change it for the desired height of the drop down.

How can I force component to re-render with hooks in React?

Simple code

const forceUpdate = React.useReducer(bool => !bool)[1];

Use:

forceUpdate();

jQuery Button.click() event is triggered twice

$("#id").off().on("click", function() {

});

Worked for me.

$("#id").off().on("click", function() {

});

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

How to remove array element in mongodb?

You can simply use $pull to remove a sub-document. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

Collection.update({
    _id: parentDocumentId
  }, {
    $pull: {
      subDocument: {
        _id: SubDocumentId
      }
    }
  });

This will find your parent document against given ID and then will remove the element from subDocument which matched the given criteria.

Read more about pull here.

What is better, adjacency lists or adjacency matrices for graph problems in C++?

This answer is not just for C++ since everything mentioned is about the data structures themselves, regardless of language. And, my answer is assuming that you know the basic structure of adjacency lists and matrices.

Memory

If memory is your primary concern you can follow this formula for a simple graph that allows loops:

An adjacency matrix occupies n2/8 byte space (one bit per entry).

An adjacency list occupies 8e space, where e is the number of edges (32bit computer).

If we define the density of the graph as d = e/n2 (number of edges divided by the maximum number of edges), we can find the "breakpoint" where a list takes up more memory than a matrix:

8e > n2/8 when d > 1/64

So with these numbers (still 32-bit specific) the breakpoint lands at 1/64. If the density (e/n2) is bigger than 1/64, then a matrix is preferable if you want to save memory.

You can read about this at wikipedia (article on adjacency matrices) and a lot of other sites.

Side note: One can improve the space-efficiency of the adjacency matrix by using a hash table where the keys are pairs of vertices (undirected only).

Iteration and lookup

Adjacency lists are a compact way of representing only existing edges. However, this comes at the cost of possibly slow lookup of specific edges. Since each list is as long as the degree of a vertex the worst case lookup time of checking for a specific edge can become O(n), if the list is unordered. However, looking up the neighbours of a vertex becomes trivial, and for a sparse or small graph the cost of iterating through the adjacency lists might be negligible.

Adjacency matrices on the other hand use more space in order to provide constant lookup time. Since every possible entry exists you can check for the existence of an edge in constant time using indexes. However, neighbour lookup takes O(n) since you need to check all possible neighbours. The obvious space drawback is that for sparse graphs a lot of padding is added. See the memory discussion above for more information on this.

If you're still unsure what to use: Most real-world problems produce sparse and/or large graphs, which are better suited for adjacency list representations. They might seem harder to implement but I assure you they aren't, and when you write a BFS or DFS and want to fetch all neighbours of a node they're just one line of code away. However, note that I'm not promoting adjacency lists in general.

Error: Local workspace file ('angular.json') could not be found

I was trying to set my Ionic 4 app to run as a pwa. When I run the command:

ng add @angular/pwa

...got the error message. After some try and error I discovered that when my project was created the start command was wrong. I was using an Ionic 3 version:

ionic start myApp tabs --type=ionic-angular

And the correct is:

ionic start myApp tabs --type=angular

with no 'ionic-' in type. This solved the error.

How do I launch a Git Bash window with particular working directory using a script?

This is the command which can be executed directly in Run dialog box (shortcut is win+R) and also works well saved as a .bat script:

cmd /c (start /d "/path/to/dir" bash --login) && exit

Convert Promise to Observable

You can add a wrapper around promise functionality to return an Observable to observer.

  • Creating a Lazy Observable using defer() operator which allows you to create the Observable only when the Observer subscribes.
import { of, Observable, defer } from 'rxjs'; 
import { map } from 'rxjs/operators';


function getTodos$(): Observable<any> {
  return defer(()=>{
    return fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => {
        return json;
      })
  });
}

getTodos$().
 subscribe(
   (next)=>{
     console.log('Data is:', next);
   }
)

How to set cache: false in jQuery.get call

Per the JQuery documentation, .get() only takes the url, data (content), dataType, and success callback as its parameters. What you're really looking to do here is modify the jqXHR object before it gets sent. With .ajax(), this is done with the beforeSend() method. But since .get() is a shortcut, it doesn't allow it.

It should be relatively easy to switch your .ajax() calls to .get() calls though. After all, .get() is just a subset of .ajax(), so you can probably use all the default values for .ajax() (except, of course, for beforeSend()).

Edit:

::Looks at Jivings' answer::

Oh yeah, forgot about the cache parameter! While beforeSend() is useful for adding other headers, the built-in cache parameter is far simpler here.

how to convert JSONArray to List of Object using camel-jackson

I had similar json response coming from client. Created one main list class, and one POJO class.

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Root cause: Corrupted user profile of user account used to start database

The main thread here seems to be a corrupted user account profile for the account that is used to start the DB engine. This is the account that was specified for the "SQL Server Database" engine during installation. In the setup event log, it's also indicated by the following entry:

SQLSVCACCOUNT:                 NT AUTHORITY\SYSTEM

According to the link provided by @royki:

The root cause of this issue, in most cases, is that the profile of the user being used for the service account (in my case it was local system) is corrupted.

This would explain why other respondents had success after changing to different accounts:

  • bmjjr suggests changing to "NT AUTHORITY\NETWORK SERVICE"
  • comments to @bmjjr indicate different accounts "I used NT AUTHORITY\LOCAL SERVICE. That helped too"
  • @Julio Nobre had success with "NT Authority\System "

Fix: reset the corrupt user profile

To fix the user profile that's causing the error, follow the steps listed KB947215.

The main steps from KB947215 are summarized as follows:-

  1. Open regedit
  2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
  3. Navigate to the SID for the corrupted profile

    To find the SID, click on each SID GUID, review the value for the ProfileImagePath value, and see if it's the correct account. For system accounts, there's a different way to know the SID for the account that failed:

The main system account SIDs of interest are:

SID          Name               Also Known As
S-1-5-18     Local System       NT AUTHORITY\SYSTEM
S-1-5-19     LocalService       NT AUTHORITY\LOCAL SERVICE
S-1-5-20     NetworkService     NT AUTHORITY\NETWORK SERVICE

For information on additional SIDs, see Well-known security identifiers in Windows operating systems.

  1. If there are two entries (e.g. with a .bak) at the end for the SID in question, or the SID in question ends in .bak, ensure to follow carefully the steps in the KB947215 article.
  2. Reset the values for RefCount and State to be 0.
  3. Reboot.
  4. Retry the SQL Server installation.

Mocking Extension Methods with Moq

I like to use the wrapper (adapter pattern) when I am wrapping the object itself. I'm not sure I'd use that for wrapping an extension method, which is not part of the object.

I use an internal Lazy Injectable Property of either type Action, Func, Predicate, or delegate and allow for injecting (swapping out) the method during a unit test.

    internal Func<IMyObject, string, object> DoWorkMethod
    {
        [ExcludeFromCodeCoverage]
        get { return _DoWorkMethod ?? (_DoWorkMethod = (obj, val) => { return obj.DoWork(val); }); }
        set { _DoWorkMethod = value; }
    } private Func<IMyObject, string, object> _DoWorkMethod;

Then you call the Func instead of the actual method.

    public object SomeFunction()
    {
        var val = "doesn't matter for this example";
        return DoWorkMethod.Invoke(MyObjectProperty, val);
    }

For a more complete example, check out http://www.rhyous.com/2016/08/11/unit-testing-calls-to-complex-extension-methods/

jquery live hover

jQuery 1.4.1 now supports "hover" for live() events, but only with one event handler function:

$("table tr").live("hover",

function () {

});

Alternatively, you can provide two functions, one for mouseenter and one for mouseleave:

$("table tr").live({
    mouseenter: function () {

    },
    mouseleave: function () {

    }
});

Installing specific laravel version with composer create-project

Installing specific laravel version with composer create-project

composer global require laravel/installer

Then, if you want install specific version then just edit version values "6." , "5.8."

composer create-project --prefer-dist laravel/laravel Projectname "6.*"

Run Local Development Server

php artisan serve

Most efficient T-SQL way to pad a varchar on the left to a certain length?

How about this:

replace((space(3 - len(MyField))

3 is the number of zeros to pad

Printing a char with printf

Yes, it prints GARBAGE unless you are lucky.

VERY IMPORTANT.

The type of the printf/sprintf/fprintf argument MUST match the associated format type char.

If the types don't match and it compiles, the results are very undefined.

Many newer compilers know about printf and issue warnings if the types do not match. If you get these warnings, FIX them.

If you want to convert types for arguments for variable functions, you must supply the cast (ie, explicit conversion) because the compiler can't figure out that a conversion needs to be performed (as it can with a function prototype with typed arguments).

printf("%d\n", (int) ch)

In this example, printf is being TOLD that there is an "int" on the stack. The cast makes sure that whatever thing sizeof returns (some sort of long integer, usually), printf will get an int.

printf("%d", (int) sizeof('\n'))

Why can't variables be declared in a switch statement?

I believe the issue at hand is that is the statement was skipped, and you tried to use the var elsewhere, it wouldn't be declared.

Use a cell value in VBA function with a variable

VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.

Dim val1 As Integer, val2 As Integer, i As Integer

For i = 1 To 333

  Sheets("Feuil2").Activate
  ActiveSheet.Cells(i, 1).Select

    val1 = Cells(i, 1).Value
    val2 = Cells(i, 2).Value

Sheets("Classeur2.csv").Select
Cells(val1, val2).Select

ActiveCell.FormulaR1C1 = "1"

Next i

How can I solve equations in Python?

There are two ways to approach this problem: numerically and symbolically.

To solve it numerically, you have to first encode it as a "runnable" function - stick a value in, get a value out. For example,

def my_function(x):
    return 2*x + 6

It is quite possible to parse a string to automatically create such a function; say you parse 2x + 6 into a list, [6, 2] (where the list index corresponds to the power of x - so 6*x^0 + 2*x^1). Then:

def makePoly(arr):
    def fn(x):
        return sum(c*x**p for p,c in enumerate(arr))
    return fn

my_func = makePoly([6, 2])
my_func(3)    # returns 12

You then need another function which repeatedly plugs an x-value into your function, looks at the difference between the result and what it wants to find, and tweaks its x-value to (hopefully) minimize the difference.

def dx(fn, x, delta=0.001):
    return (fn(x+delta) - fn(x))/delta

def solve(fn, value, x=0.5, maxtries=1000, maxerr=0.00001):
    for tries in xrange(maxtries):
        err = fn(x) - value
        if abs(err) < maxerr:
            return x
        slope = dx(fn, x)
        x -= err/slope
    raise ValueError('no solution found')

There are lots of potential problems here - finding a good starting x-value, assuming that the function actually has a solution (ie there are no real-valued answers to x^2 + 2 = 0), hitting the limits of computational accuracy, etc. But in this case, the error minimization function is suitable and we get a good result:

solve(my_func, 16)    # returns (x =) 5.000000000000496

Note that this solution is not absolutely, exactly correct. If you need it to be perfect, or if you want to try solving families of equations analytically, you have to turn to a more complicated beast: a symbolic solver.

A symbolic solver, like Mathematica or Maple, is an expert system with a lot of built-in rules ("knowledge") about algebra, calculus, etc; it "knows" that the derivative of sin is cos, that the derivative of kx^p is kpx^(p-1), and so on. When you give it an equation, it tries to find a path, a set of rule-applications, from where it is (the equation) to where you want to be (the simplest possible form of the equation, which is hopefully the solution).

Your example equation is quite simple; a symbolic solution might look like:

=> LHS([6, 2]) RHS([16])

# rule: pull all coefficients into LHS
LHS, RHS = [lh-rh for lh,rh in izip_longest(LHS, RHS, 0)], [0]

=> LHS([-10,2]) RHS([0])

# rule: solve first-degree poly
if RHS==[0] and len(LHS)==2:
    LHS, RHS = [0,1], [-LHS[0]/LHS[1]]

=> LHS([0,1]) RHS([5])

and there is your solution: x = 5.

I hope this gives the flavor of the idea; the details of implementation (finding a good, complete set of rules and deciding when each rule should be applied) can easily consume many man-years of effort.

Find object by its property in array of objects with AngularJS way

The solucion that work for me is the following

$filter('filter')(data, {'id':10}) 

How to drop columns by name in a data frame

I tried to delete a column while using the package data.table and got an unexpected result. I kind of think the following might be worth posting. Just a little cautionary note.

[ Edited by Matthew ... ]

DF = read.table(text = "
     fruit state grade y1980 y1990 y2000
     apples Ohio   aa    500   100   55
     apples Ohio   bb      0     0   44
     apples Ohio   cc    700     0   33
     apples Ohio   dd    300    50   66
", sep = "", header = TRUE, stringsAsFactors = FALSE)

DF[ , !names(DF) %in% c("grade")]   # all columns other than 'grade'
   fruit state y1980 y1990 y2000
1 apples  Ohio   500   100    55
2 apples  Ohio     0     0    44
3 apples  Ohio   700     0    33
4 apples  Ohio   300    50    66

library('data.table')
DT = as.data.table(DF)

DT[ , !names(dat4) %in% c("grade")]    # not expected !! not the same as DF !!
[1]  TRUE  TRUE FALSE  TRUE  TRUE  TRUE

DT[ , !names(DT) %in% c("grade"), with=FALSE]    # that's better
    fruit state y1980 y1990 y2000
1: apples  Ohio   500   100    55
2: apples  Ohio     0     0    44
3: apples  Ohio   700     0    33
4: apples  Ohio   300    50    66

Basically, the syntax for data.table is NOT exactly the same as data.frame. There are in fact lots of differences, see FAQ 1.1 and FAQ 2.17. You have been warned!

Bootstrap 3 .col-xs-offset-* doesn't work?

As per the latest bootstrap v3.3.7 xs-offseting is allowed. See the documentation here bootstrap offseting. So you can use

<div class="col-xs-2 col-xs-offset-1">.col-xs-2 .col-xs-offset-1</div>

Convert URL to File or Blob for FileReader.readAsDataURL

The suggested edit queue is full for @tibor-udvari's excellent fetch answer, so I'll post my suggested edits as a new answer.

This function gets the content type from the header if returned, otherwise falls back on a settable default type.

async function getFileFromUrl(url, name, defaultType = 'image/jpeg'){
  const response = await fetch(url);
  const data = await response.blob();
  return new File([data], name, {
    type: response.headers.get('content-type') || defaultType,
  });
}

// `await` can only be used in an async body, but showing it here for simplicity.
const file = await getFileFromUrl('https://example.com/image.jpg', 'example.jpg');

How to set cookies in laravel 5 independently inside controller

You are going right way my friend.Now if you want retrive cookie anywhere in project just put this code $val = Cookie::get('COOKIE_NAME'); That's it! For more information how can this done click here

Understanding the main method of python

Python does not have a defined entry point like Java, C, C++, etc. Rather it simply executes a source file line-by-line. The if statement allows you to create a main function which will be executed if your file is loaded as the "Main" module rather than as a library in another module.

To be clear, this means that the Python interpreter starts at the first line of a file and executes it. Executing lines like class Foobar: and def foobar() creates either a class or a function and stores them in memory for later use.

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

The table names are case-sensitive so you should use lower-case nat instead of upper-case NAT. For example;

iptables -t nat -A POSTROUTING -s 192.168.1.1/24 -o eth0 -j MASQUERADE

mysql SELECT IF statement with OR

IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment

Will do the job as Buttle Butkus suggested.

C++ - Decimal to binary converting

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

void Decimal2Binary(long value,char *b,int len)
{
    if(value>0)
    {
        do
        {
            if(value==1)
            {
                *(b+len-1)='1';
                break;
            }
            else
            {
                *(b+len-1)=(value%2)+48;
                value=value/2;
                len--;
            }
        }while(1);
    }
}
long Binary2Decimal(char *b,int len)
{
    int i=0;
    int j=0;
    long value=0;
    for(i=(len-1);i>=0;i--)
    {
        if(*(b+i)==49)
        {
            value+=pow(2,j);
        }
        j++;
    }
    return value;
}
int main()
{
    char data[11];//????BIT????????
    long value=1023;
    memset(data,'0',sizeof(data));
    data[10]='\0';//????
    Decimal2Binary(value,data,10);
    printf("%d->%s\n",value,data);
    value=Binary2Decimal(data,10);
    printf("%s->%d",data,value);
    return 0;
}

download a file from Spring boot rest service

If you need to download a huge file from the server's file system, then ByteArrayResource can take all Java heap space. In that case, you can use FileSystemResource

How to "properly" print a list?

If you are using Python3:

print('[',end='');print(*L, sep=', ', end='');print(']')

Triangle Draw Method

There is not a drawTriangle method neither in Graphics nor Graphics2D. You need to do it by yourself. You can draw three lines using the drawLine method or use one these methods:

These methods work with polygons. You may change the prefix draw to fill when you want to fill the polygon defined by the point set. I inserted the documentation links. Take a look to learn how to use them.

There is the GeneralPath class too. It can be used with Graphics2D, which is capable to draw Shapes. Take a look:

Linq order by, group by and order by each group?

Sure:

var query = grades.GroupBy(student => student.Name)
                  .Select(group => 
                        new { Name = group.Key,
                              Students = group.OrderByDescending(x => x.Grade) })
                  .OrderBy(group => group.Students.First().Grade);

Note that you can get away with just taking the first grade within each group after ordering, because you already know the first entry will be have the highest grade.

Then you could display them with:

foreach (var group in query)
{
    Console.WriteLine("Group: {0}", group.Name);
    foreach (var student in group.Students)
    {
        Console.WriteLine("  {0}", student.Grade);
    }
}

java get file size efficiently

If you want the file size of multiple files in a directory, use Files.walkFileTree. You can obtain the size from the BasicFileAttributes that you'll receive.

This is much faster then calling .length() on the result of File.listFiles() or using Files.size() on the result of Files.newDirectoryStream(). In my test cases it was about 100 times faster.

Difference between setUp() and setUpBeforeClass()

From the Javadoc:

Sometimes several tests need to share computationally expensive setup (like logging into a database). While this can compromise the independence of tests, sometimes it is a necessary optimization. Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those the current class.

How to install Anaconda on RaspBerry Pi 3 Model B

Installing Miniconda on Raspberry Pi and adding Python 3.5 / 3.6

Skip the first section if you have already installed Miniconda successfully.

Installation of Miniconda on Raspberry Pi

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
sudo md5sum Miniconda3-latest-Linux-armv7l.sh
sudo /bin/bash Miniconda3-latest-Linux-armv7l.sh

Accept the license agreement with yes

When asked, change the install location: /home/pi/miniconda3

Do you wish the installer to prepend the Miniconda3 install location to PATH in your /root/.bashrc ? yes

Now add the install path to the PATH variable:

sudo nano /home/pi/.bashrc

Go to the end of the file .bashrc and add the following line:

export PATH="/home/pi/miniconda3/bin:$PATH"

Save the file and exit.

To test if the installation was successful, open a new terminal and enter

conda

If you see a list with commands you are ready to go.

But how can you use Python versions greater than 3.4 ?


Adding Python 3.5 / 3.6 to Miniconda on Raspberry Pi

After the installation of Miniconda I could not yet install Python versions higher than Python 3.4, but i needed Python 3.5. Here is the solution which worked for me on my Raspberry Pi 4:

First i added the Berryconda package manager by jjhelmus (kind of an up-to-date version of the armv7l version of Miniconda):

conda config --add channels rpi

Only now I was able to install Python 3.5 or 3.6 without the need for compiling it myself:

conda install python=3.5
conda install python=3.6

Afterwards I was able to create environments with the added Python version, e.g. with Python 3.5:

conda create --name py35 python=3.5

The new environment "py35" can now be activated:

source activate py35

Using Python 3.7 on Raspberry Pi

Currently Jonathan Helmus, who is the developer of berryconda, is working on adding Python 3.7 support, if you want to see if there is an update or if you want to support him, have a look at this pull request. (update 20200623) berryconda is now inactive, This project is no longer active, no recipe will be updated and no packages will be added to the rpi channel. If you need to run Python 3.7 on your Pi right now, you can do so without Miniconda. Check if you are running the latest version of Raspbian OS called Buster. Buster ships with Python 3.7 preinstalled (source), so simply run your program with the following command:

Python3.7 app-that-needs-python37.py

I hope this solution will work for you too!

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

If you don't have permissions to change your default DB you could manually select a different DB at the top of your queries...

USE [SomeOtherDb]
SELECT 'I am now using a different DB'

Will work as long as you have permission to the other DB

Creating a copy of an object in C#

You could do:

class myClass : ICloneable
{
    public String test;
    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

then you can do

myClass a = new myClass();
myClass b = (myClass)a.Clone();

N.B. MemberwiseClone() Creates a shallow copy of the current System.Object.

How can I open a website in my web browser using Python?

You can simply simply achieve it with any python module that gives you an interaction with command line(cmd) like subprocess, os, etc. but here I came up with examples on only two modules.

Here is syntax (command) cmd /c start browser_name "URL"

Example

import os
# or open with iexplore
os.system('cmd /c start iexplore "http://your_url"')

# or open with chrome
os.system('cmd /c start chrome "http://your_url"')
__import__('subprocess').getoutput('cmd /c start iexplore "http://your_url"')

You can also run the command in the cmd it will work to or use other module call click which mainly used for writing command line utilities.

here is how

import click

click.launch('http://your_url')

Deserialize JSON string to c# object

Use this code:

var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);

How can I open a link in a new window?

You can also use the jquery prop() method for this.

$(function(){
  $('yourselector').prop('target', '_blank');
}); 

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

Using Ubuntu, got the same issue I noticed that the owner of some of the directories in ~/workspace/.metadata/.plugins/ ...etc... was root changed owner to me and the error stopped happening.

Looks like the same sort of issue may be caused by multiple causes.

Any way to break if statement in PHP?

i have a simple solution without lot of changes. the initial statement is

I want to break the if statement above and stop executing echo "yes"; or such codes which are no longer necessary to be executed, there may be or may not be an additional condition, is there way to do this?

so, it seem simple. try code like this.

$a="test";
if("test"==$a)
{
  if (1==0){
      echo "yes"; // this line while never be executed. 
      // and can be reexecuted simply by changing if (1==0) to if (1==1) 
  }
}
echo "finish";

if you want to try without this code, it's simple. and you can back when you want. another solution is comment blocks. or simply thinking and try in another separated code and copy paste only the result in your final code. and if a code is no longer nescessary, in your case, the result can be

$a="test";
echo "finish";

with this code, the original statement is completely respected.. :) and more readable!

Set the space between Elements in Row Flutter

There are many ways of doing it, I'm listing a few here:

  1. Use SizedBox if you want to set some specific space

    Row(
      children: <Widget>[
        Text("1"),
        SizedBox(width: 50), // give it width
        Text("2"),
      ],
    )
    

    enter image description here


  1. Use Spacer if you want both to be as far apart as possible.

    Row(
      children: <Widget>[
        Text("1"),
        Spacer(), // use Spacer
        Text("2"),
      ],
    )
    

    enter image description here


  1. Use mainAxisAlignment according to your needs:

    Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly, // use whichever suits your need
      children: <Widget>[
        Text("1"),
        Text("2"),
      ],
    )
    

    enter image description here


  1. Use Wrap instead of Row and give some spacing

    Wrap(
      spacing: 100, // set spacing here
      children: <Widget>[
        Text("1"),
        Text("2"),
      ],
    )
    

    enter image description here


  1. Use Wrap instead of Row and give it alignment

    Wrap(
      alignment: WrapAlignment.spaceAround, // set your alignment
      children: <Widget>[
        Text("1"),
        Text("2"),
      ],
    )
    

    enter image description here

undefined reference to `WinMain@16'

I was encountering this error while compiling my application with SDL. This was caused by SDL defining it's own main function in SDL_main.h. To prevent SDL define the main function an SDL_MAIN_HANDLED macro has to be defined before the SDL.h header is included.

How to wrap text in LaTeX tables?

I like the simplicity of tabulary package:

\usepackage{tabulary}
...
\begin{tabulary}{\linewidth}{LCL}
    \hline
    Short sentences      & \#  & Long sentences                                                 \\
    \hline
    This is short.       & 173 & This is much loooooooonger, because there are many more words.  \\
    This is not shorter. & 317 & This is still loooooooonger, because there are many more words. \\
    \hline
\end{tabulary} 

In the example, you arrange the whole width of the table with respect to \textwidth. E.g 0.4 of it. Then the rest is automatically done by the package.

Most of the example is taken from http://en.wikibooks.org/wiki/LaTeX/Tables .

Why are only a few video games written in Java?

.NET definitely has some of the same issues that Java has when it comes to intense 3D performance. Microsoft has also invested a lot more time and money in the development of the libraries when it comes to working with 3D heavy operations.

(...personally, I also think they had a leg up when it comes to the magic between DirectX and .NET)

How to detect browser using angularjs?

Angular library uses document.documentMode to identify IE . It holds major version number for IE, or NaN/undefined if User Agent is not IE.

/**
* documentMode is an IE-only property
* http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
*/
var msie = document.documentMode;

https://github.com/angular/angular.js/blob/v1.5.0/src/Angular.js#L167-L171

Example with $document (angular wrapper for window.document)

// var msie = document.documentMode;
var msie = $document[0].documentMode;
// if is IE (documentMode contains IE version)
if (msie) {
  // IE logic here

  if (msie === 9) {
    // IE 9 logic here

  }
}

Set cursor position on contentEditable <div>

I took Nico Burns's answer and made it using jQuery:

  • Generic: For every div contentEditable="true"
  • Shorter

You'll need jQuery 1.6 or higher:

savedRanges = new Object();
$('div[contenteditable="true"]').focus(function(){
    var s = window.getSelection();
    var t = $('div[contenteditable="true"]').index(this);
    if (typeof(savedRanges[t]) === "undefined"){
        savedRanges[t]= new Range();
    } else if(s.rangeCount > 0) {
        s.removeAllRanges();
        s.addRange(savedRanges[t]);
    }
}).bind("mouseup keyup",function(){
    var t = $('div[contenteditable="true"]').index(this);
    savedRanges[t] = window.getSelection().getRangeAt(0);
}).on("mousedown click",function(e){
    if(!$(this).is(":focus")){
        e.stopPropagation();
        e.preventDefault();
        $(this).focus();
    }
});

_x000D_
_x000D_
savedRanges = new Object();_x000D_
$('div[contenteditable="true"]').focus(function(){_x000D_
    var s = window.getSelection();_x000D_
    var t = $('div[contenteditable="true"]').index(this);_x000D_
    if (typeof(savedRanges[t]) === "undefined"){_x000D_
        savedRanges[t]= new Range();_x000D_
    } else if(s.rangeCount > 0) {_x000D_
        s.removeAllRanges();_x000D_
        s.addRange(savedRanges[t]);_x000D_
    }_x000D_
}).bind("mouseup keyup",function(){_x000D_
    var t = $('div[contenteditable="true"]').index(this);_x000D_
    savedRanges[t] = window.getSelection().getRangeAt(0);_x000D_
}).on("mousedown click",function(e){_x000D_
    if(!$(this).is(":focus")){_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $(this).focus();_x000D_
    }_x000D_
});
_x000D_
div[contenteditable] {_x000D_
    padding: 1em;_x000D_
    font-family: Arial;_x000D_
    outline: 1px solid rgba(0,0,0,0.5);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div contentEditable="true"></div>_x000D_
<div contentEditable="true"></div>_x000D_
<div contentEditable="true"></div>
_x000D_
_x000D_
_x000D_

View the change history of a file using Git versioning

If you're using the git GUI (on Windows) under the Repository menu you can use "Visualize master's History". Highlight a commit in the top pane and a file in the lower right and you'll see the diff for that commit in the lower left.

Open Sublime Text from Terminal in macOS

The following worked for me

open -a Sublime\ Text file_name.txt
open -a Sublime\ Text Folder_Path

You can use alias to make it event simple like

Add the following line in your

~/.bash_profile

alias sublime="open -a Sublime\ Text $@"

Then next time you can use following command to open files/folders

sublime file_name.txt
sublime Folder_Path

Creating a new dictionary in Python

d = dict()

or

d = {}

or

import types
d = types.DictType.__new__(types.DictType, (), {})

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I'm not sure for JPA 1.0 but you can pass a Collection in JPA 2.0:

String qlString = "select item from Item item where item.name IN :names"; 
Query q = em.createQuery(qlString, Item.class);

List<String> names = Arrays.asList("foo", "bar");

q.setParameter("names", names);
List<Item> actual = q.getResultList();

assertNotNull(actual);
assertEquals(2, actual.size());

Tested with EclipseLInk. With Hibernate 3.5.1, you'll need to surround the parameter with parenthesis:

String qlString = "select item from Item item where item.name IN (:names)";

But this is a bug, the JPQL query in the previous sample is valid JPQL. See HHH-5126.

Looping through the content of a file in Bash

This might be the simplest answer and maybe it don't work in all cases, but it is working great for me:

while read line;do echo "$line";done<peptides.txt

if you need to enclose in parenthesis for spaces:

while read line;do echo \"$line\";done<peptides.txt

Ahhh this is pretty much the same as the answer that got upvoted most, but its all on one line.

Bootstrap 3 unable to display glyphicon properly

the icons and the css are now seperated out from bootstrap. here is a fiddle that is from another stackoverflow answer

@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc2/css/bootstrap-glyphicons.css");

http://jsfiddle.net/aQrPd/1/

Bootstrap 3 Glyphicons CDN

What's the difference between isset() and array_key_exists()?

Answer to an old question as no answer here seem to address the 'warning' problem (explanation follows)

Basically, in this case of checking if a key exists in an array, isset

  • tells if the expression (array) is defined, and the key is set
  • no warning or error if the var is not defined, not an array ...
  • but returns false if the value for that key is null

and array_key_exists

  • tells if a key exists in an array as the name implies
  • but gives a warning if the array parameter is not an array

So how do we check if a key exists which value may be null in a variable

  • that may or may not be an array
  • (or similarly is a multidimensional array for which the key check happens at dim 2 and dim 1 value may not be an array for the 1st dim (etc...))

without getting a warning, without missing the existing key when its value is null (what were the PHP devs thinking would also be an interesting question, but certainly not relevant on SO). And of course we don't want to use @

isset($var[$key]);            // silent but misses null values
array_key_exists($key, $var); // works but warning if $var not defined/array

It seems is_array should be involved in the equation, but it gives a warning if $var is not defined, so that could be a solution:

if (isset($var[$key]) || 
    isset($var) && is_array($var) && array_key_exists($key, $var)) ...

which is likely to be faster if the tests are mainly on non-null values. Otherwise for an array with mostly null values

if (isset($var) && is_array($var) && array_key_exists($key, $var)) ...

will do the work.

Failed Apache2 start, no error log

in the apache virtualhost you have to define the path to the error log file. when apache2 start for the first time it will create it automatically.

for example ErrorLog "/var/www/www.localhost.com/log-apache2/error.log" in the apache virtualhost..

Eloquent ORM laravel 5 Get Array of ids

You could use lists() :

test::where('id' ,'>' ,0)->lists('id')->toArray();

NOTE : Better if you define your models in Studly Case format, e.g Test.


You could also use get() :

test::where('id' ,'>' ,0)->get('id');

UPDATE: (For versions >= 5.2)

The lists() method was deprecated in the new versions >= 5.2, now you could use pluck() method instead :

test::where('id' ,'>' ,0)->pluck('id')->toArray();

NOTE: If you need a string, for example in a blade, you can use function without the toArray() part, like:

test::where('id' ,'>' ,0)->pluck('id');

How to add hamburger menu in bootstrap

CSS only (no icon sets) Codepen

_x000D_
_x000D_
.nav-link #navBars {_x000D_
margin-top: -3px;_x000D_
padding: 8px 15px 3px;_x000D_
border: 1px solid rgba(0,0,0,.125);_x000D_
border-radius: .25rem;_x000D_
}_x000D_
_x000D_
.nav-link #navBars input {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.nav-link #navBars span {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
display: block;_x000D_
margin-bottom: 6px;_x000D_
width: 24px;_x000D_
height: 2px;_x000D_
background-color: rgba(125, 125, 126, 1);_x000D_
border-radius: .25rem;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
   <!-- <a class="navbar-brand" href="#">_x000D_
      <img src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="">_x000D_
      Bootstrap_x000D_
      </a> -->_x000D_
   <!-- https://stackoverflow.com/questions/26317679 -->_x000D_
   <a class="nav-link" href="#">_x000D_
      <div id="navBars">_x000D_
         <input type="checkbox" /><span></span>_x000D_
         <span></span>_x000D_
         <span></span>_x000D_
      </div>_x000D_
   </a>_x000D_
   <!-- /26317679 -->_x000D_
   <div class="collapse navbar-collapse" id="navbarNav">_x000D_
      <ul class="navbar-nav">_x000D_
         <li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Features</a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>_x000D_
         <li class="nav-item"><a class="nav-link disabled" href="#">Disabled</a></li>_x000D_
      </ul>_x000D_
   </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Drawing in Java using Canvas

You've got to override your Canvas's paint(Graphics g) method and perform your drawing there. See the paint() documentation.

As it states, the default operation is to clear the canvas, so your call to the canvas' graphics object doesn't perform as you would expect.

How can I select all elements without a given class in jQuery?

You can use the .not() method or :not() selector

Code based on your example:

$("ul#list li").not(".active") // not method
$("ul#list li:not(.active)")   // not selector

Python: json.loads returns items prefixing with 'u'

Unicode is an appropriate type here. The JSONDecoder docs describe the conversion table and state that json string objects are decoded into Unicode objects

https://docs.python.org/2/library/json.html#encoders-and-decoders

JSON                    Python
==================================
object                  dict
array                   list
string                  unicode
number (int)            int, long
number (real)           float
true                    True
false                   False
null                    None

"encoding determines the encoding used to interpret any str objects decoded by this instance (UTF-8 by default)."

How to split one text file into multiple *.txt files?

If each part have the same lines number, for example 22, here my solution:
split --numeric-suffixes=2 --additional-suffix=.txt -l 22 file.txt file
and you obtain file2.txt with the first 22 lines, file3.txt the 22 next line…

Thank @hamruta-takawale, @dror-s and @stackoverflowuser2010

SQLite - UPSERT *not* INSERT or REPLACE

Beginning with version 3.24.0 UPSERT is supported by SQLite.

From the documentation:

UPSERT is a special syntax addition to INSERT that causes the INSERT to behave as an UPDATE or a no-op if the INSERT would violate a uniqueness constraint. UPSERT is not standard SQL. UPSERT in SQLite follows the syntax established by PostgreSQL. UPSERT syntax was added to SQLite with version 3.24.0 (pending).

An UPSERT is an ordinary INSERT statement that is followed by the special ON CONFLICT clause

enter image description here

Image source: https://www.sqlite.org/images/syntax/upsert-clause.gif

How to open standard Google Map application from my application?

You can also use the code snippet below, with this manner the existence of google maps is checked before the intent is started.

Uri gmmIntentUri = Uri.parse(String.format(Locale.ENGLISH,"geo:%f,%f", latitude, longitude));
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
    startActivity(mapIntent);
}

Reference: https://developers.google.com/maps/documentation/android-api/intents

Is there any way to return HTML in a PHP function? (without building the return value as a string)

This may be a sketchy solution, and I'd appreciate anybody pointing out whether this is a bad idea, since it's not a standard use of functions. I've had some success getting HTML out of a PHP function without building the return value as a string with the following:

function noStrings() {
    echo ''?>
        <div>[Whatever HTML you want]</div>
    <?php;
}

The just 'call' the function:

noStrings();

And it will output:

<div>[Whatever HTML you want]</div>

Using this method, you can also define PHP variables within the function and echo them out inside the HTML.

right click context menu for datagridview

You can use the CellMouseEnter and CellMouseLeave to track the row number that the mouse is currently hovering over.

Then use a ContextMenu object to display you popup menu, customised for the current row.

Here's a quick and dirty example of what I mean...

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        ContextMenu m = new ContextMenu();
        m.MenuItems.Add(new MenuItem("Cut"));
        m.MenuItems.Add(new MenuItem("Copy"));
        m.MenuItems.Add(new MenuItem("Paste"));

        int currentMouseOverRow = dataGridView1.HitTest(e.X,e.Y).RowIndex;

        if (currentMouseOverRow >= 0)
        {
            m.MenuItems.Add(new MenuItem(string.Format("Do something to row {0}", currentMouseOverRow.ToString())));
        }

        m.Show(dataGridView1, new Point(e.X, e.Y));

    }
}

Android: how to hide ActionBar on certain activities

As you are asking about how to hide in a certain activity, this is what you need :

getSupportActionBar().hide(); 

Hibernate dialect for Oracle Database 11g?

According to supported databases, Oracle 11g is not officially supported. Although, I believe you shouldn't have any problems using org.hibernate.dialect.OracleDialect.

Android emulator: How to monitor network traffic?

I would suggest you use Wireshark.

Steps:

  1. Install Wireshark.
  2. Select the network connection that you are using for the calls(for eg, select the Wifi if you are using it)
  3. There will be many requests and responses, close extra applications.
  4. Usually the requests are in green color, once you spot your request, copy the destination address and use the filter on top by typing ip.dst==52.187.182.185 by putting the destination address.

You can make use of other filtering techniques mentioned here to get specific traffic.

Angles between two n-dimensional vectors in Python

For the few who may have (due to SEO complications) ended here trying to calculate the angle between two lines in python, as in (x0, y0), (x1, y1) geometrical lines, there is the below minimal solution (uses the shapely module, but can be easily modified not to):

from shapely.geometry import LineString
import numpy as np

ninety_degrees_rad = 90.0 * np.pi / 180.0

def angle_between(line1, line2):
    coords_1 = line1.coords
    coords_2 = line2.coords

    line1_vertical = (coords_1[1][0] - coords_1[0][0]) == 0.0
    line2_vertical = (coords_2[1][0] - coords_2[0][0]) == 0.0

    # Vertical lines have undefined slope, but we know their angle in rads is = 90° * p/180
    if line1_vertical and line2_vertical:
        # Perpendicular vertical lines
        return 0.0
    if line1_vertical or line2_vertical:
        # 90° - angle of non-vertical line
        non_vertical_line = line2 if line1_vertical else line1
        return abs((90.0 * np.pi / 180.0) - np.arctan(slope(non_vertical_line)))

    m1 = slope(line1)
    m2 = slope(line2)

    return np.arctan((m1 - m2)/(1 + m1*m2))

def slope(line):
    # Assignments made purely for readability. One could opt to just one-line return them
    x0 = line.coords[0][0]
    y0 = line.coords[0][1]
    x1 = line.coords[1][0]
    y1 = line.coords[1][1]
    return (y1 - y0) / (x1 - x0)

And the use would be

>>> line1 = LineString([(0, 0), (0, 1)]) # vertical
>>> line2 = LineString([(0, 0), (1, 0)]) # horizontal
>>> angle_between(line1, line2)
1.5707963267948966
>>> np.degrees(angle_between(line1, line2))
90.0

How to make div appear in front of another?

Use the CSS z-index property. Elements with a greater z-index value are positioned in front of elements with smaller z-index values.

Note that for this to work, you also need to set a position style (position:absolute, position:relative, or position:fixed) on both/all of the elements you want to order.

Arrays vs Vectors: Introductory Similarities and Differences

Those reference pretty much answered your question. Simply put, vectors' lengths are dynamic while arrays have a fixed size. when using an array, you specify its size upon declaration:

int myArray[100];
myArray[0]=1;
myArray[1]=2;
myArray[2]=3;

for vectors, you just declare it and add elements

vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
...

at times you wont know the number of elements needed so a vector would be ideal for such a situation.

Show/Hide Table Rows using Javascript classes

event.preventDefault()

Doesn't work in all browsers. Instead you could return false in OnClick event.

onClick="toggle_it('tr1');toggle_it('tr2'); return false;">

Not sure if this is the best way, but I tested in IE, FF and Chrome and its working fine.

How to create NSIndexPath for TableView

Use [NSIndexPath indexPathForRow:inSection:] to quickly create an index path.

Edit: In Swift 3:

let indexPath = IndexPath(row: rowIndex, section: sectionIndex)

Swift 5

IndexPath(row: 0, section: 0)

How to make FileFilter in java?

... What about using Apache's FileFilters from: org.apache.commons.io?

just like:

 import org.apache.commons.io.filefilter.FileFileFilter;
 import org.apache.commons.io.filefilter.WildcardFileFilter;

 ...

 File dir = new File(".");

 String[] filters = { "*.txt"};
 IOFileFilter wildCardFilter = new WildcardFileFilter(filters, IOCase.INSENSITIVE);

 String[] files = dir.list( wildCardFilter );
 for ( int i = 0; i < files.length; i++ ) {
     System.out.println(files[i]);
 }

How do I parse a string to a float or int?

Python method to check if a string is a float:

def is_float(value):
  try:
    float(value)
    return True
  except:
    return False

A longer and more accurate name for this function could be: is_convertible_to_float(value)

What is, and is not a float in Python may surprise you:

val                   is_float(val) Note
--------------------  ----------   --------------------------------
""                    False        Blank string
"127"                 True         Passed string
True                  True         Pure sweet Truth
"True"                False        Vile contemptible lie
False                 True         So false it becomes true
"123.456"             True         Decimal
"      -127    "      True         Spaces trimmed
"\t\n12\r\n"          True         whitespace ignored
"NaN"                 True         Not a number
"NaNanananaBATMAN"    False        I am Batman
"-iNF"                True         Negative infinity
"123.E4"              True         Exponential notation
".1"                  True         mantissa only
"1,234"               False        Commas gtfo
u'\x30'               True         Unicode is fine.
"NULL"                False        Null is not special
0x3fade               True         Hexadecimal
"6e7777777777777"     True         Shrunk to infinity
"1.797693e+308"       True         This is max value
"infinity"            True         Same as inf
"infinityandBEYOND"   False        Extra characters wreck it
"12.34.56"            False        Only one dot allowed
u'?'                 False        Japanese '4' is not a float.
"#56"                 False        Pound sign
"56%"                 False        Percent of what?
"0E0"                 True         Exponential, move dot 0 places
0**0                  True         0___0  Exponentiation
"-5e-5"               True         Raise to a negative number
"+1e1"                True         Plus is OK with exponent
"+1e1^5"              False        Fancy exponent not interpreted
"+1e1.3"              False        No decimals in exponent
"-+1"                 False        Make up your mind
"(1)"                 False        Parenthesis is bad

You think you know what numbers are? You are not so good as you think! Not big surprise.

Don't use this code on life-critical software!

Catching broad exceptions this way, killing canaries and gobbling the exception creates a tiny chance that a valid float as string will return false. The float(...) line of code can failed for any of a thousand reasons that have nothing to do with the contents of the string. But if you're writing life-critical software in a duck-typing prototype language like Python, then you've got much larger problems.

How to include files outside of Docker's build context?

You can also create a tarball of what the image needs first and use that as your context.

https://docs.docker.com/engine/reference/commandline/build/#/tarball-contexts

The preferred way of creating a new element with jQuery

The first option gives you more flexibilty:

var $div = $("<div>", {id: "foo", "class": "a"});
$div.click(function(){ /* ... */ });
$("#box").append($div);

And of course .html('*') overrides the content while .append('*') doesn't, but I guess, this wasn't your question.

Another good practice is prefixing your jQuery variables with $:
Is there any specific reason behind using $ with variable in jQuery

Placing quotes around the "class" property name will make it more compatible with less flexible browsers.

Shuffle an array with python, randomize array item order with python

In addition to the previous replies, I would like to introduce another function.

numpy.random.shuffle as well as random.shuffle perform in-place shuffling. However, if you want to return a shuffled array numpy.random.permutation is the function to use.

Sql connection-string for localhost server

use this connection string :

Server=HARIHARAN-PC\SQLEXPRESS;Intial Catalog=persons;Integrated Security=True;

rename person with your database name

Create a custom View by inflating a layout?

Use the LayoutInflater as I shown below.

    public View myView() {
        View v; // Creating an instance for View Object
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.myview, null);

        TextView text1 = v.findViewById(R.id.dolphinTitle);
        Button btn1 = v.findViewById(R.id.dolphinMinusButton);
        TextView text2 = v.findViewById(R.id.dolphinValue);
        Button btn2 = v.findViewById(R.id.dolphinPlusButton);

        return v;
    }

Getting coordinates of marker in Google Maps API

var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();

See the google.maps.LatLng docs and google.maps.Marker getPosition().

C# Clear all items in ListView

This is bit late, but this works for me at least using UWP

myListView.ItemsSource = null;

How to force Chrome browser to reload .css file while debugging in Visual Studio?

Easiest way on Safari 11.0 macOS SIERRA 10.12.6: Reload Page From Origin, you can use help to find out where in the menu it is located, or you can use the shortcut option(alt) + command + R.

How can I put CSS and HTML code in the same file?

Is this what you're looking for? You place you CSS between style tags in the HTML document header. I'm guessing for iPhone it's webkit so it should work.

<html>
<head>
    <style type="text/css">
    .title { color: blue; text-decoration: bold; text-size: 1em; }
    .author { color: gray; }
    </style>
</head>
<body>
    <p>
    <span class="title">La super bonne</span>
    <span class="author">proposée par Jérém</span>
    </p>
</body>
</html>

How to create a popup windows in javafx

Take a look at jfxmessagebox (http://en.sourceforge.jp/projects/jfxmessagebox/) if you are looking for very simple dialog popups.

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

to hide the horizontal scrollbars, you can set overflow-x to hidden, like this:

overflow-x: hidden;

Merge two objects with ES6

You can use Object.assign() to merge them into a new object:

_x000D_
_x000D_
const response = {_x000D_
  lat: -51.3303,_x000D_
  lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
  id: 'qwenhee-9763ae-lenfya',_x000D_
  address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = Object.assign({}, item, { location: response });_x000D_
_x000D_
console.log(newItem );
_x000D_
_x000D_
_x000D_

You can also use object spread, which is a Stage 4 proposal for ECMAScript:

_x000D_
_x000D_
const response = {_x000D_
  lat: -51.3303,_x000D_
  lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
  id: 'qwenhee-9763ae-lenfya',_x000D_
  address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = { ...item, location: response }; // or { ...response } if you want to clone response as well_x000D_
_x000D_
console.log(newItem );
_x000D_
_x000D_
_x000D_

What is the difference between #include <filename> and #include "filename"?

Some good answers here make references to the C standard but forgot the POSIX standard, especially the specific behavior of the c99 (e.g. C compiler) command.

According to The Open Group Base Specifications Issue 7,

-I directory

Change the algorithm for searching for headers whose names are not absolute pathnames to look in the directory named by the directory pathname before looking in the usual places. Thus, headers whose names are enclosed in double-quotes ( "" ) shall be searched for first in the directory of the file with the #include line, then in directories named in -I options, and last in the usual places. For headers whose names are enclosed in angle brackets ( "<>" ), the header shall be searched for only in directories named in -I options and then in the usual places. Directories named in -I options shall be searched in the order specified. Implementations shall support at least ten instances of this option in a single c99 command invocation.

So, in a POSIX compliant environment, with a POSIX compliant C compiler, #include "file.h" is likely going to search for ./file.h first, where . is the directory where is the file with the #include statement, while #include <file.h>, is likely going to search for /usr/include/file.h first, where /usr/include is your system defined usual places for headers (it's seems not defined by POSIX).

Forcing anti-aliasing using css: Is this a myth?

I disagree with Chad Birch. We can force anti-aliasing, at least in Chrome using a simple css trick with the -webkit-text-stroke property:-

-webkit-text-stroke: 1px transparent;

Increasing the JVM maximum heap size for memory intensive applications

32-bit Java is limited to approximately 1.4 to 1.6 GB.

Oracle 32 bit heap FAQ

Quote

The maximum theoretical heap limit for the 32-bit JVM is 4G. Due to various additional constraints such as available swap, kernel address space usage, memory fragmentation, and VM overhead, in practice the limit can be much lower. On most modern 32-bit Windows systems the maximum heap size will range from 1.4G to 1.6G. On 32-bit Solaris kernels the address space is limited to 2G. On 64-bit operating systems running the 32-bit VM, the max heap size can be higher, approaching 4G on many Solaris systems.

How can I show/hide component with JSF?

You can actually accomplish this without JavaScript, using only JSF's rendered attribute, by enclosing the elements to be shown/hidden in a component that can itself be re-rendered, such as a panelGroup, at least in JSF2. For example, the following JSF code shows or hides one or both of two dropdown lists depending on the value of a third. An AJAX event is used to update the display:

<h:selectOneMenu value="#{workflowProcEditBean.performedBy}">
    <f:selectItem itemValue="O" itemLabel="Originator" />
    <f:selectItem itemValue="R" itemLabel="Role" />
    <f:selectItem itemValue="E" itemLabel="Employee" />
    <f:ajax event="change" execute="@this" render="perfbyselection" />
</h:selectOneMenu>
<h:panelGroup id="perfbyselection">
    <h:selectOneMenu id="performedbyroleid" value="#{workflowProcEditBean.performedByRoleID}"
                     rendered="#{workflowProcEditBean.performedBy eq 'R'}">
        <f:selectItem itemLabel="- Choose One -" itemValue="" />
        <f:selectItems value="#{workflowProcEditBean.roles}" />
    </h:selectOneMenu>
    <h:selectOneMenu id="performedbyempid" value="#{workflowProcEditBean.performedByEmpID}"
                     rendered="#{workflowProcEditBean.performedBy eq 'E'}">
        <f:selectItem itemLabel="- Choose One -" itemValue="" />
        <f:selectItems value="#{workflowProcEditBean.employees}" />
    </h:selectOneMenu>
</h:panelGroup>

Default behavior of "git push" without a branch specified

I just committed my code to a branch and pushed it to github, like this:

git branch SimonLowMemoryExperiments
git checkout SimonLowMemoryExperiments
git add .
git commit -a -m "Lots of experimentation with identifying the memory problems"
git push origin SimonLowMemoryExperiments

How to send a GET request from PHP?

I like using fsockopen open for this.

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

Rather than using a DisplayFilter you could use a very simple CaptureFilter like

port 53

See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.

Difference between links and depends_on in docker_compose.yml

[Update Sep 2016]: This answer was intended for docker compose file v1 (as shown by the sample compose file below). For v2, see the other answer by @Windsooon.

[Original answer]:

It is pretty clear in the documentation. depends_on decides the dependency and the order of container creation and links not only does these, but also

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.

For example, assuming the following docker-compose.yml file:

web:
  image: example/my_web_app:latest
  links:
    - db
    - cache

db:
  image: postgres:latest

cache:
  image: redis:latest

With links, code inside web will be able to access the database using db:5432, assuming port 5432 is exposed in the db image. If depends_on were used, this wouldn't be possible, but the startup order of the containers would be correct.

Constants in Objective-C

I am generally using the way posted by Barry Wark and Rahul Gupta.

Although, I do not like repeating the same words in both .h and .m file. Note, that in the following example the line is almost identical in both files:

// file.h
extern NSString* const MyConst;

//file.m
NSString* const MyConst = @"Lorem ipsum";

Therefore, what I like to do is to use some C preprocessor machinery. Let me explain through the example.

I have a header file which defines the macro STR_CONST(name, value):

// StringConsts.h
#ifdef SYNTHESIZE_CONSTS
# define STR_CONST(name, value) NSString* const name = @ value
#else
# define STR_CONST(name, value) extern NSString* const name
#endif

The in my .h/.m pair where I want to define the constant I do the following:

// myfile.h
#import <StringConsts.h>

STR_CONST(MyConst, "Lorem Ipsum");
STR_CONST(MyOtherConst, "Hello world");

// myfile.m
#define SYNTHESIZE_CONSTS
#import "myfile.h"

et voila, I have all the information about the constants in .h file only.

Assigning variables with dynamic names in Java

This is not how you do things in Java. There are no dynamic variables in Java. Java variables have to be declared in the source code1.

Depending on what you are trying to achieve, you should use an array, a List or a Map; e.g.

int n[] = new int[3];
for (int i = 0; i < 3; i++) {
    n[i] = 5;
}

List<Integer> n = new ArrayList<Integer>();
for (int i = 1; i < 4; i++) {
    n.add(5);
}

Map<String, Integer> n = new HashMap<String, Integer>();
for (int i = 1; i < 4; i++) {
    n.put("n" + i, 5);
}

It is possible to use reflection to dynamically refer to variables that have been declared in the source code. However, this only works for variables that are class members (i.e. static and instance fields). It doesn't work for local variables. See @fyr's "quick and dirty" example.

However doing this kind of thing unnecessarily in Java is a bad idea. It is inefficient, the code is more complicated, and since you are relying on runtime checking it is more fragile. And this is not "variables with dynamic names". It is better described as dynamic access to variables with static names.


1 - That statement is slightly inaccurate. If you use BCEL or ASM, you can "declare" the variables in the bytecode file. But don't do it! That way lies madness!

Extract specific columns from delimited file using Awk

Not using awk but the simplest way I was able to get this done was to just use csvtool. I had other use cases as well to use csvtool and it can handle the quotes or delimiters appropriately if they appear within the column data itself.

csvtool format '%(2)\n' input.csv
csvtool format '%(2),%(3),%(4)\n' input.csv

Replacing 2 with the column number will effectively extract the column data you are looking for.

Is it possible to CONTINUE a loop from an exception?

In the construct you have provided, you don't need a CONTINUE. Once the exception is handled, the statement after the END is performed, assuming your EXCEPTION block doesn't terminate the procedure. In other words, it will continue on to the next iteration of the user_rec loop.

You also need to SELECT INTO a variable inside your BEGIN block:

SELECT attr INTO v_attr FROM attribute_table...

Obviously you must declare v_attr as well...

How can I pass selected row to commandLink inside dataTable or ui:repeat?

In JSF 1.2 this was done by <f:setPropertyActionListener> (within the command component). In JSF 2.0 (EL 2.2 to be precise, thanks to BalusC) it's possible to do it like this: action="${filterList.insert(f.id)}

How do I calculate a trendline for a graph?

Thanks to all for your help - I was off this issue for a couple of days and just came back to it - was able to cobble this together - not the most elegant code, but it works for my purposes - thought I'd share if anyone else encounters this issue:

public class Statistics
{
    public Trendline CalculateLinearRegression(int[] values)
    {
        var yAxisValues = new List<int>();
        var xAxisValues = new List<int>();

        for (int i = 0; i < values.Length; i++)
        {
            yAxisValues.Add(values[i]);
            xAxisValues.Add(i + 1);
        }

        return new Trendline(yAxisValues, xAxisValues);
    }
}

public class Trendline
{
    private readonly IList<int> xAxisValues;
    private readonly IList<int> yAxisValues;
    private int count;
    private int xAxisValuesSum;
    private int xxSum;
    private int xySum;
    private int yAxisValuesSum;

    public Trendline(IList<int> yAxisValues, IList<int> xAxisValues)
    {
        this.yAxisValues = yAxisValues;
        this.xAxisValues = xAxisValues;

        this.Initialize();
    }

    public int Slope { get; private set; }
    public int Intercept { get; private set; }
    public int Start { get; private set; }
    public int End { get; private set; }

    private void Initialize()
    {
        this.count = this.yAxisValues.Count;
        this.yAxisValuesSum = this.yAxisValues.Sum();
        this.xAxisValuesSum = this.xAxisValues.Sum();
        this.xxSum = 0;
        this.xySum = 0;

        for (int i = 0; i < this.count; i++)
        {
            this.xySum += (this.xAxisValues[i]*this.yAxisValues[i]);
            this.xxSum += (this.xAxisValues[i]*this.xAxisValues[i]);
        }

        this.Slope = this.CalculateSlope();
        this.Intercept = this.CalculateIntercept();
        this.Start = this.CalculateStart();
        this.End = this.CalculateEnd();
    }

    private int CalculateSlope()
    {
        try
        {
            return ((this.count*this.xySum) - (this.xAxisValuesSum*this.yAxisValuesSum))/((this.count*this.xxSum) - (this.xAxisValuesSum*this.xAxisValuesSum));
        }
        catch (DivideByZeroException)
        {
            return 0;
        }
    }

    private int CalculateIntercept()
    {
        return (this.yAxisValuesSum - (this.Slope*this.xAxisValuesSum))/this.count;
    }

    private int CalculateStart()
    {
        return (this.Slope*this.xAxisValues.First()) + this.Intercept;
    }

    private int CalculateEnd()
    {
        return (this.Slope*this.xAxisValues.Last()) + this.Intercept;
    }
}

Can regular expressions be used to match nested patterns?

Yes, if it is .NET RegEx-engine. .Net engine supports finite state machine supplied with an external stack. see details

Oracle date "Between" Query

You need to convert those to actual dates instead of strings, try this:

SELECT *
FROM <TABLENAME>
WHERE start_date BETWEEN TO_DATE('2010-01-15','YYYY-MM-DD') AND TO_DATE('2010-01-17', 'YYYY-MM-DD');

Edited to deal with format as specified:

SELECT *
FROM <TABLENAME>
WHERE start_date BETWEEN TO_DATE('15-JAN-10','DD-MON-YY') AND TO_DATE('17-JAN-10','DD-MON-YY');

How to pass data from child component to its parent in ReactJS?

To pass data from child component to parent component

In Parent Component:

getData(val){
    // do not forget to bind getData in constructor
    console.log(val);
}
render(){
 return(<Child sendData={this.getData}/>);
}

In Child Component:

demoMethod(){
   this.props.sendData(value);
 }

Run JavaScript when an element loses focus

How about onblur event :

<input type="text" name="name" value="value" onblur="alert(1);"/>

Why is my JavaScript function sometimes "not defined"?

It shouldn't be possible for this to happen if you're just including the scripts on the page.

The "copyArray" function should always be available when the JavaScript code starts executing no matter if it is declared before or after it -- unless you're loading the JavaScript files in dynamically with a dependency library. There are all sorts of problems with timing if that's the case.

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

How to execute a command in a remote computer?

I use the little utility which comes with PureMPI.net called execcmd.exe. Its syntax is as follows:

execcmd \\yourremoteserver <your command here>

Doesn't get any simpler than this :)

sort files by date in PHP

An example that uses RecursiveDirectoryIterator class, it's a convenient way to iterate recursively over filesystem.

$output = array();
foreach( new RecursiveIteratorIterator( 
    new RecursiveDirectoryIterator( 'path', FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS ) ) as $value ) {      
        if ( $value->isFile() ) {
            $output[] = array( $value->getMTime(), $value->getRealPath() );
        }
}

usort ( $output, function( $a, $b ) {
    return $a[0] > $b[0];
});

bool to int conversion

int x = 4<5;

Completely portable. Standard conformant. bool to int conversion is implicit!

§4.7/4 from the C++ Standard says (Integral Conversion)

If the source type is bool, the value false is converted to zero and the value true is converted to one.


As for C, as far as I know there is no bool in C. (before 1999) So bool to int conversion is relevant in C++ only. In C, 4<5 evaluates to int value, in this case the value is 1, 4>5 would evaluate to 0.

EDIT: Jens in the comment said, C99 has _Bool type. bool is a macro defined in stdbool.h header file. true and false are also macro defined in stdbool.h.

§7.16 from C99 says,

The macro bool expands to _Bool.

[..] true which expands to the integer constant 1, false which expands to the integer constant 0,[..]

Chmod recursively

Adding executable permissions, recursively, to all files (not folders) within the current folder with sh extension:

find . -name '*.sh' -type f | xargs chmod +x

* Notice the pipe (|)

Python regular expressions return true/false

One way to do this is just to test against the return value. Because you're getting <_sre.SRE_Match object at ...> it means that this will evaluate to true. When the regular expression isn't matched you'll the return value None, which evaluates to false.

import re

if re.search("c", "abcdef"):
    print "hi"

Produces hi as output.

jQuery getTime function

You don't need jquery to do that, just javascript. For example, you can do a timer using this:

<body onload="clock();">

<script type="text/javascript">
function clock() {
   var now = new Date();
   var outStr = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
   document.getElementById('clockDiv').innerHTML=outStr;
   setTimeout('clock()',1000);
}
clock();
</script>   

<div id="clockDiv"></div>

</body>

You can view a complete reference here: http://www.hunlock.com/blogs/Javascript_Dates-The_Complete_Reference

Programmatically get height of navigation bar

Do something like this ?

    NSLog(@"Navframe Height=%f",
        self.navigationController.navigationBar.frame.size.height);

The swift version is located here


UPDATE

iOS 13

As the statusBarFrame was deprecated in iOS13 you can use this:

extension UIViewController {

    /**
     *  Height of status bar + navigation bar (if navigation bar exist)
     */

    var topbarHeight: CGFloat {
        return (view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0.0) +
            (self.navigationController?.navigationBar.frame.height ?? 0.0)
    }
}

How to change colors of a Drawable in Android?

This code snippet worked for me:

PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(getResources().getColor(R.color.your_color),PorterDuff.Mode.MULTIPLY);

imgView.getDrawable().setColorFilter(porterDuffColorFilter);
imgView.setBackgroundColor(Color.TRANSPARENT)

Can't accept license agreement Android SDK Platform 24

It needs a latest stable sdk-platform installed. I installed SDK-Platform from API 25. It fixed my problem.See Screenshot below

Using Environment Variables with Vue.js

If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.

In the root create a .env file with:

VUE_APP_ENV_VARIABLE=value

And, if it's running, you need to restart serve so that the new env vars can be loaded.

With this, you will be able to use process.env.VUE_APP_ENV_VARIABLE in your project (.js and .vue files).

Update

According to @ali6p, with Vue Cli 3, isn't necessary to install dotenv dependency.

check if array is empty (vba excel)

this worked for me:

Private Function arrIsEmpty(arr as variant)
    On Error Resume Next
    arrIsEmpty = False
    arrIsEmpty = IsNumeric(UBound(arr))
End Function

How to print the array?

If you want to print the array like you print a 2D list in Python:

#include <stdio.h>

int main()
{
  int i, j;
  int my_array[3][3] = {{10, 23, 42}, {1, 654, 0}, {40652, 22, 0}};
  for(i = 0; i < 3; i++)
  {
      if (i == 0) {
          printf("[");
      }
      printf("[");
      for(j = 0; j < 3; j++)
      {
         printf("%d", my_array[i][j]);
         if (j < 2) {
             printf(", ");
         }
      }
    printf("]");
    if (i == 2) {
        printf("]");
    }

    if (i < 2) {
        printf(", ");
    }
  }
  return 0;
}

Output will be:

[[10, 23, 42], [1, 654, 0], [40652, 22, 0]]

Transfer data between iOS and Android via Bluetooth?

You could use p2pkit, or the free solution it was based on: https://github.com/GitGarage. Doesn't work very well, and its a fixer-upper for sure, but its, well, free. Works for small amounts of data transfer right now.

How to iterate through a list of dictionaries in Jinja template?

Data:

parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]

in Jinja2 iteration:

{% for dict_item in parent_list %}
   {% for key, value in dict_item.items() %}
      <h1>Key: {{key}}</h1>
      <h2>Value: {{value}}</h2>
   {% endfor %}
{% endfor %}

Note:

Make sure you have the list of dict items. If you get UnicodeError may be the value inside the dict contains unicode format. That issue can be solved in your views.py. If the dict is unicode object, you have to encode into utf-8.