Programs & Examples On #Columnheader

How can I suppress column header output for a single SQL statement?

You can fake it like this:

-- with column headings 
select column1, column2 from some_table;

-- without column headings
select column1 as '', column2 as '' from some_table;

How do I extract text that lies between parentheses (round brackets)?

Assuming that you only have one pair of parenthesis.

string s = "User name (sales)";
int start = s.IndexOf("(") + 1;
int end = s.IndexOf(")", start);
string result = s.Substring(start, end - start);

How to set session timeout in web.config

Use this in web.config:

<sessionState 

  timeout="20" 
/>

Split a string into array in Perl

Splitting a string by whitespace is very simple:

print $_, "\n" for split ' ', 'file1.gz file1.gz file3.gz';

This is a special form of split actually (as this function usually takes patterns instead of strings):

As another special case, split emulates the default behavior of the command line tool awk when the PATTERN is either omitted or a literal string composed of a single space character (such as ' ' or "\x20"). In this case, any leading whitespace in EXPR is removed before splitting occurs, and the PATTERN is instead treated as if it were /\s+/; in particular, this means that any contiguous whitespace (not just a single space character) is used as a separator.


Here's an answer for the original question (with a simple string without any whitespace):

Perhaps you want to split on .gz extension:

my $line = "file1.gzfile1.gzfile3.gz";
my @abc = split /(?<=\.gz)/, $line;
print $_, "\n" for @abc;

Here I used (?<=...) construct, which is look-behind assertion, basically making split at each point in the line preceded by .gz substring.

If you work with the fixed set of extensions, you can extend the pattern to include them all:

my $line = "file1.gzfile2.txtfile2.gzfile3.xls";
my @exts = ('txt', 'xls', 'gz');
my $patt = join '|', map { '(?<=\.' . $_ . ')' } @exts;
my @abc = split /$patt/, $line;
print $_, "\n" for @abc;

Remove characters from NSString?

All above will works fine. But the right method is this:

yourString = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

It will work like a TRIM method. It will remove all front and back spaces.

Thanks

HttpClient 4.0.1 - how to release connection?

I had the same issue and solved it by closing the response at the end of the method:

try {
    // make the request and get the entity 
} catch(final Exception e) {
    // handle the exception
} finally {
    if(response != null) {
        response.close();
    }
}

HTML - Display image after selecting filename

You can achieve this with the following code:

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

Demo: http://jsfiddle.net/ugPDx/

Android: Create spinner programmatically from array

this work for me:-

String[] array = {"A", "B", "C"};
String abc = "";


Spinner spinner = new Spinner(getContext());
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, array); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);

I am using a Fragment.

Failed to find Build Tools revision 23.0.1

I faced the same problem and I solved it doing the following:

Go to /home/[USER]/Android/Sdk/tools and execute:

$android list sdk -a

Which will show a list like:

  1. Android SDK Tools, revision 24.0.2
  2. Android SDK Platform-tools, revision 23.0.2
  3. Android SDK Platform-tools, revision 23.0.1

... and many more

Then, execute the command (attention! at your computer the third option may be different):

$android update sdk -a -u -t 3

It will install the 23.0.1 SDK Platform-tools components.

Try to build your project again.

Formatting floats in a numpy array

[ round(x,2) for x in [2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]]

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

Try this query

SELECT v.VehicleId, v.Name, ll.LocationList
FROM Vehicles v 
LEFT JOIN 
    (SELECT 
     DISTINCT
        VehicleId,
        REPLACE(
            REPLACE(
                REPLACE(
                    (
                        SELECT City as c 
                        FROM Locations x 
                        WHERE x.VehicleID = l.VehicleID FOR XML PATH('')
                    ),    
                    '</c><c>',', '
                 ),
             '<c>',''
            ),
        '</c>', ''
        ) AS LocationList
    FROM Locations l
) ll ON ll.VehicleId = v.VehicleId

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

How do I get the n-th level parent of an element in jQuery?

If you have a common parent div you can use parentsUntil() link

eg: $('#element').parentsUntil('.commonClass')

Advantage is that you need not to remember how many generation are there between this element and the common parent(defined by commonclass).

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

To replace with dashes, do the following:

text.replace(/[\W_-]/g,' ');

how to list all sub directories in a directory

Easy as this:

string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);

How can I change the app display name build with Flutter?

One problem is that in iOS Settings (iOS 12.x) if you change the Display Name, it leaves the app name and icon in iOS Settings as the old version.

Formatting MM/DD/YYYY dates in textbox in VBA

I too, one way or another stumbled on the same dilemma, why the heck Excel VBA doesn't have a Date Picker. Thanks to Sid, who made an awesome job to create something for all of us.

Nonetheless, I came to a point where I need to create my own. And I am posting it here since a lot of people I'm sure lands on this post and benefit from it.

What I did was very simple as what Sid does except that I do not use a temporary worksheet. I thought the calculations are very simple and straight forward so there's no need to dump it somewhere else. Here's the final output of the calendar:

enter image description here

How to set it up:

  • Create 42 Label controls and name it sequentially and arranged left to right, top to bottom (This labels contains greyed 25 up to greyed 5 above). Change the name of the Label controls to Label_01,Label_02 and so on. Set all 42 labels Tag property to dts.
  • Create 7 more Label controls for the header (this will contain Su,Mo,Tu...)
  • Create 2 more Label control, one for the horizontal line (height set to 1) and one for the Month and Year display. Name the Label used for displaying month and year Label_MthYr
  • Insert 2 Image controls, one to contain the left icon to scroll previous months and one to scroll next month (I prefer simple left and right arrow head icon). Name it Image_Left and Image_Right

The layout should be more or less like this (I leave the creativity to anyone who'll use this).

enter image description here

Declaration:
We need one variable declared at the very top to hold the current month selected.

Option Explicit
Private curMonth As Date

Private Procedure and Functions:

Private Function FirstCalSun(ref_date As Date) As Date
    '/* returns the first Calendar sunday */
    FirstCalSun = DateSerial(Year(ref_date), _
                  Month(ref_date), 1) - (Weekday(ref_date) - 1)
End Function

Private Sub Build_Calendar(first_sunday As Date)
    '/* This builds the calendar and adds formatting to it */
    Dim lDate As MSForms.Label
    Dim i As Integer, a_date As Date

    For i = 1 To 42
        a_date = first_sunday + (i - 1)
        Set lDate = Me.Controls("Label_" & Format(i, "00"))
        lDate.Caption = Day(a_date)
        If Month(a_date) <> Month(curMonth) Then
            lDate.ForeColor = &H80000011
        Else
            If Weekday(a_date) = 1 Then
                lDate.ForeColor = &HC0&
            Else
                lDate.ForeColor = &H80000012
            End If
        End If
    Next
End Sub

Private Sub select_label(msForm_C As MSForms.Control)
    '/* Capture the selected date */
    Dim i As Integer, sel_date As Date
    i = Split(msForm_C.Name, "_")(1) - 1
    sel_date = FirstCalSun(curMonth) + i

    '/* Transfer the date where you want it to go */
    MsgBox sel_date

End Sub

Image Events:

Private Sub Image_Left_Click()

    If Month(curMonth) = 1 Then
        curMonth = DateSerial(Year(curMonth) - 1, 12, 1)
    Else
        curMonth = DateSerial(Year(curMonth), Month(curMonth) - 1, 1)
    End If

    With Me
        .Label_MthYr.Caption = Format(curMonth, "mmmm, yyyy")
        Build_Calendar FirstCalSun(curMonth)
    End With

End Sub

Private Sub Image_Right_Click()

    If Month(curMonth) = 12 Then
        curMonth = DateSerial(Year(curMonth) + 1, 1, 1)
    Else
        curMonth = DateSerial(Year(curMonth), Month(curMonth) + 1, 1)
    End If

    With Me
        .Label_MthYr.Caption = Format(curMonth, "mmmm, yyyy")
        Build_Calendar FirstCalSun(curMonth)
    End With

End Sub

I added this to make it look like the user is clicking the label and should be done on the Image_Right control too.

Private Sub Image_Left_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
                                 ByVal X As Single, ByVal Y As Single)
    Me.Image_Left.BorderStyle = fmBorderStyleSingle
End Sub

Private Sub Image_Left_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, _
                               ByVal X As Single, ByVal Y As Single)
    Me.Image_Left.BorderStyle = fmBorderStyleNone
End Sub

Label Events:
All of this should be done for all 42 labels (Label_01 to Lable_42)
Tip: Build the first 10 and just use find and replace for the remaining.

Private Sub Label_01_Click()
    select_label Me.Label_01
End Sub

This is for hovering over dates and clicking effect.

Private Sub Label_01_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
                               ByVal X As Single, ByVal Y As Single)
    Me.Label_01.BorderStyle = fmBorderStyleSingle
End Sub

Private Sub Label_01_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, _
                               ByVal X As Single, ByVal Y As Single)
    Me.Label_01.BackColor = &H8000000B
End Sub

Private Sub Label_01_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, _
                             ByVal X As Single, ByVal Y As Single)
    Me.Label_01.BorderStyle = fmBorderStyleNone
End Sub

UserForm Events:

Private Sub UserForm_Initialize()
    '/* This is to initialize everything */
    With Me
        curMonth = DateSerial(Year(Date), Month(Date), 1)
        .Label_MthYr = Format(curMonth, "mmmm, yyyy")
        Build_Calendar FirstCalSun(curMonth)
    End With

End Sub

Again, just for the hovering over dates effect.

Private Sub UserForm_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, _
                               ByVal X As Single, ByVal Y As Single)

    With Me
        Dim ctl As MSForms.Control, lb As MSForms.Label

        For Each ctl In .Controls
            If ctl.Tag = "dts" Then
                Set lb = ctl: lb.BackColor = &H80000005
            End If
        Next
    End With

End Sub

And that's it. This is raw and you can add your own twist to it.
I've been using this for awhile and I have no issues (performance and functionality wise).
No Error Handling yet but can be easily managed I guess.
Actually, without the effects, the code is too short.
You can manage where your dates go in the select_label procedure. HTH.

C# using streams

Streams are good for dealing with large amounts of data. When it's impractical to load all the data into memory at the same time, you can open it as a stream and work with small chunks of it.

How to debug .htaccess RewriteRule not working

Enter some junk value into your .htaccess e.g. foo bar, sakjnaskljdnas any keyword not recognized by htaccess and visit your URL. If it is working, you should get a

500 Internal Server Error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request....

I suggest you to put it soon after RewriteEngine on.


Since you are on your machine. I presume you have access to apache .conf file.

open the .conf file, and look for a line similar to:

LoadModule rewrite_module modules/mod_rewrite.so

If it is commented(#), uncomment and restart apache.


To log rewrite

RewriteEngine On
RewriteLog "/path/to/rewrite.log"
RewriteLogLevel 9

Put the above 3 lines in your virtualhost. restart the httpd.

RewriteLogLevel 9 Using a high value for Level will slow down your Apache server dramatically! Use the rewriting logfile at a Level greater than 2 only for debugging! Level 9 will log almost every rewritelog detail.


UPDATE

Things have changed in Apache 2.4:

FROM Upgrading to 2.4 from 2.2

The RewriteLog and RewriteLogLevel directives have been removed. This functionality is now provided by configuring the appropriate level of logging for the mod_rewrite module using the LogLevel directive. See also the mod_rewrite logging section.

For more on LogLevel, refer LogLevel Directive

you can accomplish

RewriteLog "/path/to/rewrite.log"

in this manner now

LogLevel debug rewrite_module:debug

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

For me this simple command solved the problem:

sudo apt-get install postgresql postgresql-contrib libpq-dev python-dev

Then I can do:

 pip install psycopg2

Pass props to parent component in React.js

The question is how to pass argument from child to parent component. This example is easy to use and tested:

//Child component
class Child extends React.Component {
    render() {
        var handleToUpdate  =   this.props.handleToUpdate;
        return (<div><button onClick={() => handleToUpdate('someVar')}>Push me</button></div>
        )
    }
}

//Parent component
class Parent extends React.Component {
    constructor(props) {
        super(props);
        var handleToUpdate  = this.handleToUpdate.bind(this);
    }

    handleToUpdate(someArg){
        alert('We pass argument from Child to Parent: \n' + someArg);
    }

    render() {
        var handleToUpdate  =   this.handleToUpdate;
        return (<div>
          <Child handleToUpdate = {handleToUpdate.bind(this)} />
        </div>)
    }
}

if(document.querySelector("#demo")){
    ReactDOM.render(
        <Parent />,
        document.querySelector("#demo")
    );
}

Look at JSFIDDLE

Differences between utf8 and latin1

UTF-8 is prepared for world domination, Latin1 isn't.

If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).

Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4.

Switch firefox to use a different DNS than what is in the windows.host file

What about having different names for your dev and prod servers? That should avoid any confusions and you'd not have to edit the hosts file every time.

Convert string to number and add one

The parseInt solution is the best way to go as it is clear what is happening.

For completeness it is worth mentioning that this can also be done with the + operator

$('.load_more').live("click",function() { //When user clicks
  var newcurrentpageTemp = +$(this).attr("id") + 1; //Get the id from the hyperlink
  alert(newcurrentpageTemp);
  dosomething();
});

How to extract string following a pattern with grep, regex or perl

Since you need to match content without including it in the result (must match name=" but it's not part of the desired result) some form of zero-width matching or group capturing is required. This can be done easily with the following tools:

Perl

With Perl you could use the n option to loop line by line and print the content of a capturing group if it matches:

perl -ne 'print "$1\n" if /name="(.*?)"/' filename

GNU grep

If you have an improved version of grep, such as GNU grep, you may have the -P option available. This option will enable Perl-like regex, allowing you to use \K which is a shorthand lookbehind. It will reset the match position, so anything before it is zero-width.

grep -Po 'name="\K.*?(?=")' filename

The o option makes grep print only the matched text, instead of the whole line.

Vim - Text Editor

Another way is to use a text editor directly. With Vim, one of the various ways of accomplishing this would be to delete lines without name= and then extract the content from the resulting lines:

:v/.*name="\v([^"]+).*/d|%s//\1

Standard grep

If you don't have access to these tools, for some reason, something similar could be achieved with standard grep. However, without the look around it will require some cleanup later:

grep -o 'name="[^"]*"' filename

A note about saving results

In all of the commands above the results will be sent to stdout. It's important to remember that you can always save them by piping it to a file by appending:

> result

to the end of the command.

error: request for member '..' in '..' which is of non-class type

Parenthesis is not required to instantiate a class object when you don't intend to use a parameterised constructor.

Just use Foo foo2;

It will work.

Select a date from date picker using Selenium webdriver

Just do

  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("document.getElementById('id').value='1988-01-01'");

Converting std::__cxx11::string to std::string

If you can recompile all incompatible libs you use, do it with compiler option

-D_GLIBCXX_USE_CXX11_ABI=1

and then rebuild your project. If you can't do so, add to your project's makefile compiler option

-D_GLIBCXX_USE_CXX11_ABI=0

The define

#define _GLIBCXX_USE_CXX11_ABI 0/1

is also good but you probably need to add it to all your files while compiler option do it for all files at once.

Getting multiple values with scanf()

Just to add, we can use array as well:

int i, array[4];
printf("Enter Four Ints: ");
for(i=0; i<4; i++) {
    scanf("%d", &array[i]);
}

Read file from aws s3 bucket using node fs

This will do it:

new AWS.S3().getObject({ Bucket: this.awsBucketName, Key: keyName }, function(err, data)
{
    if (!err)
        console.log(data.Body.toString());
});

How to use getJSON, sending data with post method?

I just used post and an if:

data = getDataObjectByForm(form);
var jqxhr = $.post(url, data, function(){}, 'json')
    .done(function (response) {
        if (response instanceof Object)
            var json = response;
        else
            var json = $.parseJSON(response);
        // console.log(response);
        // console.log(json);
        jsonToDom(json);
        if (json.reload != undefined && json.reload)
            location.reload();
        $("body").delay(1000).css("cursor", "default");
    })
    .fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log("Request Failed: " + err);
        alert("Fehler!");
    });

Row numbers in query result using Microsoft Access

Though this is an old question, this has worked for me, but I've never tested its efficiency...

SELECT 
    (SELECT COUNT(t1.SourceID) 
     FROM [SourceTable] t1 
     WHERE t1.SourceID<t2.SourceID) AS RowID, 
    t2.field2, 
    t2.field3, 
    t2.field4, 
    t2.field5
FROM 
    SourceTable AS t2
ORDER BY 
    t2.SourceID;

Some advantages of this method:

  • It doesn't rely on the order of the table, either - the RowID is calculated on its actual value and those that are less than it.
  • This method can be applied to any (primary key) type (e.g. Number, String or Date).
  • This method is fairly SQL agnostic, or requires very little adaptation.

Final Thoughts

Though this will work with practically any data type, I must emphasise that, for some, it may create other problems. For instance, with strings, consider:

ID     Description    ROWID
aaa    Aardvark           1
bbb    Bear               2
ccc    Canary             3

If I were to insert: bba Boar, then the Canary RowID will change...

ID     Description    ROWID
aaa    Aardvark           1
bbb    Bear               2
bba    Boar               3
ccc    Canary             4

How to remove focus from single editText

i had a similar problem with the editText, which gained focus since the activity was started. this problem i fixed easily like this:

you add this piece of code into the layout that contains the editText in xml:

    android:id="@+id/linearlayout" 
    android:focusableInTouchMode="true"

dont forget the android:id, without it i've got an error.

the other problem i had with the editText is that once it gain the first focus, the focus never disappeared. this is a piece of my code in java, it has an editText and a button that captures the text in the editText:

    editText=(EditText) findViewById(R.id.et1);
    tvhome= (TextView)findViewById(R.id.tv_home);
    etBtn= (Button) findViewById(R.id.btn_homeadd);
    etBtn.setOnClickListener(new View.OnClickListener() 
    {   
        @Override
        public void onClick(View v)
        {
            tvhome.setText( editText.getText().toString() );

            //** this code is for hiding the keyboard after pressing the button
            View view = Settings.this.getCurrentFocus();
            if (view != null) 
            {  
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
            //**

            editText.getText().clear();//clears the text
            editText.setFocusable(false);//disables the focus of the editText 
            Log.i("onCreate().Button.onClickListener()", "et.isfocused= "+editText.isFocused());
        }
    });
    editText.setOnClickListener(new View.OnClickListener() 
    {
        @Override
        public void onClick(View v) 
        {
            if(v.getId() == R.id.et1)
            {
                v.setFocusableInTouchMode(true);// when the editText is clicked it will gain focus again

                //** this code is for enabling the keyboard at the first click on the editText
                if(v.isFocused())//the code is optional, because at the second click the keyboard shows by itself
                {
                    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
                }
                //**

                Log.i("onCreate().EditText.onClickListener()", "et.isfocused= "+v.isFocused());
            }
            else
                Log.i("onCreate().EditText.onClickListener()", "the listener did'nt consume the event");
        }
    });

hope it will help to some of you!

How do I create a simple Qt console application in C++?

I managed to create a simple console "hello world" with QT Creator

used creator 2.4.1 and QT 4.8.0 on windows 7

two ways to do this

Plain C++

do the following

  1. File- new file project
  2. under projects select : other Project
  3. select "Plain C++ Project"
  4. enter project name 5.Targets select Desktop 'tick it'
  5. project managment just click next
  6. you can use c++ commands as normal c++

or

QT Console

  1. File- new file project
  2. under projects select : other Project
  3. select QT Console Application
  4. Targets select Desktop 'tick it'
  5. project managment just click next
  6. add the following lines (all the C++ includes you need)
  7. add "#include 'iostream' "
  8. add "using namespace std; "
  9. after QCoreApplication a(int argc, cghar *argv[]) 10 add variables, and your program code..

example: for QT console "hello world"

file - new file project 'project name '

other projects - QT Console Application

Targets select 'Desktop'

project management - next

code:

    #include <QtCore/QCoreApplication>
    #include <iostream>
    using namespace std;
    int main(int argc, char *argv[])
    {
     QCoreApplication a(argc, argv);
     cout<<" hello world";
     return a.exec();
     }

ctrl -R to run

compilers used for above MSVC 2010 (QT SDK) , and minGW(QT SDK)

hope this helps someone

As I have just started to use QT recently and also searched the Www for info and examples to get started with simple examples still searching...

Maintain model of scope when changing between views in AngularJS

Solution that will work for multiple scopes and multiple variables within those scopes

This service was based off of Anton's answer, but is more extensible and will work across multiple scopes and allows the selection of multiple scope variables in the same scope. It uses the route path to index each scope, and then the scope variable names to index one level deeper.

Create service with this code:

angular.module('restoreScope', []).factory('restoreScope', ['$rootScope', '$route', function ($rootScope, $route) {

    var getOrRegisterScopeVariable = function (scope, name, defaultValue, storedScope) {
        if (storedScope[name] == null) {
            storedScope[name] = defaultValue;
        }
        scope[name] = storedScope[name];
    }

    var service = {

        GetOrRegisterScopeVariables: function (names, defaultValues) {
            var scope = $route.current.locals.$scope;
            var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);
            if (storedBaseScope == null) {
                storedBaseScope = {};
            }
            // stored scope is indexed by route name
            var storedScope = storedBaseScope[$route.current.$$route.originalPath];
            if (storedScope == null) {
                storedScope = {};
            }
            if (typeof names === "string") {
                getOrRegisterScopeVariable(scope, names, defaultValues, storedScope);
            } else if (Array.isArray(names)) {
                angular.forEach(names, function (name, i) {
                    getOrRegisterScopeVariable(scope, name, defaultValues[i], storedScope);
                });
            } else {
                console.error("First argument to GetOrRegisterScopeVariables is not a string or array");
            }
            // save stored scope back off
            storedBaseScope[$route.current.$$route.originalPath] = storedScope;
            sessionStorage.restoreScope = angular.toJson(storedBaseScope);
        },

        SaveState: function () {
            // get current scope
            var scope = $route.current.locals.$scope;
            var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);

            // save off scope based on registered indexes
            angular.forEach(storedBaseScope[$route.current.$$route.originalPath], function (item, i) {
                storedBaseScope[$route.current.$$route.originalPath][i] = scope[i];
            });

            sessionStorage.restoreScope = angular.toJson(storedBaseScope);
        }
    }

    $rootScope.$on("savestate", service.SaveState);

    return service;
}]);

Add this code to your run function in your app module:

$rootScope.$on('$locationChangeStart', function (event, next, current) {
    $rootScope.$broadcast('savestate');
});

window.onbeforeunload = function (event) {
    $rootScope.$broadcast('savestate');
};

Inject the restoreScope service into your controller (example below):

function My1Ctrl($scope, restoreScope) {
    restoreScope.GetOrRegisterScopeVariables([
         // scope variable name(s)
        'user',
        'anotherUser'
    ],[
        // default value(s)
        { name: 'user name', email: '[email protected]' },
        { name: 'another user name', email: '[email protected]' }
    ]);
}

The above example will initialize $scope.user to the stored value, otherwise will default to the provided value and save that off. If the page is closed, refreshed, or the route is changed, the current values of all registered scope variables will be saved off, and will be restored the next time the route/page is visited.

How to iterate through LinkedHashMap with lists as values

In Java 8:

Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
    System.out.println(key + " -> " + value);
});

Install / upgrade gradle on Mac OS X

And using ports:

port install gradle

Ports , tested on El Capitan

How to pass ArrayList of Objects from one to another activity using Intent in android?

To set the data in kotlin

val offerIds = ArrayList<Offer>()
offerIds.add(Offer(1))
retrunIntent.putExtra(C.OFFER_IDS, offerIds)

To get the data

 val offerIds = data.getSerializableExtra(C.OFFER_IDS) as ArrayList<Offer>?

Now access the arraylist

CSS3 transition on click using pure CSS

You can use JavaScript to do this, with onClick method. This maybe helps CSS3 transition click event

How to make a back-to-top button using CSS and HTML only?

Hope this helps somebody!

<style> html { scroll-behavior: smooth;} </style>
<a id="top"></>
<!--content here-->
<a href="#top">Back to top..</a>

Xcode 6 Bug: Unknown class in Interface Builder file

This worked for me..

Check your compiled source, whether that file(e.g; ViewController.m) is added or not, in my case ViewController file was not added so it was giving me the error..

enter image description here

How to execute a Windows command on a remote PC?

You can use native win command:

WMIC /node:ComputerName process call create “cmd.exe /c start.exe”

The WMIC is part of wbem win folder: C:\Windows\System32\wbem

python NameError: global name '__file__' is not defined

if you are using jupyter notebook like:

MODEL_NAME = os.path.basename(file)[:-3]

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-10-f391bbbab00d> in <module>
----> 1 MODEL_NAME = os.path.basename(__file__)[:-3]

NameError: name '__file__' is not defined

you should place a ' ! ' in front like this

!MODEL_NAME = os.path.basename(__file__)[:-3]

/bin/bash: -c: line 0: syntax error near unexpected token `('
/bin/bash: -c: line 0: `MODEL_NAME = os.path.basename(__file__)[:-3]'

done.....

Missing Microsoft RDLC Report Designer in Visual Studio

In addition to previous answers, here is a link to the latest SQL Server Data Tools. Note that the download link for Visual Studio 2015 is broken. ISO is available from here, links at the bottom of the page:

https://msdn.microsoft.com/en-us/library/mt204009.aspx

MSDN Subscriber Downloads do not list the VS 2015 compatible version at the time of writing.

However, even with the latest tools (February 2015), I can't open previous version of .rptproj files.

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

Use this javascript function as an example on how to accomplish this.

function isNoIframeOrIframeInMyHost() {
// Validation: it must be loaded as the top page, or if it is loaded in an iframe 
// then it must be embedded in my own domain.
// Info: IF top.location.href is not accessible THEN it is embedded in an iframe 
// and the domains are different.
var myresult = true;
try {
    var tophref = top.location.href;
    var tophostname = top.location.hostname.toString();
    var myhref = location.href;
    if (tophref === myhref) {
        myresult = true;
    } else if (tophostname !== "www.yourdomain.com") {
        myresult = false;
    }
} catch (error) { 
  // error is a permission error that top.location.href is not accessible 
  // (which means parent domain <> iframe domain)!
    myresult = false;
}
return myresult;
}

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

Maven is not working in Java 8 when Javadoc tags are incomplete

The best solution would be to fix the javadoc errors. If for some reason that is not possible (ie: auto generated source code) then you can disable this check.

DocLint is a new feature in Java 8, which is summarized as:

Provide a means to detect errors in Javadoc comments early in the development cycle and in a way that is easily linked back to the source code.

This is enabled by default, and will run a whole lot of checks before generating Javadocs. You need to turn this off for Java 8 as specified in this thread. You'll have to add this to your maven configuration:

<profiles>
  <profile>
    <id>java8-doclint-disabled</id>
    <activation>
      <jdk>[1.8,)</jdk>
    </activation>
    <properties>
      <javadoc.opts>-Xdoclint:none</javadoc.opts>
    </properties>
  </profile>
</profiles>
<build>
  <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.9</version>
        <executions>
            <execution>
                <id>attach-javadocs</id>
                <goals>
                    <goal>jar</goal>
                </goals>
                <configuration>
                    <additionalparam>${javadoc.opts}</additionalparam>
                </configuration>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <reportPlugins>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-javadoc-plugin</artifactId>
              <configuration>
                <additionalparam>${javadoc.opts}</additionalparam>
              </configuration>
            </plugin>
          </reportPlugins>
        </configuration>
      </plugin>
   </plugins>
</build>

For maven-javadoc-plugin 3.0.0+: Replace

<additionalparam>-Xdoclint:none</additionalparam>

with

<doclint>none</doclint>

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

Ok, I think I got it to work now. I deleted every Newtonsoft.Json.dll on my machine that wasn't the latest version that I could find, made sure I had the latest version in NuGet, and build it and made sure that was the latest one in the bin folder, and I left the changes in the web.config and the .csproj. Now I'm on to another error, so it must be working..

Correct way to load a Nib for a UIView subclass

Follow the following steps

  1. Create a class named MyView .h/.m of type UIView.
  2. Create a xib of same name MyView.xib.
  3. Now change the File Owner class to UIViewController from NSObject in xib. See the image below enter image description here
  4. Connect the File Owner View to your View. See the image below enter image description here

  5. Change the class of your View to MyView. Same as 3.

  6. Place controls create IBOutlets.

Here is the code to load the View:

UIViewController *controller=[[UIViewController alloc] initWithNibName:@"MyView" bundle:nil];
MyView* view=(MyView*)controller.view;
[self.view addSubview:myview];

Hope it helps.

Clarification:

UIViewController is used to load your xib and the View which the UIViewController has is actually MyView which you have assigned in the MyView xib..

Demo I have made a demo grab here

How to get the data-id attribute?

If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:

Through JavaScript

<div id='strawberry-plant' data-fruit='12'></div>

<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'

// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>

Through jQuery

// Fetching data
var fruitCount = $(this).data('fruit');
OR 
// If you updated the value, you will need to use below code to fetch new value 
// otherwise above gives the old value which is intially set.
// And also above does not work in ***Firefox***, so use below code to fetch value
var fruitCount = $(this).attr('data-fruit');

// Assigning data
$(this).attr('data-fruit','7');

Read this documentation

How to get element's width/height within directives and component?

For a bit more flexibility than with micronyks answer, you can do it like that:

1. In your template, add #myIdentifier to the element you want to obtain the width from. Example:

<p #myIdentifier>
  my-component works!
</p>

2. In your controller, you can use this with @ViewChild('myIdentifier') to get the width:

import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})
export class MyComponentComponent implements AfterViewInit {

  constructor() { }

  ngAfterViewInit() {
    console.log(this.myIdentifier.nativeElement.offsetWidth);
  }

  @ViewChild('myIdentifier')
  myIdentifier: ElementRef;

}

Security

About the security risk with ElementRef, like this, there is none. There would be a risk, if you would modify the DOM using an ElementRef. But here you are only getting DOM Elements so there is no risk. A risky example of using ElementRef would be: this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;. Like this Angular doesn't get a chance to use its sanitisation mechanisms since someFunctionDefinedBySomeUser is inserted directly into the DOM, skipping the Angular sanitisation.

Make code in LaTeX look *nice*

For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.

How to use support FileProvider for sharing content to other apps?

If you get an image from camera none of these solutions work for Android 4.4. In this case it's better to check versions.

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getContext().getPackageManager()) != null) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        uri = Uri.fromFile(file);
    } else {
        uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", file);
    }
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    startActivityForResult(intent, CAMERA_REQUEST);
}

How to split a string in Java

 String string = "004^034556-34";
 String[] parts = string.split(Pattern.quote("^"));

If you have a special character then you can use Patter.quote. If you simply have dash (-) then you can shorten the code:

 String string = "004-34";
 String[] parts = string.split("-");

If you try to add other special character in place of dash (^) then the error will generate ArrayIndexOutOfBoundsException. For that you have to use Pattern.quote.

xxxxxx.exe is not a valid Win32 application

For me, this helped: 1. Configuration properties/General/Platform Toolset = Windows XP (V110_xp) 2. C/C++ Preprocessor definitions, add "WIN32" 3. Linker/System/Minimum required version = 5.01

Why does an onclick property set with setAttribute fail to work in IE?

to make this work in both FF and IE you must write both ways:


    button_element.setAttribute('onclick','doSomething();'); // for FF
    button_element.onclick = function() {doSomething();}; // for IE

thanks to this post.

UPDATE: This is to demonstrate that sometimes it is necessary to use setAttribute! This method works if you need to take the original onclick attribute from the HTML and add it to the onclick event, so that it doesn't get overridden:

// get old onclick attribute
var onclick = button_element.getAttribute("onclick");  

// if onclick is not a function, it's not IE7, so use setAttribute
if(typeof(onclick) != "function") { 
    button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome

// if onclick is a function, use the IE7 method and call onclick() in the anonymous function
} else {
    button_element.onclick = function() { 
        doSomething();
        onclick();
    }; // for IE7
}

How to access host port from docker container

I created a docker container for doing exactly that https://github.com/qoomon/docker-host

You can then simply use container name dns to access host system e.g. curl http://dockerhost:9200

How to select date from datetime column?

Here are all formats

Say this is the column that contains the datetime value, table data.

+--------------------+
| date_created       |
+--------------------+
| 2018-06-02 15:50:30|
+--------------------+

mysql> select DATE(date_created) from data;
+--------------------+
| DATE(date_created) |
+--------------------+
| 2018-06-02         |
+--------------------+

mysql> select YEAR(date_created) from data;
+--------------------+
| YEAR(date_created) |
+--------------------+
|               2018 |
+--------------------+

mysql> select MONTH(date_created) from data;
+---------------------+
| MONTH(date_created) |
+---------------------+
|                   6 |
+---------------------+

mysql> select DAY(date_created) from data;
+-------------------+
| DAY(date_created) |
+-------------------+
|                 2 |
+-------------------+

mysql> select HOUR(date_created) from data;
+--------------------+
| HOUR(date_created) |
+--------------------+
|                 15 |
+--------------------+

mysql> select MINUTE(date_created) from data;
+----------------------+
| MINUTE(date_created) |
+----------------------+
|                   50 |
+----------------------+

mysql> select SECOND(date_created) from data;
+----------------------+
| SECOND(date_created) |
+----------------------+
|                   31 |
+----------------------+

PHP Remove elements from associative array

  ...

  $array = array(
      1 => 'Awaiting for Confirmation', 
      2 => 'Asssigned', 
      3 => 'In Progress', 
      4 => 'Completed', 
      5 => 'Mark As Spam', 
  );



  return array_values($array);
  ...

node.js + mysql connection pooling

Using the standard mysql.createPool(), connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. However if you configure it for 500 connections and use all 500 they will remain open for the durations of the process, even if they are idle!

This means if your MySQL Server max_connections is 510 your system will only have 10 mySQL connections available until your MySQL Server closes them (depends on what you have set your wait_timeout to) or your application closes! The only way to free them up is to manually close the connections via the pool instance or close the pool.

mysql-connection-pool-manager module was created to fix this issue and automatically scale the number of connections dependant on the load. Inactive connections are closed and idle connection pools are eventually closed if there has not been any activity.

    // Load modules
const PoolManager = require('mysql-connection-pool-manager');

// Options
const options = {
  ...example settings
}

// Initialising the instance
const mySQL = PoolManager(options);

// Accessing mySQL directly
var connection = mySQL.raw.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});

// Initialising connection
connection.connect();

// Performing query
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});

// Ending connection
connection.end();

Ref: https://www.npmjs.com/package/mysql-connection-pool-manager

Auto refresh code in HTML using meta tags

It looks like you probably pasted this (or used a word processor like MS Word) using a kind of double-quotes that are not recognized by the browser. Please check that your code uses actual double-quotes like this one ", which is different from the following character:

Replace the meta tag with this one and try again:

<meta http-equiv="refresh" content="5" >

How do I make a transparent canvas in html5?

Iif you want a particular <canvas id="canvasID"> to be always transparent you just have to set

#canvasID{
    opacity:0.5;
}

Instead, if you want some particular elements inside the canvas area to be transparent, you have to set transparency when you draw, i.e.

context.fillStyle = "rgba(0, 0, 200, 0.5)";

Read a text file in R line by line

I write a code to read file line by line to meet my demand which different line have different data type follow articles: read-line-by-line-of-a-file-in-r and determining-number-of-linesrecords. And it should be a better solution for big file, I think. My R version (3.3.2).

con = file("pathtotargetfile", "r")
readsizeof<-2    # read size for one step to caculate number of lines in file
nooflines<-0     # number of lines
while((linesread<-length(readLines(con,readsizeof)))>0)    # calculate number of lines. Also a better solution for big file
  nooflines<-nooflines+linesread

con = file("pathtotargetfile", "r")    # open file again to variable con, since the cursor have went to the end of the file after caculating number of lines
typelist = list(0,'c',0,'c',0,0,'c',0)    # a list to specific the lines data type, which means the first line has same type with 0 (e.g. numeric)and second line has same type with 'c' (e.g. character). This meet my demand.
for(i in 1:nooflines) {
  tmp <- scan(file=con, nlines=1, what=typelist[[i]], quiet=TRUE)
  print(is.vector(tmp))
  print(tmp)
}
close(con)

How to find row number of a value in R code

(1:nrow(mydata_2))[mydata_2[,4] == 1578]

Of course there may be more than one row with a value of 1578.

How to Find the Default Charset/Encoding in Java?

This is really strange... Once set, the default Charset is cached and it isn't changed while the class is in memory. Setting the "file.encoding" property with System.setProperty("file.encoding", "Latin-1"); does nothing. Every time Charset.defaultCharset() is called it returns the cached charset.

Here are my results:

Default Charset=ISO-8859-1
file.encoding=Latin-1
Default Charset=ISO-8859-1
Default Charset in Use=ISO8859_1

I'm using JVM 1.6 though.

(update)

Ok. I did reproduce your bug with JVM 1.5.

Looking at the source code of 1.5, the cached default charset isn't being set. I don't know if this is a bug or not but 1.6 changes this implementation and uses the cached charset:

JVM 1.5:

public static Charset defaultCharset() {
    synchronized (Charset.class) {
        if (defaultCharset == null) {
            java.security.PrivilegedAction pa =
                    new GetPropertyAction("file.encoding");
            String csn = (String) AccessController.doPrivileged(pa);
            Charset cs = lookup(csn);
            if (cs != null)
                return cs;
            return forName("UTF-8");
        }
        return defaultCharset;
    }
}

JVM 1.6:

public static Charset defaultCharset() {
    if (defaultCharset == null) {
        synchronized (Charset.class) {
            java.security.PrivilegedAction pa =
                    new GetPropertyAction("file.encoding");
            String csn = (String) AccessController.doPrivileged(pa);
            Charset cs = lookup(csn);
            if (cs != null)
                defaultCharset = cs;
            else
                defaultCharset = forName("UTF-8");
        }
    }
    return defaultCharset;
}

When you set the file encoding to file.encoding=Latin-1 the next time you call Charset.defaultCharset(), what happens is, because the cached default charset isn't set, it will try to find the appropriate charset for the name Latin-1. This name isn't found, because it's incorrect, and returns the default UTF-8.

As for why the IO classes such as OutputStreamWriter return an unexpected result,
the implementation of sun.nio.cs.StreamEncoder (witch is used by these IO classes) is different as well for JVM 1.5 and JVM 1.6. The JVM 1.6 implementation is based in the Charset.defaultCharset() method to get the default encoding, if one is not provided to IO classes. The JVM 1.5 implementation uses a different method Converters.getDefaultEncodingName(); to get the default charset. This method uses its own cache of the default charset that is set upon JVM initialization:

JVM 1.6:

public static StreamEncoder forOutputStreamWriter(OutputStream out,
        Object lock,
        String charsetName)
        throws UnsupportedEncodingException
{
    String csn = charsetName;
    if (csn == null)
        csn = Charset.defaultCharset().name();
    try {
        if (Charset.isSupported(csn))
            return new StreamEncoder(out, lock, Charset.forName(csn));
    } catch (IllegalCharsetNameException x) { }
    throw new UnsupportedEncodingException (csn);
}

JVM 1.5:

public static StreamEncoder forOutputStreamWriter(OutputStream out,
        Object lock,
        String charsetName)
        throws UnsupportedEncodingException
{
    String csn = charsetName;
    if (csn == null)
        csn = Converters.getDefaultEncodingName();
    if (!Converters.isCached(Converters.CHAR_TO_BYTE, csn)) {
        try {
            if (Charset.isSupported(csn))
                return new CharsetSE(out, lock, Charset.forName(csn));
        } catch (IllegalCharsetNameException x) { }
    }
    return new ConverterSE(out, lock, csn);
}

But I agree with the comments. You shouldn't rely on this property. It's an implementation detail.

jquery how to catch enter key and change event to tab

I know this question is older than god, but I never saw an answer that was all that elegant.

doc.on('keydown', 'input', function(e, ui) {
    if(e.keyCode === 13){
        e.preventDefault();
        $(this).nextAll('input:visible').eq(0).focus();
    }
});

that seems to get the job done in as few lines as humanly possible.

How to check task status in Celery?

Creating an AsyncResult object from the task id is the way recommended in the FAQ to obtain the task status when the only thing you have is the task id.

However, as of Celery 3.x, there are significant caveats that could bite people if they do not pay attention to them. It really depends on the specific use-case scenario.

By default, Celery does not record a "running" state.

In order for Celery to record that a task is running, you must set task_track_started to True. Here is a simple task that tests this:

@app.task(bind=True)
def test(self):
    print self.AsyncResult(self.request.id).state

When task_track_started is False, which is the default, the state show is PENDING even though the task has started. If you set task_track_started to True, then the state will be STARTED.

The state PENDING means "I don't know."

An AsyncResult with the state PENDING does not mean anything more than that Celery does not know the status of the task. This could be because of any number of reasons.

For one thing, AsyncResult can be constructed with invalid task ids. Such "tasks" will be deemed pending by Celery:

>>> task.AsyncResult("invalid").status
'PENDING'

Ok, so nobody is going to feed obviously invalid ids to AsyncResult. Fair enough, but it also has for effect that AsyncResult will also consider a task that has successfully run but that Celery has forgotten as being PENDING. Again, in some use-case scenarios this can be a problem. Part of the issue hinges on how Celery is configured to keep the results of tasks, because it depends on the availability of the "tombstones" in the results backend. ("Tombstones" is the term use in the Celery documentation for the data chunks that record how the task ended.) Using AsyncResult won't work at all if task_ignore_result is True. A more vexing problem is that Celery expires the tombstones by default. The result_expires setting by default is set to 24 hours. So if you launch a task, and record the id in long-term storage, and more 24 hours later, you create an AsyncResult with it, the status will be PENDING.

All "real tasks" start in the PENDING state. So getting PENDING on a task could mean that the task was requested but never progressed further than this (for whatever reason). Or it could mean the task ran but Celery forgot its state.

Ouch! AsyncResult won't work for me. What else can I do?

I prefer to keep track of goals than keep track of the tasks themselves. I do keep some task information but it is really secondary to keeping track of the goals. The goals are stored in storage independent from Celery. When a request needs to perform a computation depends on some goal having been achieved, it checks whether the goal has already been achieved, if yes, then it uses this cached goal, otherwise it starts the task that will effect the goal, and sends to the client that made the HTTP request a response that indicates it should wait for a result.


The variable names and hyperlinks above are for Celery 4.x. In 3.x the corresponding variables and hyperlinks are: CELERY_TRACK_STARTED, CELERY_IGNORE_RESULT, CELERY_TASK_RESULT_EXPIRES.

Replacing values from a column using a condition in R

# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0

(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:

levels(df$species) <- c(levels(df$species), "unknown") 
df$species[df$depth<10]  <- "unknown" 

How to create a custom scrollbar on a div (Facebook style)

This link should get you started. Long story short, a div that has been styled to look like a scrollbar is used to catch click-and-drag events. Wired up to these events are methods that scroll the contents of another div which is set to an arbitrary height and typically has a css rule of overflow:scroll (there are variants on the css rules but you get the idea).

I'm all about the learning experience -- but after you've learned how it works, I recommend using a library (of which there are many) to do it. It's one of those "don't reinvent" things...

Browse and display files in a git repo without cloning

Not the exact, but a way around.

Use GitHub Developer API

  1. Opening this will get you the recent commits.

    https://api.github.com/repos/learningequality/ka-lite/commits

    You can get the specific commit details by attaching the commit hash in the end of above url.

  2. All the files ( You need sha for the main tree)

    https://api.github.com/repos/learningequality/ka-lite/git/trees/7b698a988683b161bdcd48a949b01e2b336b4c01

I hope this may help.

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

At first you need to have enabled curl extension in PHP. Then you can use this function:

function file_get_contents_ssl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3000); // 3 sec.
    curl_setopt($ch, CURLOPT_TIMEOUT, 10000); // 10 sec.
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

It works similar to function file_get_contents(..).

Example:

echo file_get_contents_ssl("https://www.example.com/");

Output:

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
...

How to break out of nested loops?

A different approach is to refactor the code from two for loops into a for loop and one manual loop. That way the break in the manual loop applies to the outer loop. I used this once in a Gauss-Jordan Elimination which required three nested loops to process.

for (int i = 0; i < 1000; i++)
{
    int j = 0;

MANUAL_LOOP:;

    if (j < 1000)
    {
       if (condition)
       {
           break;
       }

       j++;
       goto MANUAL_LOOP;
    }
}

Delimiter must not be alphanumeric or backslash and preg_match

The pattern must have delimiters. Delimiters can be a forward slash (/) or any non alphanumeric characters(#,$,*,...). Examples

$pattern = "/My name is '(.*)' and im fine/"; 
$pattern = "#My name is '(.*)' and im fine#";
$pattern = "@My name is '(.*)' and im fine@";  

how do I set height of container DIV to 100% of window height?

Add this to your css:

html, body {
    height:100%;
}

If you say height:100%, you mean '100% of the parent element'. If the parent element has no specified height, nothing will happen. You only set 100% on body, but you also need to add it to html.

Disable scrolling in an iPhone web application?

document.ontouchmove = function(e){ 
    e.preventDefault(); 
}

is actually the best choice i found out it allows you to still be able to tap on input fields as well as drag things using jQuery UI draggable but it stops the page from scrolling.

Embed Youtube video inside an Android app

The video quality depends upon the Connection speed using API

alternatively for other than API means without YouTube app you can follow this link

Putting HTML inside Html.ActionLink(), plus No Link Text?

Here is (low and dirty) workaround in case you need to use ajax or some feature which you cannot use when making link manually (using tag):

<%= Html.ActionLink("LinkTextToken", "ActionName", "ControllerName").ToHtmlString().Replace("LinkTextToken", "Refresh <span class='large sprite refresh'></span>")%>

You can use any text instead of 'LinkTextToken', it is there only to be replaced, it is only important that it does not occur anywhere else inside actionlink.

How to Calculate Execution Time of a Code Snippet in C++

Thats how i do it, not much code, easy to understand, fits my needs:

void bench(std::function<void()> fnBench, std::string name, size_t iterations)
{
    if (iterations == 0)
        return;
    if (fnBench == nullptr)
        return;
    std::chrono::high_resolution_clock::time_point start, end;
    if (iterations == 1)
    {
        start = std::chrono::high_resolution_clock::now();
        fnBench();
        end = std::chrono::high_resolution_clock::now();
    }
    else
    {
        start = std::chrono::high_resolution_clock::now();
        for (size_t i = 0; i < iterations; ++i)
            fnBench();
        end = std::chrono::high_resolution_clock::now();
    }
    printf
    (
        "bench(*, \"%s\", %u) = %4.6lfs\r\n",
        name.c_str(),
        iterations,
        std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count()
    );
}

Usage:

bench
(
    []() -> void // function
    {
        // Put your code here
    },
    "the name of this", // name
    1000000 // iterations
);

How to ping multiple servers and return IP address and Hostnames using batch script?

This worked great I just add the -a option to ping to resolve the hostname. Thanks https://stackoverflow.com/users/4447323/wombat

@echo off setlocal enabledelayedexpansion set OUTPUT_FILE=result.csv

>nul copy nul %OUTPUT_FILE%
echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
    set SERVER_ADDRESS_I=UNRESOLVED
    set SERVER_ADDRESS_L=UNRESOLVED
    for /f "tokens=1,2,3" %%x in ('ping -n 1 -a %%i ^&^& echo SERVER_IS_UP') do (
    if %%x==Pinging set SERVER_ADDRESS_L=%%y
    if %%x==Pinging set SERVER_ADDRESS_I=%%z
        if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
    )
    echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
    echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
)

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

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

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

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

Window vs Page vs UserControl for WPF navigation?

Most of all has posted correct answer. I would like to add few links, so that you can refer to them and have clear and better ideas about the same:

UserControl: http://msdn.microsoft.com/en-IN/library/a6h7e207(v=vs.71).aspx

The difference between page and window with respect to WPF: Page vs Window in WPF?

Remove duplicates from an array of objects in JavaScript

Here is a solution using new filter function of JavaScript that is quite easy . Let's say you have an array like this.

var duplicatesArray = ['AKASH','AKASH','NAVIN','HARISH','NAVIN','HARISH','AKASH','MANJULIKA','AKASH','TAPASWENI','MANJULIKA','HARISH','TAPASWENI','AKASH','MANISH','HARISH','TAPASWENI','MANJULIKA','MANISH'];

The filter function will allow you to create a new array, using a callback function once for each element in the array. So you could set up the unique array like this.

var uniqueArray = duplicatesArray.filter(function(elem, pos) {return duplicatesArray.indexOf(elem) == pos;});

In this scenario your unique array will run through all of the values in the duplicate array. The elem variable represents the value of the element in the array (mike,james,james,alex), the position is it's 0-indexed position in the array (0,1,2,3...), and the duplicatesArray.indexOf(elem) value is just the index of the first occurrence of that element in the original array. So, because the element 'james' is duplicated, when we loop through all of the elements in the duplicatesArray and push them to the uniqueArray, the first time we hit james, our "pos" value is 1, and our indexOf(elem) is 1 as well, so James gets pushed to the uniqueArray. The second time we hit James, our "pos" value is 2, and our indexOf(elem) is still 1 (because it only finds the first instance of an array element), so the duplicate is not pushed. Therefore, our uniqueArray contains only unique values.

Here is the Demo of above function.Click Here for the above function example

On Selenium WebDriver how to get Text from Span Tag

I agree css is better. If you did want to do it via Xpath you could try:

    String kk = wd.findElement(By.xpath(.//*div[@id='customSelect_3']/div/span[@class='selectLabel clear'].getText()))

Is it possible to break a long line to multiple lines in Python?

DB related code looks easier on the eyes in multiple lines, enclosed by a pair of triple quotes:

SQL = """SELECT
            id, 
            fld_1, 
            fld_2, 
            fld_3, 
            ...... 
         FROM some_tbl"""

than the following one giant long line:

SQL = "SELECT id, fld_1, fld_2, fld_3, .................................... FROM some_tbl"

How to set a timer in android

Standard Java way to use timers via java.util.Timer and java.util.TimerTask works fine in Android, but you should be aware that this method creates a new thread.

You may consider using the very convenient Handler class (android.os.Handler) and send messages to the handler via sendMessageAtTime(android.os.Message, long) or sendMessageDelayed(android.os.Message, long). Once you receive a message, you can run desired tasks. Second option would be to create a Runnable object and schedule it via Handler's functions postAtTime(java.lang.Runnable, long) or postDelayed(java.lang.Runnable, long).

Set specific precision of a BigDecimal

Try this code ...

    Integer perc = 5;
    BigDecimal spread = BigDecimal.ZERO; 
    BigDecimal perc = spread.setScale(perc,BigDecimal.ROUND_HALF_UP);
    System.out.println(perc);

Result: 0.00000

How to write a simple Html.DropDownListFor()?

<%: 
     Html.DropDownListFor(
           model => model.Color, 
           new SelectList(
                  new List<Object>{ 
                       new { value = 0 , text = "Red"  },
                       new { value = 1 , text = "Blue" },
                       new { value = 2 , text = "Green"}
                    },
                  "value",
                  "text",
                   Model.Color
           )
        )
%>

or you can write no classes, put something like this directly to the view.

OSError - Errno 13 Permission denied

Another option is to ensure the file is not open anywhere else on your machine.

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

Although silly mistake but make sure to use correct module name and respect capitalization

I installed this package via command line as pip install cx_oracle in my windows machine. While importing it in spyder as cx_oracle, it kept on giving following error:

ModuleNotFoundError: No module named 'cx_oracle'.

Upon correcting the module name in import command to cx_Oracle (i.e. capital letter 'O' in oracle), it was a successful import.

What is the equivalent of "!=" in Excel VBA?

Because the inequality operator in VBA is <>

If strTest <> "" Then
    .....

the operator != is used in C#, C++.

Reading Datetime value From Excel sheet

Another option: when cell type is unknown at compile time and cell is formatted as Date Range.Value returns a desired DateTime object.


public static DateTime? GetAsDateTimeOrDefault(Range cell)
{
    object cellValue = cell.Value;
    if (cellValue is DateTime result)
    {
        return result;
    }
    return null;
}

How can I count the number of characters in a Bash variable

Use the wc utility with the print the byte counts (-c) option:

$ SO="stackoverflow"
$ echo -n "$SO" | wc -c
    13

You'll have to use the do not output the trailing newline (-n) option for echo. Otherwise, the newline character will also be counted.

How to pick a new color for each plotted line within a figure in matplotlib?

You can use a predefined "qualitative colormap" like this:

from matplotlib.cm import get_cmap

name = "Accent"
cmap = get_cmap(name)  # type: matplotlib.colors.ListedColormap
colors = cmap.colors  # type: list
axes.set_prop_cycle(color=colors)

Tested on matplotlib 3.0.3. See https://github.com/matplotlib/matplotlib/issues/10840 for discussion on why you can't call axes.set_prop_cycle(color=cmap).

A list of predefined qualititative colormaps is available at https://matplotlib.org/gallery/color/colormap_reference.html :

List of qualitative colormaps

How to convert a ruby hash object to JSON?

You should include json in your file

For Example,

require 'json'

your_hash = {one: "1", two: "2"}
your_hash.to_json

For more knowledge about json you can visit below link. Json Learning

How to run an external program, e.g. notepad, using hyperlink?

I've wrote a small extension to do so.

Since you are creating the page using C# you may want to implement this:

https://github.com/felix-d-git/DesktopAppLink

Basically u are creating some registry entries to parse the links you click in your html page.

The browser will then ask to open the specified app.

C#:

DesktopAppLink.CreateLink("applink.sample", "\"<path to exe>\"", "");

HTML:

<a href="applink.sample:">Run Desktop App</a>

Result:

enter image description here

Run a .bat file using python code

This has already been answered in detail on SO. Check out this thread, It should answer all your questions: Executing a subprocess fails

I've tried it myself with this code:

batchtest.py

from subprocess import Popen
p = Popen("batch.bat", cwd=r"C:\Path\to\batchfolder")
stdout, stderr = p.communicate()

batch.bat

echo Hello World!
pause

I've got the batchtest.py example from the aforementioned thread.

Spring cron expression for every day 1:01:am

Spring cron expression for every day 1:01:am

@Scheduled(cron = "0 1 1 ? * *")

for more information check this information:

https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm

T-SQL: How to Select Values in Value List that are NOT IN the Table?

This Should work with all SQL versions.

SELECT  E.AccessCode ,
        CASE WHEN C.AccessCode IS NOT NULL THEN 'Exist'
             ELSE 'Not Exist'
        END AS [Status]
FROM    ( SELECT    '60552' AS AccessCode
          UNION ALL
          SELECT    '80630'
          UNION ALL
          SELECT    '1611'
          UNION ALL
          SELECT    '0000'
        ) AS E
        LEFT OUTER JOIN dbo.Credentials C ON E.AccessCode = c.AccessCode

Writing to a TextBox from another thread?

On your MainForm make a function to set the textbox the checks the InvokeRequired

public void AppendTextBox(string value)
{
    if (InvokeRequired)
    {
        this.Invoke(new Action<string>(AppendTextBox), new object[] {value});
        return;
    }
    ActiveForm.Text += value;
}

although in your static method you can't just call.

WindowsFormsApplication1.Form1.AppendTextBox("hi. ");

you have to have a static reference to the Form1 somewhere, but this isn't really recommended or necessary, can you just make your SampleFunction not static if so then you can just call

AppendTextBox("hi. ");

It will append on a differnt thread and get marshalled to the UI using the Invoke call if required.

Full Sample

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        new Thread(SampleFunction).Start();
    }

    public void AppendTextBox(string value)
    {
        if (InvokeRequired)
        {
            this.Invoke(new Action<string>(AppendTextBox), new object[] {value});
            return;
        }
        textBox1.Text += value;
    }

    void SampleFunction()
    {
        // Gets executed on a seperate thread and 
        // doesn't block the UI while sleeping
        for(int i = 0; i<5; i++)
        {
            AppendTextBox("hi.  ");
            Thread.Sleep(1000);
        }
    }
}

Regex in JavaScript for validating decimal numbers

 function CheckValidAmount() {
        var amounttext = document.getElementById('txtRemittanceNumber').value;            
        if (!(/^[-+]?\d*\.?\d*$/.test(amounttext))){
            alert('Please enter only numbers into amount textbox.')
            document.getElementById('txtRemittanceNumber').value = "10.00";
        }
    }

This is the function which will take decimal number with any number of decimal places and without any decimal places.

Thanks ... :)

change html text from link with jquery

The method you are looking for is jQuery's .text() and you can used it in the following fashion:

$('#a_tbnotesverbergen').text('text here');

How to detect when a youtube video finishes playing?

What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties

  1. inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx

  2. Add the event listeners etc..

Hope this helps

How to create a localhost server to run an AngularJS project

An angular application can be deployed using any Web server on localhost. The options below outline the deployment instructions for several possible webserver deployments depending on your deployment requirements.


Microsofts Internet Information Services (IIS)

  1. Windows IIS must be enabled

    1.1. In Windows, access the Control Panel and click Add or Remove Programs.

    1.2. In the Add or Remove Programs window, click Add/Remove Windows Components.

    1.3. Select the Internet Information Services (IIS) check box, click Next, then click Finish.

    1.4. Copy and extract the Angular Application Zip file to the webserver root directory: C:\inetpub\wwwroot

  2. The Angular application can now be accessed using the following URL: http://localhost:8080

NPMs Lightweight Web Server

  1. Installing a lightweight web server 1.1. Download and install npm from: https://www.npmjs.com/get-npm 1.2. Once, npm has been installed open a command prompt and type: npm install -g http-server 1.3. Extract the Angular Zip file
  2. To run the web server, open a command prompt, and navigate to the directory where you extracted the Angular previously and type: http-server
  3. The Angular Application application can now be accessed using the following URL: http://localhost:8080

Apache Tomcat Web Server

  1. Installing Apache Tomcat version 8 1.1. Download and install Apache Tomcat from: https://tomcat.apache.org/ 1.2. Copy and extract the Angular Application Zip file to the webserver root directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps
  2. The Angular Application can now be accessed using the following URL: http://localhost:8080

Getting indices of True values in a boolean list

Using element-wise multiplication and a set:

>>> states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> set(multiply(states,range(1,len(states)+1))-1).difference({-1})

Output: {4, 5, 7}

$.ajax - dataType

  • contentType is the HTTP header sent to the server, specifying a particular format.
    Example: I'm sending JSON or XML
  • dataType is you telling jQuery what kind of response to expect.
    Expecting JSON, or XML, or HTML, etc. The default is for jQuery to try and figure it out.

The $.ajax() documentation has full descriptions of these as well.


In your particular case, the first is asking for the response to be in UTF-8, the second doesn't care. Also the first is treating the response as a JavaScript object, the second is going to treat it as a string.

So the first would be:

success: function(data) {
  // get data, e.g. data.title;
}

The second:

success: function(data) {
  alert("Here's lots of data, just a string: " + data);
}

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

For what is worth if anyone should read again this topic(like me) the correct answer would be in DateTimeFormatter definition, e.g.:

private static DateTimeFormatter DATE_FORMAT =  
            new DateTimeFormatterBuilder().appendPattern("dd/MM/yyyy[ [HH][:mm][:ss][.SSS]]")
            .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .toFormatter(); 

One should set the optional fields if they will appear. And the rest of code should be exactly the same.

How to scroll table's "tbody" independent of "thead"?

I saw this post about a month ago when I was having similar problems. I needed y-axis scrolling for a table inside of a ui dialog (yes, you heard me right). I was lucky, in that a working solution presented itself fairly quickly. However, it wasn't long before the solution took on a life of its own, but more on that later.

The problem with just setting the top level elements (thead, tfoot, and tbody) to display block, is that browser synchronization of the column sizes between the various components is quickly lost and everything packs to the smallest permissible size. Setting the widths of the columns seems like the best course of action, but without setting the widths of all the internal table components to match the total of these columns, even with a fixed table layout, there is a slight divergence between the headers and body when a scroll bar is present.

The solution for me was to set all the widths, check if a scroll bar was present, and then take the scaled widths the browser had actually decided on, and copy those to the header and footer adjusting the last column width for the size of the scroll bar. Doing this provides some fluidity to the column widths. If changes to the table's width occur, most major browsers will auto-scale the tbody column widths accordingly. All that's left is to set the header and footer column widths from their respective tbody sizes.

$table.find("> thead,> tfoot").find("> tr:first-child")
    .each(function(i,e) {
        $(e).children().each(function(i,e) {
            if (i != column_scaled_widths.length - 1) {
                $(e).width(column_scaled_widths[i] - ($(e).outerWidth() - $(e).width()));
            } else {
                $(e).width(column_scaled_widths[i] - ($(e).outerWidth() - $(e).width()) + $.position.scrollbarWidth());
            }
        });
    });

This fiddle illustrates these notions: http://jsfiddle.net/borgboyone/gbkbhngq/.

Note that a table wrapper or additional tables are not needed for y-axis scrolling alone. (X-axis scrolling does require a wrapping table.) Synchronization between the column sizes for the body and header will still be lost if the minimum pack size for either the header or body columns is encountered. A mechanism for minimum widths should be provided if resizing is an option or small table widths are expected.

The ultimate culmination from this starting point is fully realized here: http://borgboyone.github.io/jquery-ui-table/

A.

How to send email attachments?

Below is combination of what I've found from SoccerPlayer's post Here and the following link that made it easier for me to attach an xlsx file. Found Here

file = 'File.xlsx'
username=''
password=''
send_from = ''
send_to = 'recipient1 , recipient2'
Cc = 'recipient'
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Cc'] = Cc
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = ''
server = smtplib.SMTP('smtp.gmail.com')
port = '587'
fp = open(file, 'rb')
part = MIMEBase('application','vnd.ms-excel')
part.set_payload(fp.read())
fp.close()
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename='Name File Here')
msg.attach(part)
smtp = smtplib.SMTP('smtp.gmail.com')
smtp.ehlo()
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to.split(',') + msg['Cc'].split(','), msg.as_string())
smtp.quit()

Converting a datetime string to timestamp in Javascript

Seems like the problem is with the date format.

 var d = "17-09-2013 10:08",
 dArr = d.split('-'),
 ts = new Date(dArr[1] + "-" + dArr[0] + "-" + dArr[2]).getTime(); // 1379392680000

What does the line "#!/bin/sh" mean in a UNIX shell script?

It's called a shebang, and tells the parent shell which interpreter should be used to execute the script.

#!/bin/sh <--------- bourne shell compatible script
#!/usr/bin/perl  <-- perl script
#!/usr/bin/php  <--- php script
#!/bin/false <------ do-nothing script, because false returns immediately anyways.

Most scripting languages tend to interpret a line starting with # as comment and will ignore the following !/usr/bin/whatever portion, which might otherwise cause a syntax error in the interpreted language.

I want to remove double quotes from a String

If you only want to remove quotes from the beginning or the end, use the following regular expression:

'"Hello"'.replace(/(^"|"$)/g, '');

How to completely remove node.js from Windows

Scenario: Removing NodeJS when Windows has no Program Entry for your Node installation

I ran into a problem where my version of NodeJS (0.10.26) could NOT be uninstalled nor removed, because Programs & Features in Windows 7 (aka Add/Remove Programs) had no record of my having installed NodeJS... so there was no option to remove it short of manually deleting registry keys and files.

Command to verify your NodeJS version: node --version

I attempted to install the newest recommended version of NodeJS, but it failed at the end of the installation process and rolled back. Multiple versions of NodeJS also failed, and the installer likewise rolled them back as well. I could not upgrade NodeJS from the command line as I did not have SUDO installed.

SOLUTION: After spending several hours troubleshooting the problem, including upgrading NPM, I decided to reinstall the EXACT version of NodeJS on my system, over the top of the existing installation.

That solution worked, and it reinstalled NodeJS without any errors. Better yet, it also added an official entry in Add/Remove Programs dialogue.

Now that Windows was aware of the forgotten NodeJS installation, I was able to uninstall my existing version of NodeJS completely. I then successfully installed the newest recommended release of NodeJS for the Windows platform (version 4.4.5 as of this writing) without a roll-back initiating.

It took me a while to reach sucess, so I am posting this in case it helps anyone else with a similar issue.

Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
        .select(root)
        .where(predicateResult);

List<SomeClass> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();  

How to convert a string from uppercase to lowercase in Bash?

Note that tr can only handle plain ASCII, making any tr-based solution fail when facing international characters.

Same goes for the bash 4 based ${x,,} solution.

The awk tool, on the other hand, properly supports even UTF-8 / multibyte input.

y="HELLO"
val=$(echo "$y" | awk '{print tolower($0)}')
string="$val world"

Answer courtesy of liborw.

Permission denied when launch python script via bash

Okay, so first of all check if you are in the correct directory where your python script is located.
On the net, they say to run the command :

python3 your_file_name.py

But it doesn't work.
What worked for me however was:

python -u my_file_name.py

docker-compose up for only certain containers

I actually had a very similar challenge on my current project. That broght me to the idea of writing a small script which I called docker-compose-profile (or short: dcp). I published this today on GitLab as docker-compose-profile. So in short: I now can start several predefined docker-compose profiles using a command like dcp -p some-services "up -d". Feel free to try it out and give some feedback or suggestions for further improvements.

Update data on a page without refreshing

In general, if you don't know how something works, look for an example which you can learn from.

For this problem, consider this DEMO

You can see loading content with AJAX is very easily accomplished with jQuery:

$(function(){
    // don't cache ajax or content won't be fresh
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";

    // load() functions
    var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
    $("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

// end  
});

Try to understand how this works and then try replicating it. Good luck.

You can find the corresponding tutorial HERE

Update

Right now the following event starts the ajax load function:

$("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

You can also do this periodically: How to fire AJAX request Periodically?

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);) the content is updated.

You can also just load the data immediately:

$("#result").html(ajax_load).load(loadUrl);

Which has THIS corresponding demo.

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

Its an XML namespace. It is required when you use XHTML 1.0 or 1.1 doctypes or application/xhtml+xml mimetypes.

You should be using HTML5 doctype, then you don't need it for text/html. Better start from template like this :

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8 />
        <title>domcument title</title>
        <link rel="stylesheet" href="/stylesheet.css" type="text/css" />
    </head>
    <body>
            <!-- your html content -->
            <script src="/script.js"></script>
    </body>
</html>



When you have put your Doctype straight - do and validate you html and your css .
That usually will sove you layout issues.

How to declare a global variable in JavaScript

If you have to generate global variables in production code (which should be avoided) always declare them explicitly:

window.globalVar = "This is global!";

While it is possible to define a global variable by just omitting var (assuming there is no local variable of the same name), doing so generates an implicit global, which is a bad thing to do and would generate an error in strict mode.

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

Had the same problem. A colleague solved this with jQuery.Globalize.

<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/Scripts/jquery.globalize/globalize.js" type="text/javascript"></script>
<script src="/Scripts/jquery.globalize/cultures/globalize.culture.nl.js"></script>
<script type="text/javascript">
    var lang = 'nl';

    $(function () {
        Globalize.culture(lang);
    });

    // fixing a weird validation issue with dates (nl date notation) and Google Chrome
    $.validator.methods.date = function(value, element) {
        var d = Globalize.parseDate(value);
        return this.optional(element) || !/Invalid|NaN/.test(d);
    };
</script>

I am using jQuery Datepicker for selecting the date.

TCPDF Save file to folder?

Only thing that worked for me:

// save file
$pdf->Output(__DIR__ . '/example_001.pdf', 'F');
exit();

How to prevent tensorflow from allocating the totality of a GPU memory?

i tried to train unet on voc data set but because of huge image size, memory finishes. i tried all the above tips, even tried with batch size==1, yet to no improvement. sometimes TensorFlow version also causes the memory issues. try by using

pip install tensorflow-gpu==1.8.0

Removing pip's cache?

Clear the cache directory where appropriate for your system

Linux and Unix

~/.cache/pip  # and it respects the XDG_CACHE_HOME directory.

OS X

~/Library/Caches/pip

Windows

%LocalAppData%\pip\Cache

UPDATE

With pip 20.1 or later, you can find the full path for your operating system easily by typing this in the command line:

pip cache dir

Example output on my Ubuntu installation:

? pip3 cache dir
/home/tawanda/.cache/pip

size of NumPy array

This is called the "shape" in NumPy, and can be requested via the .shape attribute:

>>> a = zeros((2, 5))
>>> a.shape
(2, 5)

If you prefer a function, you could also use numpy.shape(a).

JavaScript associative array to JSON

Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).

If you convert an array to JSON, the process will only take numerical properties into account. Other properties are simply ignored and that's why you get an empty array as result. Maybe this more obvious if you look at the length of the array:

> AssocArray.length
0

What is often referred to as "associative array" is actually just an object in JS:

var AssocArray = {};  // <- initialize an object, not an array
AssocArray["a"] = "The letter A"

console.log("a = " + AssocArray["a"]); // "a = The letter A"
JSON.stringify(AssocArray); // "{"a":"The letter A"}"

Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus AssocArray.a is the same as AssocArray['a'].

Setting a minimum/maximum character count for any character using a regular expression

If you want to set Min 1 count and no Max length,

^.{1,}$

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

As something of an aside, MAXDOP can apparently be used as a workaround to a potentially nasty bug:

Returned identity values not always correct

How to put a delay on AngularJS instant search?

 <input type="text"
    ng-model ="criteria.searchtext""  
    ng-model-options="{debounce: {'default': 1000, 'blur': 0}}"
    class="form-control" 
    placeholder="Search" >

Now we can set ng-model-options debounce with time and when blur, model need to be changed immediately otherwise on save it will have older value if delay is not completed.

Threading Example in Android

Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.

Android code - Main.java

package test12.tt;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Test12Activity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final TextView txt1 = (TextView) findViewById(R.id.sm);

        new Thread(new Runnable() { 
            public void run(){        
            txt1.setText("Thread!!");
            }
        }).start();

    }    
}

Android application xml - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView  
    android:id = "@+id/sm"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"/>

</LinearLayout>

What is an unsigned char?

As for example usages of unsigned char:

unsigned char is often used in computer graphics, which very often (though not always) assigns a single byte to each colour component. It is common to see an RGB (or RGBA) colour represented as 24 (or 32) bits, each an unsigned char. Since unsigned char values fall in the range [0,255], the values are typically interpreted as:

  • 0 meaning a total lack of a given colour component.
  • 255 meaning 100% of a given colour pigment.

So you would end up with RGB red as (255,0,0) -> (100% red, 0% green, 0% blue).

Why not use a signed char? Arithmetic and bit shifting becomes problematic. As explained already, a signed char's range is essentially shifted by -128. A very simple and naive (mostly unused) method for converting RGB to grayscale is to average all three colour components, but this runs into problems when the values of the colour components are negative. Red (255, 0, 0) averages to (85, 85, 85) when using unsigned char arithmetic. However, if the values were signed chars (127,-128,-128), we would end up with (-99, -99, -99), which would be (29, 29, 29) in our unsigned char space, which is incorrect.

How can I install a .ipa file to my iPhone simulator

You can't. If it was downloaded via the iTunes store it was built for a different processor and won't work in the simulator.

Write variable to a file in Ansible

Unless you are writing very small files, you should probably use templates.

Example:

- name: copy upstart script
  template: 
    src: myCompany-service.conf.j2 
    dest: "/etc/init/myCompany-service.conf"

How can I get dictionary key as variable directly in Python (not by searching from value)?

You should iterate over keys with:

for key in mydictionary:
   print "key: %s , value: %s" % (key, mydictionary[key])

post checkbox value

You should use

<input type="submit" value="submit" />

inside your form.

and add action into your form tag for example:

<form action="booking.php" method="post">

It's post your form into action which you choose.

From php you can get this value by

$_POST['booking-check'];

CodeIgniter - return only one row?

This is better way as it gives you result in a single line:

$this->db->query("Your query")->row()->campaign_id;

Vertical Align Center in Bootstrap 4

Vertical align Using this bootstrap 4 classes:

parent: d-table

AND

child: d-table-cell & align-middle & text-center

eg:

<div class="tab-icon-holder d-table bg-light">
   <div class="d-table-cell align-middle text-center">
     <img src="assets/images/devices/Xl.png" height="30rem">
   </div>
</div>

and if you want parent be circle:

<div class="tab-icon-holder d-table bg-light rounded-circle">
   <div class="d-table-cell align-middle text-center">
     <img src="assets/images/devices/Xl.png" height="30rem">
   </div>
</div>

which two custom css classes are as follow:

.tab-icon-holder {
  width: 3.5rem;
  height: 3.5rem;
 }
.rounded-circle {
  border-radius: 50% !important
}

Final usage can be like for example:

<div class="col-md-5 mx-auto text-center">
    <div class="d-flex justify-content-around">
     <div class="tab-icon-holder d-table bg-light rounded-circle">
       <div class="d-table-cell align-middle text-center">
         <img src="assets/images/devices/Xl.png" height="30rem">
       </div>
     </div>

     <div class="tab-icon-holder d-table bg-light rounded-circle">
       <div class="d-table-cell align-middle text-center">
         <img src="assets/images/devices/Lg.png" height="30rem">
       </div>
     </div>

     ...

    </div>
</div>

Also in some cases you can use following code:

parent: h-100 d-table mx-auto

AND

child: d-table-cell & align-middle

Close Bootstrap modal on form submit

If you do not want to use jQuery, make the button type a normal button and add a click listener pointing to the function you would like to execute, and send the form in as a parameter. The button would be as follows:

<button (click)="yourSubmitFunction(yourForm)" [disabled]="!yourForm.valid" type="button" class="btn btn-primary" data-dismiss="modal">Save changes</button>

Remember to remove: (ngSubmit)="yourSubmitFunction(yourForm)" from the form div if you use this method.

How to add an Android Studio project to GitHub

First of all, create a Github account and project in Github. Go to the root folder and follow steps.

The most important thing we forgot here is ignoring the file. Every time we run Gradle or build it creates new files that are changeable from build to build and pc to pc. We do not want all the files from Android Studio to be added to Git. Files like generated code, binary files (executables) should not be added to Git (version control). So please use .gitignore file while uploading projects to Github. It also reduces the size of the project uploaded to the server.

  1. Go to root folder.
  2. git init
  3. Create .gitignore txt file in root folder. Place these content in the file. (this step not required if the file is auto-generated)

    *.iml .gradle /local.properties /.idea/workspace.xml /.idea/libraries .idea .DS_Store /build /captures .externalNativeBuild

  4. git add .
  5. git remote add origin https://github.com/username/project.git
  6. git commit - m "My First Commit"
  7. git push -u origin master

Note : As per suggestion from different developers, they always suggest to use git from the command line. It is up to you.

How do I import a pre-existing Java project into Eclipse and get up and running?

In the menu go to : - File - Import - as the filter select 'Existing Projects into Workspace' - click next - browse to the project directory at 'select root directory' - click on 'finish'

What certificates are trusted in truststore?

Is there any equivalent for the truststore? How can I view the trusted certificates?

Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)

No other difference

Comparing Arrays of Objects in JavaScript

Please try this one:

function used_to_compare_two_arrays(a, b)
{
  // This block will make the array of indexed that array b contains a elements
  var c = a.filter(function(value, index, obj) {
    return b.indexOf(value) > -1;
  });

  // This is used for making comparison that both have same length if no condition go wrong 
  if (c.length !== a.length) {
    return 0;
  } else{
    return 1;
  }
}

@JsonProperty annotation on field as well as getter/setter

My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:

For eg. consider a slight modification of your case:

@JsonProperty("fileName")
private String fileName;

@JsonProperty("fileName")
public String getFileName()
{
    return fileName;
}

@JsonProperty("fileName1")
public void setFileName(String fileName)
{
    this.fileName = fileName;
}

Both fileName field, and method getFileName, have the correct property name of fileName and setFileName has a different one fileName1, in this case Jackson will look for a fileName1 attribute in json at the point of deserialization and will create a attribute called fileName1 at the point of serialization.

Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName, it would just pick one of them as the attribute(FILENAME), and had any on of the three differed, it would have thrown an exception:

java.lang.IllegalStateException: Conflicting property name definitions

How to close existing connections to a DB

in restore wizard click "close existing connections to destination database"

in Detach Database wizard click "Drop connection" item.

iOS 9 not opening Instagram app with URL SCHEME

Apple changed the canOpenURL method on iOS 9. Apps which are checking for URL Schemes on iOS 9 and iOS 10 have to declare these Schemes as it is submitted to Apple.

Use of contains in Java ArrayList<String>

Perhaps you need to post the code that caused your exception. If the above is all you have, perhaps you just failed to actually initialise the array.

Using contains here should work though.

Display label text with line breaks in c#

You may append HTML <br /> in between your lines. Something like:

MyLabel.Text = "SomeText asdfa asd fas df asdf" + "<br />" + "Some more text";

With StringBuilder you can try:

StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />");

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

To fix this you can simply use the exclamation mark if you're sure that the object is not null when accessing its property:

list!.values

At first sight, some people might confuse this with the safe navigation operator from angular, this is not the case!

list?.values

The ! post-fix expression will tell the TS compiler that variable is not null, if that's not the case it will crash at runtime

useRef

for useRef hook use like this

const value = inputRef?.current?.value

How to assert two list contain the same elements in Python?

Given

l1 = [a,b]
l2 = [b,a]

In Python >= 3.0

assertCountEqual(l1, l2) # True

In Python >= 2.7, the above function was named:

assertItemsEqual(l1, l2) # True

In Python < 2.7

import unittest2
assertItemsEqual(l1, l2) # True

Via six module (Any Python version)

import unittest
import six
class MyTest(unittest.TestCase):
    def test(self):
        six.assertCountEqual(self, self.l1, self.l2) # True

How can I select all rows with sqlalchemy?

I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'MyTable'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    some_col = Column(String(500))

    def __init__(self, some_col):
        self.some_col = some_col

engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

for class_instance in session.query(MyTable).all():
    print(vars(class_instance))

session.close()

Can comments be used in JSON?

As many answers have already pointed out, JSON does not natively have comments. Of course sometimes you want them anyway. For Python, two ways to do that are with commentjson (# and // for Python 2 only) or json_tricks (# or // for Python 2 and Python 3), which has several other features. Disclaimer: I made json_tricks.

CSS 100% height with padding/margin

I learned how to do these sort of things reading "PRO HTML and CSS Design Patterns". The display:block is the default display value for the div, but I like to make it explicit. The container has to be the right type; position attribute is fixed, relative, or absolute.

_x000D_
_x000D_
.stretchedToMargin {_x000D_
  display: block;_x000D_
  position:absolute;_x000D_
  height:auto;_x000D_
  bottom:0;_x000D_
  top:0;_x000D_
  left:0;_x000D_
  right:0;_x000D_
  margin-top:20px;_x000D_
  margin-bottom:20px;_x000D_
  margin-right:80px;_x000D_
  margin-left:80px;_x000D_
  background-color: green;_x000D_
}
_x000D_
<div class="stretchedToMargin">_x000D_
  Hello, world_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle by Nooshu's comment

How can I export tables to Excel from a webpage

A long time ago, I discovered that Excel would open an HTML file with a table if we send it with Excel content type. Consider the document above:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Java Friends</title>
</head>
<body>
  <table style="font-weight: bold">
    <tr style="background-color:red"><td>a</td><td>b</td></tr>
    <tr><td>1</td><td>2</td></tr>
  </table>    
</body>
</html>

I ran the following bookmarklet on it:

javascript:window.open('data:application/vnd.ms-excel,'+document.documentElement.innerHTML);

and in fact I got it downloadable as a Excel file. However, I did not get the expected result - the file was open in OpenOffice.org Writer. That is my problem: I do not have Excel in this machine so I cannot try it better. Also, this trick worked more or less six years ago with older browsers and an antique version of MS Office, so I really cannot say if it will work today.

Anyway, in the document above I added a button which would download the entire document as an Excel file, in theory:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Java Friends</title>
</head>
<body>
  <table style="font-weight: bold">
    <tr style="background-color:red"><td>a</td><td>b</td></tr>
    <tr><td>1</td><td>2</td></tr>
    <tr>
      <td colspan="2">
        <button onclick="window.open('data:application/vnd.ms-excel,'+document.documentElement.innerHTML);">
            Get as Excel spreadsheet
        </button>
      </td>
    </tr>
  </table>    
</body>
</html>

Save it in a file and click on the button. I'd love to know if it worked or not, so I ask you to comment even for saying that it did not work.

Sorting int array in descending order

For primitive array types, you would have to write a reverse sort algorithm:

Alternatively, you can convert your int[] to Integer[] and write a comparator:

public class IntegerComparator implements Comparator<Integer> {

    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}

or use Collections.reverseOrder() since it only works on non-primitive array types.

and finally,

Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1);
Arrays.sort(a2, new IntegerComparator()); // OR
// Arrays.sort(a2, Collections.reverseOrder());

//Unbox the array to primitive type
a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2);

What is the correct value for the disabled attribute?

HTML5 spec:

http://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute :

The checked content attribute is a boolean attribute

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion:

The following are valid, equivalent and true:

<input type="text" disabled />
<input type="text" disabled="" />
<input type="text" disabled="disabled" />
<input type="text" disabled="DiSaBlEd" />

The following are invalid:

<input type="text" disabled="0" />
<input type="text" disabled="1" />
<input type="text" disabled="false" />
<input type="text" disabled="true" />

The absence of the attribute is the only valid syntax for false:

<input type="text" />

Recommendation

If you care about writing valid XHTML, use disabled="disabled", since <input disabled> is invalid and other alternatives are less readable. Else, just use <input disabled> as it is shorter.

Python Pandas Counting the Occurrences of a Specific value

Couple of ways using count or sum

In [338]: df
Out[338]:
  col1 education
0    a       9th
1    b       9th
2    c       8th

In [335]: df.loc[df.education == '9th', 'education'].count()
Out[335]: 2

In [336]: (df.education == '9th').sum()
Out[336]: 2

In [337]: df.query('education == "9th"').education.count()
Out[337]: 2

Hive: Filtering Data between Specified Dates when Date is a String

Hive has a lot of good date parsing UDFs: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

Just doing the string comparison as Nigel Tufnel suggests is probably the easiest solution, although technically it's unsafe. But you probably don't need to worry about that unless your tables have historical data about the medieval ages (dates with only 3 year digits) or dates from scifi novels (dates with more than 4 year digits).

Anyway, if you ever find yourself in a situation where you would want to do fancier date comparisons, or if your date format is not in a "biggest to smallest" order, e.g. the American convention of "mm/dd/yyyy", then you could use unix_timestamp with two arguments:

select *
from your_table
where unix_timestamp(your_date_column, 'yyyy-MM-dd') >= unix_timestamp('2010-09-01', 'yyyy-MM-dd')
and unix_timestamp(your_date_column, 'yyyy-MM-dd') <= unix_timestamp('2013-08-31', 'yyyy-MM-dd')

jQuery to retrieve and set selected option value of html select element

When setting with JQM, don't forget to update the UI:

$('#selectId').val('newValue').selectmenu('refresh', true);

How to place the ~/.composer/vendor/bin directory in your PATH?

To put this folder on the PATH environment variable type

export PATH="$PATH:$HOME/.composer/vendor/bin"

This appends the folder to your existing PATH, however, it is only active for your current terminal session.

If you want it to be automatically set, it depends on the shell you are using. For bash, you can append this line to $HOME/.bashrc using your favorite editor or type the following on the shell

echo 'export PATH="$PATH:$HOME/.composer/vendor/bin"' >> ~/.bashrc

In order to check if it worked, logout and login again or execute

source ~/.bashrc

on the shell.

PS: For other systems where there is no ~/.bashrc, you can also put this into ~/.bash_profile

PSS: For more recent laravel you need to put $HOME/.config/composer/vendor/bin on the PATH.

PSSS: If you want to put this folder on the path also for other shells or on the GUI, you should append the said export command to ~/.profile (cf. https://help.ubuntu.com/community/EnvironmentVariables).

Windows task scheduler error 101 launch failure code 2147943785

Had the same issue but mine was working for weeks before this. Realised I had changed my password on the server.

Remember to update your password if you've got the option selected 'Run whether user is logged on or not'

How do I get the unix timestamp in C as an int?

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

int main ()
{
   time_t seconds;

   seconds = time(NULL);
   printf("Seconds since January 1, 1970 = %ld\n", seconds);

   return(0);
}

And will get similar result:
Seconds since January 1, 1970 = 1476107865

how do I get eclipse to use a different compiler version for Java?

Eclipse uses it's own internal compiler that can compile to several Java versions.

From Eclipse Help > Java development user guide > Concepts > Java Builder

The Java builder builds Java programs using its own compiler (the Eclipse Compiler for Java) that implements the Java Language Specification.

For Eclipse Mars.1 Release (4.5.1), this can target 1.3 to 1.8 inclusive.

When you configure a project:

[project-name] > Properties > Java Compiler > Compiler compliance level

This configures the Eclipse Java compiler to compile code to the specified Java version, typically 1.8 today.

Host environment variables, eg JAVA_HOME etc, are not used.

The Oracle/Sun JDK compiler is not used.

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

Connect to SQL Server 2012 Database with C# (Visual Studio 2012)

In your connection string replace server=localhost with "server = Paul-PC\\SQLEXPRESS;"

How do I bottom-align grid elements in bootstrap fluid layout

Please note: for Bootstrap 4+ users, please consider Christophe's solution (Bootstrap 4 introduced flexbox, which provides for a more elegant CSS-only solution). The following will work for earlier versions of Bootstrap...


See http://jsfiddle.net/jhfrench/bAHfj/ for a working solution.

//for each element that is classed as 'pull-down', set its margin-top to the difference between its own height and the height of its parent
$('.pull-down').each(function() {
  var $this = $(this);
  $this.css('margin-top', $this.parent().height() - $this.height())
});

On the plus side:

  • in the spirit of Bootstrap's existing helper classes, I named the class pull-down.
  • only the element that is getting "pulled down" needs to be classed, so...
  • ...it's reusable for different element types (div, span, section, p, etc)
  • it's fairly-well supported (all the major browsers support margin-top)

Now the bad news:

  • it requires jQuery
  • it's not, as-written, responsive (sorry)

Integrity constraint violation: 1452 Cannot add or update a child row:

Also make sure that the foreign key you add is the same type of the original column, if the column you're reference is not the same type it will fail too.

How to use clock() in C++

you can measure how long your program works. The following functions help measure the CPU time since the start of the program:

  • C++ (double)clock() / CLOCKS PER SEC with ctime included.
  • python time.clock() returns floating-point value in seconds.
  • Java System.nanoTime() returns long value in nanoseconds.

my reference: Algorithms toolbox week 1 course part of data structures and algorithms specialization by University of California San Diego & National Research University Higher School of Economics

so you can add this line of code after your algorithm

cout << (double)clock() / CLOCKS_PER_SEC ;

Expected Output: the output representing the number of clock ticks per second

C# how to convert File.ReadLines into string array?

string[] lines = File.ReadLines("c:\\file.txt").ToArray();

Although one wonders why you'll want to do that when ReadAllLines works just fine.

Or perhaps you just want to enumerate with the return value of File.ReadLines:

var lines = File.ReadAllLines("c:\\file.txt");
foreach (var line in lines)
{
    Console.WriteLine("\t" + line);
}

Check if table exists in SQL Server

IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE 
TABLE_CATALOG = 'Database Name' and
TABLE_NAME = 'Table Name' and 
TABLE_SCHEMA = 'Schema Name') -- Database and Schema name in where statement can be deleted

BEGIN
--TABLE EXISTS
END

ELSE BEGIN
--TABLE DOES NOT EXISTS
END

Matplotlib: "Unknown projection '3d'" error

Just to add to Joe Kington's answer (not enough reputation for a comment) there is a good example of mixing 2d and 3d plots in the documentation at http://matplotlib.org/examples/mplot3d/mixed_subplots_demo.html which shows projection='3d' working in combination with the Axes3D import.

from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.add_subplot(2, 1, 1)
...
ax = fig.add_subplot(2, 1, 2, projection='3d')

In fact as long as the Axes3D import is present the line

from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.gca(projection='3d')

as used by the OP also works. (checked with matplotlib version 1.3.1)

Difference between static STATIC_URL and STATIC_ROOT on Django

STATIC_ROOT

The absolute path to the directory where ./manage.py collectstatic will collect static files for deployment. Example: STATIC_ROOT="/var/www/example.com/static/"

now the command ./manage.py collectstatic will copy all the static files(ie in static folder in your apps, static files in all paths) to the directory /var/www/example.com/static/. now you only need to serve this directory on apache or nginx..etc.

STATIC_URL

The URL of which the static files in STATIC_ROOT directory are served(by Apache or nginx..etc). Example: /static/ or http://static.example.com/

If you set STATIC_URL = 'http://static.example.com/', then you must serve the STATIC_ROOT folder (ie "/var/www/example.com/static/") by apache or nginx at url 'http://static.example.com/'(so that you can refer the static file '/var/www/example.com/static/jquery.js' with 'http://static.example.com/jquery.js')

Now in your django-templates, you can refer it by:

{% load static %}
<script src="{% static "jquery.js" %}"></script>

which will render:

<script src="http://static.example.com/jquery.js"></script>

What is the difference between HTML tags and elements?

This visualization can help us to find out difference between concept of element and tag (each indent means contain):

- element

        - content:

            - text 

            - other elements 

            - or empty

        - and its markup

            - tags (start or end tag)

                - element name

                - angle brackets < >

                - or attributes (just for start tag)

                - or slash / 

What's the difference between session.persist() and session.save() in Hibernate?

From this forum post

persist() is well defined. It makes a transient instance persistent. However, it doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. The spec doesn't say that, which is the problem I have with persist().

persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. This is useful in long-running conversations with an extended Session/persistence context.

A method like persist() is required.

save() does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier (e.g. "identity" generator, not "sequence"), this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is not good in a long-running conversation with an extended Session/persistence context.

How to copy folders to docker image from Dockerfile?

COPY . <destination>

Which would be in your case:

COPY . /

Child with max-height: 100% overflows parent

Your container does not have a height.

Add height: 200px;

to the containers css and the kitty will stay inside.

How to select multiple files with <input type="file">?

The whole thing should look like:

<form enctype='multipart/form-data' method='POST' action='submitFormTo.php'> 
    <input type='file' name='files[]' multiple />
    <button type='submit'>Submit</button>
</form>

Make sure you have the enctype='multipart/form-data' attribute in your <form> tag, or you can't read the files on the server side after submission!

Mobile Redirect using htaccess

For Mobiles like domain.com/m/

RewriteCond %{HTTP_REFERER} !^http://(.*).domain.com/.*$ [NC]
RewriteCond %{REQUEST_URI} !^/m/.*$
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^(.*)$ /m/ [L,R=302]

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

Something like this should work:

<%=Html.TextBox("test", new { style="width:50px" })%>

Or better:

<%=Html.TextBox("test")%>

<style type="text/css">
    input[type="text"] { width:50px; }     
</style>

How to execute a JavaScript function when I have its name as a string

BE CAREFUL!!!

One should try to avoid calling a function by string in JavaScript for two reasons:

Reason 1: Some code obfuscators will wreck your code as they will change the function names, making the string invalid.

Reason 2: It is much harder to maintain code that uses this methodology as it is much harder to locate usages of the methods called by a string.

JDK was not found on the computer for NetBeans 6.5

I have got the JDK installed

You haven't specified the version. I think it is not 6 nor 5.

JDK 6 was the latest version at time of NetBeans 6.0 - 6.9 are developed. For that reason, They require JDK 6 (or JDK 5) and do not run on JDK 7 or later.

Download JDK 6
Download latest version of NetBeans

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

What went wrong?

When you include jQuery the first time:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>

The second script plugs itself into jQuery, and "adds" $(...).datepicker.

But then you are including jQuery once again:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

It undoes the plugging in and therefore $(...).datepicker becomes undefined.

Although the first $(document).ready block appears before that, the anonymous callback function body is not executed until all scripts are loaded, and by then $(...) (window.$ to be precise) is referring to the most recently loaded jQuery.

You would not run into this if you called $('.dateinput').datepicker immediately rather than in $(document).ready callback, but then you'd need to make sure that the target element (with class dateinput) is already in the document before the script, and it's generally advised to use the ready callback.

Solution

If you want to use datepicker from jquery-ui, it would probably make most sense to include the jquery-ui script after bootstrap. jquery-ui 1.11.4 is compatible with jquery 1.6+ so it will work fine.

Alternatively (in particular if you are not using jquery-ui for anything else), you could try bootstrap-datepicker.

Checking length of dictionary object

What I do is use Object.keys() to return a list of all the keys and then get the length of that

Object.keys(dictionary).length

What HTTP traffic monitor would you recommend for Windows?

Fiddler is great when you are only interested in the http(s) side of the communications. It is also very useful when you are trying to inspect inside a https stream.

Pandas: drop a level from a multi-level column index?

You can use MultiIndex.droplevel:

>>> cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")])
>>> df = pd.DataFrame([[1,2], [3,4]], columns=cols)
>>> df
   a   
   b  c
0  1  2
1  3  4

[2 rows x 2 columns]
>>> df.columns = df.columns.droplevel()
>>> df
   b  c
0  1  2
1  3  4

[2 rows x 2 columns]

MVVM Passing EventArgs As Command Parameter

To add to what joshb has stated already - this works just fine for me. Make sure to add references to Microsoft.Expression.Interactions.dll and System.Windows.Interactivity.dll and in your xaml do:

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

I ended up using something like this for my needs. This shows that you can also pass a custom parameter:

<i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">

                <i:InvokeCommandAction Command="{Binding Path=DataContext.RowSelectedItem, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" 
                                       CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}" />
            </i:EventTrigger>
</i:Interaction.Triggers>

Regular expression: zero or more occurrences of optional character /

/*

If your delimiters are slash-based, escape it:

\/*

* means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.

Proxy with express.js

I found a shorter and very straightforward solution which works seamlessly, and with authentication as well, using express-http-proxy:

const url = require('url');
const proxy = require('express-http-proxy');

// New hostname+path as specified by question:
const apiProxy = proxy('other_domain.com:3000/BLABLA', {
    proxyReqPathResolver: req => url.parse(req.baseUrl).path
});

And then simply:

app.use('/api/*', apiProxy);

Note: as mentioned by @MaxPRafferty, use req.originalUrl in place of baseUrl to preserve the querystring:

    forwardPath: req => url.parse(req.baseUrl).path

Update: As mentioned by Andrew (thank you!), there's a ready-made solution using the same principle:

npm i --save http-proxy-middleware

And then:

const proxy = require('http-proxy-middleware')
var apiProxy = proxy('/api', {target: 'http://www.example.org/api'});
app.use(apiProxy)

Documentation: http-proxy-middleware on Github

I know I'm late to join this party, but I hope this helps someone.

How to fix "Attempted relative import in non-package" even with __init__.py

Here's one way which will piss off everyone but work pretty well. In tests run:

ln -s ../components components

Then just import components like you normally would.

Difference between a theta join, equijoin and natural join

A theta join allows for arbitrary comparison relationships (such as ≥).

An equijoin is a theta join using the equality operator.

A natural join is an equijoin on attributes that have the same name in each relationship.

Additionally, a natural join removes the duplicate columns involved in the equality comparison so only 1 of each compared column remains; in rough relational algebraic terms: ? = pR,S-as ? ?aR=aS

Return the most recent record from ElasticSearch index

I used @timestamp instead of _timestamp

{
    'size' : 1,
    'query': {
        'match_all' : {}
            },
    "sort" : [{"@timestamp":{"order": "desc"}}]
}

How to create a cron job using Bash automatically without the interactive editor?

There have been a lot of good answers around the use of crontab, but no mention of a simpler method, such as using cron.

Using cron would take advantage of system files and directories located at /etc/crontab, /etc/cron.daily,weekly,hourly or /etc/cron.d/:

cat > /etc/cron.d/<job> << EOF
SHELL=/bin/bash 
PATH=/sbin:/bin:/usr/sbin:/usr/bin 
MAILTO=root HOME=/  
01 * * * * <user> <command>
EOF

In this above example, we created a file in /etc/cron.d/, provided the environment variables for the command to execute successfully, and provided the user for the command, and the command itself. This file should not be executable and the name should only contain alpha-numeric and hyphens (more details below).

To give a thorough answer though, let's look at the differences between crontab vs cron/crond:

crontab -- maintain tables for driving cron for individual users

For those who want to run the job in the context of their user on the system, using crontab may make perfect sense.

cron -- daemon to execute scheduled commands

For those who use configuration management or want to manage jobs for other users, in which case we should use cron.

A quick excerpt from the manpages gives you a few examples of what to and not to do:

/etc/crontab and the files in /etc/cron.d must be owned by root, and must not be group- or other-writable. In contrast to the spool area, the files under /etc/cron.d or the files under /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly and /etc/cron.monthly may also be symlinks, provided that both the symlink and the file it points to are owned by root. The files under /etc/cron.d do not need to be executable, while the files under /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly and /etc/cron.monthly do, as they are run by run-parts (see run-parts(8) for more information).

Source: http://manpages.ubuntu.com/manpages/trusty/man8/cron.8.html

Managing crons in this manner is easier and more scalable from a system perspective, but will not always be the best solution.

Change x axes scale in matplotlib

The scalar formatter supports collecting the exponents. The docs are as follows:

class matplotlib.ticker.ScalarFormatter(useOffset=True, useMathText=False, useLocale=None) Bases: matplotlib.ticker.Formatter

Tick location is a plain old number. If useOffset==True and the data range is much smaller than the data average, then an offset will be determined such that the tick labels are meaningful. Scientific notation is used for data < 10^-n or data >= 10^m, where n and m are the power limits set using set_powerlimits((n,m)). The defaults for these are controlled by the axes.formatter.limits rc parameter.

your technique would be:

from matplotlib.ticker import ScalarFormatter
xfmt = ScalarFormatter()
xfmt.set_powerlimits((-3,3))  # Or whatever your limits are . . .
{{ Make your plot }}
gca().xaxis.set_major_formatter(xfmt)

To get the exponent displayed in the format x10^5, instantiate the ScalarFormatter with useMathText=True.

After Image

You could also use:

xfmt.set_useOffset(10000)

To get a result like this:

enter image description here

Update Row if it Exists Else Insert Logic with Entity Framework

Ladislav's answer was close but I had to made a couple of modifications to get this to work in EF6 (database-first). I extended my data context with my on AddOrUpdate method and so far this appears to be working well with detached objects:

using System.Data.Entity;

[....]

public partial class MyDBEntities {

  public void AddOrUpdate(MyDBEntities ctx, DbSet set, Object obj, long ID) {
      if (ID != 0) {
          set.Attach(obj);
          ctx.Entry(obj).State = EntityState.Modified;
      }
      else {
          set.Add(obj);
      }
  }
[....]

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

How to fix SSL certificate error when running Npm on Windows?

I was having same issue. After some digging I realized that many post/pre-install scripts would try to install various dependencies and some times specific repositories are used. A better way is to disable certificate check for https module for nodejs that worked for me.

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"

From this question

How to insert element as a first child?

parentElement.prepend(newFirstChild);

This is a new addition in (likely) ES7. It is now vanilla JS, probably due to the popularity in jQuery. It is currently available in Chrome, FF, and Opera. Transpilers should be able to handle it until it becomes available everywhere.

P.S. You can directly prepend strings

parentElement.prepend('This text!');

Links: developer.mozilla.org - Polyfill

Fastest way to reset every value of std::vector<int> to 0

If it's just a vector of integers, I'd first try:

memset(&my_vector[0], 0, my_vector.size() * sizeof my_vector[0]);

It's not very C++, so I'm sure someone will provide the proper way of doing this. :)

What are the differences between JSON and JSONP?

JSONP stands for “JSON with Padding” and it is a workaround for loading data from different domains. It loads the script into the head of the DOM and thus you can access the information as if it were loaded on your own domain, thus by-passing the cross domain issue.

jsonCallback(
{
    "sites":
    [
        {
            "siteName": "JQUERY4U",
            "domainName": "http://www.jquery4u.com",
            "description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips &amp; Code Snippets."
        },
        {
            "siteName": "BLOGOOLA",
            "domainName": "http://www.blogoola.com",
            "description": "Expose your blog to millions and increase your audience."
        },
        {
            "siteName": "PHPSCRIPTS4U",
            "domainName": "http://www.phpscripts4u.com",
            "description": "The Blog of Enthusiastic PHP Scripters"
        }
    ]
});

(function($) {
var url = 'http://www.jquery4u.com/scripts/jquery4u-sites.json?callback=?';

$.ajax({
   type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(json) {
       console.dir(json.sites);
    },
    error: function(e) {
       console.log(e.message);
    }
});

})(jQuery);

Now we can request the JSON via AJAX using JSONP and the callback function we created around the JSON content. The output should be the JSON as an object which we can then use the data for whatever we want without restrictions.

How do I get a YouTube video thumbnail from the YouTube API?

You can use YouTube Data API to retrieve video thumbnails, caption, description, rating, statistics and more. API version 3 requires a key*. Obtain the key and create a videos: list request:

https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=VIDEO_ID

Example PHP Code

$data = file_get_contents("https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=T0Jqdjbed40");
$json = json_decode($data);
var_dump($json->items[0]->snippet->thumbnails);

Output

object(stdClass)#5 (5) {
  ["default"]=>
  object(stdClass)#6 (3) {
    ["url"]=>
    string(46) "https://i.ytimg.com/vi/T0Jqdjbed40/default.jpg"
    ["width"]=>
    int(120)
    ["height"]=>
    int(90)
  }
  ["medium"]=>
  object(stdClass)#7 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/mqdefault.jpg"
    ["width"]=>
    int(320)
    ["height"]=>
    int(180)
  }
  ["high"]=>
  object(stdClass)#8 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/hqdefault.jpg"
    ["width"]=>
    int(480)
    ["height"]=>
    int(360)
  }
  ["standard"]=>
  object(stdClass)#9 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/sddefault.jpg"
    ["width"]=>
    int(640)
    ["height"]=>
    int(480)
  }
  ["maxres"]=>
  object(stdClass)#10 (3) {
    ["url"]=>
    string(52) "https://i.ytimg.com/vi/T0Jqdjbed40/maxresdefault.jpg"
    ["width"]=>
    int(1280)
    ["height"]=>
    int(720)
  }
}

* Not only that you need a key, you might be asked for billing information depending on the number of API requests you plan to make. However, few million requests per day are free.

Source article.