Programs & Examples On #Md5 file

Using a custom typeface in Android

I found a nice solution on the blog of Lisa Wray. With the new data binding it is possible to set the font in your XML files.

@BindingAdapter({"bind:font"})
public static void setFont(TextView textView, String fontName){
    textView.setTypeface(Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/" + fontName));
}

In XML:

<TextView
app:font="@{`Source-Sans-Pro-Regular.ttf`}"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

Error converting data types when importing from Excel to SQL Server 2008

There is a workaround.

  1. Import excel sheet with numbers as float (default).
  2. After importing, Goto Table-Design
  3. Change DataType of the column from Float to Int or Bigint
  4. Save Changes
  5. Change DataType of the column from Bigint to any Text Type (Varchar, nvarchar, text, ntext etc)
  6. Save Changes.

That's it.

Can I export a variable to the environment from a bash script without sourcing it?

I don't think this can be done but I found a workaround using alias. It will only work when you place your script in your scripts directory, otherwise your alias will have an invalid name. The only point to the work around is to be able to have a function inside a file with the same name and not have to bother sourcing it before using it. Add the following code to ~/.bashrc:

alias myFunction='unalias myFunction && . myFunction && myFunction "$@"'

You can now call myFunction without sourcing it first.

Good Patterns For VBA Error Handling

The code below shows an alternative that ensures there is only one exit point for the sub/function.

sub something()
    on error goto errHandler

    ' start of code
    ....
    ....
    'end of code

    ' 1. not needed but signals to any other developer that looks at this
    ' code that you are skipping over the error handler...
    ' see point 1...
    err.clear

errHandler:
    if err.number <> 0 then
        ' error handling code
    end if
end sub

ImportError: No module named 'selenium'

install urllib3

!pip3 install urllib3

import urllib3

than install it

!pip3 install selenium

import selenium

Python and SQLite: insert into table

#The Best way is to use `fStrings` (very easy and powerful in python3)   
#Format: f'your-string'   
#For Example:

mylist=['laks',444,'M']

cursor.execute(f'INSERT INTO mytable VALUES ("{mylist[0]}","{mylist[1]}","{mylist[2]}")')

#THATS ALL!! EASY!!
#You can use it with for loop!

Adding a newline into a string in C#

The previous answers come close, but to meet the actual requirement that the @ symbol stay close, you'd want that to be str.Replace("@", "@" + System.Environment.NewLine). That will keep the @ symbol and add the appropriate newline character(s) for the current platform.

FIFO class in Java

Queues are First In First Out structures. You request is pretty vague, but I am guessing that you need only the basic functionality which usually comes out with Queue structures. You can take a look at how you can implement it here.

With regards to your missing package, it is most likely because you will need to either download or create the package yourself by following that tutorial.

Possible to extend types in Typescript?

You can also do:

export type UserEvent = Event & { UserId: string; };

How to check if a variable is an integer or a string?

The isdigit method of the str type returns True iff the given string is nothing but one or more digits. If it's not, you know the string should be treated as just a string.

Why is String immutable in Java?

String is immutable for several reasons, here is a summary:

  • Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
  • Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.
  • Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
  • Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).

That being said, immutability of String only means you cannot change it using its public API. You can in fact bypass the normal API using reflection. See the answer here.

In your example, if String was mutable, then consider the following example:

  String a="stack";
  System.out.println(a);//prints stack
  a.setValue("overflow");
  System.out.println(a);//if mutable it would print overflow

matplotlib colorbar in each subplot

In plt.colorbar(z1_plot,cax=ax1), use ax= instead of cax=, i.e. plt.colorbar(z1_plot,ax=ax1)

How to start working with GTest and CMake

Yours and VladLosevs' solutions are probably better than mine. If you want a brute-force solution, however, try this:

SET(CMAKE_EXE_LINKER_FLAGS /NODEFAULTLIB:\"msvcprtd.lib;MSVCRTD.lib\")

FOREACH(flag_var
    CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
    CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
    if(${flag_var} MATCHES "/MD")
        string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
    endif(${flag_var} MATCHES "/MD")
ENDFOREACH(flag_var)

How to search JSON tree with jQuery

You could use Jsel - https://github.com/dragonworx/jsel (for full disclosure, I am the owner of this library).

It uses a real XPath engine and is highly customizable. Runs in both Node.js and the browser.

Given your original question, you'd find the people by name with:

// include or require jsel library (npm or browser)
var dom = jsel({
    "people": {
        "person": [{
            "name": "Peter",
            "age": 43,
            "sex": "male"},
        {
            "name": "Zara",
            "age": 65,
            "sex": "female"}]
    }
});
var person = dom.select("//person/*[@name='Peter']");
person.age === 43; // true

If you you were always working with the same JSON schema you could create your own schema with jsel, and be able to use shorter expressions like:

dom.select("//person[@name='Peter']")

Jquery how to find an Object by attribute in an Array

I have created a util service for my angular application. It have two function which use very often.

For example you have object.

First getting value from object recursively without throwing undefined error.

{prop: { nestedProp1: {nestedProp2: somevalue}}}; get nestedProp2 2 without undefined checks.

Second filter array on basis

[{prop: { nestedProp1: {nestedProp2: somevalue1}}}, {prop: { nestedProp1: {nestedProp2: somevalue2}}}];

Find object from array with nestedProp2=somevalue2

app.service('UtilService', function(httpService) {
this.mapStringKeyVal = function(map, field) {
    var lastIdentifiedVal = null;
    var parentVal = map;
    field.split('.').forEach(function(val){
        if(parentVal[val]){
            lastIdentifiedVal = parentVal[val]; 
            parentVal = parentVal[val]; 
        }
    });
    return lastIdentifiedVal;
}


this.arrayPropFilter = function(array, field,value) {
    var lastIdentifiedVal = null;
    var mapStringKeyVal = this.mapStringKeyVal;
    array.forEach(function(arrayItem){
        var valueFound = mapStringKeyVal(arrayItem,field);
        if(!lastIdentifiedVal  && valueFound && valueFound==value){
            lastIdentifiedVal = arrayItem;
        }
    });
    return lastIdentifiedVal;
}});

For solution for current question. inject UtilService and call,

UtilService.arrayPropFilter(purposeArray,'purpose','daily');

Or more advanced

UtilService.arrayPropFilter(purposeArray,'purpose.nestedProp1.nestedProp2','daily');

jQuery get html of container including the container itself

$.fn.outerHtml = function(){
    if (this.length) {
        var div = $('<div style="display:none"></div>');
        var clone =
        $(this[0].cloneNode(false)).html(this.html()).appendTo(div);
        var outer = div.html();
        div.remove();
        return outer;
    }
    else {
        return null;
    }
};

from http://forum.jquery.com/topic/jquery-getting-html-and-the-container-element-12-1-2010

Understanding PIVOT function in T-SQL

A pivot is used to convert one of the columns in your data set from rows into columns (this is typically referred to as the spreading column). In the example you have given, this means converting the PhaseID rows into a set of columns, where there is one column for each distinct value that PhaseID can contain - 1, 5 and 6 in this case.

These pivoted values are grouped via the ElementID column in the example that you have given.

Typically you also then need to provide some form of aggregation that gives you the values referenced by the intersection of the spreading value (PhaseID) and the grouping value (ElementID). Although in the example given the aggregation that will be used is unclear, but involves the Effort column.

Once this pivoting is done, the grouping and spreading columns are used to find an aggregation value. Or in your case, ElementID and PhaseIDX lookup Effort.

Using the grouping, spreading, aggregation terminology you will typically see example syntax for a pivot as:

WITH PivotData AS
(
    SELECT <grouping column>
        , <spreading column>
        , <aggregation column>
    FROM <source table>
)
SELECT <grouping column>, <distinct spreading values>
FROM PivotData
    PIVOT (<aggregation function>(<aggregation column>)
        FOR <spreading column> IN <distinct spreading values>));

This gives a graphical explanation of how the grouping, spreading and aggregation columns convert from the source to pivoted tables if that helps further.

How do I force my .NET application to run as administrator?

You can embed a manifest file in the EXE file, which will cause Windows (7 or higher) to always run the program as an administrator.

You can find more details in Step 6: Create and Embed an Application Manifest (UAC) (MSDN).

Windows 7 - Add Path

Another method that worked for me on Windows 7 that did not require administrative privileges:

Click on the Start menu, search for "environment," click "Edit environment variables for your account."

In the window that opens, select "PATH" under "User variables for username" and click the "Edit..." button. Add your new path to the end of the existing Path, separated by a semi-colon (%PATH%;C:\Python27;...;C:\NewPath). Click OK on all the windows, open a new CMD window, and test the new variable.

SQL where datetime column equals today's date?

Easy way out is to use a condition like this ( use desired date > GETDATE()-1)

your sql statement "date specific" > GETDATE()-1

How to check if a line has one of the strings in a list?

strings = ("string1", "string2", "string3")
for line in file:
    if any(s in line for s in strings):
        print "yay!"

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

  1. Select columns A:H with A1 as the active cell.
  2. Open Home ? Styles ? Conditional Formatting ? New Rule.
  3. Choose Use a formula to determine which cells to format and supply one of the following formulas¹ in the Format values where this formula is true: text box.
    • To highlight the Account and Store Manager columns when one of the four dates is blank:
              =AND(LEN($A1), COLUMN()<3, COUNTBLANK($E1:$H1))
    • To highlight the Account, Store Manager and blank date columns when one of the four dates is blank:
              =AND(LEN($A1), OR(COLUMN()<3, AND(COLUMN()>4, COUNTBLANK(A1))), COUNTBLANK($E1:$H1))
  4. Click [Format] and select a cell Fill.
  5. Click [OK] to accept the formatting and then [OK] again to create the new rule. In both cases, the Applies to: will refer to =$A:$H.

Results should be similar to the following.

  Conditionally formatting if multiple cells are blank


¹ The COUNTBLANK function was introduced with Excel 2007. It will count both true blanks and zero-length strings left by formulas (e.g. "").

Getting a timestamp for today at midnight?

You are looking to calculate the time of the most recent celestial event where the sun has passed directly below your feet, adjusted for local conventions of marking high noon and also potentially adjusting so that people have enough daylight left after returning home from work, and for other political considerations.

Daunting right? Actually this is a common problem but the complete answer is location-dependent:

$zone = new \DateTimeZone('America/New_York'); // Or your own definition of “here”
$todayStart = new \DateTime('today midnight', $zone);
$timestamp = $todayStart->getTimestamp();

Potential definitions of “here” are listed at https://secure.php.net/manual/en/timezones.php

How to create a delay in Swift?

Try the following implementation in Swift 3.0

func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { 
        completion()
    }
}

Usage

delayWithSeconds(1) {
   //Do something
}

How to prevent going back to the previous activity?

If you don't want to go back to all the activities on your application, you can use

android:launchMode="singleTask"

Learn more here: http://developer.android.com/guide/topics/manifest/activity-element.html

Android: how to make an activity return results to the activity which calls it?

If you want to finish and just add a resultCode (without data), you can call setResult(int resultCode) before finish().

For example:

...
if (everything_OK) {
    setResult(Activity.RESULT_OK); // OK! (use whatever code you want)
    finish();
}
else {
   setResult(Activity.RESULT_CANCELED); // some error ...
   finish();
}
...

Then in your calling activity, check the resultCode, to see if we're OK.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == someCustomRequestCode) {
        if (resultCode == Activity.RESULT_OK) {
            // OK!
        }
        else if (resultCode = Activity.RESULT_CANCELED) {
            // something went wrong :-(
        }
    }
}

Don't forget to call the activity with startActivityForResult(intent, someCustomRequestCode).

Select columns from result set of stored procedure

As it's been mentioned in the question, it's hard to define the 80 column temp table before executing the stored procedure.

So the other way around this is to populate the table based on the stored procedure result set.

SELECT * INTO #temp FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;'
                                   ,'EXEC MyStoredProc')

If you are getting any error, you need to enable ad hoc distributed queries by executing following query.

sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO

To execute sp_configure with both parameters to change a configuration option or to run the RECONFIGURE statement, you must be granted the ALTER SETTINGS server-level permission

Now you can select your specific columns from the generated table

SELECT col1, col2
FROM #temp

How to install sshpass on mac?

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

brew install hudochenkov/sshpass/sshpass

How to parse JSON using Node.js?

As mentioned in the above answers, We can use JSON.parse() to parse the strings to JSON But before parsing, be sure to parse the correct data or else it might bring your whole application down

it is safe to use it like this

let parsedObj = {}
try {
    parsedObj = JSON.parse(data);
} catch(e) {
    console.log("Cannot parse because data is not is proper json format")
}

Pretty Printing a pandas dataframe

A simple approach is to output as html, which pandas does out of the box:

df.to_html('temp.html')

How to compute the similarity between two text documents?

Identical to @larsman, but with some preprocessing

import nltk, string
from sklearn.feature_extraction.text import TfidfVectorizer

nltk.download('punkt') # if necessary...


stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)

def stem_tokens(tokens):
    return [stemmer.stem(item) for item in tokens]

'''remove punctuation, lowercase, stem'''
def normalize(text):
    return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))

vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english')

def cosine_sim(text1, text2):
    tfidf = vectorizer.fit_transform([text1, text2])
    return ((tfidf * tfidf.T).A)[0,1]


print cosine_sim('a little bird', 'a little bird')
print cosine_sim('a little bird', 'a little bird chirps')
print cosine_sim('a little bird', 'a big dog barks')

How do I check out an SVN project into Eclipse as a Java project?

Here are the steps:

  • Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: http://subclipse.tigris.org/install.html
  • Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.
  • Select your project's root folder and select checkout as a project in the workspace.

It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

C++ where to initialize static const

Anywhere in one compilation unit (usually a .cpp file) would do:

foo.h

class foo {
    static const string s; // Can never be initialized here.
    static const char* cs; // Same with C strings.

    static const int i = 3; // Integral types can be initialized here (*)...
    static const int j; //     ... OR in cpp.
};

foo.cpp

#include "foo.h"
const string foo::s = "foo string";
const char* foo::cs = "foo C string";
// No definition for i. (*)
const int foo::j = 4;

(*) According to the standards you must define i outside of the class definition (like j is) if it is used in code other than just integral constant expressions. See David's comment below for details.

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

Did you accidentally create the repository using the root user?

It just happens that I created the git repository as the root user.

I deleted the git repository and created it again without sudo and it works.

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

Based on DaveRandom's answer, I was also playing around and found a slightly simpler Apache solution that produces the same result (Access-Control-Allow-Origin is set to the current specific protocol + domain + port dynamically) without using any rewrite rules:

SetEnvIf Origin ^(https?://.+\.mywebsite\.com(?::\d{1,5})?)$   CORS_ALLOW_ORIGIN=$1
Header append Access-Control-Allow-Origin  %{CORS_ALLOW_ORIGIN}e   env=CORS_ALLOW_ORIGIN
Header merge  Vary "Origin"

And that's it.

Those who want to enable CORS on the parent domain (e.g. mywebsite.com) in addition to all its subdomains can simply replace the regular expression in the first line with this one:

^(https?://(?:.+\.)?mywebsite\.com(?::\d{1,5})?)$.

Note: For spec compliance and correct caching behavior, ALWAYS add the Vary: Origin response header for CORS-enabled resources, even for non-CORS requests and those from a disallowed origin (see example why).

How can I add JAR files to the web-inf/lib folder in Eclipse?

Add the jar file to your WEB-INF/lib folder. Right-click your project in Eclipse, and go to "Build Path > Configure Build Path" Add the "Web App Libraries" library This will ensure all WEB-INF/lib jars are included on the classpath. helped me..

Drag and drop in WEB-INF/lib folder and restart eclipse ans start webservice then create client

Very Long If Statement in Python

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.

For example:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass

Upload Progress Bar in PHP

HTML5 introduced a file upload api that allows you to monitor the progress of file uploads but for older browsers there's plupload a framework that specifically made to monitor file uploads and give information about them. plus it has plenty of callbacks so it can work across all browsers

Sleep function in C++

Prior to C++11, there was no portable way to do this.

A portable way is to use Boost or Ace library. There is ACE_OS::sleep(); in ACE.

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

Accordingly to this answer and to this video new keyword does next things:

  1. Creates new object.

  2. Links new object to constructor function (prototype).

  3. Makes this variable point to the new object.

  4. Executes constructor function using the new object and implicit perform return this;

  5. Assigns constructor function name to new object's property constructor.

Object.create performs only 1st and 2nd steps!!!

Get first and last date of current month with JavaScript or jQuery

I fixed it with Datejs

This is alerting the first day:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);

How to check if a list is empty in Python?

Empty lists evaluate to False in boolean contexts (such as if some_list:).

Javascript | Set all values of an array

The other answers are Ok, but a while loop seems more appropriate:

function setAll(array, value) {
  var i = array.length;
  while (i--) {
    array[i] = value;
  }
}

A more creative version:

function replaceAll(array, value) {
  var re = new RegExp(value, 'g');
  return new Array(++array.length).toString().replace(/,/g, value).match(re);
}

May not work everywhere though. :-)

S3 limit to objects in a bucket

  • There is no limit on objects per bucket.
  • There is a limit of 100 buckets per account (you need to request amazon if you need more).
  • There is no performance drop even if you store millions of objects in a single bucket.

From docs,

There is no limit to the number of objects that can be stored in a bucket and no difference in performance whether you use many buckets or just a few. You can store all of your objects in a single bucket, or you can organize them across several buckets.

as of Aug 2016

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

You need a web.config key to enable the pre 4.5 validation mode.

More Info on ValidationSettings:UnobtrusiveValidationMode:

Specifies how ASP.NET globally enables the built-in validator controls to use unobtrusive JavaScript for client-side validation logic.

Type: UnobtrusiveValidationMode

Default value: None

Remarks: If this key value is set to "None" [default], the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation logic. If this key value is set to "WebForms", ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.

Example:

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

How to take screenshot of a div with JavaScript?

<script src="/assets/backend/js/html2canvas.min.js"></script>


<script>
    $("#download").on('click', function(){
        html2canvas($("#printform"), {
            onrendered: function (canvas) {
                var url = canvas.toDataURL();

                var triggerDownload = $("<a>").attr("href", url).attr("download", getNowFormatDate()+"????????.jpeg").appendTo("body");
                triggerDownload[0].click();
                triggerDownload.remove();
            }
        });
    })
</script>

quotation

Android charting libraries

AchartEngine

You can create a plethora of different chart types relatively quickly with loads of customizable options.

How to implement Android Pull-to-Refresh

Very interesting Pull-to-Refresh by Yalantis. Gif for iOS, but you can check it :)

<com.yalantis.pulltorefresh.library.PullToRefreshView
android:id="@+id/pull_to_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
    android:id="@+id/list_view"
    android:divider="@null"
    android:dividerHeight="0dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

JavaScript - Get Portion of URL Path

If you have an abstract URL string (not from the current window.location), you can use this trick:

let yourUrlString = "http://example.com:3000/pathname/?search=test#hash";

let parser = document.createElement('a');
parser.href = yourUrlString;

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

Thanks to jlong

How can one change the timestamp of an old commit in Git?

Building on theosp's answer, I wrote a script called git-cdc (for change date commit) that I put in my PATH.

The name is important: git-xxx anywhere in your PATH allows you to type:

git xxx
# here
git cdc ... 

That script is in bash, even on Windows (since Git will be calling it from its msys environment)

#!/bin/bash
# commit
# date YYYY-mm-dd HH:MM:SS

commit="$1" datecal="$2"
temp_branch="temp-rebasing-branch"
current_branch="$(git rev-parse --abbrev-ref HEAD)"

date_timestamp=$(date -d "$datecal" +%s)
date_r=$(date -R -d "$datecal")

if [[ -z "$commit" ]]; then
    exit 0
fi

git checkout -b "$temp_branch" "$commit"
GIT_COMMITTER_DATE="$date_timestamp" GIT_AUTHOR_DATE="$date_timestamp" git commit --amend --no-edit --date "$date_r"
git checkout "$current_branch"
git rebase  --autostash --committer-date-is-author-date "$commit" --onto "$temp_branch"
git branch -d "$temp_branch"

With that, you can type:

git cdc @~ "2014-07-04 20:32:45"

That would reset author/commit date of the commit before HEAD (@~) to the specified date.

git cdc @~ "2 days ago"

That would reset author/commit date of the commit before HEAD (@~) to the same hour, but 2 days ago.


Ilya Semenov mentions in the comments:

For OS X you may also install GNU coreutils (brew install coreutils), add it to PATH (PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH") and then use "2 days ago" syntax.

Getting the size of an array in an object

Arrays have a property .length that returns the number of elements.

var st =
    {
        "itema":{},
        "itemb":
        [
            {"id":"s01","cd":"c01","dd":"d01"},
            {"id":"s02","cd":"c02","dd":"d02"}
        ]
    };

st.itemb.length // 2

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

Nothing like these two lines appears in Mike Williams' tutorial:

    wait = true;
    setTimeout("wait = true", 2000);

Here's a Version 3 port:

http://acleach.me.uk/gmaps/v3/plotaddresses.htm

The relevant bit of code is

  // ====== Geocoding ======
  function getAddress(search, next) {
    geo.geocode({address:search}, function (results,status)
      { 
        // If that was successful
        if (status == google.maps.GeocoderStatus.OK) {
          // Lets assume that the first marker is the one we want
          var p = results[0].geometry.location;
          var lat=p.lat();
          var lng=p.lng();
          // Output the data
            var msg = 'address="' + search + '" lat=' +lat+ ' lng=' +lng+ '(delay='+delay+'ms)<br>';
            document.getElementById("messages").innerHTML += msg;
          // Create a marker
          createMarker(search,lat,lng);
        }
        // ====== Decode the error status ======
        else {
          // === if we were sending the requests to fast, try this one again and increase the delay
          if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
            nextAddress--;
            delay++;
          } else {
            var reason="Code "+status;
            var msg = 'address="' + search + '" error=' +reason+ '(delay='+delay+'ms)<br>';
            document.getElementById("messages").innerHTML += msg;
          }   
        }
        next();
      }
    );
  }

Disable button in WPF?

This should do it:

<StackPanel>
    <TextBox x:Name="TheTextBox" />
    <Button Content="Click Me">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="IsEnabled" Value="True" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Text, ElementName=TheTextBox}" Value="">
                        <Setter Property="IsEnabled" Value="False" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
</StackPanel>

How to select some rows with specific rownames from a dataframe?

You can also use this:

DF[paste0("stu",c(2,3,5,9)), ]

How can I drop a table if there is a foreign key constraint in SQL Server?

1-firstly, drop the foreign key constraint after that drop the tables.

2-you can drop all foreign key via executing the following query:

DECLARE @SQL varchar(4000)=''
SELECT @SQL = 
@SQL + 'ALTER TABLE ' + s.name+'.'+t.name + ' DROP CONSTRAINT [' + RTRIM(f.name) +'];' + CHAR(13)
FROM sys.Tables t
INNER JOIN sys.foreign_keys f ON f.parent_object_id = t.object_id
INNER JOIN sys.schemas     s ON s.schema_id = f.schema_id

--EXEC (@SQL)

PRINT @SQL

if you execute the printed results @SQL, the foreign keys will be dropped.

How to get file_get_contents() to work with HTTPS?

Just add two lines in your php.ini file.

extension=php_openssl.dll

allow_url_include = On

its working for me.

Add horizontal scrollbar to html table

First, make a display: block of your table

then, set overflow-x: to auto.

table {
    display: block;
    overflow-x: auto;
    white-space: nowrap;
}

Nice and clean. No superfluous formatting.

Here are more involved examples with scrolling table captions from a page on my website.

If an issue is taken about cells not filling the entire table, append the following additional CSS code:

table tbody {
    display: table;
    width: 100%;
}

Single-threaded apartment - cannot instantiate ActiveX control

If you used [STAThread] to the main entry of your application and still get the error you may need to make a Thread-Safe call to the control... something like below. In my case with the same problem the following solution worked!

Private void YourFunc(..)
{
    if (this.InvokeRequired)
    {
        Invoke(new MethodInvoker(delegate()
        {
           // Call your method YourFunc(..);
        }));
    }
    else
    {
        ///
    }

The view 'Index' or its master was not found.

Check the generated code at MyAreaAreaRegistration.cs and make sure that the controller parameter is set to your default controller, otherwise the controller will be called bot for some reason ASP.NET MVC won't search for the views at the area folder

public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "SomeArea_default",
            "SomeArea/{controller}/{action}/{id}",
            new { controller = "SomeController", action = "Index", id = UrlParameter.Optional }
        );
    }

Where is the Postgresql config file: 'postgresql.conf' on Windows?

On my machine:

C:\Program Files (x86)\OpenERP 6.1-20121026-233219\PostgreSQL\data

Converting an OpenCV Image to Black and White

For those doing video I cobbled the following based on @tsh :

import cv2 as cv
import numpy as np

def nothing(x):pass

cap = cv.VideoCapture(0)
cv.namedWindow('videoUI', cv.WINDOW_NORMAL)
cv.createTrackbar('T','videoUI',0,255,nothing)

while(True):
    ret, frame = cap.read()
    vid_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    thresh = cv.getTrackbarPos('T','videoUI');
    vid_bw = cv.threshold(vid_gray, thresh, 255, cv.THRESH_BINARY)[1]

    cv.imshow('videoUI',cv.flip(vid_bw,1))

    if cv.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv.destroyAllWindows()

Results in:

enter image description here

Get JSON data from external URL and display it in a div as plain text

Since the desired page will be called from a different domain you need to return jsonp instead of a json.

$.get("http://theSource", {callback : "?" }, "jsonp",  function(data) {
    $('#summary').text(data.result);
});

Laravel Request getting current path with query string

Try to use the following:

\Request::getRequestUri()

<> And Not In VB.NET

The C# and VB.NET compilers often generate different IL for operations that are apparently equivalent in both languages. It just so happens that C# does the "expected" thing when you write stringvar == null, but VB.NET does not. To get the same effect in VB.NET you have to force true reference equality with the Is operator.

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

I've found an solution. I use an solution of Steve Gentile, jQuery and ASP.NET MVC – sending JSON to an Action – Revisited.

My ASP.NET MVC view code looks like:

function getplaceholders() {
        var placeholders = $('.ui-sortable');
        var results = new Array();
        placeholders.each(function() {
            var ph = $(this).attr('id');
            var sections = $(this).find('.sort');
            var section;

            sections.each(function(i, item) {
                var sid = $(item).attr('id');
                var o = { 'SectionId': sid, 'Placeholder': ph, 'Position': i };
                results.push(o);
            });
        });
        var postData = { widgets: results };
        var widgets = results;
        $.ajax({
            url: '/portal/Designer.mvc/SaveOrUpdate',
            type: 'POST',
            dataType: 'json',
            data: $.toJSON(widgets),
            contentType: 'application/json; charset=utf-8',
            success: function(result) {
                alert(result.Result);
            }
        });
    };

and my controller action is decorated with an custom attribute

[JsonFilter(Param = "widgets", JsonDataType = typeof(List<PageDesignWidget>))]
public JsonResult SaveOrUpdate(List<PageDesignWidget> widgets

Code for the custom attribute can be found here (the link is broken now).

Because the link is broken this is the code for the JsonFilterAttribute

public class JsonFilter : ActionFilterAttribute
{
    public string Param { get; set; }
    public Type JsonDataType { get; set; }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
        {
            string inputContent;
            using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
            {
                inputContent = sr.ReadToEnd();
            }
            var result = JsonConvert.DeserializeObject(inputContent, JsonDataType);
            filterContext.ActionParameters[Param] = result;
        }
    }
}

JsonConvert.DeserializeObject is from Json.NET

Link: Serializing and Deserializing JSON with Json.NET

LF will be replaced by CRLF in git - What is that and is it important?

In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.

If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line

git config core.autocrlf true

If you want to make an intelligent decision how git should handle this, read the documentation

Here is a snippet

Formatting and Whitespace

Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.

core.autocrlf

If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.

Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:

$ git config --global core.autocrlf true

If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:

$ git config --global core.autocrlf input

This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.

If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:

$ git config --global core.autocrlf false

Disable scrolling in webview?

This should be the complete answer. As suggested by @GDanger . Extend WebView to override the scroll methods and embed the custom webview within layout xml.

public class ScrollDisabledWebView extends WebView {

    private boolean scrollEnabled = false;

    public ScrollDisabledWebView(Context context) {
        super(context);
        initView(context);
    }

    public ScrollDisabledWebView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        initView(context);
    }
    // this is important. Otherwise it throws Binary Inflate Exception.
    private void initView(Context context) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY,
                                   int scrollRangeX, int scrollRangeY, int maxOverScrollX,
                                   int maxOverScrollY, boolean isTouchEvent) {
        if (scrollEnabled) {
            return super.overScrollBy(deltaX, deltaY, scrollX, scrollY,
                    scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
        }
        return false;
    }

    @Override
    public void scrollTo(int x, int y) {
        if (scrollEnabled) {
            super.scrollTo(x, y);
        }
    }

    @Override
    public void computeScroll() {
        if (scrollEnabled) {
            super.computeScroll();
        }
    }
}

And then embed in layout file as follows

<com.sample.apps.ScrollDisabledWebView
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    tools:context="com.sample.apps.HomeActivity"/>

Then in the Activity, use some additional methods for disabling scrollbars too.

ScrollDisabledWebView webView = (ScrollDisabledWebView) findViewById(R.id.webView);
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);

Color picker utility (color pipette) in Ubuntu

I recommend GPick:

sudo apt-get install gpick

Applications -> Graphics -> GPick

It has many more features than gcolor2 but is still extremely simple to use: click on one of the hex swatches, move your mouse around the screen over the colours you want to pick, then press the Space bar to add to your swatch list.

If that doesn't work, another way is to click-and-drag from the centre of the hexagon and release your mouse over the pixel that you want to sample. Then immediately hit Space to copy that color into the next swatch in rotation.

It also has a traditional colour picker (like gcolor2) in the bottom right-hand corner of the window to allow you to pick individual colours with magnification.

How to delete multiple pandas (python) dataframes from memory to save RAM?

In python automatic garbage collection deallocates the variable (pandas DataFrame are also just another object in terms of python). There are different garbage collection strategies that can be tweaked (requires significant learning).

You can manually trigger the garbage collection using

import gc
gc.collect()

But frequent calls to garbage collection is discouraged as it is a costly operation and may affect performance.

Reference

Unlink of file Failed. Should I try again?

If you are developing a web application, a common reason is to forget shutting down the server. For example this could be a simple Node.js process, or on windows your IIS process running more unobtrusive as background process.

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

Programmatically get height of navigation bar

Support iOS 13 and Below:

extension UIViewController {

    var topbarHeight: CGFloat {
        if #available(iOS 13.0, *) {
            return (view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0.0) +
                (self.navigationController?.navigationBar.frame.height ?? 0.0)
        } else {
            let topBarHeight = UIApplication.shared.statusBarFrame.size.height +
            (self.navigationController?.navigationBar.frame.height ?? 0.0)
            return topBarHeight
        }
    }
}

HTTP Status 404 - The requested resource (/) is not available

Sometimes cleaning the server works. It worked for me many times.This is only applicable if the program worked earlier but suddenly it stops working.
Steps:
" Right click on Tomcat Server -> Clean. Then restart the server."

Are "while(true)" loops so bad?

I use something similar, but with opposite logic, in a lot of my functions.

DWORD dwError = ERROR_SUCCESS;

do
{
    if ( (dwError = SomeFunction()) != ERROR_SUCCESS )
    {
         /* handle error */
         continue;
    }

    if ( (dwError = SomeOtherFunction()) != ERROR_SUCCESS )
    {
         /* handle error */
         continue;
    }
}
while ( 0 );

if ( dwError != ERROR_SUCCESS )
{
    /* resource cleanup */
}

What's a simple way to get a text input popup dialog box on an iPhone

Try this Swift code in a UIViewController -

func doAlertControllerDemo() {

    var inputTextField: UITextField?;

    let passwordPrompt = UIAlertController(title: "Enter Password", message: "You have selected to enter your passwod.", preferredStyle: UIAlertControllerStyle.Alert);

    passwordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        // Now do whatever you want with inputTextField (remember to unwrap the optional)

        let entryStr : String = (inputTextField?.text)! ;

        print("BOOM! I received '\(entryStr)'");

        self.doAlertViewDemo(); //do again!
    }));


    passwordPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        print("done");
    }));


    passwordPrompt.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Password"
        textField.secureTextEntry = false       /* true here for pswd entry */
        inputTextField = textField
    });


    self.presentViewController(passwordPrompt, animated: true, completion: nil);


    return;
}

How to create a DB link between two oracle instances

Creation of DB Link

CREATE DATABASE LINK dblinkname
CONNECT TO $usename
IDENTIFIED BY $password
USING '$sid';

(Note: sid is being passed between single quotes above. )

Example Queries for above DB Link

select * from tableA@dblinkname;

insert into tableA(select * from tableA@dblinkname);

remove space between paragraph and unordered list

I got pretty good results with my HTML mailing list by using the following:

p { margin-bottom: 0; }
ul { margin-top: 0; }

This does not reset all margin values but only those that create such a gap before ordered list, and still doesn't assume anything about default margin values.

How to edit HTML input value colour?

Add a style = color:black !important; in your input type.

Angular2 @Input to a property with get/set

You could set the @Input on the setter directly, as described below:

_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
@Input() set allowDay(value: boolean) {
    this._allowDay = value;
    this.updatePeriodTypes();
}

See this Plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.

Trying Gradle build - "Task 'build' not found in root project"

Check your file: settings.gradle for presence lines with included subprojects (for example: include chapter1-bookstore )

How to save user input into a variable in html and js

Change your javascript to:

var input = document.getElementById('userInput').value;

This will get the value that has been types into the text box, not a DOM object

PHP json_encode json_decode UTF-8

This is an encoding issue. It looks like at some point, the data gets represented as ISO-8859-1.

Every part of your process needs to be UTF-8 encoded.

  • The database connection

  • The database tables

  • Your PHP file (if you are using special characters inside that file as shown in your example above)

  • The content-type headers that you output

Direct download from Google Drive using Google Drive API

If you just want to programmatically (as oppossed to giving the user a link to open in a browser) download a file through the Google Drive API, I would suggest using the downloadUrl of the file instead of the webContentLink, as documented here: https://developers.google.com/drive/web/manage-downloads

Is it possible to interactively delete matching search pattern in Vim?

The best way is probably to use:

:%s/phrase//gc

c asks for confirmation before each deletion. g allows multiple replacements to occur on the same line.

You can also just search using /phrase, select the next match with gn, and delete it with d.

Command not found error in Bash variable assignment

You cannot have spaces around the = sign.

When you write:

STR = "foo"

bash tries to run a command named STR with 2 arguments (the strings = and foo)

When you write:

STR =foo

bash tries to run a command named STR with 1 argument (the string =foo)

When you write:

STR= foo

bash tries to run the command foo with STR set to the empty string in its environment.

I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:

  1. the first command is exactly equivalent to: STR "=" "foo",
  2. the second is the same as STR "=foo",
  3. and the last is equivalent to STR="" foo.

The relevant section of the sh language spec, section 2.9.1 states:

A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.

In that context, a word is the command that bash is going to run. Any string containing = (in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the = is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In STR = "foo", STR is not a variable assignment.

NPM: npm-cli.js not found when running npm

I run into this problem when installing node9.0.0 on windows7 at the end the solution was to just remove npm npm.cmd npx npx.cmd from C:\Program Files\nodejs\node_modules\npm\bin before doing this a workaround was to run C:\Program Files\nodejs\npm so that is one way so see if you have the same problem I had.

sorting a vector of structs

Yes: you can sort using a custom comparison function:

std::sort(info.begin(), info.end(), my_custom_comparison);

my_custom_comparison needs to be a function or a class with an operator() overload (a functor) that takes two data objects and returns a bool indicating whether the first is ordered prior to the second (i.e., first < second). Alternatively, you can overload operator< for your class type data; operator< is the default ordering used by std::sort.

Either way, the comparison function must yield a strict weak ordering of the elements.

How to loop through an associative array and get the key?

While arguably being less clear this method is faster by roughly a factor of roughly 3.5 (At least on the box I used to test)

$foo = array(
    1 => "Value1",
    2 => "Value2",
    10 => "Value10"
);
while($bar = each($foo)){
    echo $bar[0] . " => " . $bar[1];
}

I would imagine that this is due to the fact the foreach copies the entire array before iterating over it.

Git Clone from GitHub over https with two-factor authentication

Find out how to fix this here:

https://github.com/blog/1614-two-factor-authentication#how-does-it-work-for-command-line-git

How does it work for command-line Git?

If you are using SSH for Git authentication, rest easy: you don't need to do anything. If you are using HTTPS Git, instead of entering your password, enter a personal access token. These can be created by going to your personal access tokens page.

How to save a bitmap on internal storage

To Save your bitmap in sdcard use the following code

Store Image

private void storeImage(Bitmap image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        Log.d(TAG,
                "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    } 
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }  
}

To Get the Path for Image Storage

/** Create a File for saving an image or video */
private  File getOutputMediaFile(){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this. 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + getApplicationContext().getPackageName()
            + "/Files"); 

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    } 
    // Create a media file name
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
    File mediaFile;
        String mImageName="MI_"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
    return mediaFile;
} 

EDIT From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.

public onClick(View v){

switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
} 
}

Amazon AWS Filezilla transfer permission denied

If you're using Ubuntu then use the following:

sudo chown -R ubuntu /var/www/html

sudo chmod -R 755 /var/www/html

How to declare and initialize a static const array as a class member?

You are mixing pointers and arrays. If what you want is an array, then use an array:

struct test {
   static int data[10];        // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:

struct test {
   static int *data;
};
// cpp
static int* generate_data() {            // static here is "internal linkage"
   int * p = new int[10];
   for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
   return p;
}
int *test::data = generate_data();

Datatables warning(table id = 'example'): cannot reinitialise data table

You can add destroy:true to the configuration to make sure data table already present is removed before being reinitialized.

$('#example').dataTable({
    destroy: true,
    ...
});

What is the difference between C++ and Visual C++?

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell Labs as an enhancement to the C programming language and originally named "C with Classes". It was renamed to C++ in 1983.

C++ is widely used in the software industry. Some of its application domains include systems software, application software, device drivers, embedded software, high-performance server and client applications, and entertainment software such as video games. Several groups provide both free and proprietary C++ compiler software, including the GNU Project, Microsoft, Intel, Borland and others.


Microsoft Visual C++ (often abbreviated as MSVC or VC++) is an integrated development environment (IDE) product from Microsoft for the C, C++, and C++/CLI programming languages. MSVC is proprietary software; it was originally a standalone product but later became a part of Visual Studio and made available in both trialware and freeware forms. It features tools for developing and debugging C++ code, especially code written for Windows API, DirectX and .NET Framework.


So the main difference between them is that they are different things. The former is a programming language, while the latter is a commercial integrated development environment (IDE).

What is the best way to tell if a character is a letter or number in Java without using regexes?

 import java.util.Scanner;
 public class v{
 public static void main(String args[]){
 Scanner in=new Scanner(System.in);
    String str;
    int l;
    int flag=0;
    System.out.println("Enter the String:");
    str=in.nextLine();
    str=str.toLowerCase();
    str=str.replaceAll("\\s","");
    char[] ch=str.toCharArray();
    l=str.length();
    for(int i=0;i<l;i++){
        if ((ch[i] >= 'a' && ch[i]<= 'z') || (ch[i] >= 'A' && ch[i] <= 'Z')){
        flag=0;
        }
        else

        flag++;
        break;
        } 
if(flag==0)
    System.out.println("Onlt char");


}
}

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

I am going with @hofs but displaying where should put minifyEnabled.

In Module Gradle, Add minifyEnabled false in Debug block will work for me.

 android {
    compileSdkVersion 28
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.korechi.roamioapp"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        debug {
          minifyEnabled false
        }
    }

}

PHP, pass array through POST

Edit If you are asking about security, see my addendum at the bottom Edit

PHP has a serialize function provided for this specific purpose. Pass it an array, and it will give you a string representation of it. When you want to convert it back to an array, you just use the unserialize function.

$data = array('one'=>1, 'two'=>2, 'three'=>33);
$dataString = serialize($data);
//send elsewhere
$data = unserialize($dataString);

This is often used by lazy coders to save data to a database. Not recommended, but works as a quick/dirty solution.

Addendum

I was under the impression that you were looking for a way to send the data reliably, not "securely". No matter how you pass the data, if it is going through the users system, you cannot trust it at all. Generally, you should store it somewhere on the server & use a credential (cookie, session, password, etc) to look it up.

Assign output of a program to a variable using a MS batch file

You could use a batch macro for simple capturing of command outputs, a bit like the behaviour of the bash shell.

The usage of the macro is simple and looks like

%$set% VAR=application arg1 arg2

And it works even with pipes

%$set% allDrives="wmic logicaldisk get name /value | findstr "Name""

The macro uses the variable like an array and stores each line in a separate index.
In the sample of %$set% allDrives="wmic logicaldisk there will the following variables created:

allDrives.Len=5
allDrives.Max=4
allDrives[0]=Name=C:
allDrives[1]=Name=D:
allDrives[2]=Name=F:
allDrives[3]=Name=G:
allDrives[4]=Name=Z:
allDrives=<contains the complete text with line feeds>

To use it, it's not important to understand how the macro itself works.

The full example

@echo off
setlocal

call :initMacro

%$set% ipOutput="ipconfig"
call :ShowVariable ipOutput
echo First line is %ipOutput[0]%

echo( 
%$set% driveNames="wmic logicaldisk get name /value | findstr "Name""
call :ShowVariable driveNames

exit /b

:ShowVariable
setlocal EnableDelayedExpansion
for /L %%n in (0 1 !%~1.max!) do (
    echo %%n: !%~1[%%n]!
)
echo(
exit /b

:initMacro
if "!!"=="" (
    echo ERROR: Delayed Expansion must be disabled while defining macros
    (goto) 2>nul
    (goto) 2>nul
)
(set LF=^
%=empty=%
)
(set \n=^^^
%=empty=%
)

set $set=FOR /L %%N in (1 1 2) dO IF %%N==2 ( %\n%
    setlocal EnableDelayedExpansion                                 %\n%
    for /f "tokens=1,* delims== " %%1 in ("!argv!") do (            %\n%
        endlocal                                                    %\n%
        endlocal                                                    %\n%
        set "%%~1.Len=0"                                            %\n%
        set "%%~1="                                                 %\n%
        if "!!"=="" (                                               %\n%
            %= Used if delayed expansion is enabled =%              %\n%
                setlocal DisableDelayedExpansion                    %\n%
                for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %\n%
                if "!!" NEQ "" (                                    %\n%
                    endlocal                                        %\n%
                    )                                               %\n%
                setlocal DisableDelayedExpansion                    %\n%
                set "line=%%O"                                      %\n%
                setlocal EnableDelayedExpansion                     %\n%
                set pathExt=:                                       %\n%
                set path=;                                          %\n%
                set "line=!line:^=^^!"                              %\n%
                set "line=!line:"=q"^""!"                           %\n%
                call set "line=%%line:^!=q""^!%%"                   %\n%
                set "line=!line:q""=^!"                             %\n%
                set "line="!line:*:=!""                             %\n%
                for /F %%C in ("!%%~1.Len!") do (                   %\n%
                    FOR /F "delims=" %%L in ("!line!") Do (         %\n%
                        endlocal                                    %\n%
                        endlocal                                    %\n%
                        set "%%~1[%%C]=%%~L" !                      %\n%
                        if %%C == 0 (                               %\n%
                            set "%%~1=%%~L" !                       %\n%
                        ) ELSE (                                    %\n%
                            set "%%~1=!%%~1!!LF!%%~L" !             %\n%
                        )                                           %\n%
                    )                                               %\n%
                    set /a %%~1.Len+=1                              %\n%
                )                                                   %\n%
            )                                                       %\n%
        ) ELSE (                                                    %\n%
            %= Used if delayed expansion is disabled =%             %\n%
            for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %\n%
                setlocal DisableDelayedExpansion                    %\n%
                set "line=%%O"                                      %\n%
                setlocal EnableDelayedExpansion                     %\n%
                set "line="!line:*:=!""                             %\n%
                for /F %%C in ("!%%~1.Len!") DO (                   %\n%
                    FOR /F "delims=" %%L in ("!line!") DO (         %\n%
                        endlocal                                    %\n%
                        endlocal                                    %\n%
                        set "%%~1[%%C]=%%~L"                        %\n%
                    )                                               %\n%
                    set /a %%~1.Len+=1                              %\n%
                )                                                   %\n%
            )                                                       %\n%
        )                                                           %\n%
        set /a %%~1.Max=%%~1.Len-1                                  %\n%
)                                                                   %\n%
    ) else setlocal DisableDelayedExpansion^&set argv=

goto :eof

Renaming part of a filename

There are a couple of variants of a rename command, in your case, it may be as simple as

rename ABC XYZ *.dat

You may have a version which takes a Perl regex;

rename 's/ABC/XYZ/' *.dat

Is there Java HashMap equivalent in PHP?

$fruits = array (
    "fruits"  => array("a" => "Orange", "b" => "Banana", "c" => "Apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes"   => array("first", 5 => "second", "third")
);

echo $fruits["fruits"]["b"]

outputs 'Banana'

taken from http://in2.php.net/manual/en/function.array.php

convert iso date to milliseconds in javascript

if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);

How to delete the first row of a dataframe in R?

No one probably really wants to remove row one. So if you are looking for something meaningful, that is conditional selection

#remove rows that have long length and "0" value for vector E

>> setNew<-set[!(set$length=="long" & set$E==0),]

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

Just for other's reference, I just received this and found it was due to AngularJS. It's for backwards compatibility:

if (!event.preventDefault) {
    event.preventDefault = function() {
        event.returnValue = false; //ie
    };
}

How to find files recursively by file type and copy them to a directory while in ssh?

Something like this should work.

ssh [email protected] 'find -type f -name "*.pdf" -exec cp {} ./pdfsfolder \;'

Printing object properties in Powershell

The below worked really good for me. I patched together all the above answers plus read about displaying object properties in the following link and came up with the below short read about printing objects

add the following text to a file named print_object.ps1:

$date = New-Object System.DateTime
Write-Output $date | Get-Member
Write-Output $date | Select-Object -Property *

open powershell command prompt, go to the directory where that file exists and type the following:

powershell -ExecutionPolicy ByPass -File is_port_in_use.ps1 -Elevated

Just substitute 'System.DateTime' with whatever object you wanted to print. If the object is null, nothing will print out.

Socket.IO - how do I get a list of connected sockets/clients?

I see a lot of good answers here and many where quite useful but not quite what I needed. I am using sockets for a pubsub feature in which an interested client can listen to any changes in a given record.

My specific issue was that the same socket was joining the same room several times. The solution to this was to check if the socket had the room inside its rooms property already.

var room = myObj.id.toString();
if (socket.rooms.indexOf(room) === -1) {
    socket.join(room);
    socket.emit('subscribed', {to : room});
} else {
    console.log("Already in room");
}

Hope this helps someone.

Why am I not getting a java.util.ConcurrentModificationException in this example?

If you use copy-on-write collections it will work; however when you use list.iterator(), the returned Iterator will always reference the collection of elements as it was when ( as below ) list.iterator() was called, even if another thread modifies the collection. Any mutating methods called on a copy-on-write–based Iterator or ListIterator (such as add, set, or remove) will throw an UnsupportedOperationException.

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class RemoveListElementDemo {    
    private static final List<Integer> integerList;

    static {
        integerList = new CopyOnWriteArrayList<>();
        integerList.add(1);
        integerList.add(2);
        integerList.add(3);
    }

    public static void remove(Integer remove) {
        for(Integer integer : integerList) {
            if(integer.equals(remove)) {                
                integerList.remove(integer);
            }
        }
    }

    public static void main(String... args) {                
        remove(Integer.valueOf(2));

        Integer remove = Integer.valueOf(3);
        for(Integer integer : integerList) {
            if(integer.equals(remove)) {                
                integerList.remove(integer);
            }
        }
    }
}

Using moment.js to convert date to string "MM/dd/yyyy"

Use:

date.format("MM/DD/YYYY") or date.format("MM-DD-YYYY")}

Other Supported formats for reference:

Months:

M 1 2 ... 11 12

Mo 1st 2nd ... 11th 12th

MM 01 02 ... 11 12

MMM Jan Feb ... Nov Dec

MMMM January February ... November December

Day:

d 0 1 ... 5 6

do 0th 1st ... 5th 6th

dd Su Mo ... Fr Sa

ddd Sun Mon ... Fri Sat

dddd Sunday Monday ... Friday Saturday

Year:

YY 70 71 ... 29 30

YYYY 1970 1971 ... 2029 2030

Y 1970 1971 ... 9999 +10000 +10001

How to upload multiple files using PHP, jQuery and AJAX

Finally I have found the solution by using the following code:

$('body').on('click', '#upload', function(e){
        e.preventDefault();
        var formData = new FormData($(this).parents('form')[0]);

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            success: function (data) {
                alert("Data Uploaded: "+data);
            },
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });
        return false;
});

Binding Button click to a method

You have various possibilies. The most simple and the most ugly is:

XAML

<Button Name="cmdCommand" Click="Button_Clicked" Content="Command"/> 

Code Behind

private void Button_Clicked(object sender, RoutedEventArgs e) { 
    FrameworkElement fe=sender as FrameworkElement;
    ((YourClass)fe.DataContext).DoYourCommand();     
} 

Another solution (better) is to provide a ICommand-property on your YourClass. This command will have already a reference to your YourClass-object and therefore can execute an action on this class.

XAML

<Button Name="cmdCommand" Command="{Binding YourICommandReturningProperty}" Content="Command"/>

Because during writing this answer, a lot of other answers were posted, I stop writing more. If you are interested in one of the ways I showed or if you think I have made a mistake, make a comment.

Where are static variables stored in C and C++?

Where your statics go depends on whether they are zero-initialized. zero-initialized static data goes in .BSS (Block Started by Symbol), non-zero-initialized data goes in .DATA

Does it matter what extension is used for SQLite database files?

In distributable software, I dont want my customers mucking about in the database by themselves. The program reads and writes it all by itself. The only reason for a user to touch the DB file is to take a backup copy. Therefore I have named it whatever_records.db

The simple .db extension tells the user that it is a binary data file and that's all they have to know. Calling it .sqlite invites the interested user to open it up and mess something up!

Totally depends on your usage scenario I suppose.

How to check which PHP extensions have been enabled/disabled in Ubuntu Linux 12.04 LTS?

Perhaps the easiest way to see which extensions are (compiled and) loaded (not in cli) is to have a server run the following:

<?php
$ext = get_loaded_extensions();
asort($ext);
foreach ($ext as $ref) {
    echo $ref . "\n";
}

PHP cli does not necessarily have the same extensions loaded.

Node.js: Python not found exception due to node-sass and node-gyp

Node-sass tries to download the binary for you platform when installing. Node 5 is supported by 3.8 https://github.com/sass/node-sass/releases/tag/v3.8.0 If your Jenkins can't download the prebuilt binary, then you need to follow the platform requirements on Node-gyp README (Python2, VS or MSBuild, ...) If possible I'd suggest updating your Node to at least 6 since 5 isn't supported by Node anymore. If you want to upgrade to 8, you'll need to update node-sass to 4.5.3

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

Had this issue with a true HTTPS binding and the same exception with "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case...". After double checking everything in code and config, it seems like the error message is not so misleading as the inner exceptions, so after a quick check we've found out that the port 443 was hooked by skype (on the dev server). I recommend you take a look at what holding up the request (Fiddler could help here) and make sure you can reach the service front (view the .svc in your browser) and its metadata.

Good luck.

Specify sudo password for Ansible

If you are using the pass password manager, you can use the module passwordstore, which makes this very easy.

Let's say you saved your user's sudo password in pass as

Server1/User

Then you can use the decrypted value like so

{{ lookup('community.general.passwordstore', 'Server1/User')}}"

I use it in my inventory:

---
   servers:
     hosts:
       server1:
         ansible_become_pass: "{{ lookup('community.general.passwordstore', 'Server1/User')}}"

Note that you should be running gpg-agent so that you won't see a pinentry prompt every time a 'become' task is run.

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

How do I get the path to the current script with Node.js?

If you are using pkg to package your app, you'll find useful this expression:

appDirectory = require('path').dirname(process.pkg ? process.execPath : (require.main ? require.main.filename : process.argv[0]));
  • process.pkg tells if the app has been packaged by pkg.

  • process.execPath holds the full path of the executable, which is /usr/bin/node or similar for direct invocations of scripts (node test.js), or the packaged app.

  • require.main.filename holds the full path of the main script, but it's empty when Node runs in interactive mode.

  • __dirname holds the full path of the current script, so I'm not using it (although it may be what OP asks; then better use appDirectory = process.pkg ? require('path').dirname(process.execPath) : (__dirname || require('path').dirname(process.argv[0])); noting that in interactive mode __dirname is empty.

  • For interactive mode, use either process.argv[0] to get the path to the Node executable or process.cwd() to get the current directory.

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Try/catch does not seem to have an effect

If you want try/catch to work for all errors (not just the terminating errors) you can manually make all errors terminating by setting the ErrorActionPreference.

try {

   $ErrorActionPreference = "Stop"; #Make all errors terminating
   get-item filethatdoesntexist; # normally non-terminating
   write-host "You won't hit me";  
} catch{
   Write-Host "Caught the exception";
   Write-Host $Error[0].Exception;
}finally{
   $ErrorActionPreference = "Continue"; #Reset the error action pref to default
}

Alternatively... you can make your own trycatch function that accepts scriptblocks so that your try catch calls are not as kludge. I have mine return true/false just in case i need to check if there was an error... but it doesnt have to. Also, exception logging is optional, and can be taken care of in the catch, but i found myself always calling the logging function in the catch block, so i added it to the try catch function.

function log([System.String] $text){write-host $text;}

function logException{
    log "Logging current exception.";
    log $Error[0].Exception;
}


function mytrycatch ([System.Management.Automation.ScriptBlock] $try,
                    [System.Management.Automation.ScriptBlock] $catch,
                    [System.Management.Automation.ScriptBlock]  $finally = $({})){



# Make all errors terminating exceptions.
    $ErrorActionPreference = "Stop";

    # Set the trap
    trap [System.Exception]{
        # Log the exception.
        logException;

        # Execute the catch statement
        & $catch;

        # Execute the finally statement
        & $finally

        # There was an exception, return false
        return $false;
    }

    # Execute the scriptblock
    & $try;

    # Execute the finally statement
    & $finally

    # The following statement was hit.. so there were no errors with the scriptblock
    return $true;
}


#execute your own try catch
mytrycatch {
        gi filethatdoesnotexist; #normally non-terminating
        write-host "You won't hit me."
    } {
        Write-Host "Caught the exception";
    }

How to configure postgresql for the first time?

There are two methods you can use. Both require creating a user and a database.

  1. Using createuser and createdb,

    $ sudo -u postgres createuser --superuser $USER
    $ createdb mydatabase
    $ psql -d mydatabase
    
  2. Using the SQL administration commands, and connecting with a password over TCP

    $ sudo -u postgres psql postgres
    

    And, then in the psql shell

    CREATE ROLE myuser LOGIN PASSWORD 'mypass';
    CREATE DATABASE mydatabase WITH OWNER = myuser;
    

    Then you can login,

    $ psql -h localhost -d mydatabase -U myuser -p <port>
    

    If you don't know the port, you can always get it by running the following, as the postgres user,

    SHOW port;
    

    Or,

    $ grep "port =" /etc/postgresql/*/main/postgresql.conf
    

Sidenote: the postgres user

I suggest NOT modifying the postgres user.

  1. It's normally locked from the OS. No one is supposed to "log in" to the operating system as postgres. You're supposed to have root to get to authenticate as postgres.
  2. It's normally not password protected and delegates to the host operating system. This is a good thing. This normally means in order to log in as postgres which is the PostgreSQL equivalent of SQL Server's SA, you have to have write-access to the underlying data files. And, that means that you could normally wreck havoc anyway.
  3. By keeping this disabled, you remove the risk of a brute force attack through a named super-user. Concealing and obscuring the name of the superuser has advantages.

.NET DateTime to SqlDateTime Conversion

If you are checking for DBNULL, converting a SQL Datetime to a .NET DateTime should not be a problem. However, you can run into problems converting a .NET DateTime to a valid SQL DateTime.

SQL Server does not recognize dates prior to 1/1/1753. Thats the year England adopted the Gregorian Calendar. Usually checking for DateTime.MinValue is sufficient, but if you suspect that the data could have years before the 18th century, you need to make another check or use a different data type. (I often wonder what Museums use in their databases)

Checking for max date is not really necessary, SQL Server and .NET DateTime both have a max date of 12/31/9999 It may be a valid business rule but it won't cause a problem.

How to split a comma-separated value to columns

Using instring function :)

select Value, 
       substring(String,1,instr(String," ") -1) Fname,  
       substring(String,instr(String,",") +1) Sname 
from tablename;

Used two functions,
1. substring(string, position, length) ==> returns string from positon to length
2. instr(string,pattern) ==> returns position of pattern.

If we don’t provide length argument in substring it returns until end of string

Java file path in Linux

I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.

File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");

How to convert numbers between hexadecimal and decimal

Here is my function:

using System;
using System.Collections.Generic;
class HexadecimalToDecimal
{
    static Dictionary<char, int> hexdecval = new Dictionary<char, int>{
        {'0', 0},
        {'1', 1},
        {'2', 2},
        {'3', 3},
        {'4', 4},
        {'5', 5},
        {'6', 6},
        {'7', 7},
        {'8', 8},
        {'9', 9},
        {'a', 10},
        {'b', 11},
        {'c', 12},
        {'d', 13},
        {'e', 14},
        {'f', 15},
    };

    static decimal HexToDec(string hex)
    {
        decimal result = 0;
        hex = hex.ToLower();

        for (int i = 0; i < hex.Length; i++)
        {
            char valAt = hex[hex.Length - 1 - i];
            result += hexdecval[valAt] * (int)Math.Pow(16, i);
        }

        return result;
    }

    static void Main()
    {

        Console.WriteLine("Enter Hexadecimal value");
        string hex = Console.ReadLine().Trim();

        //string hex = "29A";
        Console.WriteLine("Hex {0} is dec {1}", hex, HexToDec(hex));

        Console.ReadKey();
    }
}

jQuery - hashchange event

Note that in case of IE 7 and IE 9 if statment will give true for ("onhashchange" in windows) but the window.onhashchange will never fire, so its better to store hash and check it after every 100 millisecond whether its changed or not for all versions of IE.

    if (("onhashchange" in window) && !($.browser.msie)) { 
         window.onhashchange = function () { 
              alert(window.location.hash);             
         }            
         // Or $(window).bind( 'hashchange',function(e) {  
         //       alert(window.location.hash); 
         //   });              
    }
    else { 
        var prevHash = window.location.hash;
        window.setInterval(function () {
           if (window.location.hash != prevHash) {
              prevHash = window.location.hash;
              alert(window.location.hash);
           }
        }, 100);
    }

(How) can I count the items in an enum?

How about traits, in an STL fashion? For instance:

enum Foo
{
    Bar,
    Baz
};

write an

std::numeric_limits<enum Foo>::max()

specialization (possibly constexpr if you use c++11). Then, in your test code provide any static assertions to maintain the constraints that std::numeric_limits::max() = last_item.

[Ljava.lang.Object; cannot be cast to

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to id.co.bni.switcherservice.model.SwitcherServiceSource

Problem is

(List<SwitcherServiceSource>) LoadSource.list();

This will return a List of Object arrays (Object[]) with scalar values for each column in the SwitcherServiceSource table. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values.

Solution

List<Object> result = (List<Object>) LoadSource.list(); 
Iterator itr = result.iterator();
while(itr.hasNext()){
   Object[] obj = (Object[]) itr.next();
   //now you have one array of Object for each row
   String client = String.valueOf(obj[0]); // don't know the type of column CLIENT assuming String 
   Integer service = Integer.parseInt(String.valueOf(obj[1])); //SERVICE assumed as int
   //same way for all obj[2], obj[3], obj[4]
}

Related link

JSON Stringify changes time of date because of UTC

JavaScript normally convert local timezone to UTC .

date = new Date();
date.setMinutes(date.getMinutes()-date.getTimezoneOffset())
JSON.stringify(date)

How do I revert to a previous package in Anaconda?

I had to use the install function instead:

conda install pandas=0.13.1

How do I "select Android SDK" in Android Studio?

Follow these steps:

  • Goto Android Studio Settings
  • Search for "Android SDK" using search bar
  • Ensure the path to your android sdk folder is correct.
  • After that also ensure the path is automatically updated after a prompt in your project (local.properties) file. If not, do it manually.

Hope this helps.

change type of input field with jQuery

I just did the following to change the type of an input:

$('#ID_of_element')[0].type = 'text';

and it works.

I was needing to do this because I was using jQuery UI datepickers' in an ASP NET Core 3.1 project and they were not working properly on Chromium-based browsers (see: https://stackoverflow.com/a/61296225/7420301).

Counting Chars in EditText Changed Listener

This is a slightly more general answer with more explanation for future viewers.

Add a text changed listener

If you want to find the text length or do something else after the text has been changed, you can add a text changed listener to your edit text.

EditText editText = (EditText) findViewById(R.id.testEditText);
editText.addTextChangedListener(new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count)  {

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});

The listener needs a TextWatcher, which requires three methods to be overridden: beforeTextChanged, onTextChanged, and afterTextChanged.

Counting the characters

You can get the character count in onTextChanged or beforeTextChanged with

charSequence.length()

or in afterTextChanged with

editable.length()

Meaning of the methods

The parameters are a little confusing so here is a little extra explanation.

beforeTextChanged

beforeTextChanged(CharSequence charSequence, int start, int count, int after)

  • charSequence: This is the text content before the pending change is made. You should not try to change it.
  • start: This is the index of where the new text will be inserted. If a range is selected, then it is the beginning index of the range.
  • count: This is the length of selected text that is going to be replaced. If nothing is selected then count will be 0.
  • after: this is the length of the text to be inserted.

onTextChanged

onTextChanged(CharSequence charSequence, int start, int before, int count)

  • charSequence: This is the text content after the change was made. You should not try to modify this value here. Modify the editable in afterTextChanged if you need to.
  • start: This is the index of the start of where the new text was inserted.
  • before: This is the old value. It is the length of previously selected text that was replaced. This is the same value as count in beforeTextChanged.
  • count: This is the length of text that was inserted. This is the same value as after in beforeTextChanged.

afterTextChanged

afterTextChanged(Editable editable)

Like onTextChanged, this is called after the change has already been made. However, now the text may be modified.

  • editable: This is the editable text of the EditText. If you change it, though, you have to be careful not to get into an infinite loop. See the documentation for more details.

Supplemental image from this answer

enter image description here

how to run a command at terminal from java program?

I don't know why, but for some reason, the "/bin/bash" version didn't work for me. Instead, the simpler version worked, following the example given here at Oracle Docs.

String[] args = new String[] {"ping", "www.google.com"};
Process proc = new ProcessBuilder(args).start();

pip3: command not found but python3-pip is already installed

You can make symbolic link to you pip3:

sudo ln -s $(which pip3) /usr/bin/pip3

It helps me in RHEL 7.6

How to choose between Hudson and Jenkins?

Use Jenkins.

Jenkins is the recent fork by the core developers of Hudson. To understand why, you need to know the history of the project. It was originally open source and supported by Sun. Like much of what Sun did, it was fairly open, but there was a bit of benign neglect. The source, trackers, website, etc. were hosted by Sun on their relatively closed java.net platform.

Then Oracle bought Sun. For various reasons Oracle has not been shy about leveraging what it perceives as its assets. Those include some control over the logistic platform of Hudson, and particularly control over the Hudson name. Many users and contributors weren't comfortable with that and decided to leave.

So it comes down to what Hudson vs Jenkins offers. Both Oracle's Hudson and Jenkins have the code. Hudson has Oracle and Sonatype's corporate support and the brand. Jenkins has most of the core developers, the community, and (so far) much more actual work.

Read that post I linked up top, then read the rest of these in chronological order. For balance you can read the Hudson/Oracle take on it. It's pretty clear to me who is playing defensive and who has real intentions for the project.

How to get UTF-8 working in Java webapps?

I'm with a similar problem, but, in filenames of a file I'm compressing with apache commons. So, i resolved it with this command:

convmv --notest -f cp1252 -t utf8 * -r

it works very well for me. Hope it help anyone ;)

The SQL OVER() clause - when and why is it useful?

If you only wanted to GROUP BY the SalesOrderID then you wouldn't be able to include the ProductID and OrderQty columns in the SELECT clause.

The PARTITION BY clause let's you break up your aggregate functions. One obvious and useful example would be if you wanted to generate line numbers for order lines on an order:

SELECT
    O.order_id,
    O.order_date,
    ROW_NUMBER() OVER(PARTITION BY O.order_id) AS line_item_no,
    OL.product_id
FROM
    Orders O
INNER JOIN Order_Lines OL ON OL.order_id = O.order_id

(My syntax might be off slightly)

You would then get back something like:

order_id    order_date    line_item_no    product_id
--------    ----------    ------------    ----------
    1       2011-05-02         1              5
    1       2011-05-02         2              4
    1       2011-05-02         3              7
    2       2011-05-12         1              8
    2       2011-05-12         2              1

“Unable to find manifest signing certificate in the certificate store” - even when add new key

Go to your projects "Properties" within visual studio. Then go to signing tab.

Then make sure Sign the Click Once manifests is turned off.

OR

1.Open the .csproj file in Notepad.

2.Delete the following information related to signing certificate in the certificate store xxxxx xxxxxx xxxxxxxx.pfx true false `

Worked for me.

Printing a 2D array in C

Is this any help?

#include <stdio.h>

#define MAX 10

int main()
{
    char grid[MAX][MAX];
    int i,j,row,col;

    printf("Please enter your grid size: ");
    scanf("%d %d", &row, &col);


    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            grid[i][j] = '.';
            printf("%c ", grid[i][j]);
        }
        printf("\n");
    }

    return 0;
}

How do I do pagination in ASP.NET MVC?

Well, what is the data source? Your action could take a few defaulted arguments, i.e.

ActionResult Search(string query, int startIndex, int pageSize) {...}

defaulted in the routes setup so that startIndex is 0 and pageSize is (say) 20:

        routes.MapRoute("Search", "Search/{query}/{startIndex}",
                        new
                        {
                            controller = "Home", action = "Search",
                            startIndex = 0, pageSize = 20
                        });

To split the feed, you can use LINQ quite easily:

var page = source.Skip(startIndex).Take(pageSize);

(or do a multiplication if you use "pageNumber" rather than "startIndex")

With LINQ-toSQL, EF, etc - this should "compose" down to the database, too.

You should then be able to use action-links to the next page (etc):

<%=Html.ActionLink("next page", "Search", new {
                query, startIndex = startIndex + pageSize, pageSize }) %>

Determine which element the mouse pointer is on top of in JavaScript

The target of the mousemove DOM event is the top-most DOM element under the cursor when the mouse moves:

(function(){
    //Don't fire multiple times in a row for the same element
    var prevTarget=null;
    document.addEventListener('mousemove', function(e) {
        //This will be the top-most DOM element under cursor
        var target=e.target;
        if(target!==prevTarget){
            console.log(target);
            prevTarget=target;
        }
    });
})();

This is similar to @Philip Walton's solution, but doesn't require jQuery or a setInterval.

Check for a substring in a string in Oracle without LIKE

You can do it this way using INSTR:

SELECT * FROM users WHERE INSTR(LOWER(last_name), 'z') > 0;

INSTR returns zero if the substring is not in the string.

Out of interest, why don't you want to use like?

Edit: I took the liberty of making the search case insensitive so you don't miss Bob Zebidee. :-)

PostgreSQL: How to make "case-insensitive" query

You can also read up on the ILIKE keyword. It can be quite useful at times, albeit it does not conform to the SQL standard. See here for more information: http://www.postgresql.org/docs/9.2/static/functions-matching.html

Select <a> which href ends with some string

$("a[href*=ABC]").addClass('selected');

How to select records without duplicate on just one field in SQL?

Ignore duplicate rows in SQL. I think this may help you.

    SELECT res2.*
    FROM
    (SELECT res1.*,ROW_NUMBER() OVER(PARTITION BY res1.title ORDER BY res1.id)as num
     FROM 
    (select * from [dbo].[tbl_countries])as res1
    )as res2
    WHERE res2.num=1

How to copy a row and insert in same table with a autoincrement field in MySQL?

Say the table is user(id, user_name, user_email).

You can use this query:

INSERT INTO user (SELECT NULL,user_name, user_email FROM user WHERE id = 1)

Sort array of objects by single key with date value

Data Imported

[
    {
        "gameStatus": "1",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-20 11:32:04"
    },
    {
        "gameStatus": "0",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 18:08:24"
    },
    {
        "gameStatus": "2",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 18:35:40"
    },
    {
        "gameStatus": "0",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 10:42:53"
    },
    {
        "gameStatus": "2",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-20 10:54:09"
    },
    {
        "gameStatus": "0",
        "userId": "1a2fefb0-5ae2-47eb-82ff-d1b2cc27875a",
        "created_at": "2018-12-19 18:46:22"
    },
    {
        "gameStatus": "1",
        "userId": "7118ed61-d8d9-4098-a81b-484158806d21",
        "created_at": "2018-12-20 10:50:48"
    }
]

FOR Ascending order

arr.sort(function(a, b){
    var keyA = new Date(a.updated_at),
        keyB = new Date(b.updated_at);
    // Compare the 2 dates
    if(keyA < keyB) return -1;
    if(keyA > keyB) return 1;
    return 0;
});

Example for Asc Order

[
    {
        "gameStatus": "0",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 10:42:53"
    },
    {
        "gameStatus": "0",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 18:08:24"
    },
    {
        "gameStatus": "2",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 18:35:40"
    },
    {
        "gameStatus": "0",
        "userId": "1a2fefb0-5ae2-47eb-82ff-d1b2cc27875a",
        "created_at": "2018-12-19 18:46:22"
    },
    {
        "gameStatus": "1",
        "userId": "7118ed61-d8d9-4098-a81b-484158806d21",
        "created_at": "2018-12-20 10:50:48"
    },
    {
        "gameStatus": "2",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-20 10:54:09"
    },
    {
        "gameStatus": "1",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-20 11:32:04"
    }
]

FOR Descending order

arr.sort(function(a, b){
    var keyA = new Date(a.updated_at),
        keyB = new Date(b.updated_at);
    // Compare the 2 dates
    if(keyA > keyB) return -1;
    if(keyA < keyB) return 1;
    return 0;
});

Example for Desc Order

[
    {
        "gameStatus": "1",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-20 11:32:04"
    },
    {
        "gameStatus": "2",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-20 10:54:09"
    },
    {
        "gameStatus": "1",
        "userId": "7118ed61-d8d9-4098-a81b-484158806d21",
        "created_at": "2018-12-20 10:50:48"
    },
    {
        "gameStatus": "0",
        "userId": "1a2fefb0-5ae2-47eb-82ff-d1b2cc27875a",
        "created_at": "2018-12-19 18:46:22"
    },
    {
        "gameStatus": "2",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 18:35:40"
    },
    {
        "gameStatus": "0",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 18:08:24"
    },
    {
        "gameStatus": "0",
        "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
        "created_at": "2018-12-19 10:42:53"
    }
]

How do you parse and process HTML/XML in PHP?

XML_HTMLSax is rather stable - even if it's not maintained any more. Another option could be to pipe you HTML through Html Tidy and then parse it with standard XML tools.

System.BadImageFormatException: Could not load file or assembly

My cause was different I referenced a web service then I got this message.

Then I changed my target .Net Framework 4.0 to .Net Framework 2.0 and re-refer my webservice. After a few changes problem solved. There is no error worked fine.

hope this helps!

Intermediate language used in scalac?

The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/

You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.

Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?

Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.

How to get access to raw resources that I put in res folder?

InputStream in = getResources().openRawResource(resourceName);

This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.

Edit
Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.

Pandas - Plotting a stacked Bar Chart

Are you getting errors, or just not sure where to start?

%pylab inline
import pandas as pd
import matplotlib.pyplot as plt

df2 = df.groupby(['Name', 'Abuse/NFF'])['Name'].count().unstack('Abuse/NFF').fillna(0)
df2[['abuse','nff']].plot(kind='bar', stacked=True)

stacked bar plot

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

in FF use inline style i.e.

<img src="..." class="img-responsive" style="width:100%; height:auto;" />

It rocks :)

What is the standard way to add N seconds to datetime.time in Python?

In a real world environment it's never a good idea to work solely with time, always use datetime, even better utc, to avoid conflicts like overnight, daylight saving, different timezones between user and server etc.

So I'd recommend this approach:

import datetime as dt

_now = dt.datetime.now()  # or dt.datetime.now(dt.timezone.utc)
_in_5_sec = _now + dt.timedelta(seconds=5)

# get '14:39:57':
_in_5_sec.strftime('%H:%M:%S')

Uncaught TypeError: Cannot read property 'top' of undefined

Your document does not contain any element with class content-nav, thus the method .offset() returns undefined which indeed has no top property.

You can see for yourself in this fiddle

alert($('.content-nav').offset());

(you will see "undefined")

To avoid crashing the whole code, you can have such code instead:

var top = ($('.content-nav').offset() || { "top": NaN }).top;
if (isNaN(top)) {
    alert("something is wrong, no top");
} else {
    alert(top);
}

Updated fiddle.

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

In this Eclipse Preferences panel you can change the compiler compatibility from 1.7 to 1.6. This solved the similar message I was getting. For Eclipse, it is under: Preferences -> Java -> Compiler: 'Compiler compliance level'

C# Return Different Types?

Let the method return a object from a common baseclass or interface.

public class TV:IMediaPlayer
{
   void Play(){};
}

public class Radio:IMediaPlayer
{
   void Play(){};
}

public interface IMediaPlayer
{
   void Play():
}

public class Test
{
  public void Main()
  {
     IMediaPlayer player = GetMediaPlayer();
     player.Play();
  }


  private IMediaPlayer GetMediaPlayer()
  {
     if(...)
        return new TV();
     else
        return new Radio();
  }
}

How to find if a given key exists in a C++ std::map

map<string, string> m;

check key exist or not, and return number of occurs(0/1 in map):

int num = m.count("f");  
if (num>0) {    
    //found   
} else {  
    // not found  
}

check key exist or not, and return iterator:

map<string,string>::iterator mi = m.find("f");  
if(mi != m.end()) {  
    //found  
    //do something to mi.  
} else {  
    // not found  
}  

in your question, the error caused by bad operator<< overload, because p.first is map<string, string>, you can not print it out. try this:

if(p.first != p.second) {
    cout << p.first->first << " " << p.first->second << endl;
}

What is the equivalent of the C# 'var' keyword in Java?

I know this is older but why not create a var class and create constructors with different types and depending on what constructors gets invoked you get var with different type. You could even build in methods to convert one type to another.

Checking if a collection is null or empty in Groovy

There is indeed a Groovier Way.

if(members){
    //Some work
}

does everything if members is a collection. Null check as well as empty check (Empty collections are coerced to false). Hail Groovy Truth. :)

css overflow - only 1 line of text

the best code for UX and UI is

white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
display: inherit;

How can I format DateTime to web UTC format?

Why don't just use The Round-trip ("O", "o") Format Specifier?

The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information and emits a result string that complies with ISO 8601. For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. The formatted string can be parsed back by using the DateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind.

The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values. In this string, the pairs of single quotation marks that delimit individual characters, such as the hyphens, the colons, and the letter "T", indicate that the individual character is a literal that cannot be changed. The apostrophes do not appear in the output string.

The O" or "o" standard format specifier (and the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string) takes advantage of the three ways that ISO 8601 represents time zone information to preserve the Kind property of DateTime values:

public class Example
{
   public static void Main()
   {
       DateTime dat = new DateTime(2009, 6, 15, 13, 45, 30, 
                                   DateTimeKind.Unspecified);
       Console.WriteLine("{0} ({1}) --> {0:O}", dat, dat.Kind); 

       DateTime uDat = new DateTime(2009, 6, 15, 13, 45, 30, 
                                    DateTimeKind.Utc);
       Console.WriteLine("{0} ({1}) --> {0:O}", uDat, uDat.Kind);

       DateTime lDat = new DateTime(2009, 6, 15, 13, 45, 30, 
                                    DateTimeKind.Local);
       Console.WriteLine("{0} ({1}) --> {0:O}\n", lDat, lDat.Kind);

       DateTimeOffset dto = new DateTimeOffset(lDat);
       Console.WriteLine("{0} --> {0:O}", dto);
   }
}
// The example displays the following output: 
//    6/15/2009 1:45:30 PM (Unspecified) --> 2009-06-15T13:45:30.0000000 
//    6/15/2009 1:45:30 PM (Utc) --> 2009-06-15T13:45:30.0000000Z 
//    6/15/2009 1:45:30 PM (Local) --> 2009-06-15T13:45:30.0000000-07:00 
//     
//    6/15/2009 1:45:30 PM -07:00 --> 2009-06-15T13:45:30.0000000-07:00

Replacing instances of a character in a string

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]

usernames = []

for i in names:
    if " " in i:
        i = i.replace(" ", "_")
    print(i)

Output: Joey_Tribbiani Monica_Geller Chandler_Bing Phoebe_Buffay

How to find Oracle Service Name

With SQL Developer you should also find it without writing any query. Right click on your Connection/Propriety.

You should see the name on the left under something like "connection details" and should look like "Connectionname@servicename", or on the right, under the connection's details.

ASP.NET postback with JavaScript

While Phairoh's solution seems theoretically sound, I have also found another solution to this problem. By passing the UpdatePanels id as a paramater (event target) for the doPostBack function the update panel will post back but not the entire page.

__doPostBack('myUpdatePanelId','')

*note: second parameter is for addition event args

hope this helps someone!

EDIT: so it seems this same piece of advice was given above as i was typing :)

How do I Search/Find and Replace in a standard string?

In C++11, you can do this as a one-liner with a call to regex_replace:

#include <string>
#include <regex>

using std::string;

string do_replace( string const & in, string const & from, string const & to )
{
  return std::regex_replace( in, std::regex(from), to );
}

string test = "Remove all spaces";
std::cout << do_replace(test, " ", "") << std::endl;

output:

Removeallspaces

What is the best way to call a script from another script?

import os

os.system("python myOtherScript.py arg1 arg2 arg3")  

Using os you can make calls directly to your terminal. If you want to be even more specific you can concatenate your input string with local variables, ie.

command = 'python myOtherScript.py ' + sys.argv[1] + ' ' + sys.argv[2]
os.system(command)

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

First, install QEMU. On Debian-based distributions like Ubuntu, run:

$ apt-get install qemu

Then run the following command:

$ qemu-img convert -O vmdk imagefile.dd vmdkname.vmdk

I’m assuming a flat disk image is a dd-style image. The convert operation also handles numerous other formats.

For more information about the qemu-img command, see the output of

$ qemu-img -h

Oracle SQL Query for listing all Schemas in a DB

Using sqlplus

sqlplus / as sysdba

run:

SELECT * 
FROM dba_users

Should you only want the usernames do the following:

SELECT username 
FROM dba_users

Open Popup window using javascript

First point is- showing multiple popups is not desirable in terms of usability.

But you can achieve it by using multiple popup names

var newwindow;
function createPop(url, name)
{    
   newwindow=window.open(url,name,'width=560,height=340,toolbar=0,menubar=0,location=0');  
   if (window.focus) {newwindow.focus()}
}

Better approach will be showing both in a single page in two different iFrames or Divs.

Update:

So I will suggest to create a new tab in the test.aspx page to show the report, instead of replacing the image content and placing the pdf.

Refresh Part of Page (div)

Usefetch and innerHTML to load div content

_x000D_
_x000D_
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"

async function refresh() {
  btn.disabled = true;
  dynamicPart.innerHTML = "Loading..."
  dynamicPart.innerHTML = await(await fetch(url)).text();
  setTimeout(refresh,2000);
}
_x000D_
<div id="staticPart">
  Here is static part of page

  <button id="btn" onclick="refresh()">
    Click here to start refreshing every 2s
  </button>
</div>

<div id="dynamicPart">Dynamic part</div>
_x000D_
_x000D_
_x000D_

ImportError: cannot import name

Instead of using local imports, you may import the entire module instead of the particular object. Then, in your app module, call mod_login.mod_login

app.py

from flask import Flask
import mod_login

# ...

do_stuff_with(mod_login.mod_login)

mod_login.py

from app import app

mod_login = something

iPhone UITextField - Change placeholder text color

The following only with iOS6+ (as indicated in Alexander W's comment):

UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
   [[NSAttributedString alloc]
       initWithString:@"Full Name"
       attributes:@{NSForegroundColorAttributeName:color}];

HTML 5: Is it <br>, <br/>, or <br />?

Both <br> and <br/> will do fine but I prefer <br/> because it's slightly more logical. It is logical to expect a closing tag whenever there is an opening tag. Therefore your code is slightly easier to read if you don't use an opening tag when there isn't going to be a closing tag.

All browser (except possibly some very old ones that don't matter) will display both exactly the same. However, <br> is not xHTML complient.

Why is Event.target not Element in Typescript?

Could you create your own generic interface that extends Event. Something like this?

interface DOMEvent<T extends EventTarget> extends Event {
  target: T
}

Then you can use it like:

handleChange(event: DOMEvent<HTMLInputElement>) {
  this.setState({ value: event.target.value });
}

How to execute a .bat file from a C# windows form app?

For the problem you're having about the batch file asking the user if the destination is a folder or file, if you know the answer in advance, you can do as such:

If destination is a file: echo f | [batch file path]

If folder: echo d | [batch file path]

It will essentially just pipe the letter after "echo" to the input of the batch file.

T-SQL get SELECTed value of stored procedure

Try do this:

EXEC @SelectedValue = GetMyInt

Using CMake with GNU Make: How can I see the exact commands?

Or simply export VERBOSE environment variable on the shell like this: export VERBOSE=1

Where to put default parameter value in C++?

You can do either, but never both. Usually you do it at function declaration and then all callers can use that default value. However you can do that at function definition instead and then only those who see the definition will be able to use the default value.

Declare an empty two-dimensional array in Javascript?

_x000D_
_x000D_
var arr = [];_x000D_
var rows = 3;_x000D_
var columns = 2;_x000D_
_x000D_
for (var i = 0; i < rows; i++) {_x000D_
    arr.push([]); // creates arrays in arr_x000D_
}_x000D_
console.log('elements of arr are arrays:');_x000D_
console.log(arr);_x000D_
_x000D_
for (var i = 0; i < rows; i++) {_x000D_
    for (var j = 0; j < columns; j++) {_x000D_
        arr[i][j] = null; // empty 2D array: it doesn't make much sense to do this_x000D_
    }_x000D_
}_x000D_
console.log();_x000D_
console.log('empty 2D array:');_x000D_
console.log(arr);_x000D_
_x000D_
for (var i = 0; i < rows; i++) {_x000D_
    for (var j = 0; j < columns; j++) {_x000D_
        arr[i][j] = columns * i + j + 1;_x000D_
    }_x000D_
}_x000D_
console.log();_x000D_
console.log('2D array filled with values:');_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Find the max of two or more columns with pandas

You can get the maximum like this:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]]
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]].max(axis=1)
0    1
1    8
2    3

and so:

>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

If you know that "A" and "B" are the only columns, you could even get away with

>>> df["C"] = df.max(axis=1)

And you could use .apply(max, axis=1) too, I guess.

Javascript - get array of dates between 2 dates

I use this function

function getDatesRange(startDate, stopDate) {
    const ONE_DAY = 24*3600*1000;
    var days= [];
    var currentDate = new Date(startDate);
    while (currentDate <= stopDate) {
        days.push(new Date (currentDate));
        currentDate = currentDate - 1 + 1 + ONE_DAY;
    }
    return days;
}

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

I prefer this solution:

df = spark.table(selected_table).filter(condition)

counter = df.count()

df = df.select([(counter - count(c)).alias(c) for c in df.columns])

Angular - ui-router get previous state

Add a new property called {previous} to $state on $stateChangeStart

$rootScope.$on( '$stateChangeStart', ( event, to, toParams, from, fromParams ) => {
    // Add {fromParams} to {from}
    from.params = fromParams;

    // Assign {from} to {previous} in $state
    $state.previous = from;
    ...
}

Now anywhere you need can use $state you will have previous available

previous:Object
    name:"route name"
    params:Object
        someParam:"someValue"
    resolve:Object
    template:"route template"
    url:"/route path/:someParam"

And use it like so:

$state.go( $state.previous.name, $state.previous.params );

cannot load such file -- bundler/setup (LoadError)

After spend a lot time, trying follow these answers actually after code below it worked for me. Before do it just but be sure that there is no problem in update :)

gem update --system

How do I find the date a video (.AVI .MP4) was actually recorded?

Quick Command for Finding Date/Time Metadata in Many Video Files

The following command has served me well in finding date/time metadata on various AVI/MP4 videos:

ffmpeg -i /path/to/video.mp4 -dump

Note: as mentioned in other answers, there is no guarantee that such information is available in all video files or available in a specific format.

Abbreviated Sample Output for Some AVI File

    Metadata:
      Make            : FUJIFILM
      Model           : FinePix AX655
      DateTime        : 2014:08:25 05:19:45
      JPEGInterchangeFormat:     658
      JPEGInterchangeFormatLength:    1521
      Copyright       :     
      DateTimeOriginal: 2014:08:25 05:19:45
      DateTimeDigitized: 2014:08:25 05:19:45

Abbreviated Sample Output for Some MP4 File

  Metadata:
    major_brand     : mp41
    minor_version   : 538120216
    compatible_brands: mp41
    creation_time   : 2018-03-13T15:43:24.000000Z

How to load/reference a file as a File instance from the classpath

Try getting hold of a URL for your classpath resource:

URL url = this.getClass().getResource("/com/path/to/file.txt")

Then create a file using the constructor that accepts a URI:

File file = new File(url.toURI());

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

WHERE Clause to find all records in a specific month

SELECT * FROM yourtable WHERE yourtimestampfield LIKE 'AAAA-MM%';

Where AAAA is the year you want and MM is the month you want

convert string to number node.js

Not a full answer Ok so this is just to supplement the information about parseInt, which is still very valid. Express doesn't allow the req or res objects to be modified at all (immutable). So if you want to modify/use this data effectively, you must copy it to another variable (var year = req.params.year).

Write output to a text file in PowerShell

Another way this could be accomplished is by using the Start-Transcript and Stop-Transcript commands, respectively before and after command execution. This would capture the entire session including commands.

Start-Transcript

Stop-Transcript

For this particular case Out-File is probably your best bet though.

PHP "pretty print" json_encode

And for PHP 5.3, you can use this function, which can be embedded in a class or used in procedural style:

http://svn.kd2.org/svn/misc/libs/tools/json_readable_encode.php

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

Ensure that the permissions on your home directory and on the home directory of the user on the host you're connecting to are set to 700 ( owning user rwx only to prevent others seeing the .ssh subdirectory ).

Then ensure that the ~/.ssh directory is also 700 ( user rwx ) and that the authorized_keys is 600 ( user rw ) .

Private keys in your ~/.ssh directory should be 600 or 400 ( user rw or user r )

How to retrieve field names from temporary table (SQL Server 2008)

To use information_schema and not collide with other sessions:

select * 
from tempdb.INFORMATION_SCHEMA.COLUMNS
where table_name =
    object_name(
        object_id('tempdb..#test'),
        (select database_id from sys.databases where name = 'tempdb'))

Adding line break in C# Code behind page

C# doesn't have an explicit line break character. You statements end with a semicolon so you can span your statements over many lines. These are both the same:

public string GenerateString()
{
    return "abc" + "def";
}

public string GenerateString()
{
    return
        "abc" +
        "def";
}

jQuery remove options from select

if your dropdown is in a table and you do not have id for it then you can use the following jquery:

var select_object = purchasing_table.rows[row_index].cells[cell_index].childNodes[1];
$(select_object).find('option[value='+site_name+']').remove();