Programs & Examples On #Cryptographic hash function

A cryptographic hash function is a function that takes a string of bytes of variable length and returns a fixed-length digest such that it is extremely difficult to find two inputs that yield the same output or find the original input given an output. It is also desirable for a small change in input to yield a large change in output. Common hash functions include MD5, SHA-1, SHA-256, SHA-512, and RIPEMD.

How can I hash a password in Java?

BCrypt is a very good library, and there is a Java port of it.

How to hash some string with sha256 in Java?

SHA-256 isn't an "encoding" - it's a one-way hash.

You'd basically convert the string into bytes (e.g. using text.getBytes(StandardCharsets.UTF_8)) and then hash the bytes. Note that the result of the hash would also be arbitrary binary data, and if you want to represent that in a string, you should use base64 or hex... don't try to use the String(byte[], String) constructor.

e.g.

MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));

MD5 is 128 bits but why is it 32 characters?

Those are hexidecimal digits, not characters. One digit = 4 bits.

UTF-8: General? Bin? Unicode?

You should also be aware of the fact, that with utf8_general_ci when using a varchar field as unique or primary index inserting 2 values like 'a' and 'á' would give a duplicate key error.

Rendering HTML in a WebView with custom CSS

You can Use Online Css link To set Style over existing content.

For That you have to load data in webview and enable JavaScript Support.

See Below Code:

   WebSettings webSettings=web_desc.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDefaultTextEncodingName("utf-8");
    webSettings.setTextZoom(55);
    StringBuilder sb = new StringBuilder();
    sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
    sb.append(currentHomeContent.getDescription());
    sb.append("</body></HTML>");
    currentWebView.loadDataWithBaseURL("file:///android_asset/", sb.toString(), "text/html", "utf-8", null);

Here Use StringBuilder to append String for Style.

sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
sb.append(currentHomeContent.getDescription());

PHPExcel - set cell type before writing a value in it

Followed Mark's advise and did this to set the default number formatting to text in the whole workbook:

$objPHPExcel = new PHPExcel(); 
$objPHPExcel->getDefaultStyle()
    ->getNumberFormat()
    ->setFormatCode(
        PHPExcel_Style_NumberFormat::FORMAT_TEXT
    );

And it works flawlessly. Thank you, Mark Baker.

Moment.js transform to date object

I needed to have timezone information in my date string. I was originally using moment.tz(dateStr, 'America/New_York').toString(); but then I started getting errors about feeding that string back into moment.

I tried the moment.tz(dateStr, 'America/New_York').toDate(); but then I lost timezone information which I needed.

The only solution that returned a usable date string with timezone that could be fed back into moment was moment.tz(dateStr, 'America/New_York').format();

Auto-redirect to another HTML page

You can use <meta> tag refresh, and <meta> tag in <head> section

<META http-equiv="refresh" content="5;URL=your_url"> 

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Sounds like you need to change the path to your java executable to match the newest version. Basically, installing the latest Java does not necessarily mean your machine is configured to use the latest version. You didn't mention any platform details, so that's all I can say.

jQuery .each() with input elements

Assume if all the input elements are inside a form u can refer the below code.

 // get all the inputs into an array.

    var $inputs = $('#myForm :input');

    // not sure if you wanted this, but I thought I'd add it.
    // get an associative array of just the values.
    var values = {};
    $inputs.each(function() {
        values[this.name] = $(this).val();
    });

How do you remove an array element in a foreach loop?

A better solution is to use the array_filter function:

$display_related_tags =
    array_filter($display_related_tags, function($e) use($found_tag){
        return $e != $found_tag['name'];
    });

As the php documentation reads:

As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.

In PHP 7, foreach does not use the internal array pointer.

Platform.runLater and Task in JavaFX

One reason to use an explicite Platform.runLater() could be that you bound a property in the ui to a service (result) property. So if you update the bound service property, you have to do this via runLater():

In UI thread also known as the JavaFX Application thread:

...    
listView.itemsProperty().bind(myListService.resultProperty());
...

in Service implementation (background worker):

...
Platform.runLater(() -> result.add("Element " + finalI));
...

7-zip commandline

In this 7-zip forum thread, in which many people express their desire for this feature, 7-zip's developer Igor points to the FAQ question titled "How can I store full path of file in archive?" to achieve a similar outcome.

In short:

  • separate files by volume (one list for files on C:\, one for D:\, etc)
  • then for each volume's list of files,
    1. chdir to the root directory of the appropriate volume (eg, cd /d C:\)
    2. create a file listing with paths relative to the volume's root directory (eg, C:\Foo\Bar becomes Foo\Bar)
    3. perform 7z a archive.7z @filelist as before with this new file list
    4. when extracting with full paths, make sure to chdir to the appropriate volume's root directory first

how to create Socket connection in Android?

Simple socket server app example

I've already posted a client example at: https://stackoverflow.com/a/35971718/895245 , so here goes a server example.

This example app runs a server that returns a ROT-1 cypher of the input.

You would then need to add an Exit button + some sleep delays, but this should get you started.

To play with it:

Android sockets are the same as Java's, except we have to deal with some permission issues.

src/com/cirosantilli/android_cheat/socket/Main.java

package com.cirosantilli.android_cheat.socket;

import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Main extends Activity {
    static final String TAG = "AndroidCheatSocket";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(Main.TAG, "onCreate");
        Main.this.startService(new Intent(Main.this, MyService.class));
    }

    public static class MyService extends IntentService {
        public MyService() {
            super("MyService");
        }
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(Main.TAG, "onHandleIntent");
            final int port = 12345;
            ServerSocket listener = null;
            try {
                listener = new ServerSocket(port);
                Log.d(Main.TAG, String.format("listening on port = %d", port));
                while (true) {
                    Log.d(Main.TAG, "waiting for client");
                    Socket socket = listener.accept();
                    Log.d(Main.TAG, String.format("client connected from: %s", socket.getRemoteSocketAddress().toString()));
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    PrintStream out = new PrintStream(socket.getOutputStream());
                    for (String inputLine; (inputLine = in.readLine()) != null;) {
                        Log.d(Main.TAG, "received");
                        Log.d(Main.TAG, inputLine);
                        StringBuilder outputStringBuilder = new StringBuilder("");
                        char inputLineChars[] = inputLine.toCharArray();
                        for (char c : inputLineChars)
                            outputStringBuilder.append(Character.toChars(c + 1));
                        out.println(outputStringBuilder);
                    }
                }
            } catch(IOException e) {
                Log.d(Main.TAG, e.toString());
            }
        }
    }
}

We need a Service or other background method or else: How do I fix android.os.NetworkOnMainThreadException?

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.cirosantilli.android_cheat.socket"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="22" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:label="AndroidCheatsocket">
        <activity android:name="Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".Main$MyService" />
    </application>
</manifest>

We must add: <uses-permission android:name="android.permission.INTERNET" /> or else: Java socket IOException - permission denied

On GitHub with a build.xml: https://github.com/cirosantilli/android-cheat/tree/92de020d0b708549a444ebd9f881de7b240b3fbc/socket

Javascript how to parse JSON array

The answer with the higher vote has a mistake. when I used it I find out it in line 3 :

var counter = jsonData.counters[i];

I changed it to :

var counter = jsonData[i].counters;

and it worked for me. There is a difference to the other answers in line 3:

var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
    var counter = jsonData[i].counters;
    console.log(counter.counter_name);
}

Laravel use same form for create and edit

I hope this will help you!!

form.blade.php

@php
$name         = $user->name ?? null;
$email        = $user->email ?? null;
$info         = $user->info ?? null;
$role         = $user->role ?? null;
@endphp

<div class="form-group">
        {!! Form::label('name', 'Name') !!}
        {!! Form::text('name', $name, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
        {!! Form::label('email', 'Email') !!}
        {!! Form::email('email', $email, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
        {!! Form::label('role', 'Função') !!}
        {!! Form::text('role', $role, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
        {!! Form::label('info', 'Informações') !!}
        {!! Form::textarea('info', $info, ['class' => 'form-control']) !!}
</div>

<a class="btn btn-danger float-right" href="{{ route('users.index') }}">CANCELAR</a>

create.blade.php

@extends('layouts.app')

@section('title', 'Criar usuário')

@section('content')
        {!! Form::open(['action' => 'UsersController@store', 'method' => 'POST'])  !!}
            @include('users.form')
            <div class="form-group">
                {!! Form::label('password', 'Senha') !!}
                {!! Form::password('password', ['class' => 'form-control']) !!}
            </div>
            <div class="form-group">
                {!! Form::label('password', 'Confirmação de senha') !!}
                {!! Form::password('password_confirmation', ['class' => 'form-control']) !!}
            </div>
            {!! Form::submit('ADICIONAR', array('class' => 'btn btn-primary')) !!}
        {!! Form::close() !!}
@endsection

edit.blade.php

@extends('layouts.app')

@section('title', 'Editar usuário')

@section('content')
        {!! Form::model($user, ['route' => ['users.update', $user->id], 'method' => 'PUT']) !!}
            @include('users.form', compact('user'))
            {!! Form::submit('EDITAR', ['class' => 'btn btn-primary']) !!}
        {!! Form::close() !!}
        <a href="{{route('users.editPassword', $user->id)}}">Editar senha</a>
@endsection

UsersController.php

use App\User;

Class UsersController extends Controller {
  #... 
    public function create()
    {
        return view('users.create';
    }

    public function edit($id)
    {
        $user  = User::findOrFail($id);
        return view('users.edit', compact('user');
    }
}

JAVA_HOME directory in Linux

echo $JAVA_HOME will print the value if it's set. However, if you didn't set it manually in your startup scripts, it probably isn't set.

If you try which java and it doesn't find anything, Java may not be installed on your machine, or at least isn't in your path. Depending on which Linux distribution you have and whether or not you have root access, you can go to http://www.java.com to download the version you need. Then, you can set JAVA_HOME to point to this directory. Remember, that this is just a convention and shouldn't be used to determine if java is installed or not.

Android: Test Push Notification online (Google Cloud Messaging)

Found a very easy way to do this.

Open http://phpfiddle.org/

Paste following php script in box. In php script set API_ACCESS_KEY, set device ids separated by coma.

Press F9 or click Run.

Have fun ;)

<?php


// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );


$registrationIds = array("YOUR DEVICE IDS WILL GO HERE" );

// prep the bundle
$msg = array
(
    'message'       => 'here is a message. message',
    'title'         => 'This is a title. title',
    'subtitle'      => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1
);

$fields = array
(
    'registration_ids'  => $registrationIds,
    'data'              => $msg
);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );

echo $result;
?>

For FCM, google url would be: https://fcm.googleapis.com/fcm/send

For FCM v1 google url would be: https://fcm.googleapis.com/v1/projects/YOUR_GOOGLE_CONSOLE_PROJECT_ID/messages:send

Note: While creating API Access Key on google developer console, you have to use 0.0.0.0/0 as ip address. (For testing purpose).

In case of receiving invalid Registration response from GCM server, please cross check the validity of your device token. You may check the validity of your device token using following url:

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=YOUR_DEVICE_TOKEN

Some response codes:

Following is the description of some response codes you may receive from server.

{ "message_id": "XXXX" } - success
{ "message_id": "XXXX", "registration_id": "XXXX" } - success, device registration id has been changed mainly due to app re-install
{ "error": "Unavailable" } - Server not available, resend the message
{ "error": "InvalidRegistration" } - Invalid device registration Id 
{ "error": "NotRegistered"} - Application was uninstalled from the device

Should operator<< be implemented as a friend or as a member function?

If possible, as non-member and non-friend functions.

As described by Herb Sutter and Scott Meyers, prefer non-friend non-member functions to member functions, to help increase encapsulation.

In some cases, like C++ streams, you won't have the choice and must use non-member functions.

But still, it does not mean you have to make these functions friends of your classes: These functions can still acess your class through your class accessors. If you succeed in writting those functions this way, then you won.

About operator << and >> prototypes

I believe the examples you gave in your question are wrong. For example;

ostream & operator<<(ostream &os) {
    return os << paragraph;
}

I can't even start to think how this method could work in a stream.

Here are the two ways to implement the << and >> operators.

Let's say you want to use a stream-like object of type T.

And that you want to extract/insert from/into T the relevant data of your object of type Paragraph.

Generic operator << and >> function prototypes

The first being as functions:

// T << Paragraph
T & operator << (T & p_oOutputStream, const Paragraph & p_oParagraph)
{
   // do the insertion of p_oParagraph
   return p_oOutputStream ;
}

// T >> Paragraph
T & operator >> (T & p_oInputStream, const Paragraph & p_oParagraph)
{
   // do the extraction of p_oParagraph
   return p_oInputStream ;
}

Generic operator << and >> method prototypes

The second being as methods:

// T << Paragraph
T & T::operator << (const Paragraph & p_oParagraph)
{
   // do the insertion of p_oParagraph
   return *this ;
}

// T >> Paragraph
T & T::operator >> (const Paragraph & p_oParagraph)
{
   // do the extraction of p_oParagraph
   return *this ;
}

Note that to use this notation, you must extend T's class declaration. For STL objects, this is not possible (you are not supposed to modify them...).

And what if T is a C++ stream?

Here are the prototypes of the same << and >> operators for C++ streams.

For generic basic_istream and basic_ostream

Note that is case of streams, as you can't modify the C++ stream, you must implement the functions. Which means something like:

// OUTPUT << Paragraph
template <typename charT, typename traits>
std::basic_ostream<charT,traits> & operator << (std::basic_ostream<charT,traits> & p_oOutputStream, const Paragraph & p_oParagraph)
{
   // do the insertion of p_oParagraph
   return p_oOutputStream ;
}

// INPUT >> Paragraph
template <typename charT, typename traits>
std::basic_istream<charT,traits> & operator >> (std::basic_istream<charT,traits> & p_oInputStream, const CMyObject & p_oParagraph)
{
   // do the extract of p_oParagraph
   return p_oInputStream ;
}

For char istream and ostream

The following code will work only for char-based streams.

// OUTPUT << A
std::ostream & operator << (std::ostream & p_oOutputStream, const Paragraph & p_oParagraph)
{
   // do the insertion of p_oParagraph
   return p_oOutputStream ;
}

// INPUT >> A
std::istream & operator >> (std::istream & p_oInputStream, const Paragraph & p_oParagraph)
{
   // do the extract of p_oParagraph
   return p_oInputStream ;
}

Rhys Ulerich commented about the fact the char-based code is but a "specialization" of the generic code above it. Of course, Rhys is right: I don't recommend the use of the char-based example. It is only given here because it's simpler to read. As it is only viable if you only work with char-based streams, you should avoid it on platforms where wchar_t code is common (i.e. on Windows).

Hope this will help.

Make footer stick to bottom of page correctly

do it using jQuery put inside code on the <head></head> tag

<script type="text/javascript">
$(document).ready(function() { 
    var docHeight = $(window).height();
    var footerHeight = $('#footer').height();
    var footerTop = $('#footer').position().top + footerHeight;  
    if (footerTop < docHeight) {
        $('#footer').css('margin-top', 10 + (docHeight - footerTop) + 'px');
    }
});
</script>

How do I check the difference, in seconds, between two dates?

>>> from datetime import datetime

>>>  a = datetime.now()

# wait a bit 
>>> b = datetime.now()

>>> d = b - a # yields a timedelta object
>>> d.seconds
7

(7 will be whatever amount of time you waited a bit above)

I find datetime.datetime to be fairly useful, so if there's a complicated or awkward scenario that you've encountered, please let us know.

EDIT: Thanks to @WoLpH for pointing out that one is not always necessarily looking to refresh so frequently that the datetimes will be close together. By accounting for the days in the delta, you can handle longer timestamp discrepancies:

>>> a = datetime(2010, 12, 5)
>>> b = datetime(2010, 12, 7)
>>> d = b - a
>>> d.seconds
0
>>> d.days
2
>>> d.seconds + d.days * 86400
172800

ld cannot find -l<library>

I had a similar problem with another library and the reason why it didn't found it, was that I didn't run the make install (after running ./configure and make) for that library. The make install may require root privileges (in this case use: sudo make install). After running the make install you should have the so files in the correct folder, i.e. here /usr/local/lib and not in the folder mentioned by you.

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

Consider these filenames:

C:\temp\file.txt - This is a path, an absolute path, and a canonical path.

.\file.txt - This is a path. It's neither an absolute path nor a canonical path.

C:\temp\myapp\bin\..\\..\file.txt - This is a path and an absolute path. It's not a canonical path.

A canonical path is always an absolute path.

Converting from a path to a canonical path makes it absolute (usually tack on the current working directory so e.g. ./file.txt becomes c:/temp/file.txt). The canonical path of a file just "purifies" the path, removing and resolving stuff like ..\ and resolving symlinks (on unixes).

Also note the following example with nio.Paths:

String canonical_path_string = "C:\\Windows\\System32\\";
String absolute_path_string = "C:\\Windows\\System32\\drivers\\..\\";

System.out.println(Paths.get(canonical_path_string).getParent());
System.out.println(Paths.get(absolute_path_string).getParent());

While both paths refer to the same location, the output will be quite different:

C:\Windows
C:\Windows\System32\drivers

Getting MAC Address

Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily:

from uuid import getnode as get_mac
mac = get_mac()

The return value is the mac address as 48 bit integer.

How to drop all tables from a database with one SQL query?

The simplest way is to drop the whole database and create it once again:

drop database db_name
create database db_name

That's all.

Android, getting resource ID from string?

You can use this function to get resource ID.

public static int getResourceId(String pVariableName, String pResourcename, String pPackageName) 
{
    try {
        return getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}

So if you want to get for drawable call function like this

getResourceId("myIcon", "drawable", getPackageName());

and for string you can call it like this

getResourceId("myAppName", "string", getPackageName());

Read this

Is an HTTPS query string secure?

SSL first connects to the host, so the host name and port number are transferred as clear text. When the host responds and the challenge succeeds, the client will encrypt the HTTP request with the actual URL (i.e. anything after the third slash) and and send it to the server.

There are several ways to break this security.

It is possible to configure a proxy to act as a "man in the middle". Basically, the browser sends the request to connect to the real server to the proxy. If the proxy is configured this way, it will connect via SSL to the real server but the browser will still talk to the proxy. So if an attacker can gain access of the proxy, he can see all the data that flows through it in clear text.

Your requests will also be visible in the browser history. Users might be tempted to bookmark the site. Some users have bookmark sync tools installed, so the password could end up on deli.ci.us or some other place.

Lastly, someone might have hacked your computer and installed a keyboard logger or a screen scraper (and a lot of Trojan Horse type viruses do). Since the password is visible directly on the screen (as opposed to "*" in a password dialog), this is another security hole.

Conclusion: When it comes to security, always rely on the beaten path. There is just too much that you don't know, won't think of and which will break your neck.

Getting unique values in Excel by using formulas only

I've pasted what I use in my excel file below. This picks up unique values from range L11:L300 and populate them from in column V, V11 onwards. In this case I have this formula in v11 and drag it down to get all the unique values.

=INDEX(L$11:L$300,MATCH(0,COUNTIF(V$10:V10,L$11:L$300),0))

or

=INDEX(L$11:L$300,MATCH(,COUNTIF(V$10:V10,L$11:L$300),))

this is an array formula

How to wait until WebBrowser is completely loaded in VB.NET?

I made similar function (only that works to me); sorry it is in C# but easy to translate...

private void WaitForPageLoad () {

     while (pageReady == false)
         Application.DoEvents();

     while (webBrowser1.IsBusy || webBrowser1.ReadyState != WebBrowserReadyState.Complete)
         Application.DoEvents();
}

How to count duplicate value in an array in javascript

Single line based on reduce array function

_x000D_
_x000D_
const uniqueCount =  ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
const distribution = uniqueCount.reduce((acum,cur) => Object.assign(acum,{[cur]: (acum[cur] || 0)+1}),{});
console.log(JSON.stringify(distribution,null,2));
_x000D_
_x000D_
_x000D_

Converting HTML string into DOM elements?

You can use a DOMParser, like so:

_x000D_
_x000D_
var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";_x000D_
var doc = new DOMParser().parseFromString(xmlString, "text/xml");_x000D_
console.log(doc.firstChild.innerHTML); // => <a href="#">Link..._x000D_
console.log(doc.firstChild.firstChild.innerHTML); // => Link
_x000D_
_x000D_
_x000D_

Exception: Serialization of 'Closure' is not allowed

Direct Closure serialisation is not allowed by PHP. But you can use powefull class like PHP Super Closure : https://github.com/jeremeamia/super_closure

This class is really simple to use and is bundled into the laravel framework for the queue manager.

From the github documentation :

$helloWorld = new SerializableClosure(function ($name = 'World') use ($greeting) {
    echo "{$greeting}, {$name}!\n";
});

$serialized = serialize($helloWorld);

XMLHttpRequest cannot load an URL with jQuery

Found a possible workaround that I don't believe was mentioned.

Here is a good description of the problem: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Basically as long as you use forms/url-encoded/plain text content types you are fine.

$.ajax({
    type: "POST",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'text/plain'
    },
    dataType: "json",
    url: "http://localhost/endpoint",
    data: JSON.stringify({'DataToPost': 123}),
    success: function (data) {
        alert(JSON.stringify(data));
    }
});     

I use it with ASP.NET WebAPI2. So on the other end:

public static void RegisterWebApi(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    config.Formatters.Clear();
    config.Formatters.Add(new JsonMediaTypeFormatter());

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}

This way Json formatter gets used when parsing plain text content type.

And don't forget in Web.config:

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, POST" />
  </customHeaders>
</httpProtocol>    

Hope this helps.

How do I install SciPy on 64 bit Windows?

You can either download a scientific Python distribution. One of the ones mentioned here: https://scipy.org/install.html

Or pip install from a whl file here if the above is not an option for you.

http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy

Java: Difference between the setPreferredSize() and setSize() methods in components

setSize() or setBounds() can be used when no layout manager is being used.

However, if you are using a layout manager you can provide hints to the layout manager using the setXXXSize() methods like setPreferredSize() and setMinimumSize() etc.

And be sure that the component's container uses a layout manager that respects the requested size. The FlowLayout, GridBagLayout, and SpringLayout managers use the component's preferred size (the latter two depending on the constraints you set), but BorderLayout and GridLayout usually don't.If you specify new size hints for a component that's already visible, you need to invoke the revalidate method on it to make sure that its containment hierarchy is laid out again. Then invoke the repaint method.

Copy an entire worksheet to a new worksheet in Excel 2010

It is simpler just to run an exact copy like below to put the copy in as the last sheet

Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Master")
ws1.Copy ThisWorkbook.Sheets(Sheets.Count)
End Sub

Android Gradle Could not reserve enough space for object heap

in gradle.properties, you can even delete

org.gradle.jvmargs=-Xmx1536m

such lines or comment them out. Let android studio decide for it. When I ran into this same problem, none of above solutions worked for me. Commenting out this line in gradle.properties helped in solving that error.

Spring Boot: Cannot access REST Controller on localhost (404)

You need to modify the Starter-Application class as shown below.

@SpringBootApplication

@EnableAutoConfiguration

@ComponentScan(basePackages="com.nice.application")

@EnableJpaRepositories("com.spring.app.repository")

public class InventoryApp extends SpringBootServletInitializer {..........

And update the Controller, Service and Repository packages structure as I mentioned below.

Example: REST-Controller

package com.nice.controller; --> It has to be modified as
package com.nice.application.controller;

You need to follow proper package structure for all packages which are in Spring Boot MVC flow.

So, If you modify your project bundle package structures correctly then your spring boot app will work correctly.

Re-doing a reverted merge in Git

Instead of using git-revert you could have used this command in the devel branch to throw away (undo) the wrong merge commit (instead of just reverting it).

git checkout devel
git reset --hard COMMIT_BEFORE_WRONG_MERGE

This will also adjust the contents of the working directory accordingly. Be careful:

  • Save your changes in the develop branch (since the wrong merge) because they too will be erased by the git-reset. All commits after the one you specify as the git reset argument will be gone!
  • Also, don't do this if your changes were already pulled from other repositories because the reset will rewrite history.

I recommend to study the git-reset man-page carefully before trying this.

Now, after the reset you can re-apply your changes in devel and then do

git checkout devel
git merge 28s

This will be a real merge from 28s into devel like the initial one (which is now erased from git's history).

How to configure CORS in a Spring Boot + Spring Security application?

For properties configuration

# ENDPOINTS CORS CONFIGURATION (EndpointCorsProperties)
endpoints.cors.allow-credentials= # Set whether credentials are supported. When not set, credentials are not supported.
endpoints.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers.
endpoints.cors.allowed-methods=GET # Comma-separated list of methods to allow. '*' allows all methods.
endpoints.cors.allowed-origins= # Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled.
endpoints.cors.exposed-headers= # Comma-separated list of headers to include in a response.
endpoints.cors.max-age=1800 # How long, in seconds, the response from a pre-flight request can be cached by clients.

application/x-www-form-urlencoded or multipart/form-data?

Just a little hint from my side for uploading HTML5 canvas image data:

I am working on a project for a print-shop and had some problems due to uploading images to the server that came from an HTML5 canvas element. I was struggling for at least an hour and I did not get it to save the image correctly on my server.

Once I set the contentType option of my jQuery ajax call to application/x-www-form-urlencoded everything went the right way and the base64-encoded data was interpreted correctly and successfully saved as an image.


Maybe that helps someone!

What is the cleanest way to get the progress of JQuery ajax request?

http://www.htmlgoodies.com/beyond/php/show-progress-report-for-long-running-php-scripts.html

I was searching for a similar solution and found this one use full.

var es;

function startTask() {
    es = new EventSource('yourphpfile.php');

//a message is received
es.addEventListener('message', function(e) {
    var result = JSON.parse( e.data );

    console.log(result.message);       

    if(e.lastEventId == 'CLOSE') {
        console.log('closed');
        es.close();
        var pBar = document.getElementById('progressor');
        pBar.value = pBar.max; //max out the progress bar
    }
    else {

        console.log(response); //your progress bar action
    }
});

es.addEventListener('error', function(e) {
    console.log('error');
    es.close();
});

}

and your server outputs

header('Content-Type: text/event-stream');
// recommended to prevent caching of event data.
header('Cache-Control: no-cache'); 

function send_message($id, $message, $progress) {
    $d = array('message' => $message , 'progress' => $progress); //prepare json

    echo "id: $id" . PHP_EOL;
    echo "data: " . json_encode($d) . PHP_EOL;
    echo PHP_EOL;

   ob_flush();
   flush();
}


//LONG RUNNING TASK
 for($i = 1; $i <= 10; $i++) {
    send_message($i, 'on iteration ' . $i . ' of 10' , $i*10); 

    sleep(1);
 }

send_message('CLOSE', 'Process complete');

Load CSV file with Spark

This is in PYSPARK

path="Your file path with file name"

df=spark.read.format("csv").option("header","true").option("inferSchema","true").load(path)

Then you can check

df.show(5)
df.count()

Changing default startup directory for command prompt in Windows 7

While adding a AutoRun entry to HKEY_CURRENT_USER\Software\Microsoft\Command Processor like Shinnok's answer is the way to go it can also really mess things up, you really should try to detect a simple cmd.exe startup vs a script/program using cmd.exe as a child process:

IF /I x"%COMSPEC%"==x%CMDCMDLINE% (cd /D c:\)

What's the best way to parse a JSON response from the requests library?

Since you're using requests, you should use the response's json method.

import requests

response = requests.get(...)
data = response.json()

It autodetects which decoder to use.

Get Value of a Edit Text field

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

  Button  rtn = (Button)findViewById(R.id.button);
  EditText edit_text   = (EditText)findViewById(R.id.edittext1);

    rtn .setOnClickListener(
        new View.OnClickListener()
        {
            public void onClick(View view)
            {
                Log.v("EditText value=", edit_text.getText().toString());
            }
        });
}

jQuery datepicker years shown

If you look down the demo page a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "Year dropdown shows last 20 years" demo , and hit view source:

$("#restricting").datepicker({ 
    yearRange: "-20:+0", // this is the option you're looking for
    showOn: "both", 
    buttonImage: "templates/images/calendar.gif", 
    buttonImageOnly: true 
});

You'll want to do the same (obviously changing -20 to -100 or something).

How to get an object's properties in JavaScript / jQuery?

Spotlight.js is a great library for iterating over the window object and other host objects looking for certain things.

// find all "length" properties
spotlight.byName('length');

// or find all "map" properties on jQuery
spotlight.byName('map', { 'object': jQuery, 'path': '$' });

// or all properties with `RegExp` values
spotlight.byKind('RegExp');

// or all properties containing "oo" in their name
spotlight.custom(function(value, key) { return key.indexOf('oo') > -1; });

You'll like it for this.

Counting the number of elements in array

Best practice of getting length is use length filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}

But you can calculate count of elements in for loop. For example:

{% set count = 0 %}
{% for nc in notcount %}
    {% set count = count + 1 %}
{% endfor %}

{{ count }}

This solution helps if you want to calculate count of elements by condition, for example you have a property name inside object and you want to calculate count of objects with not empty names:

{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
    {% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}

{{ countNotEmpty }}

Useful links:

How to write "not in ()" sql query using join

This article:

may be if interest to you.

In a couple of words, this query:

SELECT  d1.short_code
FROM    domain1 d1
LEFT JOIN
        domain2 d2
ON      d2.short_code = d1.short_code
WHERE   d2.short_code IS NULL

will work but it is less efficient than a NOT NULL (or NOT EXISTS) construct.

You can also use this:

SELECT  short_code
FROM    domain1
EXCEPT
SELECT  short_code
FROM    domain2

This is using neither NOT IN nor WHERE (and even no joins!), but this will remove all duplicates on domain1.short_code if any.

Heap space out of memory

There are a variety of tools that you can use to help diagnose this problem. The JDK includes JVisualVM that will allow you to attach to your running process and show what objects might be growing out of control. Netbeans has a wrapper around it that works fairly well. Eclipse has the Eclipse Memory Analyzer which is the one I use most often, just seems to handle large dump files a bit better. There's also a command line option, -XX:+HeapDumpOnOutOfMemoryError that will give you a file that is basically a snapshot of your process memory when your program crashed. You can use any of the above mentioned tools to look at it, it can really help a lot when diagnosing these sort of problems.

Depending on how hard the program is working, it may be a simple case of the JVM not knowing when a good time to garbage collect may be, you might also look into the parallel garbage collection options as well.

Linux Process States

While waiting for read() or write() to/from a file descriptor return, the process will be put in a special kind of sleep, known as "D" or "Disk Sleep". This is special, because the process can not be killed or interrupted while in such a state. A process waiting for a return from ioctl() would also be put to sleep in this manner.

An exception to this is when a file (such as a terminal or other character device) is opened in O_NONBLOCK mode, passed when its assumed that a device (such as a modem) will need time to initialize. However, you indicated block devices in your question. Also, I have never tried an ioctl() that is likely to block on a fd opened in non blocking mode (at least not knowingly).

How another process is chosen depends entirely on the scheduler you are using, as well as what other processes might have done to modify their weights within that scheduler.

Some user space programs under certain circumstances have been known to remain in this state forever, until rebooted. These are typically grouped in with other "zombies", but the term would not be correct as they are not technically defunct.

What's the most efficient way to test two integer ranges for overlap?

If you were dealing with, given two ranges [x1:x2] and [y1:y2], natural / anti-natural order ranges at the same time where:

  • natural order: x1 <= x2 && y1 <= y2 or
  • anti-natural order: x1 >= x2 && y1 >= y2

then you may want to use this to check:

they are overlapped <=> (y2 - x1) * (x2 - y1) >= 0

where only four operations are involved:

  • two subtractions
  • one multiplication
  • one comparison

How to get HTTP response code for a URL in Java?

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");

. . . . . . .

System.out.println("Value" + connection.getResponseCode());
             System.out.println(connection.getResponseMessage());
             System.out.println("content"+connection.getContent());

Cleanest way to write retry logic?

Retry helper: a generic java implementation that contains both returnable and void type retries.

import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RetryHelper {
  private static final Logger log = LoggerFactory.getLogger(RetryHelper.class);
  private int retryWaitInMS;
  private int maxRetries;

  public RetryHelper() {
    this.retryWaitInMS = 300;
    this.maxRetries = 3;
  }

  public RetryHelper(int maxRetry) {
    this.maxRetries = maxRetry;
    this.retryWaitInMS = 300;
  }

  public RetryHelper(int retryWaitInSeconds, int maxRetry) {
    this.retryWaitInMS = retryWaitInSeconds;
    this.maxRetries = maxRetry;
  }

  public <T> T retryAndReturn(Supplier<T> supplier) {
    try {
      return supplier.get();
    } catch (Exception var3) {
      return this.retrySupplier(supplier);
    }
  }

  public void retry(Runnable runnable) {
    try {
      runnable.run();
    } catch (Exception var3) {
      this.retrySupplier(() -> {
        runnable.run();
        return null;
      });
    }

  }

  private <T> T retrySupplier(Supplier<T> supplier) {
    log.error("Failed <TASK>, will be retried " + this.maxRetries + " times.");
    int retryCounter = 0;

    while(retryCounter < this.maxRetries) {
      try {
        return supplier.get();
      } catch (Exception var6) {
        ++retryCounter;
        log.error("<TASK> failed on retry: " + retryCounter + " of " + this.maxRetries + " with error: " + var6.getMessage());
        if (retryCounter >= this.maxRetries) {
          log.error("Max retries exceeded.");
          throw var6;
        }

        try {
          Thread.sleep((long)this.retryWaitInMS);
        } catch (InterruptedException var5) {
          var5.printStackTrace();
        }
      }
    }

    return supplier.get();
  }

  public int getRetryWaitInMS() {
    return this.retryWaitInMS;
  }

  public int getMaxRetries() {
    return this.maxRetries;
  }
}

Usage:

    try {
      returnValue = new RetryHelper().retryAndReturn(() -> performSomeTask(args));
      //or no return type:
      new RetryHelper().retry(() -> mytask(args));
    } catch(Exception ex){
      log.error(e.getMessage());
      throw new CustomException();
    }

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

click or change event on radio using jquery

Try

$(document).ready(

instead of

$('document').ready(

or you can use a shorthand form

$(function(){
});

Resource u'tokenizers/punkt/english.pickle' not found

import nltk
nltk.download('punkt')

Open the Python prompt and run the above statements.

The sent_tokenize function uses an instance of PunktSentenceTokenizer from the nltk.tokenize.punkt module. This instance has already been trained and works well for many European languages. So it knows what punctuation and characters mark the end of a sentence and the beginning of a new sentence.

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

As mentioned in the comments, there cannot be a continuous scale on variable of the factor type. You could change the factor to numeric as follows, just after you define the meltDF variable.

meltDF$variable=as.numeric(levels(meltDF$variable))[meltDF$variable]

Then, execute the ggplot command

  ggplot(meltDF[meltDF$value == 1,]) + geom_point(aes(x = MW, y =   variable)) +
     scale_x_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200)) +
     scale_y_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200))

And you will have your chart.

Hope this helps

Decimal values in SQL for dividing results

CAST( ROUND(columnA *1.00 / columnB, 2) AS FLOAT)

Clearing a string buffer/builder after loop

Already good answer there. Just add a benchmark result for StringBuffer and StringBuild performance difference use new instance in loop or use setLength(0) in loop.

The summary is: In a large loop

  • StringBuilder is much faster than StringBuffer
  • Create new StringBuilder instance in loop have no difference with setLength(0). (setLength(0) have very very very tiny advantage than create new instance.)
  • StringBuffer is slower than StringBuilder by create new instance in loop
  • setLength(0) of StringBuffer is extremely slower than create new instance in loop.

Very simple benchmark (I just manually changed the code and do different test ):

public class StringBuilderSpeed {
public static final char ch[] = new char[]{'a','b','c','d','e','f','g','h','i'};

public static void main(String a[]){
    int loopTime = 99999999;
    long startTime = System.currentTimeMillis();
    StringBuilder sb = new StringBuilder();
    for(int i = 0 ; i < loopTime; i++){
        for(char c : ch){
            sb.append(c);
        }
        sb.setLength(0);
    }
    long endTime = System.currentTimeMillis();
    System.out.println("Time cost: " + (endTime - startTime));
}

}

New StringBuilder instance in loop: Time cost: 3693, 3862, 3624, 3742

StringBuilder setLength: Time cost: 3465, 3421, 3557, 3408

New StringBuffer instance in loop: Time cost: 8327, 8324, 8284

StringBuffer setLength Time cost: 22878, 23017, 22894

Again StringBuilder setLength to ensure not my labtop got some issue to use such long for StringBuffer setLength :-) Time cost: 3448

How to tell whether a point is to the right or left side of a line

I wanted to provide with a solution inspired by physics.

Imagine a force applied along the line and you are measuring the torque of the force about the point. If the torque is positive (counterclockwise) then the point is to the "left" of the line, but if the torque is negative the point is the "right" of the line.

So if the force vector equals the span of the two points defining the line

fx = x_2 - x_1
fy = y_2 - y_1

you test for the side of a point (px,py) based on the sign of the following test

var torque = fx*(py-y_1)-fy*(px-x_1)
if  torque>0  then
     "point on left side"
else if torque <0 then
     "point on right side"  
else
     "point on line"
end if

jQuery: keyPress Backspace won't fire?

I came across this myself. I used .on so it looks a bit different but I did this:

 $('#element').on('keypress', function() {
   //code to be executed
 }).on('keydown', function(e) {
   if (e.keyCode==8)
     $('element').trigger('keypress');
 });

Adding my Work Around here. I needed to delete ssn typed by user so i did this in jQuery

  $(this).bind("keydown", function (event) {
        // Allow: backspace, delete
        if (event.keyCode == 46 || event.keyCode == 8) 
        {
            var tempField = $(this).attr('name');
            var hiddenID = tempField.substr(tempField.indexOf('_') + 1);
            $('#' + hiddenID).val('');
            $(this).val('')
            return;
        }  // Allow: tab, escape, and enter
        else if (event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
        // Allow: Ctrl+A
        (event.keyCode == 65 && event.ctrlKey === true) ||
        // Allow: home, end, left, right
        (event.keyCode >= 35 && event.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        }
        else 
        {
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) &&       (event.keyCode < 96 || event.keyCode > 105)) 
            {
                event.preventDefault();
            }
        }
    });

Trying to get Laravel 5 email to work

If you ever have the same trouble and try everything online and it doesn't work, it is probably the config cache file that is sending the wrong information. You can find it in bootstrap/cache/config.php. Make sure the credentials are right in there. It took me a week to figure that out. I hope this will help someone someday.

Stop form from submitting , Using Jquery

Again, AJAX is async. So the showMsg function will be called only after success response from the server.. and the form submit event will not wait until AJAX success.

Move the e.preventDefault(); as first line in the click handler.

$("form").submit(function (e) {
      e.preventDefault(); // this will prevent from submitting the form.
      ...

See below code,

I want it to be allowed HasJobInProgress == False

$(document).ready(function () {
    $("form").submit(function (e) {
        e.preventDefault(); //prevent default form submit
        $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data);
            },
            cache: false
        });
    });
});
$("#cancelButton").click(function () {
    window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
});
$("[type=text]").focus(function () {
    $(this).select();
});
function showMsg(hasCurrentJob) {
    if (hasCurrentJob == "True") {
        alert("The current clients has a job in progress. No changes can be saved until current job completes");
        return false;
    } else {
       $("form").unbind('submit').submit();
    }
}

Make a directory and copy a file

You can use the shell for this purpose.

Set shl = CreateObject("WScript.Shell") 
shl.Run "cmd mkdir YourDir" & copy "

100% height minus header?

If your browser supports CSS3, try using the CSS element Calc()

height: calc(100% - 65px);

you might also want to adding browser compatibility options:

height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */

also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622

Removing header column from pandas dataframe

I think you cant remove column names, only reset them by range with shape:

print df.shape[1]
2

print range(df.shape[1])
[0, 1]

df.columns = range(df.shape[1])
print df
    0   1
0  23  12
1  21  44
2  98  21

This is same as using to_csv and read_csv:

print df.to_csv(header=None,index=False)
23,12
21,44
98,21

print pd.read_csv(io.StringIO(u""+df.to_csv(header=None,index=False)), header=None)
    0   1
0  23  12
1  21  44
2  98  21

Next solution with skiprows:

print df.to_csv(index=False)
A,B
23,12
21,44
98,21

print pd.read_csv(io.StringIO(u""+df.to_csv(index=False)), header=None, skiprows=1)
    0   1
0  23  12
1  21  44
2  98  21

Passing a local variable from one function to another

First way is

function function1()
{
  var variable1=12;
  function2(variable1);
}

function function2(val)
{
  var variableOfFunction1 = val;

// Then you will have to use this function for the variable1 so it doesn't really help much unless that's what you want to do. }

Second way is

var globalVariable;
function function1()
{
  globalVariable=12;
  function2();
}

function function2()
{
  var local = globalVariable;
}

create table with sequence.nextval in oracle

You can use Oracle's SQL Developer tool to do that (My Oracle DB version is 11). While creating a table choose Advanced option and click on the Identity Column tab at the bottom and from there choose Column Sequence. This will generate a AUTO_INCREMENT column (Corresponding Trigger and Squence) for you.

can not find module "@angular/material"

import {MatButtonModule} from '@angular/material/button';

Spring Boot @autowired does not work, classes in different package

When I add @ComponentScan("com.firstday.spring.boot.services") or scanBasePackages{"com.firstday.spring.boot.services"} jsp is not loaded. So when I add the parent package of project in @SpringBootApplication class it's working fine in my case

Code Example:-

package com.firstday.spring.boot.firstday;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = {"com.firstday.spring.boot"})
public class FirstDayApplication {

    public static void main(String[] args) {
        SpringApplication.run(FirstDayApplication.class, args);
    }

}

Calculating the angle between the line defined by two points

A few answers here have tried to explain the "screen" issue where top left is 0,0 and bottom right is (positive) screen width, screen height. Most grids have the Y axis as positive above X not below.

The following method will work with screen values instead of "grid" values. The only difference to the excepted answer is the Y values are inverted.

/**
 * Work out the angle from the x horizontal winding anti-clockwise 
 * in screen space. 
 * 
 * The value returned from the following should be 315. 
 * <pre>
 * x,y -------------
 *     |  1,1
 *     |    \
 *     |     \
 *     |     2,2
 * </pre>
 * @param p1
 * @param p2
 * @return - a double from 0 to 360
 */
public static double angleOf(PointF p1, PointF p2) {
    // NOTE: Remember that most math has the Y axis as positive above the X.
    // However, for screens we have Y as positive below. For this reason, 
    // the Y values are inverted to get the expected results.
    final double deltaY = (p1.y - p2.y);
    final double deltaX = (p2.x - p1.x);
    final double result = Math.toDegrees(Math.atan2(deltaY, deltaX)); 
    return (result < 0) ? (360d + result) : result;
}

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

Find the division remainder of a number

Use the % instead of the / when you divide. This will return the remainder for you. So in your case

26 % 7 = 5

char initial value in Java

As you will see in linked discussion there is no need for initializing char with special character as it's done for us and is represented by '\u0000' character code.

So if we want simply to check if specified char was initialized just write:

if(charVariable != '\u0000'){
 actionsOnInitializedCharacter();
}

Link to question: what's the default value of char?

Storage permission error in Marshmallow

Seems user has declined the permission and app tries to write to external disk, causing error.

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

Check https://developer.android.com/training/permissions/requesting.html

This video will give you a better idea about UX, handling Runtime permissions https://www.youtube.com/watch?v=iZqDdvhTZj0

What is the "Temporary ASP.NET Files" folder for?

Thats where asp.net puts dynamically compiled assemblies.

How do you make an array of structs in C?

move

struct body bodies[n];

to after

struct body
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
};

Rest all looks fine.

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

Make sure you have the Visual C++ Redistributable package installed on your machine.

DateTimePicker: pick both date and time

DateTime Picker can be used to pick both date and time that is why it is called 'Date and Time Picker'. You can set the "Format" property to "Custom" and set combination of different format specifiers to represent/pick date/time in different formats in the "Custom Format" property. However if you want to change Date, then the pop-up calendar can be used whereas in case of Time selection (in the same control you are bound to use up/down keys to change values.

For example a custom format " ddddd, MMMM dd, yyyy hh:mm:ss tt " will give you a result like this : "Thursday, August 20, 2009 02:55:23 PM".

You can play around with different combinations for format specifiers to suit your need e.g MMMM will give "August" whereas MM will give "Aug"

SFTP file transfer using Java JSch

Usage:

sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");

Implementation

How do I work with dynamic multi-dimensional arrays in C?

Here is working code that defines a subroutine make_3d_array to allocate a multidimensional 3D array with N1, N2 and N3 elements in each dimension, and then populates it with random numbers. You can use the notation A[i][j][k] to access its elements.

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


// Method to allocate a 2D array of floats
float*** make_3d_array(int nx, int ny, int nz) {
    float*** arr;
    int i,j;

    arr = (float ***) malloc(nx*sizeof(float**));

    for (i = 0; i < nx; i++) {
        arr[i] = (float **) malloc(ny*sizeof(float*));

        for(j = 0; j < ny; j++) {
            arr[i][j] = (float *) malloc(nz * sizeof(float));
        }
    }

    return arr;
} 



int main(int argc, char *argv[])
{
    int i, j, k;
    size_t N1=10,N2=20,N3=5;

    // allocates 3D array
    float ***ran = make_3d_array(N1, N2, N3);

    // initialize pseudo-random number generator
    srand(time(NULL)); 

    // populates the array with random numbers
    for (i = 0; i < N1; i++){
        for (j=0; j<N2; j++) {
            for (k=0; k<N3; k++) {
                ran[i][j][k] = ((float)rand()/(float)(RAND_MAX));
            }
        }
   }

    // prints values
    for (i=0; i<N1; i++) {
        for (j=0; j<N2; j++) {
            for (k=0; k<N3; k++) {
                printf("A[%d][%d][%d] = %f \n", i,j,k,ran[i][j][k]);
            }
        }
    }

    free(ran);
}

why I can't get value of label with jquery and javascript?

Label's aren't form elements. They don't have a value. They have innerHTML and textContent.

Thus,

$('#telefon').html() 
// or
$('#telefon').text()

or

var telefon = document.getElementById('telefon');
telefon.innerHTML;

If you are starting with your form element, check out the labels list of it. That is,

var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea

Hibernate Union alternatives

You could use id in (select id from ...) or id in (select id from ...)

e.g. instead of non-working

from Person p where p.name="Joe"
union
from Person p join p.children c where c.name="Joe"

you could do

from Person p 
  where p.id in (select p1.id from Person p1 where p1.name="Joe") 
    or p.id in (select p2.id from Person p2 join p2.children c where c.name="Joe");

At least using MySQL, you will run into performance problems with it later, though. It's sometimes easier to do a poor man's join on two queries instead:

// use set for uniqueness
Set<Person> people = new HashSet<Person>((List<Person>) query1.list());
people.addAll((List<Person>) query2.list());
return new ArrayList<Person>(people);

It's often better to do two simple queries than one complex one.

EDIT:

to give an example, here is the EXPLAIN output of the resulting MySQL query from the subselect solution:

mysql> explain 
  select p.* from PERSON p 
    where p.id in (select p1.id from PERSON p1 where p1.name = "Joe") 
      or p.id in (select p2.id from PERSON p2 
        join CHILDREN c on p2.id = c.parent where c.name="Joe") \G
*************************** 1. row ***************************
           id: 1
  select_type: PRIMARY
        table: a
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 247554
        Extra: Using where
*************************** 2. row ***************************
           id: 3
  select_type: DEPENDENT SUBQUERY
        table: NULL
         type: NULL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: NULL
        Extra: Impossible WHERE noticed after reading const tables
*************************** 3. row ***************************
           id: 2
  select_type: DEPENDENT SUBQUERY
        table: a1
         type: unique_subquery
possible_keys: PRIMARY,name,sortname
          key: PRIMARY
      key_len: 4
          ref: func
         rows: 1
        Extra: Using where
3 rows in set (0.00 sec)

Most importantly, 1. row doesn't use any index and considers 200k+ rows. Bad! Execution of this query took 0.7s wheres both subqueries are in the milliseconds.

How to disable Hyper-V in command line?

Command line:

dism /online /disable-feature /featurename:microsoft-hyper-v-all

If anyone is getting:

We couldn’t complete the updates, Undoing changes

after trying to disable the Hyper-V, try uninstalling Hyper-V virtual network adapters from your Device Manager->Network Adapters

php form action php self

Another (and in my opinion proper) method is use the __FILE__ constant if you don't like to rely on $_SERVER variables.

$parts = explode(DIRECTORY_SEPARATOR, __FILE__);
$fileName = end($parts);
echo $fileName;

About magic and predefined constants: 1, 2.

How do I prompt for Yes/No/Cancel input in a Linux shell script?

read -p "Are you alright? (y/n) " RESP
if [ "$RESP" = "y" ]; then
  echo "Glad to hear it"
else
  echo "You need more bash programming"
fi

Split (explode) pandas dataframe string entry to separate rows

Another solution that uses python copy package

import copy
new_observations = list()
def pandas_explode(df, column_to_explode):
    new_observations = list()
    for row in df.to_dict(orient='records'):
        explode_values = row[column_to_explode]
        del row[column_to_explode]
        if type(explode_values) is list or type(explode_values) is tuple:
            for explode_value in explode_values:
                new_observation = copy.deepcopy(row)
                new_observation[column_to_explode] = explode_value
                new_observations.append(new_observation) 
        else:
            new_observation = copy.deepcopy(row)
            new_observation[column_to_explode] = explode_values
            new_observations.append(new_observation) 
    return_df = pd.DataFrame(new_observations)
    return return_df

df = pandas_explode(df, column_name)

Retrieve WordPress root directory path?

Note: This answer is really old and things may have changed in WordPress land since.

I am guessing that you need to detect the WordPress root from your plugin or theme. I use the following code in FireStats to detect the root WordPress directory where FireStats is installed a a WordPress plugin.

function fs_get_wp_config_path()
{
    $base = dirname(__FILE__);
    $path = false;

    if (@file_exists(dirname(dirname($base))."/wp-config.php"))
    {
        $path = dirname(dirname($base))."/wp-config.php";
    }
    else
    if (@file_exists(dirname(dirname(dirname($base)))."/wp-config.php"))
    {
        $path = dirname(dirname(dirname($base)))."/wp-config.php";
    }
    else
        $path = false;

    if ($path != false)
    {
        $path = str_replace("\\", "/", $path);
    }
    return $path;
}

How to list only top level directories in Python?

A safer option that does not fail when there is no directory.

def listdirs(folder):
    if os.path.exists(folder):
         return [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]
    else:
         return []

JavaScript - Get Portion of URL Path

There is a property of the built-in window.location object that will provide that for the current window.

// If URL is http://www.somedomain.com/account/search?filter=a#top

window.location.pathname // /account/search

// For reference:

window.location.host     // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash     // #top
window.location.href     // http://www.somedomain.com/account/search?filter=a#top
window.location.port     // (empty string)
window.location.protocol // http:
window.location.search   // ?filter=a  


Update, use the same properties for any URL:

It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location object and anchor elements implement the interface.

So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:

var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";

el.host        // www.somedomain.com (includes port if there is one[1])
el.hostname    // www.somedomain.com
el.hash        // #top
el.href        // http://www.somedomain.com/account/search?filter=a#top
el.pathname    // /account/search
el.port        // (port if there is one[1])
el.protocol    // http:
el.search      // ?filter=a

[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right

This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.

JSFiddle example

There's also a coming URL object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

Another solution is to migrate the database to e.g 2012 when you "export" the DB from e.g. Sql Server manager 2014. This is done in menu Tasks-> generate scripts when right-click on DB. Just follow this instruction:

https://www.mssqltips.com/sqlservertip/2810/how-to-migrate-a-sql-server-database-to-a-lower-version/

It generates an scripts with everything and then in your SQL server manager e.g. 2012 run the script as specified in the instruction. I have performed the test with success.

How do I vertically center text with CSS?

I needed a row of clickable elephants, vertically centered, but without using a table to get around some Internet Explorer 9 weirdness.

I eventually found the nicest CSS (for my needs) and it's great with Firefox, Chrome, and Internet Explorer 11. Sadly Internet Explorer 9 is still laughing at me...

_x000D_
_x000D_
div {_x000D_
  border: 1px dotted blue;_x000D_
  display: inline;_x000D_
  line-height: 100px;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
span {_x000D_
  border: 1px solid red;_x000D_
  display: inline-block;_x000D_
  line-height: normal;_x000D_
  vertical-align: middle;_x000D_
}_x000D_
_x000D_
.out {_x000D_
  border: 3px solid silver;_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="out" onclick="alert(1)">_x000D_
  <div> <span><img src="http://www.birdfolk.co.uk/littleredsolo.png"/></span> </div>_x000D_
  <div> <span>A lovely clickable option.</span> </div>_x000D_
</div>_x000D_
_x000D_
<div class="out" onclick="alert(2)">_x000D_
  <div> <span><img src="http://www.birdfolk.co.uk/bang2/Ship01.png"/></span> </div>_x000D_
  <div> <span>Something charming to click on.</span> </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Obviously you don't need the borders, but they can help you see how it works.

How can I debug git/git-shell related problems?

Git 2.22 (Q2 2019) introduces trace2 with commit ee4512e by Jeff Hostetler:

trace2: create new combined trace facility

Create a new unified tracing facility for git.
The eventual intent is to replace the current trace_printf* and trace_performance* routines with a unified set of git_trace2* routines.

In addition to the usual printf-style API, trace2 provides higer-level event verbs with fixed-fields allowing structured data to be written.
This makes post-processing and analysis easier for external tools.

Trace2 defines 3 output targets.
These are set using the environment variables "GIT_TR2", "GIT_TR2_PERF", and "GIT_TR2_EVENT".
These may be set to "1" or to an absolute pathname (just like the current GIT_TRACE).

Note: regarding environment variable name, always use GIT_TRACExxx, not GIT_TRxxx.
So actually GIT_TRACE2, GIT_TRACE2_PERF or GIT_TRACE2_EVENT.
See the Git 2.22 rename mentioned later below.

What follows is the initial work on this new tracing feature, with the old environment variable names:

  • GIT_TR2 is intended to be a replacement for GIT_TRACE and logs command summary data.

  • GIT_TR2_PERF is intended as a replacement for GIT_TRACE_PERFORMANCE.
    It extends the output with columns for the command process, thread, repo, absolute and relative elapsed times.
    It reports events for child process start/stop, thread start/stop, and per-thread function nesting.

  • GIT_TR2_EVENT is a new structured format. It writes event data as a series of JSON records.

Calls to trace2 functions log to any of the 3 output targets enabled without the need to call different trace_printf* or trace_performance* routines.

See commit a4d3a28 (21 Mar 2019) by Josh Steadmon (steadmon).
(Merged by Junio C Hamano -- gitster -- in commit 1b40314, 08 May 2019)

trace2: write to directory targets

When the value of a trace2 environment variable is an absolute path referring to an existing directory, write output to files (one per process) underneath the given directory.
Files will be named according to the final component of the trace2 SID, followed by a counter to avoid potential collisions.

This makes it more convenient to collect traces for every git invocation by unconditionally setting the relevant trace2 envvar to a constant directory name.


See also commit f672dee (29 Apr 2019), and commit 81567ca, commit 08881b9, commit bad229a, commit 26c6f25, commit bce9db6, commit 800a7f9, commit a7bc01e, commit 39f4317, commit a089724, commit 1703751 (15 Apr 2019) by Jeff Hostetler (jeffhostetler).
(Merged by Junio C Hamano -- gitster -- in commit 5b2d1c0, 13 May 2019)

The new documentation now includes config settings which are only read from the system and global config files (meaning repository local and worktree config files and -c command line arguments are not respected.)

Example:

$ git config --global trace2.normalTarget ~/log.normal
$ git version
git version 2.20.1.155.g426c96fcdb

yields

$ cat ~/log.normal
12:28:42.620009 common-main.c:38                  version 2.20.1.155.g426c96fcdb
12:28:42.620989 common-main.c:39                  start git version
12:28:42.621101 git.c:432                         cmd_name version (version)
12:28:42.621215 git.c:662                         exit elapsed:0.001227 code:0
12:28:42.621250 trace2/tr2_tgt_normal.c:124 atexit elapsed:0.001265 code:0

And for performance measure:

$ git config --global trace2.perfTarget ~/log.perf
$ git version
git version 2.20.1.155.g426c96fcdb

yields

$ cat ~/log.perf
12:28:42.620675 common-main.c:38                  | d0 | main                     | version      |     |           |           |            | 2.20.1.155.g426c96fcdb
12:28:42.621001 common-main.c:39                  | d0 | main                     | start        |     |  0.001173 |           |            | git version
12:28:42.621111 git.c:432                         | d0 | main                     | cmd_name     |     |           |           |            | version (version)
12:28:42.621225 git.c:662                         | d0 | main                     | exit         |     |  0.001227 |           |            | code:0
12:28:42.621259 trace2/tr2_tgt_perf.c:211         | d0 | main                     | atexit       |     |  0.001265 |           |            | code:0

As documented in Git 2.23 (Q3 2019), the environment variable to use is GIT_TRACE2.

See commit 6114a40 (26 Jun 2019) by Carlo Marcelo Arenas Belón (carenas).
See commit 3efa1c6 (12 Jun 2019) by Ævar Arnfjörð Bjarmason (avar).
(Merged by Junio C Hamano -- gitster -- in commit e9eaaa4, 09 Jul 2019)

That follows the work done in Git 2.22: commit 4e0d3aa, commit e4b75d6 (19 May 2019) by SZEDER Gábor (szeder).
(Merged by Junio C Hamano -- gitster -- in commit 463dca6, 30 May 2019)

trace2: rename environment variables to GIT_TRACE2*

For an environment variable that is supposed to be set by users, the GIT_TR2* env vars are just too unclear, inconsistent, and ugly.

Most of the established GIT_* environment variables don't use abbreviations, and in case of the few that do (GIT_DIR, GIT_COMMON_DIR, GIT_DIFF_OPTS) it's quite obvious what the abbreviations (DIR and OPTS) stand for.
But what does TR stand for? Track, traditional, trailer, transaction, transfer, transformation, transition, translation, transplant, transport, traversal, tree, trigger, truncate, trust, or ...?!

The trace2 facility, as the '2' suffix in its name suggests, is supposed to eventually supercede Git's original trace facility.
It's reasonable to expect that the corresponding environment variables follow suit, and after the original GIT_TRACE variables they are called GIT_TRACE2; there is no such thing is 'GIT_TR'.

All trace2-specific config variables are, very sensibly, in the 'trace2' section, not in 'tr2'.

OTOH, we don't gain anything at all by omitting the last three characters of "trace" from the names of these environment variables.

So let's rename all GIT_TR2* environment variables to GIT_TRACE2*, before they make their way into a stable release.


Git 2.24 (Q3 2019) improves the Git repository initialization.

See commit 22932d9, commit 5732f2b, commit 58ebccb (06 Aug 2019) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit b4a1eec, 09 Sep 2019)

common-main: delay trace2 initialization

We initialize the trace2 system in the common main() function so that all programs (even ones that aren't builtins) will enable tracing.

But trace2 startup is relatively heavy-weight, as we have to actually read on-disk config to decide whether to trace.
This can cause unexpected interactions with other common-main initialization. For instance, we'll end up in the config code before calling initialize_the_repository(), and the usual invariant that the_repository is never NULL will not hold.

Let's push the trace2 initialization further down in common-main, to just before we execute cmd_main().


Git 2.24 (Q4 2019) makes also sure that output from trace2 subsystem is formatted more prettily now.

See commit 742ed63, commit e344305, commit c2b890a (09 Aug 2019), commit ad43e37, commit 04f10d3, commit da4589c (08 Aug 2019), and commit 371df1b (31 Jul 2019) by Jeff Hostetler (jeffhostetler).
(Merged by Junio C Hamano -- gitster -- in commit 93fc876, 30 Sep 2019)

And, still Git 2.24

See commit 87db61a, commit 83e57b0 (04 Oct 2019), and commit 2254101, commit 3d4548e (03 Oct 2019) by Josh Steadmon (steadmon).
(Merged by Junio C Hamano -- gitster -- in commit d0ce4d9, 15 Oct 2019)

trace2: discard new traces if target directory has too many files

Signed-off-by: Josh Steadmon

trace2 can write files into a target directory.
With heavy usage, this directory can fill up with files, causing difficulty for trace-processing systems.

This patch adds a config option (trace2.maxFiles) to set a maximum number of files that trace2 will write to a target directory.

The following behavior is enabled when the maxFiles is set to a positive integer:

  • When trace2 would write a file to a target directory, first check whether or not the traces should be discarded.
    Traces should be discarded if:
    • there is a sentinel file declaring that there are too many files
    • OR, the number of files exceeds trace2.maxFiles.
      In the latter case, we create a sentinel file named git-trace2-discard to speed up future checks.

The assumption is that a separate trace-processing system is dealing with the generated traces; once it processes and removes the sentinel file, it should be safe to generate new trace files again.

The default value for trace2.maxFiles is zero, which disables the file count check.

The config can also be overridden with a new environment variable: GIT_TRACE2_MAX_FILES.


And Git 2.24 (Q4 2019) teach trace2 about git push stages.

See commit 25e4b80, commit 5fc3118 (02 Oct 2019) by Josh Steadmon (steadmon).
(Merged by Junio C Hamano -- gitster -- in commit 3b9ec27, 15 Oct 2019)

push: add trace2 instrumentation

Signed-off-by: Josh Steadmon

Add trace2 regions in transport.c and builtin/push.c to better track time spent in various phases of pushing:

  • Listing refs
  • Checking submodules
  • Pushing submodules
  • Pushing refs

With Git 2.25 (Q1 2020), some of the Documentation/technical is moved to header *.h files.

See commit 6c51cb5, commit d95a77d, commit bbcfa30, commit f1ecbe0, commit 4c4066d, commit 7db0305, commit f3b9055, commit 971b1f2, commit 13aa9c8, commit c0be43f, commit 19ef3dd, commit 301d595, commit 3a1b341, commit 126c1cc, commit d27eb35, commit 405c6b1, commit d3d7172, commit 3f1480b, commit 266f03e, commit 13c4d7e (17 Nov 2019) by Heba Waly (HebaWaly).
(Merged by Junio C Hamano -- gitster -- in commit 26c816a, 16 Dec 2019)

trace2: move doc to trace2.h

Signed-off-by: Heba Waly

Move the functions documentation from Documentation/technical/api-trace2.txt to trace2.h as it's easier for the developers to find the usage information beside the code instead of looking for it in another doc file.

Only the functions documentation section is removed from Documentation/technical/api-trace2.txt as the file is full of details that seemed more appropriate to be in a separate doc file as it is, with a link to the doc file added in the trace2.h. Also the functions doc is removed to avoid having redundandt info which will be hard to keep syncronized with the documentation in the header file.

(although that reorganization had a side effect on another command, explained and fixed with Git 2.25.2 (March 2020) in commit cc4f2eb (14 Feb 2020) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 1235384, 17 Feb 2020))


With Git 2.27 (Q2 2020): Trace2 enhancement to allow logging of the environment variables.

See commit 3d3adaa (20 Mar 2020) by Josh Steadmon (steadmon).
(Merged by Junio C Hamano -- gitster -- in commit 810dc64, 22 Apr 2020)

trace2: teach Git to log environment variables

Signed-off-by: Josh Steadmon
Acked-by: Jeff Hostetler

Via trace2, Git can already log interesting config parameters (see the trace2_cmd_list_config() function). However, this can grant an incomplete picture because many config parameters also allow overrides via environment variables.

To allow for more complete logs, we add a new trace2_cmd_list_env_vars() function and supporting implementation, modeled after the pre-existing config param logging implementation.


With Git 2.27 (Q2 2020), teach codepaths that show progress meter to also use the start_progress() and the stop_progress() calls as a "region" to be traced.

See commit 98a1364 (12 May 2020) by Emily Shaffer (nasamuffin).
(Merged by Junio C Hamano -- gitster -- in commit d98abce, 14 May 2020)

trace2: log progress time and throughput

Signed-off-by: Emily Shaffer

Rather than teaching only one operation, like 'git fetch', how to write down throughput to traces, we can learn about a wide range of user operations that may seem slow by adding tooling to the progress library itself.

Operations which display progress are likely to be slow-running and the kind of thing we want to monitor for performance anyways.

By showing object counts and data transfer size, we should be able to make some derived measurements to ensure operations are scaling the way we expect.

And:

With Git 2.27 (Q2 2020), last-minute fix for our recent change to allow use of progress API as a traceable region.

See commit 3af029c (15 May 2020) by Derrick Stolee (derrickstolee).
(Merged by Junio C Hamano -- gitster -- in commit 85d6e28, 20 May 2020)

progress: call trace2_region_leave() only after calling _enter()

Signed-off-by: Derrick Stolee

A user of progress API calls start_progress() conditionally and depends on the display_progress() and stop_progress() functions to become no-op when start_progress() hasn't been called.

As we added a call to trace2_region_enter() to start_progress(), the calls to other trace2 API calls from the progress API functions must make sure that these trace2 calls are skipped when start_progress() hasn't been called on the progress struct.

Specifically, do not call trace2_region_leave() from stop_progress() when we haven't called start_progress(), which would have called the matching trace2_region_enter().


That last part is more robust with Git 2.29 (Q4 2020):

See commit ac900fd (10 Aug 2020) by Martin Ågren (none).
(Merged by Junio C Hamano -- gitster -- in commit e6ec620, 17 Aug 2020)

progress: don't dereference before checking for NULL

Signed-off-by: Martin Ågren

In stop_progress(), we're careful to check that p_progress is non-NULL before we dereference it, but by then we have already dereferenced it when calling finish_if_sparse(*p_progress).
And, for what it's worth, we'll go on to blindly dereference it again inside stop_progress_msg().

We could return early if we get a NULL-pointer, but let's go one step further and BUG instead.
The progress API handles NULL just fine, but that's the NULL-ness of *p_progress, e.g., when running with --no-progress.
If p_progress is NULL, chances are that's a mistake.
For symmetry, let's do the same check in stop_progress_msg(), too.


With Git 2.29 (Q4 2020), there is even more trace, this time in a Git development environment.

See commit 4441f42 (09 Sep 2020) by Han-Wen Nienhuys (hanwen).
(Merged by Junio C Hamano -- gitster -- in commit c9a04f0, 22 Sep 2020)

refs: add GIT_TRACE_REFS debugging mechanism

Signed-off-by: Han-Wen Nienhuys

When set in the environment, GIT_TRACE_REFS makes git print operations and results as they flow through the ref storage backend. This helps debug discrepancies between different ref backends.

Example:

$ GIT_TRACE_REFS="1" ./git branch
15:42:09.769631 refs/debug.c:26         ref_store for .git
15:42:09.769681 refs/debug.c:249        read_raw_ref: HEAD: 0000000000000000000000000000000000000000 (=> refs/heads/ref-debug) type 1: 0
15:42:09.769695 refs/debug.c:249        read_raw_ref: refs/heads/ref-debug: 3a238e539bcdfe3f9eb5010fd218640c1b499f7a (=> refs/heads/ref-debug) type 0: 0
15:42:09.770282 refs/debug.c:233        ref_iterator_begin: refs/heads/ (0x1)
15:42:09.770290 refs/debug.c:189        iterator_advance: refs/heads/b4 (0)
15:42:09.770295 refs/debug.c:189        iterator_advance: refs/heads/branch3 (0)

git now includes in its man page:

GIT_TRACE_REFS

Enables trace messages for operations on the ref database. See GIT_TRACE for available trace output options.


With Git 2.30 (Q1 2021), like die() and error(), a call to warning() will also trigger a trace2 event.

See commit 0ee10fd (23 Nov 2020) by Jonathan Tan (jhowtan).
(Merged by Junio C Hamano -- gitster -- in commit 2aeafbc, 08 Dec 2020)

Can I define a class name on paragraph using Markdown?

Raw HTML is actually perfectly valid in markdown. For instance:

Normal *markdown* paragraph.

<p class="myclass">This paragraph has a class "myclass"</p>

Just make sure the HTML is not inside a code block.

PHP max_input_vars

Have just attempted this fix with 5.3.3 and there's no change. Googling around I found this web page http://anothersysadmin.wordpress.com/2012/02/16/php-5-3-max_input_vars-and-big-forms/ detailing other settings which need changing if your server uses the Suhosin patch which Apache under Debian does.

The site explains:

So, if you want to increase this number to, say, 3000 from the default number which is 1000, you have to put in your php.ini these lines:

max_input_vars = 3000 suhosin.post.max_vars = 3000 suhosin.request.max_vars = 3000

I tested it (added settings to php.ini both in /etc/php5/apache2 and /etc/php5/cli, and restarted Apache successfully) but still no max_input_vars variable in phpinfo.

A few sites point to PHP 5.3.9 as the first PHP version in which this change will take, so my fault for not RTM properly in the first place, although I'm interested to see people reporting it working in version above 5.3.3 but below 5.3.9.

How to compare two vectors for equality element by element in C++?

C++11 standard on == for std::vector

Others have mentioned that operator== does compare vector contents and works, but here is a quote from the C++11 N3337 standard draft which I believe implies that.

We first look at Chapter 23.2.1 "General container requirements", which documents things that must be valid for all containers, including therefore std::vector.

That section Table 96 "Container requirements" which contains an entry:

Expression   Operational semantics
===========  ======================
a == b       distance(a.begin(), a.end()) == distance(b.begin(), b.end()) &&
             equal(a.begin(), a.end(), b.begin())

The distance part of the semantics means that the size of both containers are the same, but stated in a generalized iterator friendly way for non random access addressable containers. distance() is defined at 24.4.4 "Iterator operations".

Then the key question is what does equal() mean. At the end of the table we see:

Notes: the algorithm equal() is defined in Clause 25.

and in section 25.2.11 "Equal" we find its definition:

template<class InputIterator1, class InputIterator2>
bool equal(InputIterator1 first1, InputIterator1 last1,
           InputIterator2 first2);

template<class InputIterator1, class InputIterator2,
class BinaryPredicate>
bool equal(InputIterator1 first1, InputIterator1 last1,
           InputIterator2 first2, BinaryPredicate pred);

1 Returns: true if for every iterator i in the range [first1,last1) the following corresponding conditions hold: *i == *(first2 + (i - first1)), pred(*i, *(first2 + (i - first1))) != false. Otherwise, returns false.

In our case, we care about the overloaded version without BinaryPredicate version, which corresponds to the first pseudo code definition *i == *(first2 + (i - first1)), which we see is just an iterator-friendly definition of "all iterated items are the same".

Similar questions for other containers:

PHPExcel how to set cell value dynamically

I asume you have connected to your database already.

$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);

$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
    $col = 0;
    foreach($row_data as $key=>$value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}

async/await - when to return a Task vs void?

According to Microsoft documentation, should NEVER use async void

Do not do this: The following example uses async void which makes the HTTP request complete when the first await is reached:

  • Which is ALWAYS a bad practice in ASP.NET Core apps.

  • Accesses the HttpResponse after the HTTP request is complete.

  • Crashes the process.

How do I remove blue "selected" outline on buttons?

You can remove the blue outline by using outline: none.

However, I would highly recommend styling your focus states too. This is to help users who are visually impaired.

Check out: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#navigation-mechanisms-focus-visible. More reading here: http://outlinenone.com

JSON - Iterate through JSONArray

You could try my (*heavily borrowed from various sites) recursive method to go through all JSON objects and JSON arrays until you find JSON elements. This example actually searches for a particular key and returns all values for all instances of that key. 'searchKey' is the key you are looking for.

ArrayList<String> myList = new ArrayList<String>();
myList = findMyKeyValue(yourJsonPayload,null,"A"); //if you only wanted to search for A's values

    private ArrayList<String> findMyKeyValue(JsonElement element, String key, String searchKey) {

    //OBJECT
    if(element.isJsonObject()) {
        JsonObject jsonObject = element.getAsJsonObject();

        //loop through all elements in object

        for (Map.Entry<String,JsonElement> entry : jsonObject.entrySet()) {
            JsonElement array = entry.getValue();
            findMyKeyValue(array, entry.getKey(), searchKey);

        }

    //ARRAY
    } else if(element.isJsonArray()) {
        //when an array is found keep 'key' as that is the array's name i.e. pass it down

        JsonArray jsonArray = element.getAsJsonArray();

        //loop through all elements in array
        for (JsonElement childElement : jsonArray) {
            findMyKeyValue(childElement, key, searchKey);
        }

    //NEITHER
    } else {

        //System.out.println("SKey: " + searchKey + " Key: " + key );

            if (key.equals(searchKey)){
                listOfValues.add(element.getAsString());
            }
    }
    return listOfValues;
}

jQuery .val() vs .attr("value")

Example more... attr() is various, val() is just one! Prop is boolean are different.

_x000D_
_x000D_
//EXAMPLE 1 - RESULT_x000D_
$('div').append($('input.idone').attr('value')).append('<br>');_x000D_
$('div').append($('input[name=nametwo]').attr('family')).append('<br>');_x000D_
$('div').append($('input#idtwo').attr('name')).append('<br>');_x000D_
$('div').append($('input[name=nameone]').attr('value'));_x000D_
_x000D_
$('div').append('<hr>'); //EXAMPLE 2_x000D_
$('div').append($('input.idone').val()).append('<br>');_x000D_
_x000D_
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VAL_x000D_
$('div').append($('input.idone').val('idonenew')).append('<br>');_x000D_
$('input.idone').attr('type','initial');_x000D_
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VALUE_x000D_
$('div').append($('input[name=nametwo]').attr('value', 'new-jquery-pro')).append('<br>');_x000D_
$('input#idtwo').attr('type','initial');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="hidden" class="idone" name="nameone" value="one-test" family="family-number-one">_x000D_
<input type="hidden" id="idtwo" name="nametwo" value="two-test" family="family-number-two">_x000D_
<br>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

SystemError: Parent module '' not loaded, cannot perform relative import

If you go one level up in running the script in the command line of your bash shell, the issue will be resolved. To do this, use cd .. command to change the working directory in which your script will be running. The result should look like this:

[username@localhost myProgram]$

rather than this:

[username@localhost app]$

Once you are there, instead of running the script in the following format:

python3 mymodule.py

Change it to this:

python3 app/mymodule.py

This process can be repeated once again one level up depending on the structure of your Tree diagram. Please also include the compilation command line that is giving you that mentioned error message.

How to increase editor font size?

File -> Settings -> Editor -> Colors & Fonts -> Font.

Mysql select distinct

DISTINCT is not a function that applies only to some columns. It's a query modifier that applies to all columns in the select-list.

That is, DISTINCT reduces rows only if all columns are identical to the columns of another row.

DISTINCT must follow immediately after SELECT (along with other query modifiers, like SQL_CALC_FOUND_ROWS). Then following the query modifiers, you can list columns.

  • RIGHT: SELECT DISTINCT foo, ticket_id FROM table...

    Output a row for each distinct pairing of values across ticket_id and foo.

  • WRONG: SELECT foo, DISTINCT ticket_id FROM table...

    If there are three distinct values of ticket_id, would this return only three rows? What if there are six distinct values of foo? Which three values of the six possible values of foo should be output?
    It's ambiguous as written.

How to make program go back to the top of the code instead of closing

Use an infinite loop:

while True:
    print('Hello world!')

This certainly can apply to your start() function as well; you can exit the loop with either break, or use return to exit the function altogether, which also terminates the loop:

def start():
    print ("Welcome to the converter toolkit made by Alan.")

    while True:
        op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")

        if op == "1":
            f1 = input ("Please enter your fahrenheit temperature: ")
            f1 = int(f1)

            a1 = (f1 - 32) / 1.8
            a1 = str(a1)

            print (a1+" celsius") 

        elif op == "2":
            m1 = input ("Please input your the amount of meters you wish to convert: ")
            m1 = int(m1)
            m2 = (m1 * 100)

            m2 = str(m2)
            print (m2+" m")

        if op == "3":
            mb1 = input ("Please input the amount of megabytes you want to convert")
            mb1 = int(mb1)
            mb2 = (mb1 / 1024)
            mb3 = (mb2 / 1024)

            mb3 = str(mb3)

            print (mb3+" GB")

        else:
            print ("Sorry, that was an invalid command!")

If you were to add an option to quit as well, that could be:

if op.lower() in {'q', 'quit', 'e', 'exit'}:
    print("Goodbye!")
    return

for example.

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

Try this:

Xvfb :21 -screen 0 1024x768x24 +extension RANDR &
Xvfb --help

+extension name        Enable extension
-extension name        Disable extension

Post Build exited with code 1

I have added this for future visitors since this is quite an active question.

ROBOCOPY exits with "success codes" which are under 8. See: http://support.microsoft.com/kb/954404

This means that:

robocopy exit code 0 = no files copied
robocopy exit code 1 = files copied
When the result is 1, this becomes an error exit code in visual studio.

So i solved this easily by adding this to the bottom of the batch file

exit 0

Suggest that handle ROBOCOPY errors in this fashion

rem each robocopy statement and then underneath have the error check.
if %ERRORLEVEL% GEQ 8 goto failed

rem end of batch file
GOTO success

:failed
rem do not pause as it will pause msbuild.
exit 1

:success
exit 0    

Confusion will set in when no files are copied = no error in VS. Then when there are changes, files do get copied, VS errors but everything the developer wanted was done.

Additional Tip: Do not use a pause in the script as this would become an indefinite pause in the VS build. while developing the script, use something like timeout 10. You will notice this and comment it out rather than have a hanging build.

Understanding the difference between Object.create() and new SomeFunction()

The difference is the so-called "pseudoclassical vs. prototypal inheritance". The suggestion is to use only one type in your code, not mixing the two.

In pseudoclassical inheritance (with "new" operator), imagine that you first define a pseudo-class, and then create objects from that class. For example, define a pseudo-class "Person", and then create "Alice" and "Bob" from "Person".

In prototypal inheritance (using Object.create), you directly create a specific person "Alice", and then create another person "Bob" using "Alice" as a prototype. There is no "class" here; all are objects.

Internally, JavaScript uses "prototypal inheritance"; the "pseudoclassical" way is just some sugar.

See this link for a comparison of the two ways.

Hashmap does not work with int, char

Generics only support object types, not primitives. Unlike C++ templates, generics don't involve code generatation and there is only one HashMap code regardless of the number of generic types of it you use.

Trove4J gets around this by pre-generating selected collections to use primitives and supports TCharIntHashMap which to can wrap to support the Map<Character, Integer> if you need to.

TCharIntHashMap: An open addressed Map implementation for char keys and int values.

Return a `struct` from a function in C

As far as I can remember, the first versions of C only allowed to return a value that could fit into a processor register, which means that you could only return a pointer to a struct. The same restriction applied to function arguments.

More recent versions allow to pass around larger data objects like structs. I think this feature was already common during the eighties or early nineties.

Arrays, however, can still be passed and returned only as pointers.

Why can't I call a public method in another class?

You're trying to call an instance method on the class. To call an instance method on a class you must create an instance on which to call the method. If you want to call the method on non-instances add the static keyword. For example

class Example {
  public static string NonInstanceMethod() {
    return "static";
  }
  public string InstanceMethod() { 
    return "non-static";
  }
}

static void SomeMethod() {
  Console.WriteLine(Example.NonInstanceMethod());
  Console.WriteLine(Example.InstanceMethod());  // Does not compile
  Example v1 = new Example();
  Console.WriteLine(v1.InstanceMethod());
}

Convert a PHP script into a stand-alone windows executable

ExeOutput is also can Turn PHP Websites into Windows Applications and Software

Turn PHP Websites into Windows Applications and Software

Applications made with ExeOutput for PHP run PHP scripts, PHP applications, and PHP websites natively, and do not require a web server, a web browser, or PHP distribution. They are stand-alone and work on any computer with recent Windows versions.

ExeOutput for PHP is a powerful website compiler that works with all of the elements found on modern sites: PHP scripts, JavaScript, HTML, CSS, XML, PDF files, Flash, Flash videos, Silverlight videos, databases, and images. Combining these elements with PHP Runtime and PHP Extensions, ExeOutput for PHP builds an EXE file that contains your complete application.

http://www.exeoutput.com/

For loop in multidimensional javascript array

You can do something like this:

var cubes = [
 [1, 2, 3],
 [4, 5, 6],    
 [7, 8, 9],
];

for(var i = 0; i < cubes.length; i++) {
    var cube = cubes[i];
    for(var j = 0; j < cube.length; j++) {
        display("cube[" + i + "][" + j + "] = " + cube[j]);
    }
}

Working jsFiddle:

The output of the above:

cube[0][0] = 1
cube[0][1] = 2
cube[0][2] = 3
cube[1][0] = 4
cube[1][1] = 5
cube[1][2] = 6
cube[2][0] = 7
cube[2][1] = 8
cube[2][2] = 9

Pass variables from servlet to jsp

This is an servlet code which contain a string variable a. the value for a is getting from an html page with form. then set the variable into the request object. then pass it to jsp using forward and requestdispatcher methods.

String a=req.getParameter("username");
req.setAttribute("name", a);
RequestDispatcher rd=req.getRequestDispatcher("/login.jsp");
rd.forward(req, resp);

in jsp follow these steps shown below in the program

<%String name=(String)request.getAttribute("name");
out.print("your name"+name);%>

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

Make sure all services windows are closed before starting install/uninstall

Remove last characters from a string in C#. An elegant way?

Use lastIndexOf. Like:

string var = var.lastIndexOf(',');

Can I use if (pointer) instead of if (pointer != NULL)?

Question is answered, but I would like to add my points.

I will always prefer if(pointer) instead of if(pointer != NULL) and if(!pointer) instead of if(pointer == NULL):

  • It is simple, small
  • Less chances to write a buggy code, suppose if I misspelled equality check operator == with =
    if(pointer == NULL) can be misspelled if(pointer = NULL) So I will avoid it, best is just if(pointer).
    (I also suggested some Yoda condition in one answer, but that is diffrent matter)

  • Similarly for while (node != NULL && node->data == key), I will simply write while (node && node->data == key) that is more obvious to me (shows that using short-circuit).

  • (may be stupid reason) Because NULL is a macro, if suppose some one redefine by mistake with other value.

What is the difference between XAMPP or WAMP Server & IIS?

WAMP stands for Windows,Apache,Mysql,Php

XAMPP stands for X-os,Apache,Mysql,Php,Perl. (x-os means it can use for any operating system)

Advantages of XAMPP:

  • It is cross-platform software

  • It possesses many other essential modules such as phpMyAdmin, OpenSSL, MediaWiki, WordPress, Joomla and more.

  • it is easy to configure and use.

Advantages of WAMP:

  • It is easy to Use. (Changing Configuration)

  • WAMP is Available for both 64 bit and 32-bit system.

if you are running projects which have specific version requirements WAMP is better choice because you can switch between multiple versions. for example 7x and PHP 5x or Magento2.2.4 won't work on php7.2 but Magento2.3.needs php7.2 or up to work.

i suggest using laragon :

Laragon works out of the box with not only MySQL/MariaDB but also PostgreSQL & MongoDB. With Laragon, they are portable & reliable so you can focus on what matters Laragon is a portable, isolated, fast & powerful universal development environment for PHP, Node.js, Python, Java, Go, Ruby. It is fast, lightweight, easy-to-use and easy-to-extend.

Laragon is great for building and managing modern web applications. It is focused on performance - designed around stability, simplicity, flexibility and freedom.

Laragon is very lightweight and will stay as lean as possible. The core binary itself is less than 2MB and uses less than 4MB RAM when running.

Laragon doesn’t use Windows services. It has its own service orchestration which manages services asynchronously and non-blocking so you’ll find things run fast & smoothly with Laragon.

Advantages of Laragon:

  • Pretty URLs
    Use app.test instead of localhost/app.

  • Portable
    You can move Laragon folder around (to another disks, to another laptops, sync to Cloud,…) without any worries.

  • Isolated
    Laragon has an isolated environment with your OS - it will keep your system clean.

  • Easy Operation

    Unlike others which pre-config for you, Laragon auto-configsall the complicated things. That why you can add another versions of PHP, Python, Ruby, Java, Go, Apache, Nginx, MySQL, PostgreSQL, MongoDB,… effortlessly.

  • Modern & Powerful
    Laragon comes with modern architect which is suitable to build modern web apps. You can work with both Apache & Nginx as they are fully-managed. Also, Laragon makes things a lot easier:Wanna have a Wordpress CMS? Just 1 click.Wanna show your local project to customers? Just 1 click.Wanna enable/disable a PHP extension? Just 1 click.

Delete duplicate elements from an array

It's easier using Array.filter:

var unique = arr.filter(function(elem, index, self) {
    return index === self.indexOf(elem);
})

What is the correct way to declare a boolean variable in Java?

There is no reason to do that. In fact, I would choose to combine declaration and initialization as in

final Boolean isMatch = email1.equals (email2);

using the final keyword so you can't change it (accidentally) afterwards anymore either.

Dynamic constant assignment

Constants in ruby cannot be defined inside methods. See the notes at the bottom of this page, for example

How to store phone numbers on MySQL databases?

You can use varchar for storing phone numbers, so you need not remove the formatting

How to round the minute of a datetime object

The shortest way I know

min = tm.minute // 10 * 10

iPhone/iPad browser simulator?

I use mobile-browser-emulator chrome plug-in which is has iphone device types. It actually uses user-agent and size of device on which based responsive pages are rendered

jQuery get html of container including the container itself

var x = $('#container').get(0).outerHTML;

UPDATE : This is now supported by Firefox as of FireFox 11 (March 2012)

As others have pointed out, this will not work in FireFox. If you need it to work in FireFox, then you might want to take a look at the answer to this question : In jQuery, are there any function that similar to html() or text() but return the whole content of matched component?

Bootstrap 4 dropdown with search

I took the answer from PirateApp and made it reusable. If you include this script it will transform all selects with the class '.dropdown' to searchable dropdowns.

_x000D_
_x000D_
$('.dropdown').each(function(index, dropdown) {

  //Find the input search box
  let search = $(dropdown).find('.search');

  //Find every item inside the dropdown
  let items = $(dropdown).find('.dropdown-item');

  //Capture the event when user types into the search box
  $(search).on('input', function() {
    filter($(search).val().trim().toLowerCase())
  });

  //For every word entered by the user, check if the symbol starts with that word
  //If it does show the symbol, else hide it
  function filter(word) {
    let length = items.length
    let collection = []
    let hidden = 0
    for (let i = 0; i < length; i++) {
      if (items[i].value.toString().toLowerCase().includes(word)) {
        $(items[i]).show()
      } else {
        $(items[i]).hide()
        hidden++
      }
    }

    //If all items are hidden, show the empty view
    if (hidden === length) {
      $(dropdown).find('.dropdown_empty').show();
    } else {
      $(dropdown).find('.dropdown_empty').hide();
    }
  }

  //If the user clicks on any item, set the title of the button as the text of the item
  $(dropdown).find('.dropdown-menu').find('.menuItems').on('click', '.dropdown-item', function() {
    $(dropdown).find('.dropdown-toggle').text($(this)[0].value);
    $(dropdown).find('.dropdown-toggle').dropdown('toggle');
  })
});
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div class="dropdown">
  <button class="btn btn-sm btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Benutzer
    </button>
  <div class="dropdown-menu" aria-labelledby="dropdown_user">
    <form class="px-4 py-2">
      <input type="search" class="form-control search" placeholder="Suche.." autofocus="autofocus">
    </form>
    <div class="menuItems">
      <input type="button" class="dropdown-item" type="button" value="Test1" />
      <input type="button" class="dropdown-item" type="button" value="Test2" />
      <input type="button" class="dropdown-item" type="button" value="Test3" />
    </div>
    <div style="display:none;" class="dropdown-header dropdown_empty">No entry found</div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Can I add and remove elements of enumeration at runtime in Java

No, enums are supposed to be a complete static enumeration.

At compile time, you might want to generate your enum .java file from another source file of some sort. You could even create a .class file like this.

In some cases you might want a set of standard values but allow extension. The usual way to do this is have an interface for the interface and an enum that implements that interface for the standard values. Of course, you lose the ability to switch when you only have a reference to the interface.

How to create an Array with AngularJS's ng-model

How to create an array of inputs with ng-model

Use the ng-repeat directive:

<ol>
  <li ng-repeat="n in [] | range:count">
    <input name="telephone-{{$index}}"
           ng-model="telephones[$index].value" >
  </li>
</ol>

The DEMO

_x000D_
_x000D_
angular.module("app",[])_x000D_
.controller("ctrl",function($scope){_x000D_
  $scope.count = 3;_x000D_
  $scope.telephones = [];_x000D_
})_x000D_
.filter("range",function() {_x000D_
  return (x,n) => Array.from({length:n},(x,index)=>(index));_x000D_
})
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>_x000D_
<body ng-app="app" ng-controller="ctrl">_x000D_
    <button>_x000D_
      Array length_x000D_
      <input type="number" ng-model="count" _x000D_
             ng-change="telephones.length=count">_x000D_
    </button>_x000D_
    <ol>_x000D_
      <li ng-repeat="n in [] | range:count">_x000D_
        <input name="telephone-{{$index}}"_x000D_
               ng-model="telephones[$index].value" >_x000D_
      </li>_x000D_
    </ol>  _x000D_
    {{telephones}}_x000D_
</body>
_x000D_
_x000D_
_x000D_

Why are my PowerShell scripts not running?

You need to run Set-ExecutionPolicy:

Set-ExecutionPolicy Restricted <-- Will not allow any powershell scripts to run.  Only individual commands may be run.

Set-ExecutionPolicy AllSigned <-- Will allow signed powershell scripts to run.

Set-ExecutionPolicy RemoteSigned <-- Allows unsigned local script and signed remote powershell scripts to run.

Set-ExecutionPolicy Unrestricted <-- Will allow unsigned powershell scripts to run.  Warns before running downloaded scripts.

Set-ExecutionPolicy Bypass <-- Nothing is blocked and there are no warnings or prompts.

How to Query an NTP Server using C#?

http://www.codeproject.com/Articles/237501/Windows-Phone-NTP-Client is going to work well for Windows Phone .

Adding the relevant code

/// <summary>
/// Class for acquiring time via Ntp. Useful for applications in which correct world time must be used and the 
/// clock on the device isn't "trusted."
/// </summary>
public class NtpClient
{
    /// <summary>
    /// Contains the time returned from the Ntp request
    /// </summary>
    public class TimeReceivedEventArgs : EventArgs
    {
        public DateTime CurrentTime { get; internal set; }
    }

    /// <summary>
    /// Subscribe to this event to receive the time acquired by the NTP requests
    /// </summary>
    public event EventHandler<TimeReceivedEventArgs> TimeReceived;

    protected void OnTimeReceived(DateTime time)
    {
        if (TimeReceived != null)
        {
            TimeReceived(this, new TimeReceivedEventArgs() { CurrentTime = time });
        }
    }


    /// <summary>
    /// Not reallu used. I put this here so that I had a list of other NTP servers that could be used. I'll integrate this
    /// information later and will provide method to allow some one to choose an NTP server.
    /// </summary>
    public string[] NtpServerList = new string[]
    {
        "pool.ntp.org ",
        "asia.pool.ntp.org",
        "europe.pool.ntp.org",
        "north-america.pool.ntp.org",
        "oceania.pool.ntp.org",
        "south-america.pool.ntp.org",
        "time-a.nist.gov"
    };

    string _serverName;
    private Socket _socket;

    /// <summary>
    /// Constructor allowing an NTP server to be specified
    /// </summary>
    /// <param name="serverName">the name of the NTP server to be used</param>
    public NtpClient(string serverName)
    {
        _serverName = serverName;
    }


    /// <summary>
    /// 
    /// </summary>
    public NtpClient()
        : this("time-a.nist.gov")
    { }

    /// <summary>
    /// Begins the network communication required to retrieve the time from the NTP server
    /// </summary>
    public void RequestTime()
    {
        byte[] buffer = new byte[48];
        buffer[0] = 0x1B;
        for (var i = 1; i < buffer.Length; ++i)
            buffer[i] = 0;
        DnsEndPoint _endPoint = new DnsEndPoint(_serverName, 123);

        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        SocketAsyncEventArgs sArgsConnect = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
        sArgsConnect.Completed += (o, e) =>
        {
            if (e.SocketError == SocketError.Success)
            {
                SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
                sArgs.Completed +=
                    new EventHandler<SocketAsyncEventArgs>(sArgs_Completed);
                sArgs.SetBuffer(buffer, 0, buffer.Length);
                sArgs.UserToken = buffer;
                _socket.SendAsync(sArgs);
            }
        };
        _socket.ConnectAsync(sArgsConnect);

    }

    void sArgs_Completed(object sender, SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            byte[] buffer = (byte[])e.Buffer;
            SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs();
            sArgs.RemoteEndPoint = e.RemoteEndPoint;

            sArgs.SetBuffer(buffer, 0, buffer.Length);
            sArgs.Completed += (o, a) =>
            {
                if (a.SocketError == SocketError.Success)
                {
                    byte[] timeData = a.Buffer;

                    ulong hTime = 0;
                    ulong lTime = 0;

                    for (var i = 40; i <= 43; ++i)
                        hTime = hTime << 8 | buffer[i];
                    for (var i = 44; i <= 47; ++i)
                        lTime = lTime << 8 | buffer[i];
                    ulong milliseconds = (hTime * 1000 + (lTime * 1000) / 0x100000000L);

                    TimeSpan timeSpan =
                        TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
                    var currentTime = new DateTime(1900, 1, 1) + timeSpan;
                    OnTimeReceived(currentTime);

                }
            };
            _socket.ReceiveAsync(sArgs);
        }
    }
}

Usage :

public partial class MainPage : PhoneApplicationPage
{
    private NtpClient _ntpClient;
    public MainPage()
    {
        InitializeComponent();
        _ntpClient = new NtpClient();
        _ntpClient.TimeReceived += new EventHandler<NtpClient.TimeReceivedEventArgs>(_ntpClient_TimeReceived);
    }

    void _ntpClient_TimeReceived(object sender, NtpClient.TimeReceivedEventArgs e)
    {
        this.Dispatcher.BeginInvoke(() =>
                                        {
                                            txtCurrentTime.Text = e.CurrentTime.ToLongTimeString();
                                            txtSystemTime.Text = DateTime.Now.ToUniversalTime().ToLongTimeString();
                                        });
    }

    private void UpdateTimeButton_Click(object sender, RoutedEventArgs e)
    {
        _ntpClient.RequestTime();
    }
}

MySQL: Set user variable from result of query

First lets take a look at how can we define a variable in mysql

To define a varible in mysql it should start with '@' like @{variable_name} and this '{variable_name}', we can replace it with our variable name.

Now, how to assign a value in a variable in mysql. For this we have many ways to do that

  1. Using keyword 'SET'.

Example :-

mysql >  SET @a = 1;
  1. Without using keyword 'SET' and using ':='.

Example:-

mysql > @a:=1;
  1. By using 'SELECT' statement.

Example:-

mysql > select 1 into @a;

Here @a is user defined variable and 1 is going to be assigned in @a.

Now how to get or select the value of @{variable_name}.

we can use select statement like

Example :-

mysql > select @a;

it will show the output and show the value of @a.

Now how to assign a value from a table in a variable.

For this we can use two statement like :-

1.

@a := (select emp_name from employee where emp_id = 1);
select emp_name into @a from employee where emp_id = 1;

Always be careful emp_name must return single value otherwise it will throw you a error in this type statements.

refer this:- http://www.easysolutionweb.com/sql-pl-sql/how-to-assign-a-value-in-a-variable-in-mysql

Use HTML5 to resize an image before upload

Here is what I ended up doing and it worked great.

First I moved the file input outside of the form so that it is not submitted:

<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />
<form id="uploadImageForm" enctype="multipart/form-data">
    <input id="name" value="#{name}" />
    ... a few more inputs ... 
</form>

Then I changed the uploadPhotos function to handle only the resizing:

window.uploadPhotos = function(url){
    // Read in file
    var file = event.target.files[0];

    // Ensure it's an image
    if(file.type.match(/image.*/)) {
        console.log('An image has been loaded');

        // Load the image
        var reader = new FileReader();
        reader.onload = function (readerEvent) {
            var image = new Image();
            image.onload = function (imageEvent) {

                // Resize the image
                var canvas = document.createElement('canvas'),
                    max_size = 544,// TODO : pull max size from a site config
                    width = image.width,
                    height = image.height;
                if (width > height) {
                    if (width > max_size) {
                        height *= max_size / width;
                        width = max_size;
                    }
                } else {
                    if (height > max_size) {
                        width *= max_size / height;
                        height = max_size;
                    }
                }
                canvas.width = width;
                canvas.height = height;
                canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                var dataUrl = canvas.toDataURL('image/jpeg');
                var resizedImage = dataURLToBlob(dataUrl);
                $.event.trigger({
                    type: "imageResized",
                    blob: resizedImage,
                    url: dataUrl
                });
            }
            image.src = readerEvent.target.result;
        }
        reader.readAsDataURL(file);
    }
};

As you can see I'm using canvas.toDataURL('image/jpeg'); to change the resized image into a dataUrl adn then I call the function dataURLToBlob(dataUrl); to turn the dataUrl into a blob that I can then append to the form. When the blob is created, I trigger a custom event. Here is the function to create the blob:

/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
    var BASE64_MARKER = ';base64,';
    if (dataURL.indexOf(BASE64_MARKER) == -1) {
        var parts = dataURL.split(',');
        var contentType = parts[0].split(':')[1];
        var raw = parts[1];

        return new Blob([raw], {type: contentType});
    }

    var parts = dataURL.split(BASE64_MARKER);
    var contentType = parts[0].split(':')[1];
    var raw = window.atob(parts[1]);
    var rawLength = raw.length;

    var uInt8Array = new Uint8Array(rawLength);

    for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }

    return new Blob([uInt8Array], {type: contentType});
}
/* End Utility function to convert a canvas to a BLOB      */

Finally, here is my event handler that takes the blob from the custom event, appends the form and then submits it.

/* Handle image resized events */
$(document).on("imageResized", function (event) {
    var data = new FormData($("form[id*='uploadImageForm']")[0]);
    if (event.blob && event.url) {
        data.append('image_data', event.blob);

        $.ajax({
            url: event.url,
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(data){
               //handle errors...
            }
        });
    }
});

Is there a performance difference between i++ and ++i in C?

Please don't let the question of "which one is faster" be the deciding factor of which to use. Chances are you're never going to care that much, and besides, programmer reading time is far more expensive than machine time.

Use whichever makes most sense to the human reading the code.

Failed to load ApplicationContext from Unit Test: FileNotFound

Give the below

@ContextConfiguration(locations =  {"classpath*:/spring/test-context.xml"})

And in pom.xml give the following plugin:

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-surefire-plugin</artifactId>
   <version>2.20.1</version>
<configuration>
    <additionalClasspathElements>
       <additionalClasspathElement>${basedir}/src/test/resources</additionalClasspathElement>
    </additionalClasspathElements>
</configuration>

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

I was really struggling with this mismatch between ChromeDriver v74.0.3729.6 and the Chrome Browser v73.0. I finally found a way to get ChromeDriver to an earlier version,

  1. In Chrome > About Google Chrome, copy the the version number, except for the last group. For instance, 72.0.3626.

  2. Paste that version at the end of this url and visit it. It will come back with a version, which you should copy. https://chromedriver.storage.googleapis.com/LATEST_RELEASE_

  3. Back in the command line, run bundle exec chromedriver-update <copied version>

Get array of object's keys

Use Object.keys:

_x000D_
_x000D_
var foo = {_x000D_
  'alpha': 'puffin',_x000D_
  'beta': 'beagle'_x000D_
};_x000D_
_x000D_
var keys = Object.keys(foo);_x000D_
console.log(keys) // ['alpha', 'beta'] _x000D_
// (or maybe some other order, keys are unordered).
_x000D_
_x000D_
_x000D_

This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.

The ES5-shim has a implementation of Object.keys you can steal

"continue" in cursor.forEach()

Each iteration of the forEach() will call the function that you have supplied. To stop further processing within any given iteration (and continue with the next item) you just have to return from the function at the appropriate point:

elementsCollection.forEach(function(element){
  if (!element.shouldBeProcessed)
    return; // stop processing this iteration

  // This part will be avoided if not neccessary
  doSomeLengthyOperation();
});

Access parent DataContext from DataTemplate

You can use RelativeSource to find the parent element, like this -

Binding="{Binding Path=DataContext.CurveSpeedMustBeSpecified, 
RelativeSource={RelativeSource AncestorType={x:Type local:YourParentElementType}}}"

See this SO question for more details about RelativeSource.

Fast ceiling of an integer division in C / C++

How about this? (requires y non-negative, so don't use this in the rare case where y is a variable with no non-negativity guarantee)

q = (x > 0)? 1 + (x - 1)/y: (x / y);

I reduced y/y to one, eliminating the term x + y - 1 and with it any chance of overflow.

I avoid x - 1 wrapping around when x is an unsigned type and contains zero.

For signed x, negative and zero still combine into a single case.

Probably not a huge benefit on a modern general-purpose CPU, but this would be far faster in an embedded system than any of the other correct answers.

How to make phpstorm display line numbers by default?

On the Mac version 8.0.1 has this setting here:

PhpStorm > Preferences > Editor (this is in the second section on the left - i.e. IDE Settings NOT Project Settings) > Appearance > Show line numbers

How to convert all elements in an array to integer in JavaScript?

var inp=readLine();//reading the input as one line string
var nums=inp.split(" ").map(Number);//making an array of numbers
console.log(nums);`

input : 1 9 0 65 5 7 output:[ 1, 9, 0, 65, 5, 7 ]

what if we dont use .map(Number)

code

var inp=readLine();//reading the input as one line string
var nums=inp.split(" ");//making an array of strings
console.log(nums);

input : 1 9 0 65 5 7 output:[ '1', '9', '0', '65', '5', '7']

Can you force Vue.js to reload/re-render?

Try to use this.$router.go(0); to manually reload the current page.

Add custom message to thrown exception while maintaining stack trace in Java

Following code is a simple example that worked for me.Let me call the function main as parent function and divide as child function.
Basically i am throwing a new exception with my custom message (for the parent's call) if an exception occurs in child function by catching the Exception in the child first.

class Main {
    public static void main(String args[]) {
        try{
            long ans=divide(0);
            System.out.println("answer="+ans);
        }
        catch(Exception e){
            System.out.println("got exception:"+e.getMessage());

        }

    }
    public static long divide(int num) throws Exception{
        long x=-1;
        try {
            x=5/num;
        }
        catch (Exception e){
            throw new Exception("Error occured in divide for number:"+num+"Error:"+e.getMessage());
        }
        return x;
    }
}  

the last line return x will not run if error occurs somewhere in between.

CSS two divs next to each other

You can use flexbox to lay out your items:

_x000D_
_x000D_
#parent {_x000D_
  display: flex;_x000D_
}_x000D_
#narrow {_x000D_
  width: 200px;_x000D_
  background: lightblue;_x000D_
  /* Just so it's visible */_x000D_
}_x000D_
#wide {_x000D_
  flex: 1;_x000D_
  /* Grow to rest of container */_x000D_
  background: lightgreen;_x000D_
  /* Just so it's visible */_x000D_
}
_x000D_
<div id="parent">_x000D_
  <div id="wide">Wide (rest of width)</div>_x000D_
  <div id="narrow">Narrow (200px)</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This is basically just scraping the surface of flexbox. Flexbox can do pretty amazing things.


For older browser support, you can use CSS float and a width properties to solve it.

_x000D_
_x000D_
#narrow {_x000D_
  float: right;_x000D_
  width: 200px;_x000D_
  background: lightblue;_x000D_
}_x000D_
#wide {_x000D_
  float: left;_x000D_
  width: calc(100% - 200px);_x000D_
  background: lightgreen;_x000D_
}
_x000D_
<div id="parent">_x000D_
  <div id="wide">Wide (rest of width)</div>_x000D_
  <div id="narrow">Narrow (200px)</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Numpy AttributeError: 'float' object has no attribute 'exp'

Probably there's something wrong with the input values for X and/or T. The function from the question works ok:

import numpy as np
from math import e

def sigmoid(X, T):
  return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))

X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])

print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))

Result:

[[15 16]
 [ 5 10]]

[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]

[[ 0.99999969  0.99999989]
 [ 0.99330715  0.9999546 ]]

Probably it's the dtype of your input arrays. Changing X to:

X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)

Gives:

Traceback (most recent call last):
  File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
    print sigmoid(X, T)
  File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
    return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp

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

I am using large data sets exported to a python file in the form

XVals1 = [.........] 
XVals2 = [.........] 

Each list is of identical length. I use

>>> a1 = np.array(SV.XVals1)

>>> a2 = np.array(SV.XVals2)

Then

>>> A = np.matrix([a1,a2])

What is the maximum length of a valid email address?

user

The maximum total length of a user name is 64 characters.

domain

Maximum of 255 characters in the domain part (the one after the “@”)

However, there is a restriction in RFC 2821 reading:

The maximum total length of a reverse-path or forward-path is 256 characters, including the punctuation and element separators”. Since addresses that don’t fit in those fields are not normally useful, the upper limit on address lengths should normally be considered to be 256, but a path is defined as: Path = “<” [ A-d-l “:” ] Mailbox “>” The forward-path will contain at least a pair of angle brackets in addition to the Mailbox, which limits the email address to 254 characters.

How to get Selected Text from select2 when using <input>

Used this for show text

var data = $('#id-selected-input').select2('data'); 
data.forEach(function (item) { 
    alert(item.text); 
})

How to export and import environment variables in windows?

To export user variables, open a command prompt and use regedit with /e

Example :

regedit /e "%userprofile%\Desktop\my_user_env_variables.reg" "HKEY_CURRENT_USER\Environment"

if, elif, else statement issues in Bash

There is a space missing between elif and [:

elif[ "$seconds" -gt 0 ]

should be

elif [ "$seconds" -gt 0 ]

As I see this question is getting a lot of views, it is important to indicate that the syntax to follow is:

if [ conditions ]
# ^ ^          ^

meaning that spaces are needed around the brackets. Otherwise, it won't work. This is because [ itself is a command.

The reason why you are not seeing something like elif[: command not found (or similar) is that after seeing if and then, the shell is looking for either elif, else, or fi. However it finds another then (after the mis-formatted elif[). Only after having parsed the statement it would be executed (and an error message like elif[: command not found would be output).

Foreach in a Foreach in MVC View

You have:

foreach (var category in Model.Categories)

and then

@foreach (var product in Model)

Based on that view and model it seems that Model is of type Product if yes then the second foreach is not valid. Actually the first one could be the one that is invalid if you return a collection of Product.

UPDATE:

You are right, I am returning the model of type Product. Also, I do understand what is wrong now that you've pointed it out. How am I supposed to do what I'm trying to do then if I can't do it this way?

I'm surprised your code compiles when you said you are returning a model of Product type. Here's how you can do it:

@foreach (var category in Model)
{
    <h3><u>@category.Name</u></h3>

    <div>
        <ul>    
            @foreach (var product in category.Products)
            {
                <li>
                    put the rest of your code
                </li>
            }
        </ul>
    </div>
}

That suggest that instead of returning a Product, you return a collection of Category with Products. Something like this in EF:

// I am typing it here directly 
// so I'm not sure if this is the correct syntax.
// I assume you know how to do this,
// anyway this should give you an idea.
context.Categories.Include(o=>o.Product)

Generic List - moving an item within the list

List<T>.Remove() and List<T>.RemoveAt() do not return the item that is being removed.

Therefore you have to use this:

var item = list[oldIndex];
list.RemoveAt(oldIndex);
list.Insert(newIndex, item);

List<T> or IList<T>

If you are exposing your class through a library that others will use, you generally want to expose it via interfaces rather than concrete implementations. This will help if you decide to change the implementation of your class later to use a different concrete class. In that case the users of your library won't need to update their code since the interface doesn't change.

If you are just using it internally, you may not care so much, and using List<T> may be ok.

How to merge two arrays in JavaScript and de-duplicate items

For n arrays, you can get the union like so.

function union(arrays) {
    return new Set(arrays.flat()).keys();
};

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

I found the Chrome app "Advanced REST Client" excellent to work with REST services. You can set the Content-Type to application/json among other things: Advanced REST client

Shell Script: How to write a string to file and to stdout on console?

You can use >> to print in another file.

echo "hello" >> logfile.txt

Maximum request length exceeded.

I had to edit the C:\Windows\System32\inetsrv\config\applicationHost.config file and add <requestLimits maxAllowedContentLength="1073741824" /> to the end of the...

<configuration>
    <system.webServer>
        <security>
            <requestFiltering>

section.

As per This Microsoft Support Article

How to find out if a file exists in C# / .NET?

System.IO.File:

using System.IO;

if (File.Exists(path)) 
{
    Console.WriteLine("file exists");
} 

sql how to cast a select query

You just CAST() this way

SELECT cast(yourNumber as varchar(10))
FROM yourTable

Then if you want to JOIN based on it, you can use:

SELECT *
FROM yourTable t1
INNER JOIN yourOtherTable t2
    on cast(t1.yourNumber as varchar(10)) = t2.yourString

How do I get a plist as a Dictionary in Swift?

Here is a bit shorter version, based on @connor 's answer

guard let path = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist"),
    let myDict = NSDictionary(contentsOfFile: path) else {
    return nil
}

let value = dict.value(forKey: "CLIENT_ID") as! String?

$(document).ready(function() is not working

Set events after loading DOM Elements.

$(function () {
        $(document).on("click","selector",function (e) {
          alert("hi");

        });

    });

React native ERROR Packager can't listen on port 8081

In order to fix this issue, the process I have mentioned below.

Please cancel the current process of“react-native run-android” by CTRL + C or CMD + C

Close metro bundler(terminal) window command line which opened automatically.

Run the command again on terminal, “react-native run-android

Setting state on componentDidMount()

It is not an anti-pattern to call setState in componentDidMount. In fact, ReactJS provides an example of this in their documentation:

You should populate data with AJAX calls in the componentDidMount lifecycle method. This is so you can use setState to update your component when the data is retrieved.

Example From Doc

componentDidMount() {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

Is there a way to create multiline comments in Python?

Yes, it is fine to use both:

'''
Comments
'''

and

"""
Comments
"""

But, the only thing you all need to remember while running in an IDE, is you have to 'RUN' the entire file to be accepted as multiple lines codes. Line by line 'RUN' won't work properly and will show an error.

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

Salam,

You don't need to change port no.

only go to task manager & end task any other programs that are running.

and then can you START APACHE.......

Sincerely,

Environment variable substitution in sed

You can use other characters besides "/" in substitution:

sed "s#$1#$2#g" -i FILE

R define dimensions of empty data frame

seq_along may help to find out how many rows in your data file and create a data.frame with the desired number of rows

    listdf <- data.frame(ID=seq_along(df),
                              var1=seq_along(df), var2=seq_along(df))

Difference between VARCHAR2(10 CHAR) and NVARCHAR2(10)

  • The NVARCHAR2 stores variable-length character data. When you create a table with the NVARCHAR2 column, the maximum size is always in character length semantics, which is also the default and only length semantics for the NVARCHAR2 data type.

    The NVARCHAR2data type uses AL16UTF16character set which encodes Unicode data in the UTF-16 encoding. The AL16UTF16 use 2 bytes to store a character. In addition, the maximum byte length of an NVARCHAR2 depends on the configured national character set.

  • VARCHAR2 The maximum size of VARCHAR2 can be in either bytes or characters. Its column only can store characters in the default character set while the NVARCHAR2 can store virtually any characters. A single character may require up to 4 bytes.

By defining the field as:

  • VARCHAR2(10 CHAR) you tell Oracle it can use enough space to store 10 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.
  • NVARCHAR2(10) you tell Oracle it can store 10 characters with 2 bytes per character

In Summary:

  • VARCHAR2(10 CHAR) can store maximum of 10 characters and maximum of 40 bytes (depends on the configured national character set).

  • NVARCHAR2(10) can store maximum of 10 characters and maximum of 20 bytes (depends on the configured national character set).

Note: Character set can be UTF-8, UTF-16,....

Please have a look at this tutorial for more detail.

Have a good day!

How to install Android SDK Build Tools on the command line?

However, it is too slow on running

Yes, I've had the same problem. Some of the file downloads are extremely slow (or at least they have been in the last couple of days). If you want to download everything there's not a lot you can do about that.

The result is that nothing in folder build-tools, and I want is aapt and apkbuilder, since I want to build apk from command line without ant.

Did you let it run to completion?

One thing you can do is filter the packages that are being downloaded using the -t switch.

For example:

tools/android update sdk --no-ui -t platform-tool

When I tried this the other day I got version 18.0.0 of the build tools installed. For some reason the latest version 18.0.1 is not included by this filter and the only way to get it was to install everything with the --all switch.

Select the values of one property on all objects of an array in PowerShell

Caution, member enumeration only works if the collection itself has no member of the same name. So if you had an array of FileInfo objects, you couldn't get an array of file lengths by using

 $files.length # evaluates to array length

And before you say "well obviously", consider this. If you had an array of objects with a capacity property then

 $objarr.capacity

would work fine UNLESS $objarr were actually not an [Array] but, for example, an [ArrayList]. So before using member enumeration you might have to look inside the black box containing your collection.

(Note to moderators: this should be a comment on rageandqq's answer but I don't yet have enough reputation.)

how to generate web service out of wsdl

You cannot guarantee that the automatically-generated WSDL will match the WSDL from which you create the service interface.

In your scenario, you should place the WSDL file on your web site somewhere, and have consumers use that URL. You should disable the Documentation protocol in the web.config so that "?wsdl" does not return a WSDL. See <protocols> Element.

Also, note the first paragraph of that article:

This topic is specific to a legacy technology. XML Web services and XML Web service clients should now be created using Windows Communication Foundation (WCF).

Calculating the difference between two Java date instances

Just call getTime on each, take the difference, and divide by the number of milliseconds in a day.

Passing Arrays to Function in C++

The question has already been answered, but I thought I'd add an answer with more precise terminology and references to the C++ standard.

Two things are going on here, array parameters being adjusted to pointer parameters, and array arguments being converted to pointer arguments. These are two quite different mechanisms, the first is an adjustment to the actual type of the parameter, whereas the other is a standard conversion which introduces a temporary pointer to the first element.

Adjustments to your function declaration:

dcl.fct#5:

After determining the type of each parameter, any parameter of type “array of T” (...) is adjusted to be “pointer to T”.

So int arg[] is adjusted to be int* arg.

Conversion of your function argument:

conv.array#1

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion is applied. The result is a pointer to the first element of the array.

So in printarray(firstarray, 3);, the lvalue firstarray of type "array of 3 int" is converted to a prvalue (temporary) of type "pointer to int", pointing to the first element.

Check if input is integer type in C

I've been searching for a simpler solution using only loops and if statements, and this is what I came up with. The program also works with negative integers and correctly rejects any mixed inputs that may contain both integers and other characters.


#include <stdio.h>
#include <stdlib.h> // Used for atoi() function
#include <string.h> // Used for strlen() function

#define TRUE 1
#define FALSE 0

int main(void)
{
    char n[10]; // Limits characters to the equivalent of the 32 bits integers limit (10 digits)
    int intTest;
    printf("Give me an int: ");

    do
    {        
        scanf(" %s", n);

        intTest = TRUE; // Sets the default for the integer test variable to TRUE

        int i = 0, l = strlen(n);
        if (n[0] == '-') // Tests for the negative sign to correctly handle negative integer values
            i++;
        while (i < l)
        {            
            if (n[i] < '0' || n[i] > '9') // Tests the string characters for non-integer values
            {              
                intTest = FALSE; // Changes intTest variable from TRUE to FALSE and breaks the loop early
                break;
            }
            i++;
        }
        if (intTest == TRUE)
            printf("%i\n", atoi(n)); // Converts the string to an integer and prints the integer value
        else
            printf("Retry: "); // Prints "Retry:" if tested FALSE
    }
    while (intTest == FALSE); // Continues to ask the user to input a valid integer value
    return 0;
}

How to connect android emulator to the internet

I have Mac OS X 10.7.2, Eclipse Helios Service Release 2. I also work via Proxy and my IP settings are via DHCP. I solved this issue firstly using this article http://www.gitshah.com/2011/02/android-fixing-no-internet-connection.html, then I removed Emulator settings and just go to Run->Run Configurations->Target->Additional Emulator Command Line Options and type there -http-proxy xxx.xx.111.1:3128 . Also I would like to say that when I typed also a DNS like this: -dns-server xxx.xx.111.1 -http-proxy xxx.xx.111.1:3128 it did not work, but when I removed DNS it worked. Also I would like to note, that Additional Emulator Command Line Options are not visible without scrolling to the bottom of that window. I also want to note, that when you change emulator options, all apps will work. But If you write Additional Emulator Command Line Options, you need to write them every time for every app target in Run Configurations.

How to get milliseconds from LocalDateTime in Java 8

If you have a Java 8 Clock, then you can use clock.millis() (although it recommends you use clock.instant() to get a Java 8 Instant, as it's more accurate).

Why would you use a Java 8 clock? So in your DI framework you can create a Clock bean:

@Bean
public Clock getClock() {
    return Clock.systemUTC();
}

and then in your tests you can easily Mock it:

@MockBean private Clock clock;

or you can have a different bean:

@Bean
public Clock getClock() {
    return Clock.fixed(instant, zone);
}

which helps with tests that assert dates and times immeasurably.

How to remove all MySQL tables from the command-line without DROP database permissions?

The accepted answer does not work for databases that have large numbers of tables, e.g. Drupal databases. Instead, see the script here: https://stackoverflow.com/a/12917793/1507877 which does work on MySQL 5.5. CAUTION: Around line 11, there is a "WHERE table_schema = SCHEMA();" This should instead be "WHERE table_schema = 'INSERT NAME OF DB INTO WHICH IMPORT WILL OCCUR';"

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

I had the same problem when my network config was incorrect and DNS was not resolving. In other words the issue could arise when there is no Network Access.

How to get correct timestamp in C#

Your mistake is using new DateTime(), which returns January 1, 0001 at 00:00:00.000 instead of current date and time. The correct syntax to get current date and time is DateTime.Now, so change this:

String timeStamp = GetTimestamp(new DateTime());

to this:

String timeStamp = GetTimestamp(DateTime.Now);

How to get the cell value by column name not by index in GridView in asp.net

Although its a long time but this relatively small piece of code seems easy to read and get:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
   int index;
   string cellContent;

    foreach (TableCell tc in ((GridView)sender).HeaderRow.Cells)
    {
       if( tc.Text.Equals("yourColumnName") )
       {
         index = ((GridView)sender).HeaderRow.Cells.GetCellIndex(tc);
         cellContent = ((GridView)sender).SelectedRow.Cells[index].Text;
         break;
       }
    }
}

error: use of deleted function

gcc 4.6 supports a new feature of deleted functions, where you can write

hdealt() = delete;

to disable the default constructor.

Here the compiler has obviously seen that a default constructor can not be generated, and =delete'd it for you.

How do I change the formatting of numbers on an axis with ggplot?

x <- rnorm(10) * 100000
y <- seq(0, 1, length = 10)
p <- qplot(x, y)
library(scales)
p + scale_x_continuous(labels = comma)

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

This is my .env mail settings

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=hello27
MAIL_ENCRYPTION=tls

i was getting thesame error as stated in the question but by using

php artisan config:cache

Everything worked fine

Query for documents where array size is greater than 1

I know its old question, but I am trying this with $gte and $size in find. I think to find() is faster.

db.getCollection('collectionName').find({ name : { $gte : {  $size : 1 } }})

Which HTTP methods match up to which CRUD methods?

The building blocks of REST are mainly the resources (and URI) and the hypermedia. In this context, GET is the way to get a representation of the resource (which can indeed be mapped to a SELECT in CRUD terms).

However, you shouldn't necessarily expect a one-to-one mapping between CRUD operations and HTTP verbs. The main difference between PUT and POST is about their idempotent property. POST is also more commonly used for partial updates, as PUT generally implies sending a full new representation of the resource.

I'd suggest reading this:

The HTTP specification is also a useful reference:

The PUT method requests that the enclosed entity be stored under the supplied Request-URI.

[...]

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,

How to use SVG markers in Google Maps API v3

Yes you can use an .svg file for the icon just like you can .png or another image file format. Just set the url of the icon to the directory where the .svg file is located. For example:

var icon = {
        url: 'path/to/images/car.svg',
        size: new google.maps.Size(sizeX, sizeY),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(sizeX/2, sizeY/2)
};

var marker = new google.maps.Marker({
        position: event.latLng,
        map: map,
        draggable: false,
        icon: icon
});

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

I think you got it a bit wrong. Someone in the thread you pasted says that you can stop anti-aliasing by using px instead of pt, not that you can force it by using the latter. I'm a bit sceptical to both of the claims though...

check for null date in CASE statement, where have I gone wrong?

select Id, StartDate,
Case IsNull (StartDate , '01/01/1800')
When '01/01/1800' then
  'Awaiting'
Else
  'Approved'
END AS StartDateStatus
From MyTable

How do I search for an object by its ObjectId in the mongo console?

Not strange at all, people do this all the time. Make sure the collection name is correct (case matters) and that the ObjectId is exact.

Documentation is here

> db.test.insert({x: 1})

> db.test.find()                                               // no criteria
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }      

> db.test.find({"_id" : ObjectId("4ecc05e55dd98a436ddcc47c")}) // explicit
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }

> db.test.find(ObjectId("4ecc05e55dd98a436ddcc47c"))           // shortcut
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }

MySQL skip first 10 results

There is an OFFSET as well that should do the trick:

SELECT column FROM table
LIMIT 10 OFFSET 10

Finding duplicate values in a SQL table

To delete records whose names are duplicate

;WITH CTE AS    
(

    SELECT ROW_NUMBER() OVER (PARTITION BY name ORDER BY name) AS T FROM     @YourTable    
)

DELETE FROM CTE WHERE T > 1

iPhone get SSID without private library

Here's the cleaned up ARC version, based on @elsurudo's code:

- (id)fetchSSIDInfo {
     NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
     NSLog(@"Supported interfaces: %@", ifs);
     NSDictionary *info;
     for (NSString *ifnam in ifs) {
         info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
         NSLog(@"%@ => %@", ifnam, info);
         if (info && [info count]) { break; }
     }
     return info;
}

Printing newlines with print() in R

An alternative to cat() is writeLines():

> writeLines("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename
>

An advantage is that you don't have to remember to append a "\n" to the string passed to cat() to get a newline after your message. E.g. compare the above to the same cat() output:

> cat("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename>

and

> cat("File not supplied.\nUsage: ./program F=filename","\n")
File not supplied.
Usage: ./program F=filename
>

The reason print() doesn't do what you want is that print() shows you a version of the object from the R level - in this case it is a character string. You need to use other functions like cat() and writeLines() to display the string. I say "a version" because precision may be reduced in printed numerics, and the printed object may be augmented with extra information, for example.

Change div width live with jQuery

There are two ways to do this:

CSS: Use width as %, like 75%, so the width of the div will change automatically when user resizes the browser.

Javascipt: Use resize event

$(window).bind('resize', function()
{
    if($(window).width() > 500)
        $('#divID').css('width', '300px');
    else
        $('divID').css('width', '200px');
});

Hope this will help you :)

What is a Sticky Broadcast?

If an Activity calls onPause with a normal broadcast, receiving the Broadcast can be missed. A sticky broadcast can be checked after it was initiated in onResume.

Update 6/23/2020

Sticky broadcasts are deprecated.

See sendStickyBroadcast documentation.

This method was deprecated in API level 21.

Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

Implement

Intent intent = new Intent("some.custom.action");
intent.putExtra("some_boolean", true);
sendStickyBroadcast(intent);

Resources

PHP is_numeric or preg_match 0-9 validation

is_numeric() tests whether a value is a number. It doesn't necessarily have to be an integer though - it could a decimal number or a number in scientific notation.

The preg_match() example you've given only checks that a value contains the digits zero to nine; any number of them, and in any sequence.

Note that the regular expression you've given also isn't a perfect integer checker, the way you've written it. It doesn't allow for negatives; it does allow for a zero-length string (ie with no digits at all, which presumably shouldn't be valid?), and it allows the number to have any number of leading zeros, which again may not be the intended.

[EDIT]

As per your comment, a better regular expression might look like this:

/^[1-9][0-9]*$/

This forces the first digit to only be between 1 and 9, so you can't have leading zeros. It also forces it to be at least one digit long, so solves the zero-length string issue.

You're not worried about negatives, so that's not an issue.

You might want to restrict the number of digits, because as things stand, it will allow strings that are too big to be stored as integers. To restrict this, you would change the star into a length restriction like so:

/^[1-9][0-9]{0,15}$/

This would allow the string to be between 1 and 16 digits long (ie the first digit plus 0-15 further digits). Feel free to adjust the numbers in the curly braces to suit your own needs. If you want a fixed length string, then you only need to specify one number in the braces.

Hope that helps.

Label python data points on plot

How about print (x, y) at once.

from matplotlib import pyplot as plt

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

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

plt.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

plt.grid()
plt.show()

enter image description here

Firebase Permission Denied

  1. Open firebase, select database on the left hand side.
  2. Now on the right hand side, select [Realtime database] from the drown and change the rules to:
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Pip install - Python 2.7 - Windows 7

pip is installed by default when we install Python in windows. After setting up the environment variables path for python executables, we can run python interpreter from the command line on windows CMD After that, we can directly use the python command with pip option to install further packages as following:-

C:\ python -m pip install python_module_name

This will install the module using pip.