Programs & Examples On #Typedescriptor

Returning JSON from a PHP Script

It is also good to set the access security - just replace * with the domain you want to be able to reach it.

<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
    $response = array();
    $response[0] = array(
        'id' => '1',
        'value1'=> 'value1',
        'value2'=> 'value2'
    );

echo json_encode($response); 
?>

Here is more samples on that: how to bypass Access-Control-Allow-Origin?

HTML Mobile -forcing the soft keyboard to hide

I am fighting the soft keyboard on the Honeywell Dolphin 70e with Android 4.0.3. I don't need the keyboard because the input comes from the builtin barcode reader through the 'scanwedge', set to generate key events.

What I found was that the trick described in the earlier answers of:

input.blur();
input.focus();

works, but only once, right at page initialization. It puts the focus in the input element without showing the soft keyboard. It does NOT work later, e.g. after a TAB character in the suffix of the barcode causes the onblur or oninput event on the input element.

To read and process lots of barcodes, you may use a different postfix than TAB (9), e.g. 8, which is not interpreted by the browser. In the input.keydown event, use e.keyCode == 8 to detect a complete barcode to be processed.

This way, you initialize the page with focus in the input element, with keyboard hidden, all barcodes go to the input element, and the focus never leaves that element. Of course, the page cannot have other input elements (like buttons), because then you will not be able to return to the barcode input element with the soft keyboard hidden.

Perhaps reloading the page after a button click may be able to hide the keyboard. So use ajax for fast processing of barcodes, and use a regular asp.net button with PostBack to process a button click and reload the page to return focus to the barcode input with the keyboard hidden.

How to make a node.js application run permanently?

No need to install any other package.

Run this command

node server.js > stdout.txt 2> stderr.txt &

server.js is your server file or it can be api.js

After that hit "exit" to close terminal

exit

Django Forms: if not valid, show form with error message

UPDATE: Added a more detailed description of the formset errors.


Form.errors combines all field and non_field_errors. Therefore you can simplify the html to this:

template

    {% load form_tags %}

    {% if form.errors %}
    <div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
        <div id="form_errors">
            {% for key, value in form.errors.items %}
                <span class="fieldWrapper">
                    {{ key }}:{{ value }}
                </span>
            {% endfor %}
        </div>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    {% endif %}


If you want to generalise it you can create a list_errors.html which you include in every form template. It handles form and formset errors:

    {% if form.errors %}
    <div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
        <div id="form_errors">

            {% for key, value in form.errors.items %}
                <span class="fieldWrapper">
                    {{ key }}:{{ value }}
                </span>
            {% endfor %}
        </div>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    {% elif formset.total_error_count %}
    <div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
        <div id="form_errors">
            {% if formset.non_form_errors %}
                {{ formset.non_form_errors }}
            {% endif %}
            {% for form in formset.forms %}
                {% if form.errors %}
                    Form number {{ forloop.counter }}:
                    <ul class="errorlist">
                    {% for key, error in form.errors.items %}
                        <li>{{form.fields|get_label:key}}
                            <ul class="errorlist">
                                <li>{{error}}</li>
                            </ul>
                        </li>
                    {% endfor %}
                    </ul>
                {% endif %}
            {% endfor %}

        </div>
    </div>

    {% endif %}

form_tags.py

from django import template

register = template.Library()


def get_label(a_dict, key):
    return getattr(a_dict.get(key), 'label', 'No label')


register.filter("get_label", get_label)

One caveat: In contrast to forms Formset.errors does not include non_field_errors.

Loop through each cell in a range of cells when given a Range object

To make a note on Dick's answer, this is correct, but I would not recommend using a For Each loop. For Each creates a temporary reference to the COM Cell behind the scenes that you do not have access to (that you would need in order to dispose of it).

See the following for more discussion:

How do I properly clean up Excel interop objects?

To illustrate the issue, try the For Each example, close your application, and look at Task Manager. You should see that an instance of Excel is still running (because all objects were not disposed of properly).

A cleaner way to handle this is to query the spreadsheet using ADO:

http://technet.microsoft.com/en-us/library/ee692882.aspx

I can't access http://localhost/phpmyadmin/

A cleaner way is to create the new configuration file:

/etc/apache2/conf-available/phpmyadmin.conf

and write the following in it:

Include /etc/phpmyadmin/apache.conf

then, soft link the file to the directory /etc/apache2/conf-enabled:

sudo ln -s /etc/apache2/conf-available/phpmyadmin.conf /etc/apache2/conf-enabled

How to send FormData objects with Ajax-requests in jQuery?

I believe you could do it like this :

var fd = new FormData();    
fd.append( 'file', input.files[0] );

$.ajax({
  url: 'http://example.com/script.php',
  data: fd,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  }
});

Notes:

  • Setting processData to false lets you prevent jQuery from automatically transforming the data into a query string. See the docs for more info.

  • Setting the contentType to false is imperative, since otherwise jQuery will set it incorrectly.

Filter Extensions in HTML form upload

The accept attribute specifies a comma-separated list of content types (MIME types) that the target of the form will process correctly. Unfortunately this attribute is ignored by all the major browsers, so it does not affect the browser's file dialog in any way.

Checking for an empty file in C++

C++17 solution:

#include <filesystem>

const auto filepath = <path to file> (as a std::string or std::filesystem::path)

auto isEmpty = (std::filesystem::file_size(filepath) == 0);

Assumes you have the filepath location stored, I don't think you can extract a filepath from an std::ifstream object.

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

This isn’t a solution in the sense that it doesn’t resolve the conditions which cause the message to appear in the logs, but the message can be suppressed by appending the following to conf/logging.properties:

org.apache.catalina.webresources.Cache.level = SEVERE

This filters out the “Unable to add the resource” logs, which are at level WARNING.

In my view a WARNING is not necessarily an error that needs to be addressed, but rather can be ignored if desired.

Find package name for Android apps to use Intent to launch Market app from web

The following bash script can be used to display the package and activity names in an apk, and launch the application by passing it an APK file.

apk_start.sh

package=`aapt dump badging $* | grep package | awk '{print $2}' | sed s/name=//g | sed s/\'//g`
activity=`aapt dump badging $* | grep Activity | awk '{print $2}' | sed s/name=//g | sed s/\'//g`
echo
echo package : $package
echo activity: $activity
echo
echo Launching application on device....
echo
adb shell am start -n $package/$activity

Then to launch the application in the emulator, simply supply the APK filename like so:

apk_start.sh /tmp/MyApp.apk

Of course if you just want the package and activity name of the apk to be displayed, delete the last line of the script.

You can stop an application in the same way by using this script:

apk_stop.sh

package=`aapt dump badging $* | grep package | awk '{print $2}' | sed s/name=//g | sed s/\'//g`
adb shell am force-stop $package

like so:

apk_stop.sh /tmp/MyApp.apk

Important Note: aapt can be found here:

<android_sdk_home>/build-tools/android-<ver>/aapt

File Not Found when running PHP with Nginx

in case it helps someone, my issue seems to be just because I was using a subfolder under my home directory, even though permissions seem correct and I don't have SELinux or anything like that. changing it to be under /var/www/something/something made it work.

(if I ever found the real cause, and remember this answer, I'll update it)

How to convert char to int?

You can try something like this:

int val = Convert.ToInt32("" + '1');

Add CSS3 transition expand/collapse

This is my solution that adjusts the height automatically:

_x000D_
_x000D_
function growDiv() {_x000D_
  var growDiv = document.getElementById('grow');_x000D_
  if (growDiv.clientHeight) {_x000D_
    growDiv.style.height = 0;_x000D_
  } else {_x000D_
    var wrapper = document.querySelector('.measuringWrapper');_x000D_
    growDiv.style.height = wrapper.clientHeight + "px";_x000D_
  }_x000D_
  document.getElementById("more-button").value = document.getElementById("more-button").value == 'Read more' ? 'Read less' : 'Read more';_x000D_
}
_x000D_
#more-button {_x000D_
  border-style: none;_x000D_
  background: none;_x000D_
  font: 16px Serif;_x000D_
  color: blue;_x000D_
  margin: 0 0 10px 0;_x000D_
}_x000D_
_x000D_
#grow input:checked {_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
#more-button:hover {_x000D_
  color: black;_x000D_
}_x000D_
_x000D_
#grow {_x000D_
  -moz-transition: height .5s;_x000D_
  -ms-transition: height .5s;_x000D_
  -o-transition: height .5s;_x000D_
  -webkit-transition: height .5s;_x000D_
  transition: height .5s;_x000D_
  height: 0;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<input type="button" onclick="growDiv()" value="Read more" id="more-button">_x000D_
_x000D_
<div id='grow'>_x000D_
  <div class='measuringWrapper'>_x000D_
    <div class="text">Here is some more text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae urna nulla. Vivamus a purus mi. In hac habitasse platea dictumst. In ac tempor quam. Vestibulum eleifend vehicula ligula, et cursus nisl gravida sit_x000D_
      amet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I used the workaround that r3bel posted: Can you use CSS3 to transition from height:0 to the variable height of content?

All possible array initialization syntaxes

Repeat without LINQ:

float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);

How to parse JSON with VBA without external libraries?

Call me simple but I just declared a Variant and split the responsetext from my REST GET on the quote comma quote between each item, then got the value I wanted by looking for the last quote with InStrRev. I'm sure that's not as elegant as some of the other suggestions but it works for me.

         varLines = Split(.responsetext, """,""")
        strType = Mid(varLines(8), InStrRev(varLines(8), """") + 1)

Format JavaScript date as yyyy-mm-dd

You can try this: https://www.npmjs.com/package/timesolver

npm i timesolver

Use it in your code:

const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, "YYYY-MM-DD");

You can get the date string by using this method:

getString

Intermediate language used in scalac?

maybe this will help you out:

http://lampwww.epfl.ch/~paltherr/phd/altherr-phd.pdf

or this page:

www.scala-lang.org/node/6372‎

MongoDB SELECT COUNT GROUP BY

This type of query worked for me:

 db.events.aggregate({$group: {_id : "$date", number:  { $sum : 1} }} )

See http://docs.mongodb.org/manual/tutorial/aggregation-with-user-preference-data/

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

You can also use the iteration count (i) as the key:

render() {
    return (
      <ol>
        {this.props.results.map((result, i) => (
          <li key={i}>{result.text}</li>
        ))}
      </ol>
    );
}

How can I use getSystemService in a non-activity class (LocationManager)?

One way I have gotten around this is by create a static class for instances. I used it a lot in AS3 I has worked great for me in android development too.

Config.java

public final class Config {
    public static MyApp context = null;
}

MyApp.java

public class MyApp extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Config.context = this;
    }
    ...
}

You can then access the context or by using Config.context

LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = Config.context.getSystemService(context);

Error: fix the version conflict (google-services plugin)

Please change your project-level build.gradle file in which you have to change your dependencies class path of google-services or build.gradle path.

buildscript {

    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
        classpath 'com.google.gms:google-services:4.0.1'
    }
}

Git in Visual Studio - add existing project?

After slogging around Visual Studio I finally figured out the answer that took far longer than it should have.

In order to take an existing project without source control and put it to an existing EMPTY (this is important) GitHub repository, the process is simple, but tricky, because your first inclination is to use the Team Explorer, which is wrong and is why you're having problems.

First, add it to source control. There are some explanations of that above, and everybody gets this far.

Now, this opens an empty LOCAL repository and the trick which nobody ever tells you about is to ignore the Team Explorer completely and go to the Solution Explorer, right click the solution and click Commit.

This then commits all differences between your existing solution and the local repository, essentially updating it with all these new files. Give it a default commit name 'initial files' or whatever floats your boat and commit.

Then simply click Sync on the next screen and drop in the EMPTY GitHub repository URL. Make sure it's empty or you'll have master branch conflicts and it won't let you. So either use a new repository or delete the old one that you had previously screwed up. Bear in mind this is Visual Studio 2013, so your mileage may vary.

How to sort pandas data frame using values from several columns?

Note : Everything up here is correct,just replace sort --> sort_values() So, it becomes:

 import pandas as pd
 df = pd.read_csv('data.csv')
 df.sort_values(ascending=False,inplace=True)

Refer to the official website here.

Search text in stored procedure in SQL Server

 SELECT DISTINCT OBJECT_NAME([id]),[text] 

 FROM syscomments   

 WHERE [id] IN (SELECT [id] FROM sysobjects WHERE xtype IN 

 ('TF','FN','V','P') AND status >= 0) AND  

 ([text] LIKE '%text to be search%' ) 

OBJECT_NAME([id]) --> Object Name (View,Store Procedure,Scalar Function,Table function name)

id (int) = Object identification number

xtype char(2) Object type. Can be one of the following object types:

FN = Scalar function

P = Stored procedure

V = View

TF = Table function

How do I get the max ID with Linq to Entity?

try this

int intIdt = db.Users.Max(u => u.UserId);

Update:

If no record then generate exception using above code try this

int? intIdt = db.Users.Max(u => (int?)u.UserId);

Pseudo-terminal will not be allocated because stdin is not a terminal

All relevant information is in the existing answers, but let me attempt a pragmatic summary:

tl;dr:

  • DO pass the commands to run using a command-line argument:
    ssh jdoe@server '...'

    • '...' strings can span multiple lines, so you can keep your code readable even without the use of a here-document:
      ssh jdoe@server ' ... '
  • Do NOT pass the commands via stdin, as is the case when you use a here-document:
    ssh jdoe@server <<'EOF' # Do NOT do this ... EOF

Passing the commands as an argument works as-is, and:

  • the problem with the pseudo-terminal will not even arise.
  • you won't need an exit statement at the end of your commands, because the session will automatically exit after the commands have been processed.

In short: passing commands via stdin is a mechanism that is at odds with ssh's design and causes problems that must then be worked around.
Read on, if you want to know more.


Optional background information:

ssh's mechanism for accepting commands to execute on the target server is a command-line argument: the final operand (non-option argument) accepts a string containing one or more shell commands.

  • By default, these commands run unattended, in an non-interactive shell, without the use of a (pseudo) terminal (option -T is implied), and the session automatically ends when the last command finishes processing.

  • In the event that your commands require user interaction, such as responding to an interactive prompt, you can explicitly request the creation of a pty (pseudo-tty), a pseudo terminal, that enables interacting with the remote session, using the -t option; e.g.:

    • ssh -t jdoe@server 'read -p "Enter something: "; echo "Entered: [$REPLY]"'

    • Note that the interactive read prompt only works correctly with a pty, so the -t option is needed.

    • Using a pty has a notable side effect: stdout and stderr are combined and both reported via stdout; in other words: you lose the distinction between regular and error output; e.g.:

      • ssh jdoe@server 'echo out; echo err >&2' # OK - stdout and stderr separate

      • ssh -t jdoe@server 'echo out; echo err >&2' # !! stdout + stderr -> stdout

In the absence of this argument, ssh creates an interactive shell - including when you send commands via stdin, which is where the trouble begins:

  • For an interactive shell, ssh normally allocates a pty (pseudo-terminal) by default, except if its stdin is not connected to a (real) terminal.

    • Sending commands via stdin means that ssh's stdin is no longer connected to a terminal, so no pty is created, and ssh warns you accordingly:
      Pseudo-terminal will not be allocated because stdin is not a terminal.

    • Even the -t option, whose express purpose is to request creation of a pty, is not enough in this case: you'll get the same warning.

      • Somewhat curiously, you must then double the -t option to force creation of a pty: ssh -t -t ... or ssh -tt ... shows that you really, really mean it.

      • Perhaps the rationale for requiring this very deliberate step is that things may not work as expected. For instance, on macOS 10.12, the apparent equivalent of the above command, providing the commands via stdin and using -tt, does not work properly; the session gets stuck after responding to the read prompt:
        ssh -tt jdoe@server <<<'read -p "Enter something: "; echo "Entered: [$REPLY]"'


In the unlikely event that the commands you want to pass as an argument make the command line too long for your system (if its length approaches getconf ARG_MAX - see this article), consider copying the code to the remote system in the form of a script first (using, e.g., scp), and then send a command to execute that script.

In a pinch, use -T, and provide the commands via stdin, with a trailing exit command, but note that if you also need interactive features, using -tt in lieu of -T may not work.

How can we dynamically allocate and grow an array

Take a look at implementation of Java ArrayList. Java ArrayList internally uses a fixed size array and reallocates the array once number of elements exceed current size. You can also implement on similar lines.

Force youtube embed to start in 720p

Use this, it works 100% _your_videocode?rel=0&vq=hd1080"

How to sort strings in JavaScript

since strings can be compared directly in javascript, this will do the job

list.sort(function (a, b) {
    return a.attr > b.attr ? 1: -1;
})

the subtraction in a sort function is used only when non alphabetical (numerical) sort is desired and of course it does not work with strings

Could not complete the operation due to error 80020101. IE

I dont know why but it worked for me. If you have comments like

//Comment

Then it gives this error. To fix this do

/*Comment*/

Doesn't make sense but it worked for me.

How to sort an array of objects with jquery or javascript

Well, it appears that instead of creating a true multidimensional array, you've created an array of (almost) JavaScript Objects. Try defining your arrays like this ->

var array = [ [id,name,value], [id,name,value] ]

Hopefully that helps!

flutter run: No connected devices

None of the suggestions worked until I ran:

flutter config --android-sdk ANDROID_SDK_PATH

Use "PATH" = your path. For example:

flutter config --android-sdk C:\Users\%youruser%\AppData\Local\Android\Sdk

Is there a way to make npm install (the command) to work behind proxy?

Try to find .npmrc in C:\Users\.npmrc

then open (notepad), write, and save inside :

proxy=http://<username>:<pass>@<proxyhost>:<port>

PS : remove "<" and ">" please !!

Convert .pfx to .cer

openssl rsa -in f.pem -inform PEM -out f.der -outform DER

Export specific rows from a PostgreSQL table as INSERT SQL script

SQL Workbench has such a feature.

After running a query, right click on the query results and choose "Copy Data As SQL > SQL Insert"

Regular expression to remove HTML tags from a string

A trivial approach would be to replace

<[^>]*>

with nothing. But depending on how ill-structured your input is that may well fail.

What and When to use Tuple?

Tuple classes allow developers to be 'quick and lazy' by not defining a specific class for a specific use.

The property names are Item1, Item2, Item3 ..., which may not be meaningful in some cases or without documentation.

Tuple classes have strongly typed generic parameters. Still users of the Tuple classes may infer from the type of generic parameters.

Using Java with Nvidia GPUs (CUDA)

From the research I have done, if you are targeting Nvidia GPUs and have decided to use CUDA over OpenCL, I found three ways to use the CUDA API in java.

  1. JCuda (or alternative)- http://www.jcuda.org/. This seems like the best solution for the problems I am working on. Many of libraries such as CUBLAS are available in JCuda. Kernels are still written in C though.
  2. JNI - JNI interfaces are not my favorite to write, but are very powerful and would allow you to do anything CUDA can do.
  3. JavaCPP - This basically lets you make a JNI interface in Java without writing C code directly. There is an example here: What is the easiest way to run working CUDA code in Java? of how to use this with CUDA thrust. To me, this seems like you might as well just write a JNI interface.

All of these answers basically are just ways of using C/C++ code in Java. You should ask yourself why you need to use Java and if you can't do it in C/C++ instead.

If you like Java and know how to use it and don't want to work with all the pointer management and what-not that comes with C/C++ then JCuda is probably the answer. On the other hand, the CUDA Thrust library and other libraries like it can be used to do a lot of the pointer management in C/C++ and maybe you should look at that.

If you like C/C++ and don't mind pointer management, but there are other constraints forcing you to use Java, then JNI might be the best approach. Though, if your JNI methods are just going be wrappers for kernel commands you might as well just use JCuda.

There are a few alternatives to JCuda such as Cuda4J and Root Beer, but those do not seem to be maintained. Whereas at the time of writing this JCuda supports CUDA 10.1. which is the most up-to-date CUDA SDK.

Additionally there are a few java libraries that use CUDA, such as deeplearning4j and Hadoop, that may be able to do what you are looking for without requiring you to write kernel code directly. I have not looked into them too much though.

Navigate to another page with a button in angular 2

 <button type="button" class="btn btn-primary-outline pull-right" (click)="btnClick();"><i class="fa fa-plus"></i> Add</button>


import { Router } from '@angular/router';

btnClick= function () {
        this.router.navigate(['/user']);
};

How to auto adjust table td width from the content

you could also use display: table insted of tables. Divs are way more flexible than tables.

Example:

_x000D_
_x000D_
.table {_x000D_
   display: table;_x000D_
   border-collapse: collapse;_x000D_
}_x000D_
 _x000D_
.table .table-row {_x000D_
   display: table-row;_x000D_
}_x000D_
 _x000D_
.table .table-cell {_x000D_
   display: table-cell;_x000D_
   text-align: left;_x000D_
   vertical-align: top;_x000D_
   border: 1px solid black;_x000D_
}
_x000D_
<div class="table">_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test1123</div>_x000D_
 </div>_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test123</div>_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I run git log to see changes only for a specific branch?

The problem I was having, which I think is similar to this, is that master was too far ahead of my branch point for the history to be useful. (Navigating to the branch point would take too long.)

After some trial and error, this gave me roughly what I wanted:

git log --graph --decorate --oneline --all ^master^!

SSIS Excel Connection Manager failed to Connect to the Source

After researching everywhere finally i have found out temporary solution. Because i have try all the solution installing access drivers but still i am facing same issues.

For excel source, Before this step you need to change the setting. Save excel file as 2010 format.xlsx

Also set Project Configuration Properties for Debugging Run64BitRuntime = False

  1. Drag and drop the excel source
  2. Double click on the excel source and connect excel. Any way you will get an same error no table or view cannot load....
  3. Click ok
  4. Right click on excel source, click on show advanced edit.
  5. In that click on component properties.
  6. You can see openrowset. In that right side you need to enter you excel sheet name example: if in excel sheet1 then you need to enter sheet1$. I.e end with dollar symbol. And click ok.
  7. Now you can do other works connecting to destination.

I am using visual studio 2017, sql server 2017, office 2016, and Microsoft access database 2010 engine 32bit. Os windows 10 64 bit.

This is temporary solution. Because many peoples are searching for this type of question. Finally I figured out and this solution is not available in any of the website.

Capturing URL parameters in request.GET

def some_view(request, *args, **kwargs):
    if kwargs.get('q', None):
        # Do something here ..

Why docker container exits immediately

I added read shell statement at the end. This keeps the main process of the container - startup shell script - running.

How do I loop through or enumerate a JavaScript object?

You can just iterate over it like:

for (var key in p) {
  alert(p[key]);
}

Note that key will not take on the value of the property, it's just an index value.

Working with SQL views in Entity Framework Core

Here is a new way to work with SQL views in EF Core: Query Types.

How do I dump an object's fields to the console?

I came across this thread because I was looking for something similar. I like the responses and they gave me some ideas so I tested the .to_hash method and worked really well for the use case too. soo:

object.to_hash

Meaning of $? (dollar question mark) in shell scripts

echo $? - Gives the EXIT STATUS of the most recently executed command . This EXIT STATUS would most probably be a number with ZERO implying Success and any NON-ZERO value indicating Failure

? - This is one special parameter/variable in bash.

$? - It gives the value stored in the variable "?".

Some similar special parameters in BASH are 1,2,*,# ( Normally seen in echo command as $1 ,$2 , $* , $# , etc., ) .

Find the maximum value in a list of tuples in Python

In addition to max, you can also sort:

>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)

Finding duplicate integers in an array and display how many times they occurred

Since you can't use LINQ, you can do this with collections and loops instead:

static void Main(string[] args)
{              
    int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
    var dict = new Dictionary<int, int>();

    foreach(var value in array)
    {
        if (dict.ContainsKey(value))
            dict[value]++;
        else
            dict[value] = 1;
    }

    foreach(var pair in dict)
        Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
    Console.ReadKey();
}

How to read multiple Integer values from a single line of input in Java?

This works fine ....

int a = nextInt(); int b = nextInt(); int c = nextInt();

Or you can read them in a loop

Remove all special characters with RegExp

var desired = stringToReplace.replace(/[^\w\s]/gi, '')

As was mentioned in the comments it's easier to do this as a whitelist - replace the characters which aren't in your safelist.

The caret (^) character is the negation of the set [...], gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores (\w) and whitespace (\s).

How to delete a file after checking whether it exists

if (File.Exists(path))
{
    File.Delete(path);
}

How do I set path while saving a cookie value in JavaScript?

For access cookie in whole app (use path=/):

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/"; 
}

Note:

If you set path=/,
Now the cookie is available for whole application/domain. If you not specify the path then current cookie is save just for the current page you can't access it on another page(s).

For more info read- http://www.quirksmode.org/js/cookies.html (Domain and path part)

If you use cookies in jquery by plugin jquery-cookie:

$.cookie('name', 'value', { expires: 7, path: '/' });
//or
$.cookie('name', 'value', { path: '/' });

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

beside all other good answers, this could happen if you use merge to persist an object and accidentally forget to use merged reference of the object in the parent class. consider the following example

merge(A);
B.setA(A);
persist(B);

In this case, you merge A but forget to use merged object of A. to solve the problem you must rewrite the code like this.

A=merge(A);//difference is here
B.setA(A);
persist(B);

Change type of varchar field to integer: "cannot be cast automatically to type integer"

You can do it like:

change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'

or try this:

change_column :table_name, :column_name, :integer, using: 'column_name::integer'

If you are interested to find more about this topic read this article: https://kolosek.com/rails-change-database-column

How can I generate a random number in a certain range?

To extend what Rahul Gupta said:

You can use Java function int random = Random.nextInt(n).
This returns a random int in the range [0, n-1].

I.e., to get the range [20, 80] use:

final int random = new Random().nextInt(61) + 20; // [0, 60] + 20 => [20, 80]

To generalize more:

final int min = 20;
final int max = 80;
final int random = new Random().nextInt((max - min) + 1) + min;

Create numpy matrix filled with NaNs

Are you familiar with numpy.nan?

You can create your own method such as:

def nans(shape, dtype=float):
    a = numpy.empty(shape, dtype)
    a.fill(numpy.nan)
    return a

Then

nans([3,4])

would output

array([[ NaN,  NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN,  NaN]])

I found this code in a mailing list thread.

How to hide columns in an ASP.NET GridView with auto-generated columns?

In the rowdatabound method for 2nd column

GridView gv = (sender as GridView);
gv.HeaderRow.Cells[2].Visible = false;
e.Row.Cells[2].Visible = false;

JavaScript blob filename without link

saveFileOnUserDevice = function(file){ // content: blob, name: string
        if(navigator.msSaveBlob){ // For ie and Edge
            return navigator.msSaveBlob(file.content, file.name);
        }
        else{
            let link = document.createElement('a');
            link.href = window.URL.createObjectURL(file.content);
            link.download = file.name;
            document.body.appendChild(link);
            link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
            link.remove();
            window.URL.revokeObjectURL(link.href);
        }
    }

right click context menu for datagridview

Use the CellMouseDown event on the DataGridView. From the event handler arguments you can determine which cell was clicked. Using the PointToClient() method on the DataGridView you can determine the relative position of the pointer to the DataGridView, so you can pop up the menu in the correct location.

(The DataGridViewCellMouseEvent parameter just gives you the X and Y relative to the cell you clicked, which isn't as easy to use to pop up the context menu.)

This is the code I used to get the mouse position, then adjust for the position of the DataGridView:

var relativeMousePosition = DataGridView1.PointToClient(Cursor.Position);
this.ContextMenuStrip1.Show(DataGridView1, relativeMousePosition);

The entire event handler looks like this:

private void DataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    // Ignore if a column or row header is clicked
    if (e.RowIndex != -1 && e.ColumnIndex != -1)
    {
        if (e.Button == MouseButtons.Right)
        {
            DataGridViewCell clickedCell = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];

            // Here you can do whatever you want with the cell
            this.DataGridView1.CurrentCell = clickedCell;  // Select the clicked cell, for instance

            // Get mouse position relative to the vehicles grid
            var relativeMousePosition = DataGridView1.PointToClient(Cursor.Position);

            // Show the context menu
            this.ContextMenuStrip1.Show(DataGridView1, relativeMousePosition);
        }
    }
}

ASP.NET: Session.SessionID changes between requests

Using Neville's answer (deleting requireSSL = true, in web.config) and slightly modifying Joel Etherton's code, here is the code that should handle a site that runs in both SSL mode and non SSL mode, depending on the user and the page (I am jumping back into code and haven't tested it on SSL yet, but expect it should work - will be too busy later to get back to this, so here it is:

if (HttpContext.Current.Response.Cookies.Count > 0)
        {
            foreach (string s in HttpContext.Current.Response.Cookies.AllKeys)
            {
                if (s == FormsAuthentication.FormsCookieName || s.ToLower() == "asp.net_sessionid")
                {
                    HttpContext.Current.Response.Cookies[s].Secure = HttpContext.Current.Request.IsSecureConnection;
                }
            }
        }

Laravel where on relationship object

With multiple joins, use something like this code:

$someId = 44;
Event::with(["owner", "participants" => function($q) use($someId){
    $q->where('participants.IdUser', '=', 1);
    //$q->where('some other field', $someId);
}])

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

I too faced the same issue.

Follow the below step to solve the issue on (CORS) compliance in browsers.

Include REDRock in your solution with the Cors reference. Include WebActivatorEx reference to Web API solution.

Then Add the file CorsConfig in the Web API App_Start Folder.

[assembly: PreApplicationStartMethod(typeof(WebApiNamespace.CorsConfig), "PreStart")]

namespace WebApiNamespace
{
    public static class CorsConfig
    {
        public static void PreStart()
        {
            GlobalConfiguration.Configuration.MessageHandlers.Add(new RedRocket.WebApi.Cors.CorsHandler());
        }
    }
}

With these changes done i was able to access the webapi in all browsers.

Run a command over SSH with JSch

This is a shameless plug, but I'm just now writing some extensive Javadoc for JSch.

Also, there is now a Manual in the JSch Wiki (written mainly by me).


About the original question, there is not really an example for handling the streams. Reading/writing a stream is done as always.

But there simply can't be a sure way to know when one command in a shell has finished just from reading the shell's output (this is independent of the SSH protocol).

If the shell is interactive, i.e. it has a terminal attached, it will usually print a prompt, which you could try to recognize. But at least theoretically this prompt string could also occur in normal output from a command. If you want to be sure, open individual exec channels for each command instead of using a shell channel. The shell channel is mainly used for interactive use by a human user, I think.

A valid provisioning profile for this executable was not found... (again)

File > Workspace Settings > Set Build system to "Legacy Build System"

Invalid URI: The format of the URI could not be determined

Sounds like it might be a realative uri. I ran into this problem when doing cross-browser Silverlight; on my blog I mentioned a workaround: pass a "context" uri as the first parameter.

If the uri is realtive, the context uri is used to create a full uri. If the uri is absolute, then the context uri is ignored.

EDIT: You need a "scheme" in the uri, e.g., "ftp://" or "http://"

Reset all the items in a form

You can create the form again and dispose the old one.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnReset_Click(object sender, EventArgs e)
    {
        Form1 NewForm = new Form1();           
        NewForm.Show();
        this.Dispose(false);
    }
}

Datatype for storing ip address in SQL Server

The following answer is based on answers by M. Turnhout and Jerry Birchler to this question but with the following improvements:

  • Replaced the use of undocumented functions (sys.fn_varbintohexsubstring, fn_varbintohexstr) with CONVERT() for binary styles
  • Replaced XML "hacks" ( CAST('' as xml).value('xs:hexBinary()) ) with CONVERT() for binary styles
  • Fixed bug in Jerry Birchler's implementation of fn_ConvertIpAddressToBinary (as pointed out by C.Plock)
  • Add minor syntax sugar

The code has been tested in SQL Server 2014 and SQL Server 2016 (see test cases at the end)

IPAddressVarbinaryToString

Converts 4 bytes values to IPV4 and 16 byte values to IPV6 string representations. Note that this function does not shorten addresses.

ALTER FUNCTION dbo.IPAddressVarbinaryToString
(
    @varbinaryValue VARBINARY( 16 )
)
RETURNS VARCHAR(39)
AS
BEGIN
    IF @varbinaryValue IS NULL
        RETURN NULL;
    ELSE IF DATALENGTH( @varbinaryValue ) = 4
        RETURN 
            CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 1, 1 ))) + '.' +
            CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 2, 1 ))) + '.' +
            CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 3, 1 ))) + '.' +
            CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 4, 1 )));
    ELSE IF DATALENGTH( @varbinaryValue ) = 16
        RETURN 
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  1, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  3, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  5, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  7, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue,  9, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 11, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 13, 2 ), 2 ) + ':' +
            CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 15, 2 ), 2 );

    RETURN 'Invalid';
END

Test Cases:

SELECT dbo.IPAddressVarbinaryToString(0x00000000000000000000000000000000) -- 0000:0000:0000:0000:0000:0000:0000:0000 (no address shortening)
SELECT dbo.IPAddressVarbinaryToString(0x00010002000300400500060070000089) -- 0001:0002:0003:0040:0500:0600:7000:0089
SELECT dbo.IPAddressVarbinaryToString(0xC0A80148) -- 255.168.1.72
SELECT dbo.IPAddressVarbinaryToString(0x7F000001) -- 127.0.0.1 (no address shortening)
SELECT dbo.IPAddressVarbinaryToString(NULL) -- NULL

IPAddressStringToVarbinary

Converts IPV4 and IPV6 string representations to 4 byte and 16 bytes binary values respectively. Note that this function is able to parse most (all of the commonly used) of shorthand address representations (e.g. 127...1 and 2001:db8::1319:370:7348). To force this function to always return 16 byte binary values uncomment leading 0s concatenation at the end of the function.

ALTER FUNCTION [dbo].[IPAddressStringToVarbinary]
(
    @IPAddress VARCHAR( 39 )
)
RETURNS VARBINARY(16) AS
BEGIN

IF @ipAddress IS NULL
    RETURN NULL;

DECLARE @bytes VARBINARY(16), @token VARCHAR(4),
    @vbytes VARBINARY(16) = 0x, @vbzone VARBINARY(2),
    @tIPAddress VARCHAR( 40 ),
    @colIndex TINYINT,
    @delim CHAR(1) = '.',
    @prevColIndex TINYINT = 0,
    @parts TINYINT = 0, @limit TINYINT = 4;

-- Get position if IPV4 delimiter
SET @colIndex = CHARINDEX( @delim, @ipAddress );

-- If not IPV4, then assume IPV6
IF @colIndex = 0
BEGIN
    SELECT @delim = ':', @limit = 8, @colIndex = CHARINDEX( @delim, @ipAddress );

    -- Get number of parts (delimiters)
    WHILE @colIndex > 0
        SELECT @parts += 1, @colIndex = CHARINDEX( @delim, @ipAddress, @colIndex + 1 );

    SET @colIndex = CHARINDEX( @delim, @ipAddress );

    IF @colIndex = 0
        RETURN NULL;
END

-- Add trailing delimiter (need new variable of larger size)
SET @tIPAddress = @IPAddress + @delim;

WHILE @colIndex > 0
BEGIN
    SET @token = SUBSTRING( @tIPAddress, @prevColIndex + 1, @Colindex - @prevColIndex - 1 );

    IF @delim = ':'
    BEGIN
        SELECT @vbzone = CONVERT( VARBINARY(2), RIGHT( '0000' + @token, 4 ), 2 ), @vbytes += @vbzone;

        -- Handles consecutive sections of zeros representation rule (i.e. ::)(https://en.wikipedia.org/wiki/IPv6#Address_representation)
        IF @token = ''
            WHILE @parts + 1 < @limit
                SELECT @vbytes += @vbzone, @parts += 1;
    END
    ELSE
    BEGIN
        SELECT @vbzone = CONVERT( VARBINARY(1), CONVERT( TINYINT, @token )), @vbytes += @vbzone
    END

    SELECT @prevColIndex = @colIndex, @colIndex = CHARINDEX( @delim, @tIPAddress, @colIndex + 1 ) 
END

SET @bytes =
    CASE @delim
        WHEN ':' THEN @vbytes
        ELSE /*0x000000000000000000000000 +*/ @vbytes -- Return IPV4 addresses as 4 byte binary (uncomment leading 0s section to force 16 byte binary)
    END 

RETURN @bytes

END

Test Cases

Valid cases

SELECT dbo.IPAddressStringToVarbinary( '0000:0000:0000:0000:0000:0000:0000:0001' ) -- 0x0000000000000000000000000001 (check bug fix)
SELECT dbo.IPAddressStringToVarbinary( '0001:0002:0003:0040:0500:0600:7000:0089' ) -- 0x00010002000300400500060070000089
SELECT dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1319::370:7348' )     -- 0x20010DB885A308D31319000003707348 (check short hand)
SELECT dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1319:0000:370:7348' ) -- 0x20010DB885A308D31319000003707348
SELECT dbo.IPAddressStringToVarbinary( '192.168.1.72' ) -- 0xC0A80148
SELECT dbo.IPAddressStringToVarbinary( '127...1' ) -- 0x7F000001 (check short hand)
SELECT dbo.IPAddressStringToVarbinary( NULL ) -- NULL
SELECT dbo.IPAddressStringToVarbinary( '' ) -- NULL
-- Check that conversions return original address
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '0001:0002:0003:0040:0500:0600:7000:0089' )) -- '0001:0002:0003:0040:0500:0600:7000:0089' 
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '127...1' )) -- 127.0.0.1
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '192.168.1.72' )) -- 192.168.1.72
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1319::370:7348' ))     -- 2001:0db8:85a3:08d3:1319:0000:0370:7348
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1314:0000:370:7348' )) -- 2001:0db8:85a3:08d3:1319:0000:0370:7348
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3::370:7348' )) -- 2001:0DB8:85A3:08D3:0000:0000:0370:7348
-- This is technically an invalid IPV6 (according to Wikipedia) but it parses correctly
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8::1319::370:7348' )) -- 2001:0DB8:0000:0000:1319:0000:0370:7348

Invalid cases

SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8::1319::7348' )) -- 2001:0DB8:0000:0000:0000:1319:0000:7348 (ambiguous address)
SELECT dbo.IPAddressStringToVarbinary( '127.1' ) -- 127.0.0.1 (not supported short-hand)
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '127.1' )) -- 127.0.0.1 (not supported short-hand)
SELECT dbo.IPAddressStringToVarbinary( '0300.0000.0002.0353' ) -- octal byte values
SELECT dbo.IPAddressStringToVarbinary( '0xC0.0x00.0x02.0xEB' ) -- hex values
SELECT dbo.IPAddressStringToVarbinary( 'C0.00.02.EB' ) -- hex values

Specify multiple attribute selectors in CSS

Simple input[name=Sex][value=M] would do pretty nice. And it's actually well-described in the standard doc:

Multiple attribute selectors can be used to refer to several attributes of an element, or even several times to the same attribute.

Here, the selector matches all SPAN elements whose "hello" attribute has exactly the value "Cleveland" and whose "goodbye" attribute has exactly the value "Columbus":

span[hello="Cleveland"][goodbye="Columbus"] { color: blue; }

As a side note, using quotation marks around an attribute value is required only if this value is not a valid identifier.

JSFiddle Demo

SQL to Entity Framework Count Group-By

A useful extension is to collect the results in a Dictionary for fast lookup (e.g. in a loop):

var resultDict = _dbContext.Projects
    .Where(p => p.Status == ProjectStatus.Active)
    .GroupBy(f => f.Country)
    .Select(g => new { country = g.Key, count = g.Count() })
    .ToDictionary(k => k.country, i => i.count);

Originally found here: http://www.snippetsource.net/Snippet/140/groupby-and-count-with-ef-in-c

Can we execute a java program without a main() method?

Since you tagged Java-ee as well - then YES it is possible.

and in core java as well it is possible using static blocks

and check this How can you run a Java program without main method?

Edit:
as already pointed out in other answers - it does not support from Java 7

executing shell command in background from script

For example you have a start program named run.sh to start it working at background do the following command line. ./run.sh &>/dev/null &

Count how many files in directory PHP

Working Demo

<?php

$directory = "../images/team/harry/"; // dir location
if (glob($directory . "*.*") != false)
{
 $filecount = count(glob($directory . "*.*"));
 echo $filecount;
}
else
{
 echo 0;
}

?>

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

import the ReactiveForms Module to your components module

How to add data validation to a cell using VBA

Use this one:

Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")

Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws.Name & "'!" & range1.Address
End With

Note that when you're using Dim range1, rng As range, only rng has type of Range, but range1 is Variant. That's why I'm using Dim range1 As Range, rng As Range.
About meaning of parameters you can read is MSDN, but in short:

  • Type:=xlValidateList means validation type, in that case you should select value from list
  • AlertStyle:=xlValidAlertStop specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.
  • in your original code, Operator:= xlBetween is odd. It can be used only if two formulas are provided for validation.
  • Formula1:="='" & ws.Name & "'!" & range1.Address for list data validation provides address of list with values (in format =Sheet!A1:A5)

SHA-1 fingerprint of keystore certificate

I am using Ubuntu 12.0.4 and I have get the Certificate fingerprints in this way for release key store on command prompt after generate keystore file , you can use this key for released app ,if you are using google map in your app ,so this can show the map properly inside app after release,, i got the result on command prompt below

_x000D_
_x000D_
administrator@user:~$ keytool -list -v -keystore /home/administrator/mykeystore/mykeystore.jks -alias myprojectalias_x000D_
_x000D_
 _x000D_
Enter keystore password:  ******_x000D_
_x000D_
Alias name: myprojectalias_x000D_
_x000D_
Creation date: 22 Apr, 2014_x000D_
_x000D_
Entry type: PrivateKeyEntry_x000D_
_x000D_
Certificate chain length: 1_x000D_
Certificate[1]:_x000D_
Owner: CN=xyz, OU= xyz, O= xyz, L= xyz, ST= xyz, C=91_x000D_
Issuer: CN= xyz, OU= xyz, O= xyz, L= xyz, ST= xyz, C=91_x000D_
_x000D_
Serial number: 7c4rwrfdff_x000D_
Valid from: Fri Apr 22 11:59:55 IST 2014 until: Tue Apr 14 11:59:55 IST 2039_x000D_
_x000D_
Certificate fingerprints:_x000D_
     MD5:  95:A2:4B:3A:0D:40:23:FF:F1:F3:45:26:F5:1C:CE:86_x000D_
     SHA1: DF:95:Y6:7B:D7:0C:CD:25:04:11:54:FA:40:A7:1F:C5:44:94:AB:90_x000D_
     SHA276: 00:7E:B6:EC:55:2D:C6:C9:43:EE:8A:42:BB:5E:14:BB:33:FD:A4:A8:B8:5C:2A:DE:65:5C:A3:FE:C0:14:A8:02_x000D_
     Signature algorithm name: SHA276withRSA_x000D_
     Version: 2_x000D_
_x000D_
Extensions: _x000D_
_x000D_
 ObjectId: 2.6.28.14 Criticality=false_x000D_
SubjectKeyIdentifier [_x000D_
KeyIdentifier [_x000D_
0000: 1E A1 57 F2 81 AR 57 D6   AC 54 65 89 E0 77 65 D9  ..W...Q..Tb..W6._x000D_
0010: 3B 38 9C E1             
_x000D_
_x000D_
_x000D_

On Windows Platform we can get the keystore for debug mode by using the below way

_x000D_
_x000D_
C:\Program Files\Java\jdk1.8.0_102\bin>keytool -l_x000D_
.android\debug.keystore -alias androiddebugkey -s_x000D_
id_x000D_
Alias name: androiddebugkey_x000D_
Creation date: Oct 21, 2016_x000D_
Entry type: PrivateKeyEntry_x000D_
Certificate chain length: 1_x000D_
Certificate[1]:_x000D_
Owner: C=US, O=Android, CN=Android Debug_x000D_
Issuer: C=US, O=Android, CN=Android Debug_x000D_
Serial number: 1_x000D_
Valid from: Fri Oct 21 00:50:00 IST 2016 until: S_x000D_
Certificate fingerprints:_x000D_
         MD5:  86:E3:2E:D7:0E:22:D6:23:2E:D8:E7:E_x000D_
         SHA1: B4:6F:BE:13:AA:FF:E5:AB:58:20:A9:B_x000D_
         SHA256: 15:88:E2:1E:42:6F:61:72:02:44:68_x000D_
56:49:4C:32:D6:17:34:A6:7B:A5:A6_x000D_
         Signature algorithm name: SHA1withRSA
_x000D_
_x000D_
_x000D_

How should strace be used?

In simple words, strace traces all system calls issued by a program along with their return codes. Think things such as file/socket operations and a lot more obscure ones.

It is most useful if you have some working knowledge of C since here system calls would more accurately stand for standard C library calls.

Let's say your program is /usr/local/bin/cough. Simply use:

strace /usr/local/bin/cough <any required argument for cough here>

or

strace -o <out_file> /usr/local/bin/cough <any required argument for cough here>

to write into 'out_file'.

All strace output will go to stderr (beware, the sheer volume of it often asks for a redirection to a file). In the simplest cases, your program will abort with an error and you'll be able to see what where its last interactions with the OS in strace output.

More information should be available with:

man strace

Padding zeros to the left in postgreSQL

The to_char() function is there to format numbers:

select to_char(column_1, 'fm000') as column_2
from some_table;

The fm prefix ("fill mode") avoids leading spaces in the resulting varchar. The 000 simply defines the number of digits you want to have.

psql (9.3.5)
Type "help" for help.

postgres=> with sample_numbers (nr) as (
postgres(>     values (1),(11),(100)
postgres(> )
postgres-> select to_char(nr, 'fm000')
postgres-> from sample_numbers;
 to_char
---------
 001
 011
 100
(3 rows)

postgres=>

For more details on the format picture, please see the manual:
http://www.postgresql.org/docs/current/static/functions-formatting.html

Javascript - How to show escape characters in a string?

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nWorld""

_x000D_
_x000D_
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
    console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
    max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).

JSON.stringify takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("), the word Hello, a backslash (\), the letter n, the word World, and the closing quote ("). The linefeed in the string is escaped in the output as a \ and an n because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.

How to compare two strings are equal in value, what is the best method?

Not forgetting

.equalsIgnoreCase(String)

if you're not worried about that sort of thing...

Read CSV with Scanner()

Please stop writing faulty CSV parsers!

I've seen hundreds of CSV parsers and so called tutorials for them online.

Nearly every one of them gets it wrong!

This wouldn't be such a bad thing as it doesn't affect me but people who try to write CSV readers and get it wrong tend to write CSV writers, too. And get them wrong as well. And these ones I have to write parsers for.

Please keep in mind that CSV (in order of increasing not so obviousness):

  1. can have quoting characters around values
  2. can have other quoting characters than "
  3. can even have other quoting characters than " and '
  4. can have no quoting characters at all
  5. can even have quoting characters on some values and none on others
  6. can have other separators than , and ;
  7. can have whitespace between seperators and (quoted) values
  8. can have other charsets than ascii
  9. should have the same number of values in each row, but doesn't always
  10. can contain empty fields, either quoted: "foo","","bar" or not: "foo",,"bar"
  11. can contain newlines in values
  12. can not contain newlines in values if they are not delimited
  13. can not contain newlines between values
  14. can have the delimiting character within the value if properly escaped
  15. does not use backslash to escape delimiters but...
  16. uses the quoting character itself to escape it, e.g. Frodo's Ring will be 'Frodo''s Ring'
  17. can have the quoting character at beginning or end of value, or even as only character ("foo""", """bar", """")
  18. can even have the quoted character within the not quoted value; this one is not escaped

If you think this is obvious not a problem, then think again. I've seen every single one of these items implemented wrongly. Even in major software packages. (e.g. Office-Suites, CRM Systems)

There are good and correctly working out-of-the-box CSV readers and writers out there:

If you insist on writing your own at least read the (very short) RFC for CSV.

How to add favicon.ico in ASP.NET site

for me, it didn't work without specifying the MIME in web.config, under <system.webServer><staticContent>

<mimeMap fileExtension=".ico" mimeType="image/ico" />

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

Since the username and password is added in config.inc.php, you need to change:

$cfg['Servers'][$i]['auth_type'] = 'cookie';

TO:

$cfg['Servers'][$i]['auth_type'] = 'config';

And save the file.

You will then need to restart WAMP after making the above changes.

How to draw circle in html page?

There is not technically a way to draw a circle with HTML (there isn’t a <circle> HTML tag), but a circle can be drawn.

The best way to draw one is to add border-radius: 50% to a tag such as div. Here’s an example:

<div style="width: 50px; height: 50px; border-radius: 50%;">You can put text in here.....</div>

How to get array keys in Javascript?

I think you should use an Object ({}) and not an array ([]) for this.

A set of data is associated with each key. It screams for using an object. Do:

var obj = {};
obj[46] = { sel:46, min:0,  max:52 };
obj[666] = { whatever:true };

// This is what for..in is for
for (var prop in obj) {
  console.log(obj[prop]);
}

Maybe some utility stuff like this can help:

window.WidthRange = (function () {
  var obj = {};
  return {
    getObj: function () {return obj;}
    , add: function (key, data) {
        obj[key] = data;
        return this; // enabling chaining
      }
  }
})();

// Usage (using chaining calls):
WidthRange.add(66, {foo: true})
.add(67, {bar: false})
.add(69, {baz: 'maybe', bork:'absolutely'});

var obj = WidthRange.getObj();
for (var prop in obj) {
  console.log(obj[prop]);
}

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

For anyone who finds themselves with the following problem (grouping by ensuring zero and null values are treated as equals)...

SELECT AccountNumber, Amount AS MyAlias
FROM Transactions
GROUP BY AccountNumber, ISNULL(Amount, 0)

(I.e. SQL Server complains that you haven't included the field Amount in your Group By or aggregate function)

...remember to place the exact same function in your SELECT...

SELECT AccountNumber, ISNULL(Amount, 0) AS MyAlias
FROM Transactions
GROUP BY AccountNumber, ISNULL(Amount, 0)

Subset data.frame by date

Well, it's clearly not a number since it has dashes in it. The error message and the two comments tell you that it is a factor but the commentators are apparently waiting and letting the message sink in. Dirk is suggesting that you do this:

 EPL2011_12$Date2 <- as.Date( as.character(EPL2011_12$Date), "%d-%m-%y")

After that you can do this:

 EPL2011_12FirstHalf <- subset(EPL2011_12, Date2 > as.Date("2012-01-13") )

R date functions assume the format is either "YYYY-MM-DD" or "YYYY/MM/DD". You do need to compare like classes: date to date, or character to character.

How can I reset or revert a file to a specific revision?

Many answers here claims to use git reset ... <file> or git checkout ... <file> but by doing so, you will loose every modifications on <file> committed after the commit you want to revert.

If you want to revert changes from one commit on a single file only, just as git revert would do but only for one file (or say a subset of the commit files), I suggest to use both git diff and git apply like that (with <sha> = the hash of the commit you want to revert) :

git diff <sha>^ <sha> path/to/file.ext | git apply -R

Basically, it will first generate a patch corresponding to the changes you want to revert, and then reverse-apply the patch to drop those changes.

Of course, it shall not work if reverted lines had been modified by any commit between <sha1> and HEAD (conflict).

Implicit function declarations in C

It should be considered an error. But C is an ancient language, so it's only a warning.
Compiling with -Werror (gcc) fixes this problem.

When C doesn't find a declaration, it assumes this implicit declaration: int f();, which means the function can receive whatever you give it, and returns an integer. If this happens to be close enough (and in case of printf, it is), then things can work. In some cases (e.g. the function actually returns a pointer, and pointers are larger than ints), it may cause real trouble.

Note that this was fixed in newer C standards (C99, C11). In these standards, this is an error. However, gcc doesn't implement these standards by default, so you still get the warning.

Is there any simple way to convert .xls file to .csv file? (Excel)

Install these 2 packages

<packages>
  <package id="ExcelDataReader" version="3.3.0" targetFramework="net451" />
  <package id="ExcelDataReader.DataSet" version="3.3.0" targetFramework="net451" />
</packages>

Helper function

using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExcelToCsv
{
    public class ExcelFileHelper
    {
        public static bool SaveAsCsv(string excelFilePath, string destinationCsvFilePath)
        {

            using (var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                IExcelDataReader reader = null;
                if (excelFilePath.EndsWith(".xls"))
                {
                    reader = ExcelReaderFactory.CreateBinaryReader(stream);
                }
                else if (excelFilePath.EndsWith(".xlsx"))
                {
                    reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                }

                if (reader == null)
                    return false;

                var ds = reader.AsDataSet(new ExcelDataSetConfiguration()
                {
                    ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                    {
                        UseHeaderRow = false
                    }
                });

                var csvContent = string.Empty;
                int row_no = 0;
                while (row_no < ds.Tables[0].Rows.Count)
                {
                    var arr = new List<string>();
                    for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                    {
                        arr.Add(ds.Tables[0].Rows[row_no][i].ToString());
                    }
                    row_no++;
                    csvContent += string.Join(",", arr) + "\n";
                }
                StreamWriter csv = new StreamWriter(destinationCsvFilePath, false);
                csv.Write(csvContent);
                csv.Close();
                return true;
            }
        }
    }
}

Usage :

var excelFilePath = Console.ReadLine();
string output = Path.ChangeExtension(excelFilePath, ".csv");
ExcelFileHelper.SaveAsCsv(excelFilePath, output);

Implementing SearchView in action bar


For Searchview use these code

  1. For XML

    <android.support.v7.widget.SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/searchView">
    
    </android.support.v7.widget.SearchView>
    

  2. In your Fragment or Activity

    package com.example.user.salaryin;
    
    import android.app.ProgressDialog;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.view.MenuItemCompat;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.SearchView;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Toast;
    import com.example.user.salaryin.Adapter.BusinessModuleAdapter;
    import com.example.user.salaryin.Network.ApiClient;
    import com.example.user.salaryin.POJO.ProductDetailPojo;
    import com.example.user.salaryin.Service.ServiceAPI;
    import java.util.ArrayList;
    import java.util.List;
    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    
    
    public class OneFragment extends Fragment implements SearchView.OnQueryTextListener {
    
    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    ArrayList<ProductDetailPojo> arrayList;
    BusinessModuleAdapter adapter;
    private ProgressDialog pDialog;
    GridLayoutManager gridLayoutManager;
    SearchView searchView;
    
    public OneFragment() {
        // Required empty public constructor
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        View rootView = inflater.inflate(R.layout.one_fragment,container,false);
    
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Please wait...");
    
    
        searchView=(SearchView)rootView.findViewById(R.id.searchView);
        searchView.setQueryHint("Search BY Brand");
        searchView.setOnQueryTextListener(this);
    
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(this.getActivity());
        recyclerView.setLayoutManager(layoutManager);
        gridLayoutManager = new GridLayoutManager(this.getActivity().getApplicationContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setHasFixedSize(true);
        getImageData();
    
    
        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.one_fragment, container, false);
        return rootView;
    }
    
    
    private void getImageData() {
        pDialog.show();
        ServiceAPI service = ApiClient.getRetrofit().create(ServiceAPI.class);
        Call<List<ProductDetailPojo>> call = service.getBusinessImage();
    
        call.enqueue(new Callback<List<ProductDetailPojo>>() {
            @Override
            public void onResponse(Call<List<ProductDetailPojo>> call, Response<List<ProductDetailPojo>> response) {
                if (response.isSuccessful()) {
                    arrayList = (ArrayList<ProductDetailPojo>) response.body();
                    adapter = new BusinessModuleAdapter(arrayList, getActivity());
                    recyclerView.setAdapter(adapter);
                    pDialog.dismiss();
                } else if (response.code() == 401) {
                    pDialog.dismiss();
                    Toast.makeText(getActivity(), "Data is not found", Toast.LENGTH_SHORT).show();
                }
    
            }
    
            @Override
            public void onFailure(Call<List<ProductDetailPojo>> call, Throwable t) {
                Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
                pDialog.dismiss();
    
            }
        });
    }
    
       /* @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_search, menu);
        MenuItem menuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        searchView.setQueryHint("Search Product");
        searchView.setOnQueryTextListener(this);
    }*/
    
    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }
    
    @Override
    public boolean onQueryTextChange(String newText) {
        newText = newText.toLowerCase();
        ArrayList<ProductDetailPojo> newList = new ArrayList<>();
        for (ProductDetailPojo productDetailPojo : arrayList) {
            String name = productDetailPojo.getDetails().toLowerCase();
    
            if (name.contains(newText) )
                newList.add(productDetailPojo);
            }
        adapter.setFilter(newList);
        return true;
       }
    }
    
  3. In adapter class

     public void setFilter(List<ProductDetailPojo> newList){
        arrayList=new ArrayList<>();
        arrayList.addAll(newList);
        notifyDataSetChanged();
    }
    

VueJs get url query

You can also get them with pure javascript.

For example:

new URL(location.href).searchParams.get('page')

For this url: websitename.com/user/?page=1, it would return a value of 1

How to recompile with -fPIC

Briefly, the error means that you can't use a static library to be linked w/ a dynamic one. The correct way is to have a libavcodec compiled into a .so instead of .a, so the other .so library you are trying to build will link well.

The shortest way to do so is to add --enable-shared at ./configure options. Or even you may try to disable shared (or static) libraries at all... you choose what is suitable for you!

jQuery - how can I find the element with a certain id?

This is one more option to find the element for above question

$("#tbIntervalos").find('td[id="'+horaInicial+'"]')

Nodejs cannot find installed module on Windows

For windows, everybody said you should set environment variables for nodejs and npm modules, but do you know why? For some modules, they have command line tool, after installed the module, there'are [module].cmd file in C:\Program Files\nodejs, and it's used for launch in window command. So if you don't add the path containing the cmd file to environment variables %PATH% , you won't launch them successfully through command window.

GDB: break if variable equal value

You can use a watchpoint for this (A breakpoint on data instead of code).

You can start by using watch i.
Then set a condition for it using condition <breakpoint num> i == 5

You can get the breakpoint number by using info watch

What is the default database path for MongoDB?

For a Windows machine start the mongod process by specifying the dbpath:

mongod --dbpath \mongodb\data

Reference: Manage mongod Processes

Start an activity from a fragment

You may have to replace getActivity() with MainActivity.this for those that are having issues with this.

CREATE TABLE LIKE A1 as A2

You can use below query to create table and insert distinct values into this table:

Select Distinct Column1, Column2, Column3 into New_Users from Old_Users

Capture iOS Simulator video for App Preview

You can combine QuickTime Player + iMovie(Free)

At first choose your desired simulator from xcode and record screen using QuickTime Player. After that use iMovie for making App Preview and finally upload the video with Safari browser.**enter image description here**It's simple... :)

ImageView - have height match width?

Here's how I solved that problem:

int pHeight =  picture.getHeight();
int pWidth = picture.getWidth();
int vWidth = preview.getWidth();
preview.getLayoutParams().height = (int)(vWidth*((double)pHeight/pWidth));

preview - imageView with width setted to "match_parent" and scaleType to "cropCenter"

picture - Bitmap object to set in imageView src.

That's works pretty well for me.

Language Books/Tutorials for popular languages

For Objective C:

Cocoa Programming for Mac OSX - Third Edition Aaron Hillegass Published by Addison Wesley

Programming in Objective C, Stephen G Kochan,

PHP - auto refreshing page

use this code ,it will automatically refresh in 5 seconds, you can change time in refresh

<?php $url1=$_SERVER['REQUEST_URI']; header("Refresh: 5; URL=$url1"); ?>

Escaping special characters in Java Regular Expressions

I wrote this pattern:

Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");

And use it in this method:

String escapeSpecialRegexChars(String str) {

    return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}

Then you can use it like this, for example:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*" + escapeSpecialRegexChars(text) + ".*");
}

We needed to do that because, after escaping, we add some regex expressions. If not, you can simply use \Q and \E:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*\\Q" + text + "\\E.*")
}

How to pass an event object to a function in Javascript?

Although this is the accepted answer, toto_tico's answer below is better :)

Try making the onclick js use 'return' to ensure the desired return value gets used...

<button type="button" value="click me" onclick="return check_me();" />

In DB2 Display a table's definition

All that metadata is held in the DB2 catalog tables in the SYSIBM 'schema'. It varies for the DB2/z mainframe product and the DB2/LUW distributed product but they're coming closer and closer with each release.

IBM conveniently place all their manuals up on the publib site for the world to access. My area of expertise, DB2/z, has the pages you want here.

There are a number of tables there that you'll need to reference:

SYSTABLES        for table information.
SYSINDEXES    \
SYSINDEXPART   + for index information.
SYSKEYS       /
SYSCOLUMNS       for column information.

The list of all information centers is here which should point you to the DB2/LUW version if that's your area of interest.

How to remove provisioning profiles from Xcode

Update for Xcode 8.3

This no longer works in Xcode 8.3. It appears to be related to Apple's move to automate provisioning profile and certificate generation:

The simplest "solution" (or workaround) is to make sure Xcode is closed, then via Terminal:

rm ~/Library/MobileDevice/Provisioning\ Profiles/*.mobileprovision  

In Xcode 7 & 8:

  1. Open Preferences > Accounts

  2. Select your apple ID from the list

  3. On the right-hand side, select the team your provisioning profile belongs to

  4. Click View Details

  5. Under Provisioning Profiles, right-click the one you want to delete and select Move to Trash:

access key and value of object using *ngFor

None of the answers here worked for me out of the box, here is what worked for me:

Create pipes/keys.ts with contents:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform
{
    transform(value:any, args:string[]): any {
        let keys:any[] = [];
        for (let key in value) {
            keys.push({key: key, value: value[key]});
        }
        return keys;
    }
}

Add to app.module.ts (Your main module):

import { KeysPipe } from './pipes/keys';

and then add to your module declarations array something like this:

@NgModule({
    declarations: [
        KeysPipe
    ]
})
export class AppModule {}

Then in your view template you can use something like this:

<option *ngFor="let entry of (myData | keys)" value="{{ entry.key }}">{{ entry.value }}</option>

Here is a good reference I found if you want to read more.

ASP.NET Web Site or ASP.NET Web Application?

Compilation Firstly there is a difference in compilation. Web Site is not pre-compiled on server, it is compiled on file. It may be an advantage because when you want to change something in your Web Site you can just download a specific file from server, change it and upload this file back to server and everything would work fine. In Web Application you can't do this because everthing is pre-compiled and you end up with only one dll. When you change something in one file of your project you have to re-compile everything again. So if you would like to have a possibility to change some files on server Web Site is better solution for you. It also allows many developers to work on one Web Site. On the other side, if you don't want your code to be available on server you should rather choose Web Application. This option is also better for Unit Testing because of one DLL file being created after publishing your website.

Project structure There is also a difference in the structure of the project. In Web Application you have a project file just like you had it in normal application. In Web Site there is no traditional project file, all you have is solution file. All references and settings are stored in web.config file. @Page directive There is a different attribute in @Page directive for the file that contains class associated with this page. In Web Application it is standard "CodeBehind", in Web Site you use "CodeFile". You can see this in the examples below:

Web Application:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"  
Inherits="WebApplication._Default" %>  

Web Site:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 

Namespaces - In the example above you can see also another difference - how namespaces are created. In Web Application namespace is simply a name of the project. In Website there is default namespace ASP for dynamically compiled pages.

Edit and Continue- In Web Application Edit and Continue option is available (to turn it on you have to go to Tools Menu, click Options then find Edit and Continue in Debugging). This feature is not working in Web Site.ASP.NET MVCIf you want to develop web applications using

ASP.NET MVC (Model View Controller) the best and default option is Web Application. Although it's possible to use MVC in Web Site it's not recommended.

Summary - The most important difference between ASP.NET Web Application and Web Site is compilation. So if you work on a bigger project where a few people can modify it it's better to use Web Site. But if you're doing a smaller project you can use Web Application as well.

Object of class DateTime could not be converted to string

If you are using Twig templates for Symfony, you can use the classic {{object.date_attribute.format('d/m/Y')}} to obtain the desired formatted date.

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

Route::group(['middleware' => 'web'], function () {
Route::auth();

Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);

Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
    Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
    Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});

How can I add to a List's first position?

Use List<T>.Insert(0, item) or a LinkedList<T>.AddFirst().

Opening database file from within SQLite command-line shell

I wonder why no one was able to get what the question actually asked. It stated What is the command within the SQLite shell tool to specify a database file?

A sqlite db is on my hard disk E:\ABCD\efg\mydb.db. How do I access it with sqlite3 command line interface? .open E:\ABCD\efg\mydb.db does not work. This is what question asked.

I found the best way to do the work is

  • copy-paste all your db files in 1 directory (say E:\ABCD\efg\mydbs)
  • switch to that directory in your command line
  • now open sqlite3 and then .open mydb.db

This way you can do the join operation on different tables belonging to different databases as well.

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

Is it possible to decrypt SHA1

SHA1 is a one way hash. So you can not really revert it.

That's why applications use it to store the hash of the password and not the password itself.

Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.

Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.

Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.

In his blog he shows a table that tells us the probability of collisions for a given input set.

Hash Collision Probabilities Table

As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.

A simple java program will show us what his table shows:

public class Main {

    public static void main(String[] args) {
        char[] inputValue = new char[10];

        Map<Integer, String> hashValues = new HashMap<Integer, String>();

        int collisionCount = 0;

        for (int i = 0; i < 77163; i++) {
            String asString = nextValue(inputValue);
            int hashCode = asString.hashCode();
            String collisionString = hashValues.put(hashCode, asString);
            if (collisionString != null) {
                collisionCount++;
                System.out.println("Collision: " + asString + " <-> " + collisionString);
            }
        }

        System.out.println("Collision count: " + collisionCount);
    }

    private static String nextValue(char[] inputValue) {
        nextValue(inputValue, 0);

        int endIndex = 0;
        for (int i = 0; i < inputValue.length; i++) {
            if (inputValue[i] == 0) {
                endIndex = i;
                break;
            }
        }

        return new String(inputValue, 0, endIndex);
    }

    private static void nextValue(char[] inputValue, int index) {
        boolean increaseNextIndex = inputValue[index] == 'z';

        if (inputValue[index] == 0 || increaseNextIndex) {
            inputValue[index] = 'A';
        } else {
            inputValue[index] += 1;
        }

        if (increaseNextIndex) {
            nextValue(inputValue, index + 1);
        }

    }

}

My output end with:

Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135

It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A and z.

Let's take the last reported collision and check

System.out.println("VvV".hashCode());
System.out.println("WWV".hashCode());

My output is

86390
86390

Conclusion:

If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.

And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.

How to merge lists into a list of tuples?

The output which you showed in problem statement is not the tuple but list

list_c = [(1,5), (2,6), (3,7), (4,8)]

check for

type(list_c)

considering you want the result as tuple out of list_a and list_b, do

tuple(zip(list_a,list_b)) 

.do extension in web pages?

I've occasionally thought that it might serve a purpose to add a layer of security by obscuring the back-end interpreter through a remapping of .php or whatever to .aspx or whatever so that any potential hacker would be sent down the wrong path, at least for a while. I never bothered to try it and I don't do a lot of webserver work any more so I'm unlikely to.

However, I'd be interested in the perspective of an experienced server admin on that notion.

Array of Matrices in MATLAB

I was doing some volume rendering in octave (matlab clone) and building my 3D arrays (ie an array of 2d slices) using

buffer=zeros(1,512*512*512,"uint16");
vol=reshape(buffer,512,512,512);

Memory consumption seemed to be efficient. (can't say the same for the subsequent speed of computations :^)

Show/hide widgets in Flutter programmatically

bool _visible = false;

 void _toggle() {
    setState(() {
      _visible = !_visible;
    });
  }

onPressed: _toggle,

Visibility(
            visible:_visible,
            child: new Container(
            child: new  Container(
              padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 10.0),
              child: new Material(
                elevation: 10.0,
                borderRadius: BorderRadius.circular(25.0),
                child: new ListTile(
                  leading: new Icon(Icons.search),
                  title: new TextField(
                    controller: controller,
                    decoration: new InputDecoration(
                        hintText: 'Search for brands and products', border: InputBorder.none,),
                    onChanged: onSearchTextChanged,
                  ),
                  trailing: new IconButton(icon: new Icon(Icons.cancel), onPressed: () {
                    controller.clear();
                    onSearchTextChanged('');
                  },),
                ),
              ),
            ),
          ),
          ),

How to create <input type=“text”/> dynamically

Maybe the method document.createElement(); is what you're looking for.

How to replace sql field value

You could just use REPLACE:

UPDATE myTable SET emailCol = REPLACE(emailCol, '.com', '.org')`.

But take into account an email address such as [email protected] will be updated to [email protected].

If you want to be on a safer side, you should check for the last 4 characters using RIGHT, and append .org to the SUBSTRING manually instead. Notice the usage of UPPER to make the search for the .com ending case insensitive.

UPDATE myTable 
SET emailCol = SUBSTRING(emailCol, 1, LEN(emailCol)-4) + '.org'
WHERE UPPER(RIGHT(emailCol,4)) = '.COM';

See it working in this SQLFiddle.

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

For me, it is exactly what the maven of eclipse complains

enter image description here

So, I press Edit button and change path to the JDK Folder, then clean project and everything starts to work

Where can I get a list of Ansible pre-defined variables?

https://github.com/f500/ansible-dumpall
FYI: this github project shows you how to list 90% of variables across all hosts. I find it more globally useful than single host commands. The README includes instructions for building a simple inventory report. It's even more valuable to run this at the end of a playbook to see all the Facts. To also debug Task behaviour use register:

The result is missing a few items: - included YAML file variables - extra-vars - a number of the Ansible internal vars described here: Ansible Behavioural Params

Redirecting a page using Javascript, like PHP's Header->Location

You cannot mix JS and PHP that way, PHP is rendered before the page is sent to the browser (i.e. before the JS is run)

You can use window.location to change your current page.

$('.entry a:first').click(function() {
    window.location = "http://google.ca";
});

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.

The for loop you specified is absolutely correct.

Although i will do all the loops for you once again.

int sum = 0;
// for loop

for (int i = 1; i<= 100; i++){
    sum = sum + i;
}
System.out.println(sum);

// while loop

sum = 0;
int j = 1;

while(j<=100){
    sum = sum + j;
    j++;
}

System.out.println(sum);

// do while loop

sum = 0;
j = 1;

do{
    sum = sum + j;
    j++;
}
while(j<=100);

System.out.println(sum);

In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.

fcntl substitute on Windows

The substitute of fcntl on windows are win32api calls. The usage is completely different. It is not some switch you can just flip.

In other words, porting a fcntl-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl call does and then find the equivalent win32api code, if any.

There's also the possibility that some code using fcntl has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.

If you provide more details about the fcntl calls people can find windows equivalents.

How to get the difference between two arrays in JavaScript?

A solution using indexOf() will be ok for small arrays but as they grow in length the performance of the algorithm approaches O(n^2). Here's a solution that will perform better for very large arrays by using objects as associative arrays to store the array entries as keys; it also eliminates duplicate entries automatically but only works with string values (or values which can be safely stored as strings):

function arrayDiff(a1, a2) {
  var o1={}, o2={}, diff=[], i, len, k;
  for (i=0, len=a1.length; i<len; i++) { o1[a1[i]] = true; }
  for (i=0, len=a2.length; i<len; i++) { o2[a2[i]] = true; }
  for (k in o1) { if (!(k in o2)) { diff.push(k); } }
  for (k in o2) { if (!(k in o1)) { diff.push(k); } }
  return diff;
}

var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
arrayDiff(a1, a2); // => ['c', 'd']
arrayDiff(a2, a1); // => ['c', 'd']

start/play embedded (iframe) youtube-video on click of an image

This should work perfect just copy this div code

<div onclick="thevid=document.getElementById('thevideo'); thevid.style.display='block'; this.style.display='none'">
<img style="cursor: pointer;" alt="" src="http://oi59.tinypic.com/33trpyo.jpg" />
</div>
<div id="thevideo" style="display: none;">
<embed width="631" height="466" type="application/x-shockwave-flash" src="https://www.youtube.com/v/26EpwxkU5js?version=3&amp;hl=en_US&amp;autoplay=1" allowFullScreen="true" allowscriptaccess="always" allowfullscreen="true" />
</div>

CSS Circle with border

Try this:

.circle {
    height: 20px;
    width: 20px;
    padding: 5px;
    text-align: center; 
    border-radius: 50%;
    display: inline-block;
    color:#fff;
    font-size:1.1em;
    font-weight:600;
    background-color: rgba(0,0,0,0.1);
    border: 1px solid rgba(0,0,0,0.2);
}

How to properly add 1 month from now to current date in moment.js

According to the latest doc you can do the following-

Add a day

moment().add(1, 'days').calendar();

Add Year

moment().add(1, 'years').calendar();

Add Month

moment().add(1, 'months').calendar();

Hibernate: Automatically creating/updating the db tables based on entity classes

In support to @thorinkor's answer I would extend my answer to use not only @Table (name = "table_name") annotation for entity, but also every child variable of entity class should be annotated with @Column(name = "col_name"). This results into seamless updation to the table on the go.

For those who are looking for a Java class based hibernate config, the rule applies in java based configurations also(NewHibernateUtil). Hope it helps someone else.

XML Schema Validation : Cannot find the declaration of element

The targetNamespace of your XML Schema does not match the namespace of the Root element (dot in Test.Namespace vs. comma in Test,Namespace)

Once you make the above agree, you have to consider that your element2 has an attribute order that is not in your XSD.

How to verify that a specific method was not called using Mockito?

Use the second argument on the Mockito.verify method, as in:

Mockito.verify(dependency, Mockito.times(0)).someMethod()

Search and replace a line in a file in Python

fileinput is quite straightforward as mentioned on previous answers:

import fileinput

def replace_in_file(file_path, search_text, new_text):
    with fileinput.input(file_path, inplace=True) as f:
        for line in f:
            new_line = line.replace(search_text, new_text)
            print(new_line, end='')

Explanation:

  • fileinput can accept multiple files, but I prefer to close each single file as soon as it is being processed. So placed single file_path in with statement.
  • print statement does not print anything when inplace=True, because STDOUT is being forwarded to the original file.
  • end='' in print statement is to eliminate intermediate blank new lines.

Can be used as follows:

file_path = '/path/to/my/file'
replace_in_file(file_path, 'old-text', 'new-text')

how to compare two string dates in javascript?

var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
    alert ("Error!");
}

Demo Jsfiddle

sqlite3.OperationalError: unable to open database file

This worked for me:

conn = sqlite3.connect("C:\\users\\guest\\desktop\\example.db")

Note: Double slashes in the full path

Using python v2.7 on Win 7 enterprise and Win Xp Pro

Hope this helps someone.

Access PHP variable in JavaScript

I'm not sure how necessary this is, and it adds a call to getElementById, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:

<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>

And then in your JavaScript:

var size_of_widget = document.getElementById("metadata-size-of-widget").title;

pthread function from a class

My favorite way to handle a thread is to encapsulate it inside a C++ object. Here's an example:

class MyThreadClass
{
public:
   MyThreadClass() {/* empty */}
   virtual ~MyThreadClass() {/* empty */}

   /** Returns true if the thread was successfully started, false if there was an error starting the thread */
   bool StartInternalThread()
   {
      return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
   }

   /** Will not return until the internal thread has exited. */
   void WaitForInternalThreadToExit()
   {
      (void) pthread_join(_thread, NULL);
   }

protected:
   /** Implement this method in your subclass with the code you want your thread to run. */
   virtual void InternalThreadEntry() = 0;

private:
   static void * InternalThreadEntryFunc(void * This) {((MyThreadClass *)This)->InternalThreadEntry(); return NULL;}

   pthread_t _thread;
};

To use it, you would just create a subclass of MyThreadClass with the InternalThreadEntry() method implemented to contain your thread's event loop. You'd need to call WaitForInternalThreadToExit() on the thread object before deleting the thread object, of course (and have some mechanism to make sure the thread actually exits, otherwise WaitForInternalThreadToExit() would never return)

What is difference between INNER join and OUTER join

This is the best and simplest way to understand joins:

enter image description here

Credits go to the writer of this article HERE

In a Bash script, how can I exit the entire script if a certain condition occurs?

If you will invoke the script with source, you can use return <x> where <x> will be the script exit status (use a non-zero value for error or false). But if you invoke an executable script (i.e., directly with its filename), the return statement will result in a complain (error message "return: can only `return' from a function or sourced script").

If exit <x> is used instead, when the script is invoked with source, it will result in exiting the shell that started the script, but an executable script will just terminate, as expected.

To handle either case in the same script, you can use

return <x> 2> /dev/null || exit <x>

This will handle whichever invocation may be suitable. That is assuming you will use this statement at the script's top level. I would advise against directly exiting the script from within a function.

Note: <x> is supposed to be just a number.

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

Check /etc/phpmyadmin/config-db.php file

  1. Go to terminal
  2. run vi /etc/phpmyadmin/config-db.php
  3. check the information
  4. Hit Ctrl + X
  5. Try login to phpmyadmin again through the web using the information from the config file.

JUnit 5: How to assert an exception is thrown?

Here is an easy way.

@Test
void exceptionTest() {

   try{
        model.someMethod("invalidInput");
        fail("Exception Expected!");
   }
   catch(SpecificException e){

        assertTrue(true);
   }
   catch(Exception e){
        fail("wrong exception thrown");
   }

}

It only succeeds when the Exception you expect is thrown.

How to split and modify a string in NodeJS?

Use split and map function:

var str = "123, 124, 234,252";
var arr = str.split(",");
arr = arr.map(function (val) { return +val + 1; });

Notice +val - string is casted to a number.

Or shorter:

var str = "123, 124, 234,252";
var arr = str.split(",").map(function (val) { return +val + 1; });

edit 2015.07.29

Today I'd advise against using + operator to cast variable to a number. Instead I'd go with a more explicit but also more readable Number call:

_x000D_
_x000D_
var str = "123, 124, 234,252";_x000D_
var arr = str.split(",").map(function (val) {_x000D_
  return Number(val) + 1;_x000D_
});_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

edit 2017.03.09

ECMAScript 2015 introduced arrow function so it could be used instead to make the code more concise:

_x000D_
_x000D_
var str = "123, 124, 234,252";_x000D_
var arr = str.split(",").map(val => Number(val) + 1);_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

How do I specify a password to 'psql' non-interactively?

An alternative to using the PGPASSWORD environment variable is to use the conninfo string according to the documentation:

An alternative way to specify connection parameters is in a conninfo string or a URI, which is used instead of a database name. This mechanism give you very wide control over the connection.

$ psql "host=<server> port=5432 dbname=<db> user=<user> password=<password>"

postgres=>

AngularJS $watch window resize inside directive

// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag

---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';

@Directive({
       selector: '[resize]',
       host: { '(window:resize)': 'onResize()' } // Window resize listener
})

export class AutoResize {

element: ElementRef; // Element that associated to attribute.
$window: any;
       constructor(_element: ElementRef) {

         this.element = _element;
         // Get instance of DOM window.
         this.$window = angular.element(window);

         this.onResize();

    }

    // Adjust height of element.
    onResize() {
         $(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
   }
}

Reorder / reset auto increment primary key

You could drop the primary key column and re-create it. All the ids should then be reassigned in order.

However this is probably a bad idea in most situations. If you have other tables that have foreign keys to this table then it will definitely not work.

AngularJS custom filter function

Additionally, if you want to use the filter in your controller the same way you do it here:

<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}
</div>

You could do something like:

var filteredItems =  $scope.$eval('items | filter:filter:criteriaMatch(criteria)');

Format date as dd/MM/yyyy using pipes

I think that it's because the locale is hardcoded into the DatePipe. See this link:

And there is no way to update this locale by configuration right now.

Is there a standard sign function (signum, sgn) in C/C++?

The accepted Answer with the overload below does indeed not trigger -Wtype-limits.

template <typename T> inline constexpr
  int signum(T x, std::false_type) {
  return T(0) < x;
}

template <typename T> inline constexpr
  int signum(T x, std::true_type) {
  return (T(0) < x) - (x < T(0));
}

template <typename T> inline constexpr
  int signum(T x) {
  return signum(x, std::is_signed<T>());
}

For C++11 an alternative could be.

template <typename T>
typename std::enable_if<std::is_unsigned<T>::value, int>::type
inline constexpr signum(T const x) {
    return T(0) < x;  
}

template <typename T>
typename std::enable_if<std::is_signed<T>::value, int>::type
inline constexpr signum(T const x) {
    return (T(0) < x) - (x < T(0));  
}

For me it does not trigger any warnings on GCC 5.3.1.

Should Jquery code go in header or footer?

Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.

IsNullOrEmpty with Object

obj1 != null  

is the right way.

String defines IsNullOrEmpty as a nicer way to say

obj1 == null || obj == String.Empty

so it does more than just check for nullity.

There may be other classes that define a method to check for a sematically "blank or null" object, but that would depend on the semantics of the class, and is by no means universal.

It's also possible to create extension method to do this kind of thing if it helps the readability of your code. For example, a similar approach to collections:

public static bool IsNullOrEmpty (this ICollection collection)
{
    return collection == null || collection.Count == 0;
}

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

I changed the package name while coding an update so that I could debug it on my device via Eclipse, without deleting the old version that was installed. Without reverting the package name I was using when trying to reinstall, I got this same error. Using the same package name the reinstall was successful.

Center image in table td in CSS

Simple way to do it for html5 in css:

td img{
    display: block;
    margin-left: auto;
    margin-right: auto;

}

Worked for me perfectly.

$rootScope.$broadcast vs. $scope.$emit

Use RxJS in a Service

What about in a situation where you have a Service that's holding state for example. How could I push changes to that Service, and other random components on the page be aware of such a change? Been struggling with tackling this problem lately

Build a service with RxJS Extensions for Angular.

<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/rx/dist/rx.all.js"></script>
<script src="//unpkg.com/rx-angular/dist/rx.angular.js"></script>
var app = angular.module('myApp', ['rx']);

app.factory("DataService", function(rx) {
  var subject = new rx.Subject(); 
  var data = "Initial";

  return {
      set: function set(d){
        data = d;
        subject.onNext(d);
      },
      get: function get() {
        return data;
      },
      subscribe: function (o) {
         return subject.subscribe(o);
      }
  };
});

Then simply subscribe to the changes.

app.controller('displayCtrl', function(DataService) {
  var $ctrl = this;

  $ctrl.data = DataService.get();
  var subscription = DataService.subscribe(function onNext(d) {
      $ctrl.data = d;
  });

  this.$onDestroy = function() {
      subscription.dispose();
  };
});

Clients can subscribe to changes with DataService.subscribe and producers can push changes with DataService.set.

The DEMO on PLNKR.

Count specific character occurrences in a string

This is the simple way:

text = "the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3

How to remove all .svn directories from my application directories

Alternatively, if you want to export a copy without modifying the working copy, you can use rsync:

rsync -a --exclude .svn path/to/working/copy path/to/export

If file exists then delete the file

fileExists() is a method of FileSystemObject, not a global scope function.

You also have an issue with the delete, DeleteFile() is also a method of FileSystemObject.

Furthermore, it seems you are moving the file and then attempting to deal with the overwrite issue, which is out of order. First you must detect the name collision, so you can choose the rename the file or delete the collision first. I am assuming for some reason you want to keep deleting the new files until you get to the last one, which seemed implied in your question.

So you could use the block:

if NOT fso.FileExists(newname) Then  

    file.move fso.buildpath(OUT_PATH, newname)           

else

    fso.DeleteFile newname
    file.move fso.buildpath(OUT_PATH, newname)  

end if 

Also be careful that your string comparison with the = sign is case sensitive. Use strCmp with vbText compare option for case insensitive string comparison.

Positive Number to Negative Number in JavaScript?

num * -1

This would do it for you.

Make iframe automatically adjust height according to the contents without using scrollbar?

I wanted to make an iframe behave like a normal page (I needed to make a fullscreen banner inside an iframe element), so here is my script:

    (function (window, undefined) {

    var frame,
        lastKnownFrameHeight = 0,
        maxFrameLoadedTries = 5,
        maxResizeCheckTries = 20;

    //Resize iframe on window resize
    addEvent(window, 'resize', resizeFrame);

    var iframeCheckInterval = window.setInterval(function () {
        maxFrameLoadedTries--;
        var frames = document.getElementsByTagName('iframe');
        if (maxFrameLoadedTries == 0 || frames.length) {
            clearInterval(iframeCheckInterval);
            frame = frames[0];
            addEvent(frame, 'load', resizeFrame);
            var resizeCheckInterval = setInterval(function () {
                resizeFrame();
                maxResizeCheckTries--;
                if (maxResizeCheckTries == 0) {
                    clearInterval(resizeCheckInterval);
                }
            }, 1000);
            resizeFrame();
        }
    }, 500);

    function resizeFrame() {
        if (frame) {
            var frameHeight = frame.contentWindow.document.body.scrollHeight;
            if (frameHeight !== lastKnownFrameHeight) {
                lastKnownFrameHeight = frameHeight;

                var viewportWidth = document.documentElement.clientWidth;
                if (document.compatMode && document.compatMode === 'BackCompat') {
                    viewportWidth = document.body.clientWidth;
                }

                frame.setAttribute('width', viewportWidth);
                frame.setAttribute('height', lastKnownFrameHeight);

                frame.style.width = viewportWidth + 'px';
                frame.style.height = frameHeight + 'px';
            }
        }
    }

    //--------------------------------------------------------------
    //  Cross-browser helpers
    //--------------------------------------------------------------

    function addEvent(elem, event, fn) {
        if (elem.addEventListener) {
            elem.addEventListener(event, fn, false);
        } else {
            elem.attachEvent("on" + event, function () {
                return (fn.call(elem, window.event));
            });
        }
    }

})(window);

The functions are self-explanatory and have comments to further explain their purpose.

How to generate an openSSL key using a passphrase from the command line?

If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.

You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar):

openssl genrsa -aes128 -passout pass:foobar 3072

However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.

A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:

openssl genrsa -aes128 -passout file:passphrase.txt 3072

Or supply the passphrase on standard input:

openssl genrsa -aes128 -passout stdin 3072

You can also used a named pipe with the file: option, or a file descriptor.


To then obtain the matching public key, you need to use openssl rsa, supplying the same passphrase with the -passin parameter as was used to encrypt the private key:

openssl rsa -passin file:passphrase.txt -pubout

(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>).


Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar:

openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub

How to cin Space in c++?

It skips all whitespace (spaces, tabs, new lines, etc.) by default. You can either change its behavior, or use a slightly different mechanism. To change its behavior, use the manipulator noskipws, as follows:

 cin >> noskipws >> a[i];

But, since you seem like you want to look at the individual characters, I'd suggest using get, like this prior to your loop

 cin.get( a, n );

Note: get will stop retrieving chars from the stream if it either finds a newline char (\n) or after n-1 chars. It stops early so that it can append the null character (\0) to the array. You can read more about the istream interface here.

Why am I getting the error "connection refused" in Python? (Sockets)

I was being able to ping my connection but was STILL getting the 'connection refused' error. Turns out I was pinging myself! That's what the problem was.

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

The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123

Cannot redeclare function php

Remove the function and check the output of:

var_dump(function_exists('parseDate'));

In which case, change the name of the function.

If you get false, you're including the file with that function twice, replace :

include

by

include_once

And replace :

require

by

require_once

EDIT : I'm just a little too late, post before beat me to it !

Iterating through a JSON object

Your loading of the JSON data is a little fragile. Instead of:

json_raw= raw.readlines()
json_object = json.loads(json_raw[0])

you should really just do:

json_object = json.load(raw)

You shouldn't think of what you get as a "JSON object". What you have is a list. The list contains two dicts. The dicts contain various key/value pairs, all strings. When you do json_object[0], you're asking for the first dict in the list. When you iterate over that, with for song in json_object[0]:, you iterate over the keys of the dict. Because that's what you get when you iterate over the dict. If you want to access the value associated with the key in that dict, you would use, for example, json_object[0][song].

None of this is specific to JSON. It's just basic Python types, with their basic operations as covered in any tutorial.

How to update only one field using Entity Framework?

I use ValueInjecter nuget to inject Binding Model into database Entity using following:

public async Task<IHttpActionResult> Add(CustomBindingModel model)
{
   var entity= await db.MyEntities.FindAsync(model.Id);
   if (entity== null) return NotFound();

   entity.InjectFrom<NoNullsInjection>(model);

   await db.SaveChangesAsync();
   return Ok();
}

Notice the usage of custom convention that doesn't update Properties if they're null from server.

ValueInjecter v3+

public class NoNullsInjection : LoopInjection
{
    protected override void SetValue(object source, object target, PropertyInfo sp, PropertyInfo tp)
    {
        if (sp.GetValue(source) == null) return;
        base.SetValue(source, target, sp, tp);
    }
}

Usage:

target.InjectFrom<NoNullsInjection>(source);

Value Injecter V2

Lookup this answer

Caveat

You won't know whether the property is intentionally cleared to null OR it just didn't have any value it. In other words, the property value can only be replaced with another value but not cleared.

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

It is used to find the how many rows contain data in a worksheet that contains data in the column "A". The full usage is

 lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row

Where ws is a Worksheet object. In the questions example it was implied that the statement was inside a With block

With ws
    lastRowIndex = .Cells(.Rows.Count, "A").End(xlUp).row
End With
  1. ws.Rows.Count returns the total count of rows in the worksheet (1048576 in Excel 2010).
  2. .Cells(.Rows.Count, "A") returns the bottom most cell in column "A" in the worksheet

Then there is the End method. The documentation is ambiguous as to what it does.

Returns a Range object that represents the cell at the end of the region that contains the source range

Particularly it doesn't define what a "region" is. My understanding is a region is a contiguous range of non-empty cells. So the expected usage is to start from a cell in a region and find the last cell in that region in that direction from the original cell. However there are multiple exceptions for when you don't use it like that:

  • If the range is multiple cells, it will use the region of rng.cells(1,1).
  • If the range isn't in a region, or the range is already at the end of the region, then it will travel along the direction until it enters a region and return the first encountered cell in that region.
  • If it encounters the edge of the worksheet it will return the cell on the edge of that worksheet.

So Range.End is not a trivial function.

  1. .row returns the row index of that cell.

Object of class stdClass could not be converted to string

try this

return $query->result_array();

Setting the height of a SELECT in IE

It is correct that there is no work-around for this aside from ditching the select element, but if you only need to show more items in your select list you can simply use the size attribute:

<select multiple="multiple" size="15">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>

Doing this you'll have additional empty lines if your collection of items lenght is smaller than size value.

What is Python buffer type for?

An example usage:

>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world

The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.

This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray:

>>> s = bytearray(1000000)   # a million zeroed bytes
>>> t = buffer(s, 1)         # slice cuts off the first byte
>>> s[1] = 5                 # set the second element in s
>>> t[0]                     # which is now also the first element in t!
'\x05'

This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.

Note that buffer has been replaced by the better named memoryview in Python 3, though you can use either in Python 2.7.

Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.

Difference between / and /* in servlet mapping url pattern

The essential difference between /* and / is that a servlet with mapping /* will be selected before any servlet with an extension mapping (like *.html), while a servlet with mapping / will be selected only after extension mappings are considered (and will be used for any request which doesn't match anything else---it is the "default servlet").

In particular, a /* mapping will always be selected before a / mapping. Having either prevents any requests from reaching the container's own default servlet.

Either will be selected only after servlet mappings which are exact matches (like /foo/bar) and those which are path mappings longer than /* (like /foo/*). Note that the empty string mapping is an exact match for the context root (http://host:port/context/).

See Chapter 12 of the Java Servlet Specification, available in version 3.1 at http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html.

Position a div container on the right side

Is this what you wanted? - http://jsfiddle.net/jomanlk/x5vyC/3/

Floats on both sides now

#wrapper{
    background:red;
    overflow:auto;
}

#c1{
   float:left;
   background:blue;
}

#c2{
    background:green;
    float:right;
}?

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

How to export a table dataframe in PySpark to csv?

If data frame fits in a driver memory and you want to save to local files system you can convert Spark DataFrame to local Pandas DataFrame using toPandas method and then simply use to_csv:

df.toPandas().to_csv('mycsv.csv')

Otherwise you can use spark-csv:

  • Spark 1.3

    df.save('mycsv.csv', 'com.databricks.spark.csv')
    
  • Spark 1.4+

    df.write.format('com.databricks.spark.csv').save('mycsv.csv')
    

In Spark 2.0+ you can use csv data source directly:

df.write.csv('mycsv.csv')

input type="submit" Vs button tag are they interchangeable?

Use <button> tag instead of <input type="button"..>. It is the advised practice in bootstrap 3.

http://getbootstrap.com/css/#buttons-tags

"Cross-browser rendering

As a best practice, we highly recommend using the <button> element whenever possible to ensure matching cross-browser rendering.

Among other things, there's a Firefox bug that prevents us from setting the line-height of <input>-based buttons, causing them to not exactly match the height of other buttons on Firefox."

What does "for" attribute do in HTML <label> tag?

The <label> tag allows you to click on the label, and it will be treated like clicking on the associated input element. There are two ways to create this association:

One way is to wrap the label element around the input element:

<label>Input here:
    <input type='text' name='theinput' id='theinput'>
</label>

The other way is to use the for attribute, giving it the ID of the associated input:

<label for="theinput">Input here:</label>
<input type='text' name='whatever' id='theinput'>

This is especially useful for use with checkboxes and buttons, since it means you can check the box by clicking on the associated text instead of having to hit the box itself.

Read more about this element in MDN.

Asp.net - Add blank item at top of dropdownlist

After your databind:

drpList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
drpList.SelectedIndex = 0;

Change priorityQueue to max priorityqueue

This can be achieved by using

PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Collections.reverseOrder());

Bootstrap : TypeError: $(...).modal is not a function

I had also faced same error when i was trying to call bootstrap modal from jquery. But this happens because we are using bootstrap modal and for this we need to attach one cdn bootstrap.min.js which is

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Hope this will help as I missed that when i was trying to call bootstrap modal from jQuery using

$('#button').on('click',function(){ $('#myModal').modal(); });

myModal is the id of Bootstrap modal and you have to give a click event to a button when you call click that button a pop up modal will be displayed.

Hide vertical scrollbar in <select> element

I think you can't. The SELECT element is rendered at a point beyond the reach of CSS and HTML. Is it grayed out?

But you can try to add a "size" atribute.

jQuery’s .bind() vs. .on()

These snippets all perform exactly the same thing:

element.on('click', function () { ... });
element.bind('click', function () { ... });
element.click(function () { ... });

However, they are very different from these, which all perform the same thing:

element.on('click', 'selector', function () { ... });
element.delegate('click', 'selector', function () { ... });
$('selector').live('click', function () { ... });

The second set of event handlers use event delegation and will work for dynamically added elements. Event handlers that use delegation are also much more performant. The first set will not work for dynamically added elements, and are much worse for performance.

jQuery's on() function does not introduce any new functionality that did not already exist, it is just an attempt to standardize event handling in jQuery (you no longer have to decide between live, bind, or delegate).

How to check if IEnumerable is null or empty?

I use this one:

    public static bool IsNotEmpty(this ICollection elements)
    {
        return elements != null && elements.Count > 0;
    }

Ejem:

List<string> Things = null;
if (Things.IsNotEmpty())
{
    //replaces ->  if (Things != null && Things.Count > 0) 
}

How to remove the URL from the printing page?

This will be the simplest solution. I tried most of the solutions in the internet but only this helped me.

@print {
    @page :footer {
        display: none
    }

    @page :header {
        display: none
    }
}

How to force a SQL Server 2008 database to go Offline

Go offline

USE master
GO
ALTER DATABASE YourDatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO

Go online

USE master
GO
ALTER DATABASE YourDatabaseName
SET ONLINE
GO

What's the difference between JavaScript and JScript?

As far as I can tell, two things:

  1. ActiveXObject constructor
  2. The idiom f(x) = y, which is roughly equivalent to f[x] = y.

How do I get rid of the "cannot empty the clipboard" error?

I got rid of the problem by unchecking the option for "Alert before overwriting cells" in Excel options. I'm using Excel 2007

Collection that allows only unique items in .NET?

You may look into something kind of Unique List as follows

public class UniqueList<T>
{
    public List<T> List
    {
        get;
        private set;
    }
    List<T> _internalList;

    public static UniqueList<T> NewList
    {
        get
        {
            return new UniqueList<T>();
        }
    }

    private UniqueList()
    {            
        _internalList = new List<T>();
        List = new List<T>();
    }

    public void Add(T value)
    {
        List.Clear();
        _internalList.Add(value);
        List.AddRange(_internalList.Distinct());
        //return List;
    }

    public void Add(params T[] values)
    {
        List.Clear();
        _internalList.AddRange(values);
        List.AddRange(_internalList.Distinct());
       // return List;
    }

    public bool Has(T value)
    {
        return List.Contains(value);
    }
}

and you can use it like follows

var uniquelist = UniqueList<string>.NewList;
uniquelist.Add("abc","def","ghi","jkl","mno");
uniquelist.Add("abc","jkl");
var _myList = uniquelist.List;

will only return "abc","def","ghi","jkl","mno" always even when duplicates are added to it

Styling a disabled input with css only

Use this CSS (jsFiddle example):

input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
  color: green
}

You have to write the most outer element on the left and the most inner element on the right.

.btn:hover input:disabled would select any disabled input elements contained in an element with a class btn which is currently hovered by the user.

I would prefer :disabled over [disabled], see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?


By the way, Laravel (PHP) generates the HTML - not the browser.

R: invalid multibyte string

I had a similarly strange problem with a file from the program e-prime (edat -> SPSS conversion), but then I discovered that there are many additional encodings you can use. this did the trick for me:

tbl <- read.delim("dir/file.txt", fileEncoding="UCS-2LE")

Bubble Sort Homework

def bubble_sort(a):
    t = 0
    sorted = False # sorted = False because we have not began to sort
    while not sorted:
    sorted = True # Assume sorted = True first, it will switch only there is any change
        for key in range(1,len(a)):
            if a[key-1] > a[key]:
                sorted = False
                t = a[key-1]; a[key-1] = a[key]; a[key] = t;
    print a

How to delete images from a private docker registry?

Problem 1

You mentioned it was your private docker registry, so you probably need to check Registry API instead of Hub registry API doc, which is the link you provided.

Problem 2

docker registry API is a client/server protocol, it is up to the server's implementation on whether to remove the images in the back-end. (I guess)

DELETE /v1/repositories/(namespace)/(repository)/tags/(tag*)

Detailed explanation

Below I demo how it works now from your description as my understanding for your questions.

I run a private docker registry. I use the default one, and listen on port 5000.

docker run -d -p 5000:5000 registry

Then I tag the local image and push into it.

$ docker tag ubuntu localhost:5000/ubuntu
$ docker push localhost:5000/ubuntu
The push refers to a repository [localhost:5000/ubuntu] (len: 1)
Sending image list
Pushing repository localhost:5000/ubuntu (1 tags)
511136ea3c5a: Image successfully pushed
d7ac5e4f1812: Image successfully pushed
2f4b4d6a4a06: Image successfully pushed
83ff768040a0: Image successfully pushed
6c37f792ddac: Image successfully pushed
e54ca5efa2e9: Image successfully pushed
Pushing tag for rev [e54ca5efa2e9] on {http://localhost:5000/v1/repositories/ubuntu/tags/latest}

After that I can use Registry API to check it exists in your private docker registry

$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags
{"latest": "e54ca5efa2e962582a223ca9810f7f1b62ea9b5c3975d14a5da79d3bf6020f37"}

Now I can delete the tag using that API !!

$ curl -X DELETE localhost:5000/v1/repositories/ubuntu/tags/latest
true

Check again, the tag doesn't exist in my private registry server

$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags/latest
{"error": "Tag not found"}

Find the max of 3 numbers in Java with different data types

Simple way without methods

int x = 1, y = 2, z = 3;

int biggest = x;
if (y > biggest) {
    biggest = y;
}
if (z > biggest) {
    biggest = z;
}
System.out.println(biggest);
//    System.out.println(Math.max(Math.max(x,y),z));

"static const" vs "#define" vs "enum"

In C, specifically? In C the correct answer is: use #define (or, if appropriate, enum)

While it is beneficial to have the scoping and typing properties of a const object, in reality const objects in C (as opposed to C++) are not true constants and therefore are usually useless in most practical cases.

So, in C the choice should be determined by how you plan to use your constant. For example, you can't use a const int object as a case label (while a macro will work). You can't use a const int object as a bit-field width (while a macro will work). In C89/90 you can't use a const object to specify an array size (while a macro will work). Even in C99 you can't use a const object to specify an array size when you need a non-VLA array.

If this is important for you then it will determine your choice. Most of the time, you'll have no choice but to use #define in C. And don't forget another alternative, that produces true constants in C - enum.

In C++ const objects are true constants, so in C++ it is almost always better to prefer the const variant (no need for explicit static in C++ though).

python - find index position in list based of partial string

indices = [i for i, s in enumerate(mylist) if 'aa' in s]

How to update multiple columns in single update statement in DB2

This is an "old school solution", when MERGE command does not work (I think before version 10).

UPDATE TARGET_TABLE T 
SET (T.VAL1, T.VAL2 ) =  
(SELECT S.VAL1, S.VAL2
 FROM SOURCE_TABLE S 
 WHERE T.KEY1 = S.KEY1 AND T.KEY2 = S.KEY2)
WHERE EXISTS 
(SELECT 1  
 FROM SOURCE_TABLE S 
 WHERE T.KEY1 = S.KEY1 AND T.KEY2 = S.KEY2 
   AND (T.VAL1 <> S.VAL1 OR T.VAL2 <> S.VAL2));