Programs & Examples On #Electronic signature

Conversion failed when converting date and/or time from character string while inserting datetime

the best way is this code

"select * from [table_1] where date between convert(date,'" + dateTimePicker1.Text + "',105) and convert(date,'" + dateTimePicker2.Text + "',105)"

Comparing two .jar files

Use Java Decompiler to turn the jar file into source code file, and then use WinMerge to perform comparison.

You should consult the copyright holder of the source code, to see whether it is OK to do so.

Use a loop to plot n charts Python

Ok, so the easiest method to create several plots is this:

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
    plt.figure()
    plt.plot(x[i],y[i])
    # Show/save figure as desired.
    plt.show()
# Can show all four figures at once by calling plt.show() here, outside the loop.
#plt.show()

Note that you need to create a figure every time or pyplot will plot in the first one created.

If you want to create several data series all you need to do is:

import matplotlib.pyplot as plt
plt.figure()
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
plt.plot(x[0],y[0],'r',x[1],y[1],'g',x[2],y[2],'b',x[3],y[3],'k')

You could automate it by having a list of colours like ['r','g','b','k'] and then just calling both entries in this list and corresponding data to be plotted in a loop if you wanted to. If you just want to programmatically add data series to one plot something like this will do it (no new figure is created each time so everything is plotted in the same figure):

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
colours=['r','g','b','k']
plt.figure() # In this example, all the plots will be in one figure.    
for i in range(len(x)):
    plt.plot(x[i],y[i],colours[i])
plt.show()

Hope this helps. If anything matplotlib has a very good documentation page with plenty of examples.

17 Dec 2019: added plt.show() and plt.figure() calls to clarify this part of the story.

CSS transition fade in

OK, first of all I'm not sure how it works when you create a div using (document.createElement('div')), so I might be wrong now, but wouldn't it be possible to use the :target pseudo class selector for this?

If you look at the code below, you can se I've used a link to target the div, but in your case it might be possible to target #new from the script instead and that way make the div fade in without user interaction, or am I thinking wrong?

Here's the code for my example:

HTML

<a href="#new">Click</a> 
<div id="new">
    Fade in ... 
</div>

CSS

#new {
    width: 100px;
    height: 100px;
    border: 1px solid #000000;
    opacity: 0;    
}


#new:target {
    -webkit-transition: opacity 2.0s ease-in;
       -moz-transition: opacity 2.0s ease-in;
         -o-transition: opacity 2.0s ease-in;
                                  opacity: 1;
}

... and here's a jsFiddle

Check for a substring in a string in Oracle without LIKE

Databases are heavily optimized for common usage scenarios (and LIKE is one of those).

You won't find a faster way of doing your search if you want to stay on the DB-level.

mssql convert varchar to float

You can convert varchars to floats, and you can do it in the manner you have expressed. Your varchar must not be a numeric value. There must be something else in it. You can use IsNumeric to test it. See this:

declare @thing varchar(100)

select @thing = '122.332'

--This returns 1 since it is numeric.
select isnumeric(@thing)

--This converts just fine.
select convert(float,@thing)

select @thing = '122.332.'

--This returns 0 since it is not numeric.
select isnumeric(@thing)

--This convert throws.
select convert(float,@thing)

HTML Mobile -forcing the soft keyboard to hide

For further readers/searchers:

As Rene Pot points out on this topic,

By adding the attribute readonly (or readonly="readonly") to the input field you should prevent anyone typing anything in it, but still be able to launch a click event on it.

With this method, you can avoid popping up the "soft" Keyboard and still launch click events / fill the input by any on-screen keyboard.

This solution also works fine with date-time-pickers which generally already implement controls.

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

Finally, I solved it modifiying these attributes on the module gradle file

  1. compileSdkVersion 25
  2. targetSdkVersion 25
  3. compile 'com.android.support:appcompat-v7:+'
  4. compile 'com.android.support:recyclerview-v7:+'

How to: Install Plugin in Android Studio

1) Launch Android Studio application

2) Choose File -> Settings (For Mac Preference )

3) Search for Plugins

enter image description here

In Android Studio 3.4.2

enter image description here

Extract substring in Bash

If we focus in the concept of:
"A run of (one or several) digits"

We could use several external tools to extract the numbers.
We could quite easily erase all other characters, either sed or tr:

name='someletters_12345_moreleters.ext'

echo $name | sed 's/[^0-9]*//g'    # 12345
echo $name | tr -c -d 0-9          # 12345

But if $name contains several runs of numbers, the above will fail:

If "name=someletters_12345_moreleters_323_end.ext", then:

echo $name | sed 's/[^0-9]*//g'    # 12345323
echo $name | tr -c -d 0-9          # 12345323

We need to use regular expresions (regex).
To select only the first run (12345 not 323) in sed and perl:

echo $name | sed 's/[^0-9]*\([0-9]\{1,\}\).*$/\1/'
perl -e 'my $name='$name';my ($num)=$name=~/(\d+)/;print "$num\n";'

But we could as well do it directly in bash(1) :

regex=[^0-9]*([0-9]{1,}).*$; \
[[ $name =~ $regex ]] && echo ${BASH_REMATCH[1]}

This allows us to extract the FIRST run of digits of any length
surrounded by any other text/characters.

Note: regex=[^0-9]*([0-9]{5,5}).*$; will match only exactly 5 digit runs. :-)

(1): faster than calling an external tool for each short texts. Not faster than doing all processing inside sed or awk for large files.

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

You can try to run:

bundle exec rake rails:update:bin

As @Dinesh mentioned in Rails 5:

rails app:update:bin

Can you call Directory.GetFiles() with multiple filters?

for

var exts = new[] { "mp3", "jpg" };

You could:

public IEnumerable<string> FilterFiles(string path, params string[] exts) {
    return
        Directory
        .EnumerateFiles(path, "*.*")
        .Where(file => exts.Any(x => file.EndsWith(x, StringComparison.OrdinalIgnoreCase)));
}

But the real benefit of EnumerateFiles shows up when you split up the filters and merge the results:

public IEnumerable<string> FilterFiles(string path, params string[] exts) {
    return 
        exts.Select(x => "*." + x) // turn into globs
        .SelectMany(x => 
            Directory.EnumerateFiles(path, x)
            );
}

It gets a bit faster if you don't have to turn them into globs (i.e. exts = new[] {"*.mp3", "*.jpg"} already).

Performance evaluation based on the following LinqPad test (note: Perf just repeats the delegate 10000 times) https://gist.github.com/zaus/7454021

( reposted and extended from 'duplicate' since that question specifically requested no LINQ: Multiple file-extensions searchPattern for System.IO.Directory.GetFiles )

What's the difference between a null pointer and a void pointer?

A null pointer is guaranteed to not compare equal to a pointer to any object. It's actual value is system dependent and may vary depending on the type. To get a null int pointer you would do

int* p = 0;

A null pointer will be returned by malloc on failure.

We can test if a pointer is null, i.e. if malloc or some other function failed simply by testing its boolean value:

if (p) {
    /* Pointer is not null */
} else {
    /* Pointer is null */
}

A void pointer can point to any type and it is up to you to handle how much memory the referenced objects consume for the purpose of dereferencing and pointer arithmetic.

What's wrong with foreign keys?

There's one good reason not to use them: If you don't understand their role or how to use them.

In the wrong situations, foreign key constraints can lead to waterfall replication of accidents. If somebody removes the wrong record, undoing it can become a mammoth task.

Also, conversely, when you need to remove something, if poorly designed, constraints can cause all sorts of locks that prevent you.

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

Vue-router redirect on page not found (404)

@mani's response is now slightly outdated as using catch-all '*' routes is no longer supported when using Vue 3 onward. If this is no longer working for you, try replacing the old catch-all path with

{ path: '/:pathMatch(.*)*', component: PathNotFound },

Essentially, you should be able to replace the '*' path with '/:pathMatch(.*)*' and be good to go!

Reason: Vue Router doesn't use path-to-regexp anymore, instead it implements its own parsing system that allows route ranking and enables dynamic routing. Since we usually add one single catch-all route per project, there is no big benefit in supporting a special syntax for *.

(from https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes)

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

How to check for a Null value in VB.NET

 If Short.TryParse(editTransactionRow.pay_id, New Short) Then editTransactionRow.pay_id.ToString()

Compiling simple Hello World program on OS X via command line

You didn't specify what the error you're seeing is.

Is the problem that gcc is giving you an error, or that you can't run gcc at all?

If it's the latter, the most likely explanation is that you didn't check "UNIX Development Support" when you installed the development tools, so the command-line executables aren't installed in your path. Re-install the development tools, and make sure to click "customize" and check that box.

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

Keep the labels from your original file like this:

df = read.table('data.txt', header = T)

If you have columns named x and y, you can address them like this:

df$x
df$y

If you'd like to actually delete the first row from a data.frame, you can use negative indices like this:

df = df[-1,]

If you'd like to delete a column from a data.frame, you can assign NULL to it:

df$x = NULL

Here are some simple examples of how to create and manipulate a data.frame in R:

# create a data.frame with 10 rows
> x = rnorm(10)
> y = runif(10)
> df = data.frame( x, y )

# write it to a file
> write.table( df, 'test.txt', row.names = F, quote = F )

# read a data.frame from a file: 
> read.table( df, 'test.txt', header = T )

> df$x
 [1] -0.95343778 -0.63098637 -1.30646529  1.38906143  0.51703237 -0.02246754
 [7]  0.20583548  0.21530721  0.69087460  2.30610998
> df$y
 [1] 0.66658148 0.15355851 0.60098886 0.14284576 0.20408723 0.58271061
 [7] 0.05170994 0.83627336 0.76713317 0.95052671

> df$x = x
> df
            y           x
1  0.66658148 -0.95343778
2  0.15355851 -0.63098637
3  0.60098886 -1.30646529
4  0.14284576  1.38906143
5  0.20408723  0.51703237
6  0.58271061 -0.02246754
7  0.05170994  0.20583548
8  0.83627336  0.21530721
9  0.76713317  0.69087460
10 0.95052671  2.30610998

> df[-1,]
            y           x
2  0.15355851 -0.63098637
3  0.60098886 -1.30646529
4  0.14284576  1.38906143
5  0.20408723  0.51703237
6  0.58271061 -0.02246754
7  0.05170994  0.20583548
8  0.83627336  0.21530721
9  0.76713317  0.69087460
10 0.95052671  2.30610998

> df$x = NULL
> df 
            y
1  0.66658148
2  0.15355851
3  0.60098886
4  0.14284576
5  0.20408723
6  0.58271061
7  0.05170994
8  0.83627336
9  0.76713317
10 0.95052671

KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element

ko.cleanNode($("#modalPartialView")[0]);
ko.applyBindings(vm, $("#modalPartialView")[0]);

works for me, but as others note, the cleanNode is internal ko function, so there is probably a better way.

How to implement swipe gestures for mobile devices?

The simplest solution I've found that doesn't require a plugin:

document.addEventListener('touchstart', handleTouchStart, false);        
document.addEventListener('touchmove', handleTouchMove, false);
var xDown = null;                                                        
var yDown = null;  

function handleTouchStart(evt) {                                         
    xDown = evt.touches[0].clientX;                                      
    yDown = evt.touches[0].clientY;                                      
}; 

function handleTouchMove(evt) {
    if ( ! xDown || ! yDown ) {
        return;
    }
    var xUp = evt.touches[0].clientX;                                    
    var yUp = evt.touches[0].clientY;
    var xDiff = xDown - xUp;
    var yDiff = yDown - yUp;

    if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
        if ( xDiff > 0 ) {
        /* left swipe */ 
        } else {
        /* right swipe */
        }                       
    } else {
        if ( yDiff > 0 ) {
        /* up swipe */ 
        } else { 
        /* down swipe */
        }                                                                 
    }
    /* reset values */
    xDown = null;
    yDown = null;                                             
};

How to add dll in c# project

In the right hand column under your solution explorer, you can see next to the reference to "Science" its marked as a warning. Either that means it cant find it, or its objecting to it for some other reason. While this is the case and your code requires it (and its not just in the references list) it wont compile.

Please post the warning message, we can try help you further.

what does this mean ? image/png;base64?

That data:image/png;base64 URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.

Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.

How to set menu to Toolbar in Android

Don't use setSupportActionBar(toolbar)

I don't know why but this works for me.

toolbar = (Toolbar) findViewById(R.id.main_toolbar);
toolbar.setSubtitle("Test Subtitle");
toolbar.inflateMenu(R.menu.main_manu);

For menu item click do this

toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {

            if(item.getItemId()==R.id.item1)
            {
                // do something
            }
            else if(item.getItemId()== R.id.filter)
            {
               // do something
            }
            else{
               // do something
            }

            return false;
        }
    });

Will update the 'why' part of this answer when I find a proper explanation.
Happy to help anyway :) Peace.

How do I merge changes to a single file, rather than merging commits?

You can checkout the old version of the file to merge, saving it under a different name, then run whatever your merge tool is on the two files.

eg.

git show B:src/common/store.ts > /tmp/store.ts (where B is the branch name/commit/tag)

meld src/common/store.ts /tmp/store.ts

How do I prevent a form from being resized by the user?

Set the highlighted properties. Set MaximimSize and MinimizeSize properties the same size

enter image description here

Regex matching in a Bash if statement

I'd prefer to use [:punct:] for that. Also, a-zA-Z09-9 could be just [:alnum:]:

[[ $TEST =~ ^[[:alnum:][:blank:][:punct:]]+$ ]]

Vim multiline editing like in sublimetext?

Ctrl-v ................ start visual block selection
6j .................... go down 6 lines
I" .................... inserts " at the beginning
<Esc><Esc> ............ finishes start
2fdl. ................. second 'd' l (goes right) . (repeats insertion)

How to select and change value of table cell with jQuery?

Using eq() you can target the third cell in the table:

$('#table_header td').eq(2).html('new content');

If you wanted to target every third cell in each row, use the nth-child-selector:

$('#table_header td:nth-child(3)').html('new content');

Commit history on remote repository

Here's a bash function that makes it easy to view the logs on a remote. It takes two optional arguments. The first one is the branch, it defaults to master. The second one is the remote, it defaults to staging.

git_log_remote() {
  branch=${1:-master}
  remote=${2:-staging}
  
  git fetch $remote
  git checkout $remote/$branch
  git log
  git checkout -
}

examples:

 $ git_log_remote
 $ git_log_remote development origin

How to send list of file in a folder to a txt file in Linux

you can just use

ls > filenames.txt

(usually, start a shell by using "Terminal", or "shell", or "Bash".) You may need to use cd to go to that folder first, or you can ls ~/docs > filenames.txt

Make: how to continue after a command fails?

Put an -f option in your rm command.

rm -f .lambda .lambda_t .activity .activity_t_lambda

initializing strings as null vs. empty string

The default constructor initializes the string to the empty string. This is the more economic way of saying the same thing.

However, the comparison to NULL stinks. That is an older syntax still in common use that means something else; a null pointer. It means that there is no string around.

If you want to check whether a string (that does exist) is empty, use the empty method instead:

if (myStr.empty()) ...

Data structure for maintaining tabular data in memory?

Have a Table class whose rows is a list of dict or better row objects

In table do not directly add rows but have a method which update few lookup maps e.g. for name if you are not adding rows in order or id are not consecutive you can have idMap too e.g.

class Table(object):
    def __init__(self):
        self.rows =  []# list of row objects, we assume if order of id
        self.nameMap = {} # for faster direct lookup for row by name

    def addRow(self, row):
        self.rows.append(row)
        self.nameMap[row['name']] = row

    def getRow(self, name):
        return self.nameMap[name]


table = Table()
table.addRow({'ID':1,'name':'a'})

conversion from infix to prefix

Algorithm ConvertInfixtoPrefix

Purpose: Convert an infix expression into a prefix expression. Begin 
// Create operand and operator stacks as empty stacks. 
Create OperandStack
Create OperatorStack

// While input expression still remains, read and process the next token.

while( not an empty input expression ) read next token from the input expression

    // Test if token is an operand or operator 
    if ( token is an operand ) 
    // Push operand onto the operand stack. 
        OperandStack.Push (token)
    endif

    // If it is a left parentheses or operator of higher precedence than the last, or the stack is empty,
    else if ( token is '(' or OperatorStack.IsEmpty() or OperatorHierarchy(token) > OperatorHierarchy(OperatorStack.Top()) )
    // push it to the operator stack
        OperatorStack.Push ( token )
    endif

    else if( token is ')' ) 
    // Continue to pop operator and operand stacks, building 
    // prefix expressions until left parentheses is found. 
    // Each prefix expression is push back onto the operand 
    // stack as either a left or right operand for the next operator. 
        while( OperatorStack.Top() not equal '(' ) 
            OperatorStack.Pop(operator) 
            OperandStack.Pop(RightOperand) 
            OperandStack.Pop(LeftOperand) 
            operand = operator + LeftOperand + RightOperand 
            OperandStack.Push(operand) 
        endwhile

    // Pop the left parthenses from the operator stack. 
    OperatorStack.Pop(operator)
    endif

    else if( operator hierarchy of token is less than or equal to hierarchy of top of the operator stack )
    // Continue to pop operator and operand stack, building prefix 
    // expressions until the stack is empty or until an operator at 
    // the top of the operator stack has a lower hierarchy than that 
    // of the token. 
        while( !OperatorStack.IsEmpty() and OperatorHierarchy(token) lessThen Or Equal to OperatorHierarchy(OperatorStack.Top()) ) 
            OperatorStack.Pop(operator) 
            OperandStack.Pop(RightOperand) 
            OperandStack.Pop(LeftOperand) 
            operand = operator + LeftOperand + RightOperand 
            OperandStack.Push(operand)
        endwhile 
        // Push the lower precedence operator onto the stack 
        OperatorStack.Push(token)
    endif
endwhile 
// If the stack is not empty, continue to pop operator and operand stacks building 
// prefix expressions until the operator stack is empty. 
while( !OperatorStack.IsEmpty() ) OperatorStack.Pop(operator) 
    OperandStack.Pop(RightOperand) 
    OperandStack.Pop(LeftOperand) 
    operand = operator + LeftOperand + RightOperand

    OperandStack.Push(operand) 
endwhile

// Save the prefix expression at the top of the operand stack followed by popping // the operand stack.

print OperandStack.Top()

OperandStack.Pop()

End

How to handle ListView click in Android

In Kotlin, add a listener to your listView as simple as java

your_listview.setOnItemClickListener { parent, view, position, id ->   

    Toast.makeText(this, position, Toast.LENGTH_SHORT).show()

 }

What should I use to open a url instead of urlopen in urllib3

The new urllib3 library has a nice documentation here
In order to get your desired result you shuld follow that:

Import urllib3
from bs4 import BeautifulSoup

url = 'http://www.thefamouspeople.com/singers.php'

http = urllib3.PoolManager()
response = http.request('GET', url)
soup = BeautifulSoup(response.data.decode('utf-8'))

The "decode utf-8" part is optional. It worked without it when i tried, but i posted the option anyway.
Source: User Guide

Remove Trailing Spaces and Update in Columns in SQL Server

Use the TRIM SQL function.

If you are using SQL Server try :

SELECT LTRIM(RTRIM(YourColumn)) FROM YourTable

Can a website detect when you are using Selenium with chromedriver?

A lot have been analyzed and discussed about a website being detected being driven by Selenium controlled ChromeDriver. Here are my two cents:

According to the article Browser detection using the user agent serving different webpages or services to different browsers is usually not among the best of ideas. The web is meant to be accessible to everyone, regardless of which browser or device an user is using. There are best practices outlined to develop a website to progressively enhance itself based on the feature availability rather than by targeting specific browsers.

However, browsers and standards are not perfect, and there are still some edge cases where some websites still detects the browser and if the browser is driven by Selenium controled WebDriver. Browsers can be detected through different ways and some commonly used mechanisms are as follows:

You can find a relevant detailed discussion in How does recaptcha 3 know I'm using selenium/chromedriver?

  • Detecting the term HeadlessChrome within headless Chrome UserAgent

You can find a relevant detailed discussion in Access Denied page with headless Chrome on Linux while headed Chrome works on windows using Selenium through Python

You can find a relevant detailed discussion in Unable to use Selenium to automate Chase site login

  • Using Bot Manager service from Akamai

You can find a relevant detailed discussion in Dynamic dropdown doesn't populate with auto suggestions on https://www.nseindia.com/ when values are passed using Selenium and Python

  • Using Bot Protection service from Datadome

You can find a relevant detailed discussion in Website using DataDome gets captcha blocked while scraping using Selenium and Python

However, using the to detect the browser looks simple but doing it well is in fact a bit tougher.

Note: At this point it's worth to mention that: it's very rarely a good idea to use user agent sniffing. There are always better and more broadly compatible way to address a certain issue.


Considerations for browser detection

The idea behind detecting the browser can be either of the following:

  • Trying to work around a specific bug in some specific variant or specific version of a webbrowser.
  • Trying to check for the existence of a specific feature that some browsers don't yet support.
  • Trying to provide different HTML depending on which browser is being used.

Alternative of browser detection through UserAgents

Some of the alternatives of browser detection are as follows:

  • Implementing a test to detect how the browser implements the API of a feature and determine how to use it from that. An example was Chrome unflagged experimental lookbehind support in regular expressions.
  • Adapting the design technique of Progressive enhancement which would involve developing a website in layers, using a bottom-up approach, starting with a simpler layer and improving the capabilities of the site in successive layers, each using more features.
  • Adapting the top-down approach of Graceful degradation in which we build the best possible site using all the features we want and then tweak it to make it work on older browsers.

Solution

To prevent the Selenium driven WebDriver from getting detected, a niche approach would include either/all of the below mentioned approaches:

  • Rotating the UserAgent in every execution of your Test Suite using fake_useragent module as follows:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from fake_useragent import UserAgent
    
    options = Options()
    ua = UserAgent()
    userAgent = ua.random
    print(userAgent)
    options.add_argument(f'user-agent={userAgent}')
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe')
    driver.get("https://www.google.co.in")
    driver.quit()
    

You can find a relevant detailed discussion in Way to change Google Chrome user agent in Selenium?

  • Rotating the UserAgent in each of your Tests using Network.setUserAgentOverride through execute_cdp_cmd() as follows:

    from selenium import webdriver
    
    driver = webdriver.Chrome(executable_path=r'C:\WebDrivers\chromedriver.exe')
    print(driver.execute_script("return navigator.userAgent;"))
    # Setting user agent as Chrome/83.0.4103.97
    driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'})
    print(driver.execute_script("return navigator.userAgent;"))
    

You can find a relevant detailed discussion in How to change the User Agent using Selenium and Python

  • Changing the property value of navigator for webdriver to undefined as follows:

    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
      "source": """
        Object.defineProperty(navigator, 'webdriver', {
          get: () => undefined
        })
      """
    })
    

You can find a relevant detailed discussion in Selenium webdriver: Modifying navigator.webdriver flag to prevent selenium detection

  • Changing the values of navigator.plugins, navigator.languages, WebGL, hairline feature, missing image, etc.

You can find a relevant detailed discussion in Is there a version of selenium webdriver that is not detectable?

You can find a relevant detailed discussion in How to bypass Google captcha with Selenium and python?


Dealing with reCAPTCHA

While dealing with and rather clicking on associated to the text I'm not a robot, it may be easier to get authenticated extracting and using the data-sitekey.

You can find a relevant detailed discussion in How to identify the 32 bit data-sitekey of ReCaptcha V2 to obtain a valid response programmatically using Selenium and Python Requests?

Search for a string in Enum and return the Enum

You can use Enum.Parse to get an enum value from the name. You can iterate over all values with Enum.GetNames, and you can just cast an int to an enum to get the enum value from the int value.

Like this, for example:

public MyColours GetColours(string colour)
{
    foreach (MyColours mc in Enum.GetNames(typeof(MyColours))) {
        if (mc.ToString().Contains(colour)) {
            return mc;
        }
    }
    return MyColours.Red; // Default value
}

or:

public MyColours GetColours(string colour)
{
    return (MyColours)Enum.Parse(typeof(MyColours), colour, true); // true = ignoreCase
}

The latter will throw an ArgumentException if the value is not found, you may want to catch it inside the function and return the default value.

SQL JOIN, GROUP BY on three tables to get totals

I am not sure I got you but this might be what you are looking for:

SELECT i.invoiceid, sum(case when i.amount is not null then i.amount else 0 end), sum(case when i.amount is not null then i.amount else 0 end) - sum(case when p.amount is not null then p.amount else 0 end) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN payments p ON ip.paymentid = p.paymentid
LEFT JOIN customers c ON p.customerid = c.customerid
WHERE c.customernumber = '100'
GROUP BY i.invoiceid

This would get you the amounts sums in case there are multiple payment rows for each invoice

How to check View Source in Mobile Browsers (Both Android && Feature Phone)

This is an old post but still a problem within the Chrome dev tools. I find the best way to check mobile source locally is to open the site locally in Xcode's iOS Simulator. Then from there you open the Safari browser and enable dev tools, if you have not already done this (go to preferences -> advanced -> show develop menu in menu bar). Now you will see the develop option in the main menu and can go to develop -> iOS Simulator -> and the page you have open in Xcode's iOS Simulator will be there. Once you click on it, it will open the web inspector and you can edit as you would normally in the browser dev tools.

I'm afraid this solution will only work on a Mac though as it uses Xcode.

How to avoid the "Circular view path" exception with Spring MVC test

Here's an easy fix if you don't actually care about rendering the view.

Create a subclass of InternalResourceViewResolver which doesn't check for circular view paths:

public class StandaloneMvcTestViewResolver extends InternalResourceViewResolver {

    public StandaloneMvcTestViewResolver() {
        super();
    }

    @Override
    protected AbstractUrlBasedView buildView(final String viewName) throws Exception {
        final InternalResourceView view = (InternalResourceView) super.buildView(viewName);
        // prevent checking for circular view paths
        view.setPreventDispatchLoop(false);
        return view;
    }
}

Then set up your test with it:

MockMvc mockMvc;

@Before
public void setUp() {
    final MyController controller = new MyController();

    mockMvc =
            MockMvcBuilders.standaloneSetup(controller)
                    .setViewResolvers(new StandaloneMvcTestViewResolver())
                    .build();
}

Java Map equivalent in C#

You can index Dictionary, you didn't need 'get'.

Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);

An efficient way to test/get values is TryGetValue (thanx to Earwicker):

if (otherExample.TryGetValue("key", out value))
{
    otherExample["key"] = value + 1;
}

With this method you can fast and exception-less get values (if present).

Resources:

Dictionary-Keys

Try Get Value

How do I remove blank elements from an array?

You can Try this

 cities.reject!(&:empty?)

numpy: most efficient frequency counts for unique values in an array

Take a look at np.bincount:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html

import numpy as np
x = np.array([1,1,1,2,2,2,5,25,1,1])
y = np.bincount(x)
ii = np.nonzero(y)[0]

And then:

zip(ii,y[ii]) 
# [(1, 5), (2, 3), (5, 1), (25, 1)]

or:

np.vstack((ii,y[ii])).T
# array([[ 1,  5],
         [ 2,  3],
         [ 5,  1],
         [25,  1]])

or however you want to combine the counts and the unique values.

How do I use a regex in a shell script?

the problem is you're trying to use regex features not supported by grep. namely, your \d won't work. use this instead:

REGEX_DATE="^[[:digit:]]{2}[-/][[:digit:]]{2}[-/][[:digit:]]{4}$"
echo "$1" | grep -qE "${REGEX_DATE}"
echo $?

you need the -E flag to get ERE in order to use {#} style.

how to view the contents of a .pem certificate

An alternative to using keytool, you can use the command

openssl x509 -in certificate.pem -text

This should work for any x509 .pem file provided you have openssl installed.

Can someone explain mappedBy in JPA and Hibernate?

MappedBy signals hibernate that the key for the relationship is on the other side.

This means that although you link 2 tables together, only 1 of those tables has a foreign key constraint to the other one. MappedBy allows you to still link from the table not containing the constraint to the other table.

How to bind RadioButtons to an enum?

I would use the RadioButtons in a ListBox, and then bind to the SelectedValue.

This is an older thread about this topic, but the base idea should be the same: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/323d067a-efef-4c9f-8d99-fecf45522395/

How do I make jQuery wait for an Ajax call to finish before it returns?

In modern JS you can simply use async/await, like:

  async function upload() {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: $(this).attr('href'),
            type: 'GET',
            timeout: 30000,
            success: (response) => {
                resolve(response);
            },
            error: (response) => {
                reject(response);
            }
        })
    })
}

Then call it in an async function like:

let response = await upload();

What does "@" mean in Windows batch scripts

It means "don't echo the command to standard output".

Rather strangely,

echo off

will send echo off to the output! So,

@echo off

sets this automatic echo behaviour off - and stops it for all future commands, too.

Source: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/batch.mspx?mfr=true

Cloud Firestore collection count

firebaseFirestore.collection("...").addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

            int Counter = documentSnapshots.size();

        }
    });

Add centered text to the middle of a <hr/>-like line

CSS

.Divider {
width: 100%; height: 30px;  text-align: center;display: flex;
}
.Side{
width: 46.665%;padding: 30px 0;
}
.Middle{
width: 6.67%;padding: 20px 0;
}

HTML

<div class="Divider">
    <div class="Side"><hr></div>
    <div class="Middle"><span>OR</span></div>
    <div class="Side"><hr></div>
</div>

You may modify the width in class "side" and "middle" based on the length of your text in the tag "span". Be sure the width of the "middle" plus 2 times of the width of "side" equal to 100%.

*.h or *.hpp for your class definitions

There is no advantage to any particular extension, other than that one may have a different meaning to you, the compiler, and/or your tools. header.h is a valid header. header.hpp is a valid header. header.hh is a valid header. header.hx is a valid header. h.header is a valid header. this.is.not.a.valid.header is a valid header in denial. ihjkflajfajfklaf is a valid header. As long as the name can be parsed properly by the compiler, and the file system supports it, it's a valid header, and the only advantage to its extension is what one reads into it.

That being said, being able to accurately make assumptions based on the extension is very useful, so it would be wise to use an easily-understandable set of rules for your header files. Personally, I prefer to do something like this:

  1. If there are already any established guidelines, follow them to prevent confusion.
  2. If all source files in the project are for the same language, use .h. There's no ambiguity.
  3. If some headers are compatible with multiple languages, while others are only compatible with a single language, extensions are based on the most restrictive language that a header is compatible with. A header compatible with C, or with both C & C++, gets .h, while a header compatible with C++ but not C gets .hpp or .hh or something of the sort.

This, of course, is but one of many ways to handle extensions, and you can't necessarily trust your first impression even if things seem straightforward. For example, I've seen mention of using .h for normal headers, and .tpp for headers that only contain definitions for templated class member functions, with .h files that define templated classes including the .tpp files that define their member functions (instead of the .h header directly containing both the function declaration and the definition). For another example, a good many people always reflect the header's language in its extension, even when there's no chance of ambiguity; to them, .h is always a C header and .hpp (or .hh, or .hxx, etc.) is always a C++ header. And yet again, some people use .h for "header associated with a source file" and .hpp for "header with all functions defined inline".

Considering this, the main advantage would come in consistently naming your headers in the same style, and making that style readily apparent to anyone examining your code. This way, anyone familiar with your usual coding style will be able to determine what you mean with any given extension with just a cursory glance.

why are there two different kinds of for loops in java?

The second for loop is any easy way to iterate over the contents of an array, without having to manually specify the number of items in the array(manual enumeration). It is much more convenient than the first when dealing with arrays.

Android WebView Cookie Problem

Don't use your raw url

Instead of:

cookieManager.setCookie(myUrl, cookieString); 

use it like this:

cookieManager.setCookie("your url host", cookieString); 

When I catch an exception, how do I get the type, file, and line number?

Source (Py v2.7.3) for traceback.format_exception() and called/related functions helps greatly. Embarrassingly, I always forget to Read the Source. I only did so for this after searching for similar details in vain. A simple question, "How to recreate the same output as Python for an exception, with all the same details?" This would get anybody 90+% to whatever they're looking for. Frustrated, I came up with this example. I hope it helps others. (It sure helped me! ;-)

import sys, traceback

traceback_template = '''Traceback (most recent call last):
  File "%(filename)s", line %(lineno)s, in %(name)s
%(type)s: %(message)s\n''' # Skipping the "actual line" item

# Also note: we don't walk all the way through the frame stack in this example
# see hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l280
# (Imagine if the 1/0, below, were replaced by a call to test() which did 1/0.)

try:
    1/0
except:
    # http://docs.python.org/2/library/sys.html#sys.exc_info
    exc_type, exc_value, exc_traceback = sys.exc_info() # most recent (if any) by default

    '''
    Reason this _can_ be bad: If an (unhandled) exception happens AFTER this,
    or if we do not delete the labels on (not much) older versions of Py, the
    reference we created can linger.

    traceback.format_exc/print_exc do this very thing, BUT note this creates a
    temp scope within the function.
    '''

    traceback_details = {
                         'filename': exc_traceback.tb_frame.f_code.co_filename,
                         'lineno'  : exc_traceback.tb_lineno,
                         'name'    : exc_traceback.tb_frame.f_code.co_name,
                         'type'    : exc_type.__name__,
                         'message' : exc_value.message, # or see traceback._some_str()
                        }

    del(exc_type, exc_value, exc_traceback) # So we don't leave our local labels/objects dangling
    # This still isn't "completely safe", though!
    # "Best (recommended) practice: replace all exc_type, exc_value, exc_traceback
    # with sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]

    print
    print traceback.format_exc()
    print
    print traceback_template % traceback_details
    print

In specific answer to this query:

sys.exc_info()[0].__name__, os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename), sys.exc_info()[2].tb_lineno

catching stdout in realtime from subprocess

Your problem is:

for line in p.stdout:
    print(">>> " + str(line.rstrip()))
    p.stdout.flush()

the iterator itself has extra buffering.

Try doing like this:

while True:
  line = p.stdout.readline()
  if not line:
     break
  print line

Echo newline in Bash prints literal \n

This could better be done as

x="\n"
echo -ne $x

-e option will interpret backslahes for the escape sequence
-n option will remove the trailing newline in the output

PS: the command echo has an effect of always including a trailing newline in the output so -n is required to turn that thing off (and make it less confusing)

What is the difference between "SMS Push" and "WAP Push"?

SMS Push uses SMS as a carrier, WAP uses download via WAP.

Numpy array dimensions

First:

By convention, in Python world, the shortcut for numpy is np, so:

In [1]: import numpy as np

In [2]: a = np.array([[1,2],[3,4]])

Second:

In Numpy, dimension, axis/axes, shape are related and sometimes similar concepts:

dimension

In Mathematics/Physics, dimension or dimensionality is informally defined as the minimum number of coordinates needed to specify any point within a space. But in Numpy, according to the numpy doc, it's the same as axis/axes:

In Numpy dimensions are called axes. The number of axes is rank.

In [3]: a.ndim  # num of dimensions/axes, *Mathematics definition of dimension*
Out[3]: 2

axis/axes

the nth coordinate to index an array in Numpy. And multidimensional arrays can have one index per axis.

In [4]: a[1,0]  # to index `a`, we specific 1 at the first axis and 0 at the second axis.
Out[4]: 3  # which results in 3 (locate at the row 1 and column 0, 0-based index)

shape

describes how many data (or the range) along each available axis.

In [5]: a.shape
Out[5]: (2, 2)  # both the first and second axis have 2 (columns/rows/pages/blocks/...) data

How to convert array into comma separated string in javascript

Use the join method from the Array type.

a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();

The join method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.

Compiling php with curl, where is curl installed?

If you're going to compile a 64bit version(x86_64) of php use: /usr/lib64/

For architectures (i386 ... i686) use /usr/lib/

I recommend compiling php to the same architecture as apache. As you're using a 64bit linux i asume your apache is also compiled for x86_64.

maven compilation failure

I had the same issue (even though the project was compiling/working fine in Eclipse), it was not when using the command line build. The reason was that I wasn't using the correct folder structure for mvn: "src/main/java/com" etc. It is looking at these folders by default (I was using "/scr/main/com" etc. which caused issues).

Use Fieldset Legend with bootstrap

Just wanted to summarize all the correct answers above in short. Because I had to spend lot of time to figure out which answer resolves the issue and what's going on behind the scenes.

There seems to be two problems of fieldset with bootstrap:

  1. The bootstrap sets the width to the legend as 100%. That is why it overlays the top border of the fieldset.
  2. There's a bottom border for the legend.

So, all we need to fix this is set the legend width to auto as follows:

legend.scheduler-border {
   width: auto; // fixes the problem 1
   border-bottom: none; // fixes the problem 2
}

Send message to specific client with socket.io and node.js

Whatever version we are using if we just console.log() the "io" object that we use in our server side nodejs code, [e.g. io.on('connection', function(socket) {...});], we can see that "io" is just an json object and there are many child objects where the socket id and socket objects are stored.

I am using socket.io version 1.3.5, btw.

If we look in the io object, it contains,

 sockets:
  { name: '/',
    server: [Circular],
    sockets: [ [Object], [Object] ],
    connected:
     { B5AC9w0sYmOGWe4fAAAA: [Object],
       'hWzf97fmU-TIwwzWAAAB': [Object] },

here we can see the socketids "B5AC9w0sYmOGWe4fAAAA" etc. So, we can do,

io.sockets.connected[socketid].emit();

Again, on further inspection we can see segments like,

 eio:
  { clients:
     { B5AC9w0sYmOGWe4fAAAA: [Object],
       'hWzf97fmU-TIwwzWAAAB': [Object] },

So, we can retrieve a socket from here by doing

io.eio.clients[socketid].emit();

Also, under engine we have,

engine:
 { clients:
    { B5AC9w0sYmOGWe4fAAAA: [Object],
      'hWzf97fmU-TIwwzWAAAB': [Object] },

So, we can also write,

io.engine.clients[socketid].emit();

So, I guess we can achieve our goal in any of the 3 ways I listed above,

  1. io.sockets.connected[socketid].emit(); OR
  2. io.eio.clients[socketid].emit(); OR
  3. io.engine.clients[socketid].emit();

100% Min Height CSS layout

Probably the shortest solution (works only in modern browsers)

This small piece of CSS makes "the middle content part fill 100% of the space in between with the footer fixed to the bottom":

html, body { height: 100%; }
your_container { min-height: calc(100% - height_of_your_footer); }

the only requirement is that you need to have a fixed height footer.

For example for this layout:

    <html><head></head><body>
      <main> your main content </main>
      </footer> your footer content </footer>
    </body></html>

you need this CSS:

    html, body { height: 100%; }
    main { min-height: calc(100% - 2em); }
    footer { height: 2em; }

PowerShell : retrieve JSON object by field value

David Brabant's answer led me to what I needed, with this addition:

x.Stuffs | where { $_.Name -eq "Darts" } | Select -ExpandProperty Type

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

Convert factor to integer

You can combine the two functions; coerce to characters thence to numerics:

> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2

Jenkins - Configure Jenkins to poll changes in SCM

I think your cron is not correct. According to what you described, you may need to change cron schedule to

*/5 * * * *

What you put in your schedule now mean it will poll the SCM at 5 past of every hour.

req.body empty on posts

you should not do JSON.stringify(data) while sending through AJAX like below.

This is NOT correct code:

function callAjax(url, data) {
    $.ajax({
        url: url,
        type: "POST",
        data: JSON.stringify(data),
        success: function(d) {
            alert("successs "+ JSON.stringify(d));
        }
    });
}   

The correct code is:

function callAjax(url, data) {
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        success: function(d) {
            alert("successs "+ JSON.stringify(d));
        }
    });
}

How do I do a not equal in Django queryset filtering?

Using exclude and filter

results = Model.objects.filter(x=5).exclude(a=true)

jQuery ajax request with json response, how to?

Try this code. You don't require the parse function because your data type is JSON so it is return JSON object.

$.ajax({
    url : base_url+"Login/submit",
    type: "POST",
    dataType: "json",
    data : {
        'username': username,
        'password': password
    },
    success: function(data)
    {
        alert(data.status);
    }
});

space between divs - display table-cell

Make a new div with whatever name (I will just use table-split) and give it a width, without adding content to it, while placing it between necessary divs that need to be separated.

You can add whatever width you find necessary. I just used 0.6% because it's what I needed for when I had to do this.

_x000D_
_x000D_
.table-split {_x000D_
  display: table-cell;_x000D_
  width: 0.6%_x000D_
}
_x000D_
<div class="table-split"></div>
_x000D_
_x000D_
_x000D_

What is the curl error 52 "empty reply from server"?

In my case it was server redirection; curl -L solved my problem.

Amazon Linux: apt-get: command not found

There can be 2 issues :=

1. Your are trying the command in machine that does not support apt-get command
because apt-get is suitable for Linux based Ubuntu machines; for MAC, try
apt-get equivalent such as Brew

2. The other issue can be that your installation was not completed properly So

The short answer:

Re-install Ubuntu from a Live CD or USB.

The long version:

The long version would be a waste of your time: your system will never
be clean, but if you insist you could try:

==> Copying everything (missing) except for the /home folder from the Live
CD/USB to your HDD.

OR

==> Do a re-install/repair over the broken system again with the Live
CD / USB stick.

OR

==> Download the deb file for apt-get and install as explained on above posts.
I would definitely go for a fresh new install as there are so many things to
do and so little time.

SQL: Select columns with NULL values only

If you need to list all rows where all the column values are NULL, then i'd use the COLLATE function. This takes a list of values and returns the first non-null value. If you add all the column names to the list, then use IS NULL, you should get all the rows containing only nulls.

SELECT * FROM MyTable WHERE COLLATE(Col1, Col2, Col3, Col4......) IS NULL

You shouldn't really have any tables with ALL the columns null, as this means you don't have a primary key (not allowed to be null). Not having a primary key is something to be avoided; this breaks the first normal form.

Return first N key:value pairs from dict

def GetNFirstItems(self):
    self.dict = {f'Item{i + 1}': round(uniform(20.40, 50.50), 2) for i in range(10)}#Example Dict
    self.get_items = int(input())
    for self.index,self.item in zip(range(len(self.dict)),self.dict.items()):
        if self.index==self.get_items:
          break
        else:
            print(self.item,",",end="")

Unusual approach, as it gives out intense O(N) time complexity.

Xcode process launch failed: Security

Hey so the accepted answer works, except if you need to debug the initial launch of the app. However I think that answer is more of a work around, and not an actual solution. From my understanding this message occurs when you have some weirdness in your provisioning profile / cert setup so make extra sure everything is in tip-top shape in that dept. before ramming your head against the wall repeatedly.

What worked for me was as follows from the apple docs:

Provisioning Profiles Known Issue If you have upgraded to the GM seed from other betas you may see your apps crashing due to provisioning profile issues.

Workaround:

  1. Connect the device via USB to your Mac

  2. Launch Xcode Choose Window ->Devices

  3. Right click on the device in left column, choose "Show Provisioning Profiles"

  4. Click on the provisioning profile in question

  5. Press the "-" button Continue to removing all affected profiles.

  6. Re-install the app

Make sure you right click on the image of the device not the name of the device or you won't see the provisioning profiles option. I restored my new phone from an old backup and there was a lot of cruft hanging around, i also had 2 different dev. certs active (not sure why) but i deleted one, made a new profile got rid of all the profiles on device and it worked.

Hope this helps someone else.

Import pfx file into particular certificate store from command line

For Windows 10:

Import certificate to Trusted Root Certification Authorities for Current User:

certutil -f -user -p oracle -importpfx root "example.pfx"

Import certificate to Trusted People for Current User:

certutil -f -user -p oracle -importpfx TrustedPeople "example.pfx"

Import certificate to Trusted Root Certification Authorities on Local Machine:

certutil -f -user -p oracle -enterprise -importpfx root "example.pfx"

Import certificate to Trusted People on Local Machine:

certutil -f -user -p oracle -enterprise -importpfx TrustedPeople "example.pfx"

How to add style from code behind?

You can't.

So just don't apply styles directly like that, and apply a class "foo", and then define that in your CSS specification:

a.foo { color : orange; }
a.foo:hover { font-weight : bold; }

How to enumerate an enum with String type?

You could iterate through an enum by implementing the ForwardIndexType protocol.

The ForwardIndexType protocol requires you to define a successor() function to step through the elements.

enum Rank: Int, ForwardIndexType {
    case Ace = 1
    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
    case Jack, Queen, King

    // ... other functions

    // Option 1 - Figure it out by hand
    func successor() -> Rank {
        switch self {
            case .Ace:
              return .Two
            case .Two:
              return .Three

            // ... etc.

            default:
              return .King
        }
    }

    // Option 2 - Define an operator!
    func successor() -> Rank {
        return self + 1
    }
}

// NOTE: The operator is defined OUTSIDE the class
func + (left: Rank, right: Int) -> Rank {
    // I'm using to/from raw here, but again, you can use a case statement
    // or whatever else you can think of

    return left == .King ? .King : Rank(rawValue: left.rawValue + right)!
}

Iterating over an open or closed range (..< or ...) will internally call the successor() function which allows you to write this:

// Under the covers, successor(Rank.King) and successor(Rank.Ace) are called to establish limits
for r in Rank.Ace...Rank.King {
    // Do something useful
}

JavaScript - populate drop down list with array

I found this also works...

var select = document.getElementById("selectNumber"); 
var options = ["1", "2", "3", "4", "5"]; 

// Optional: Clear all existing options first:
select.innerHTML = "";
// Populate list with options:
for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    select.innerHTML += "<option value=\"" + opt + "\">" + opt + "</option>";
}

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

i faced this issue where i was using SQL it is different from MYSQL the solution was puting in this format: =date('m-d-y h:m:s'); rather than =date('y-m-d h:m:s');

spring autowiring with unique beans: Spring expected single matching bean but found 2

If I'm not mistaken, the default bean name of a bean declared with @Component is the name of its class its first letter in lower-case. This means that

@Component
public class SuggestionService {

declares a bean of type SuggestionService, and of name suggestionService. It's equivalent to

@Component("suggestionService")
public class SuggestionService {

or to

<bean id="suggestionService" .../>

You're redefining another bean of the same type, but with a different name, in the XML:

<bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService">
    ...
</bean>

So, either specify the name of the bean in the annotation to be SuggestionService, or use the ID suggestionService in the XML (don't forget to also modify the <ref> element, or to remove it, since it isn't needed). In this case, the XML definition will override the annotation definition.

Rewrite all requests to index.php with nginx

Here is what worked for me to solve part 1 of this question:

    location / {
            rewrite ^([^.]*[^/])$ $1/ permanent;
            try_files $uri $uri/ /index.php =404;
            include fastcgi_params;
            fastcgi_pass php5-fpm-sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_intercept_errors on;
    }

rewrite ^([^.]*[^/])$ $1/ permanent; rewrites non-file addresses (addresses without file extensions) to have a "/" at the end. I did this because I was running into "Access denied." message when I tried to access the folder without it.

try_files $uri $uri/ /index.php =404; is borrowed from SanjuD's answer, but with an extra 404 reroute if the location still isn't found.

fastcgi_index index.php; was the final piece of the puzzle that I was missing. The folder didn't reroute to the index.php without this line.

Fastest way to convert JavaScript NodeList to Array?

Check out this blog post here that talks about the same thing. From what I gather, the extra time might have to do with walking up the scope chain.

Set width of dropdown element in HTML select dropdown options

HTML:

<select class="shortenedSelect">
    <option value="0" disabled>Please select an item</option>
    <option value="1">Item text goes in here but it is way too long to fit inside a select option that has a fixed width adding more</option>
</select>

CSS:

.shortenedSelect {
    max-width: 350px;
}

Javascript:

// Shorten select option text if it stretches beyond max-width of select element
$.each($('.shortenedSelect option'), function(key, optionElement) {
    var curText = $(optionElement).text();
    $(this).attr('title', curText);

    // Tip: parseInt('350px', 10) removes the 'px' by forcing parseInt to use a base ten numbering system.
    var lengthToShortenTo = Math.round(parseInt($(this).parent('select').css('max-width'), 10) / 7.3);

    if (curText.length > lengthToShortenTo) {
        $(this).text('... ' + curText.substring((curText.length - lengthToShortenTo), curText.length));
    }
});

// Show full name in tooltip after choosing an option
$('.shortenedSelect').change(function() {
    $(this).attr('title', ($(this).find('option:eq('+$(this).get(0).selectedIndex +')').attr('title')));
});

Works perfectly. I had the same issue myself. Check out this JSFiddle http://jsfiddle.net/jNWS6/426/

What is the Python equivalent of static variables inside a function?

Prompted by this question, may I present another alternative which might be a bit nicer to use and will look the same for both methods and functions:

@static_var2('seed',0)
def funccounter(statics, add=1):
    statics.seed += add
    return statics.seed

print funccounter()       #1
print funccounter(add=2)  #3
print funccounter()       #4

class ACircle(object):
    @static_var2('seed',0)
    def counter(statics, self, add=1):
        statics.seed += add
        return statics.seed

c = ACircle()
print c.counter()      #1
print c.counter(add=2) #3
print c.counter()      #4
d = ACircle()
print d.counter()      #5
print d.counter(add=2) #7
print d.counter()      #8    

If you like the usage, here's the implementation:

class StaticMan(object):
    def __init__(self):
        self.__dict__['_d'] = {}

    def __getattr__(self, name):
        return self.__dict__['_d'][name]
    def __getitem__(self, name):
        return self.__dict__['_d'][name]
    def __setattr__(self, name, val):
        self.__dict__['_d'][name] = val
    def __setitem__(self, name, val):
        self.__dict__['_d'][name] = val

def static_var2(name, val):
    def decorator(original):
        if not hasattr(original, ':staticman'):    
            def wrapped(*args, **kwargs):
                return original(getattr(wrapped, ':staticman'), *args, **kwargs)
            setattr(wrapped, ':staticman', StaticMan())
            f = wrapped
        else:
            f = original #already wrapped

        getattr(f, ':staticman')[name] = val
        return f
    return decorator

How to check if $_GET is empty?

Just to provide some variation here: You could check for

if ($_SERVER["QUERY_STRING"] == null)

it is completely identical to testing $_GET.

Get each line from textarea

You could use PHP constant:

$array = explode(PHP_EOL, $text);

additional notes:
1. For me this is the easiest and the safest way because it is cross platform compatible (Windows/Linux etc.)
2. It is better to use PHP CONSTANT whenever you can for faster execution

How to change the data type of a column without dropping the column with query?

MSDN says

ALTER TABLE mytable ALTER COLUMN mycolumn newtype

Beware of the limitations of the ALTER COLUMN clause listed in the article

WPF: simple TextBox data binding

Just for future needs.

In Visual Studio 2013 with .NET Framework 4.5, for a window property, try adding ElementName=window to make it work.

<Grid Name="myGrid" Height="437.274">
  <TextBox Text="{Binding Path=Name2, ElementName=window}"/>
</Grid>

How to count rows with SELECT COUNT(*) with SQLAlchemy?

I needed to do a count of a very complex query with many joins. I was using the joins as filters, so I only wanted to know the count of the actual objects. count() was insufficient, but I found the answer in the docs here:

http://docs.sqlalchemy.org/en/latest/orm/tutorial.html

The code would look something like this (to count user objects):

from sqlalchemy import func

session.query(func.count(User.id)).scalar() 

How do I run PHP code when a user clicks on a link?

Yeah, you'd need to have a javascript function triggered by an onclick that does an AJAX load of a page and then returns false, that way they won't be redirected in the browser. You could use the following in jQuery, if that's acceptable for your project:

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
    $.get("somepage.php");
    return false;
}
</script>

<a href="#" onclick="doSomething();">Click Me!</a>

You could also do a post-back if you need to use form values (use the $.post() method).

How to get input from user at runtime

`DECLARE
c_id customers.id%type := &c_id;
c_name customers.name%type;
c_add customers.address%type;
c_sal customers.salary%type;
a integer := &a`   

Here c_id customers.id%type := &c_id; statement inputs the c_id with type already defined in the table and statement a integer := &a just input integer in variable a.

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

LINQ: Select an object and change some properties without creating a new object

User u = UserCollection.Single(u => u.Id == 1);
u.FirstName = "Bob"

IOS - How to segue programmatically using swift

If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using:

performSegue(withIdentifier: "mySegueID", sender: nil)

For older versions:

performSegueWithIdentifier("mySegueID", sender: nil)

You could also do:

presentViewController(nextViewController, animated: true, completion: nil)

Or if you are in a Navigation controller:

self.navigationController?.pushViewController(nextViewController, animated: true)

How to add a new object (key-value pair) to an array in javascript?

.push() will add elements to the end of an array.

Use .unshift() if need to add some element to the beginning of array i.e:

items.unshift({'id':5});

Demo:

_x000D_
_x000D_
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.unshift({'id': 0});_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

And use .splice() in case you want to add object at a particular index i.e:

items.splice(2, 0, {'id':5});
           // ^ Given object will be placed at index 2...

Demo:

_x000D_
_x000D_
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.splice(2, 0, {'id': 2.5});_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

How to select a specific node with LINQ-to-XML

I'd use something like:

dim customer = (from c in xmldoc...<Customer> 
                where c.<ID>.Value=22 
                select c).SingleOrDefault 

Edit:

missed the c# tag, sorry......the example is in VB.NET

Calculate age given the birth date in the format YYYYMMDD

Important: This answer doesn't provide an 100% accurate answer, it is off by around 10-20 hours depending on the date.

There are no better solutions ( not in these answers anyway ). - naveen

I of course couldn't resist the urge to take up the challenge and make a faster and shorter birthday calculator than the current accepted solution. The main point for my solution, is that math is fast, so instead of using branching, and the date model javascript provides to calculate a solution we use the wonderful math

The answer looks like this, and runs ~65% faster than naveen's plus it's much shorter:

function calcAge(dateString) {
  var birthday = +new Date(dateString);
  return ~~((Date.now() - birthday) / (31557600000));
}

The magic number: 31557600000 is 24 * 3600 * 365.25 * 1000 Which is the length of a year, the length of a year is 365 days and 6 hours which is 0.25 day. In the end i floor the result which gives us the final age.

Here is the benchmarks: http://jsperf.com/birthday-calculation

To support OP's data format you can replace +new Date(dateString);
with +new Date(d.substr(0, 4), d.substr(4, 2)-1, d.substr(6, 2));

If you can come up with a better solution please share! :-)

How to get HttpClient to pass credentials along with the request?

It worked for me after I set up a user with internet access in the Windows service.

In my code:

HttpClientHandler handler = new HttpClientHandler();
handler.Proxy = System.Net.WebRequest.DefaultWebProxy;
handler.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
.....
HttpClient httpClient = new HttpClient(handler)
.... 

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

In MySQL, "Group By" uses an extra step: filesort. I realize DISTINCT is faster than GROUP BY, and that was a surprise.

How to get date in BAT file

You get and format like this

for /f "tokens=1-4 delims=/ " %%i in ("%date%") do (
     set dow=%%i
     set month=%%j
     set day=%%k
     set year=%%l
)
set datestr=%month%_%day%_%year%
echo datestr is %datestr%

Note: Above only works on US locale. It assumes the output of echo %date% looks like this: Thu 02/13/21. If you have different Windows locale settings, you will need to modify the script based on your configuration.

Android - default value in editText

First you need to load the user details somehow

Then you need to find your EditText if you don't have it-

EditText et = (EditText)findViewById(R.id.youredittext);

after you've found your EditText, call

et.setText(theUserName);

How to read data from excel file using c#

Convert the excel file to .csv file (comma separated value file) and now you can easily be able to read it.

How to use sessions in an ASP.NET MVC 4 application?

U can store any value in session like Session["FirstName"] = FirstNameTextBox.Text; but i will suggest u to take as static field in model assign value to it and u can access that field value any where in application. U don't need session. session should be avoided.

public class Employee
{
   public int UserId { get; set; }
   public string EmailAddress { get; set; }
   public static string FullName { get; set; }
}

on controller - Employee.FullName = "ABC"; Now u can access this full Name anywhere in application.

Python coding standards/best practices

PEP 8 is good, the only thing that i wish it came down harder on was the Tabs-vs-Spaces holy war.

Basically if you are starting a project in python, you need to choose Tabs or Spaces and then shoot all offenders on sight.

How to return a string value from a Bash function

You can echo a string, but catch it by piping (|) the function to something else.

You can do it with expr, though ShellCheck reports this usage as deprecated.

Assets file project.assets.json not found. Run a NuGet package restore

In visual studio 2017 please do following steps:

1) select Tool=>Options=>NuGet Package Manager=> Package Sources then uncheck Microsoft Visual Studio Offline Packages Option. enter image description here

2) now open Tool=>NuGet Package Maneger=>Package Manager Console. 3) execute command in PM>dotnet restore.

Hope its working...

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

I know it's an old question but I want to help. You can put the transactional annotation on the service method you need, in this case findTopicByID(id) should have

@Transactional(propagation=Propagation.REQUIRED, readOnly=true, noRollbackFor=Exception.class)

more info about this annotation can be found here

About the other solutions:

fetch = FetchType.EAGER 

is not a good practice, it should be used ONLY if necessary.

Hibernate.initialize(topics.getComments());

The hibernate initializer binds your classes to the hibernate technology. If you are aiming to be flexible is not a good way to go.

Hope it helps

Using if elif fi in shell scripts

sh is interpreting the && as a shell operator. Change it to -a, that’s [’s conjunction operator:

[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ]

Also, you should always quote the variables, because [ gets confused when you leave off arguments.

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

Submit form without page reloading

You'll need to submit an ajax request to send the email without reloading the page. Take a look at http://api.jquery.com/jQuery.ajax/

Your code should be something along the lines of:

$('#submit').click(function() {
    $.ajax({
        url: 'send_email.php',
        type: 'POST',
        data: {
            email: '[email protected]',
            message: 'hello world!'
        },
        success: function(msg) {
            alert('Email Sent');
        }               
    });
});

The form will submit in the background to the send_email.php page which will need to handle the request and send the email.

Reverting to a previous revision using TortoiseSVN

Right click on the folder which is under SVN control, go to TortoiseSVN ? Show log. Write down the revision you want to revert to and then go to TortoiseSVN ? Update to revision....

Enter image description here

Convert pandas DataFrame into list of lists

EDIT: as_matrix is deprecated since version 0.23.0

You can use the built in values or to_numpy (recommended option) method on the dataframe:

In [8]:
df.to_numpy()

Out[8]:
array([[  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.8,   6.1,   5.4, ...,  15.9,  14.4,   8.6],
   ..., 
   [  0.2,   1.3,   2.3, ...,  16.1,  16.1,  10.8],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4]])

If you explicitly want lists and not a numpy array add .tolist():

df.to_numpy().tolist()

Replacing Spaces with Underscores

Strtr replaces single characters instead of strings, so it's a good solution for this example. Supposedly strtr is faster than str_replace (but for this use case they're both immeasurably fast).

echo strtr('Alex Newton',' ','_');
//outputs: Alex_Newton

Date difference in years using C#

DateTime musteriDogum = new DateTime(dogumYil, dogumAy, dogumGun);

int additionalDays = ((DateTime.Now.Year - dogumYil) / 4); //Count of the years with 366 days

int extraDays = additionalDays + ((DateTime.Now.Year % 4 == 0 || musteriDogum.Year % 4 == 0) ? 1 : 0); //We add 1 if this year or year inserted has 366 days

int yearsOld = ((DateTime.Now - musteriDogum).Days - extraDays ) / 365; // Now we extract these extra days from total days and we can divide to 365

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

One extra step, when I did File -> Invalidate Caches and restarted the IDE, open a project. It popped up a toastbox on the top-right asking me whether to enable auto-import and that solved the problem.

npm install errors with Error: ENOENT, chmod

The same error during global install (npm install -g mymodule) for package with a non-existing script.

In package.json:

    ...
    "bin": {
      "module": "./bin/module"
    },
    ...

But the ./bin/module did not exist, as it was named modulejs.

Easiest way to split a string on newlines in .NET?

I'm currently using this function (based on other answers) in VB.NET:

Private Shared Function SplitLines(text As String) As String()
    Return text.Split({Environment.NewLine, vbCrLf, vbLf}, StringSplitOptions.None)
End Function

It tries to split on the platform-local newline first, and then falls back to each possible newline.

I've only needed this inside one class so far. If that changes, I will probably make this Public and move it to a utility class, and maybe even make it an extension method.

Here's how to join the lines back up, for good measure:

Private Shared Function JoinLines(lines As IEnumerable(Of String)) As String
    Return String.Join(Environment.NewLine, lines)
End Function

Modifying a file inside a jar

Check out TrueZip.

It does exactly what you want (to edit files inline inside a jar file), through a virtual file system API. It also supports nested archives (jar inside a jar) as well.

selecting rows with id from another table

SELECT terms.*
FROM terms JOIN terms_relation ON id=term_id
WHERE taxonomy='categ'

Adding local .aar files to Gradle build using "flatDirs" is not working

Add below in app gradle file implementation project(path: ':project name')

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

I'm using a very old O/S that I don't dare install libraries onto, so here's what I use;

%MonthMatrix=("Jan",0,"Feb",31,"Mar",59,"Apr",90,"May",120,"Jun",151,"Jul",181,"Aug",212,"Sep",243,"Oct",273,"Nov",304,"Dec",334);
$LeapYearCount=int($YearFourDigits/4);
$EpochDayNumber=$MonthMatrix{$MonthThreeLetters};
if ($LeapYearCount==($YearFourDigits/4)) { if ($EpochDayNumber<32) { $EpochDayNumber--; }}
$EpochDayNumber=($YearFourDigits-1970)*365+$LeapYearCount+$EpochDayNumber+$DayAsNumber-493;
$TimeOfDaySeconds=($HourAsNumber*3600)+($MinutesAsNumber*60)+$SecondsAsNumber;
$ActualEpochTime=($EpochDayNumber*86400)+$TimeOfDaySeconds;

The input variables are;

$MonthThreeLetters
$DayAsNumber
$YearFourDigits
$HourAsNumber
$MinutesAsNumber
$SecondsAsNumber

...which should be self-explanatory.

The input variables, of course, assume GMT (UTC). The output variable is "$ActualEpochTime". (Often, I only need $EpochDayNumber, so that's why that otherwise superfluous variable sits on its own.)

I've used this formula for years with nary an error.

Check if checkbox is NOT checked on click - jQuery

Check out some of the answers to this question - I think it might apply to yours:

how to run click function after default behaviour of a element

I think you're running into an inconsistency in the browser implementation of the onclick function. Some choose to toggle the checkbox before the event is fired and some after.

Why does Oracle not find oci.dll?

I notice that recent Oracle client installers change file permissions.

I had Oracle 12.0.1 32 bit client installed for a year. I recently installed Oracle 12.0.1 64 bit client. The Oracle install change ALL file permissions in the 32 bit folders.

My application suddenly failed to run.

I used PROCMON.EXE (https://docs.microsoft.com/en-us/sysinternals/downloads/) and noticed that permission was denied opening OCI.DLL

I changed the permissions for everything in the Oracle client folders and application works as expected.

Oracle: how to add minutes to a timestamp?

I prefer using an interval literal for this, because interval '30' minute or interval '5' second is a lot easier to read then 30 / (24 * 60) or 5 / (24 * 60 * 69)

e.g.

  • some_date + interval '2' hour
  • some_date + interval '30' minute
  • some_date + interval '5' second
  • some_date + interval '2' day

You can also combine several units into one expression:

  • some_date + interval '2 3:06' day to minute

Adds 2 days, 3 hours and 6 minutes to the date value

The above is also standard SQL and also works in several other DBMS.

More details in the manual: https://docs.oracle.com/database/121/SQLRF/sql_elements003.htm#SQLRF00221

BigDecimal to string

To archive the necessary result with double constructor you need to round the BigDecimal before convert it to String e.g.

new java.math.BigDecimal(10.0001).round(new java.math.MathContext(6, java.math.RoundingMode.HALF_UP)).toString()

will print the "10.0001"

Angular Directive refresh on parameter change

Link function only gets called once, so it would not directly do what you are expecting. You need to use angular $watch to watch a model variable.

This watch needs to be setup in the link function.

If you use isolated scope for directive then the scope would be

scope :{typeId:'@' }

In your link function then you add a watch like

link: function(scope, element, attrs) {
    scope.$watch("typeId",function(newValue,oldValue) {
        //This gets called when data changes.
    });
 }

If you are not using isolated scope use watch on some_prop

Printing an array in C++?

C++ can print whatever you want if you program it to do so. You'll have to go through the array yourself printing each element.

how to set background image in submit button?

You can try the following code:

background-image:url('url of your image') 10px 10px no-repeat

Delete the first three rows of a dataframe in pandas

I think a more explicit way of doing this is to use drop.

The syntax is:

df.drop(label)

And as pointed out by @tim and @ChaimG, this can be done in-place:

df.drop(label, inplace=True)

One way of implementing this could be:

df.drop(df.index[:3], inplace=True)

And another "in place" use:

df.drop(df.head(3).index, inplace=True)

Python dictionary: Get list of values for list of keys

reduce(lambda x,y: mydict.get(y) and x.append(mydict[y]) or x, mykeys,[])

incase there are keys not in dict.

How to add text inside the doughnut chart using Chart.js?

@rap-2-h and @Ztuons Ch's answer doesn't allow for the showTooltips option to be active, but what you can do is create and layer a second canvas object behind the one rendering the chart.

The important part is the styling required in the divs and for the canvas object itself so that they render on top of each other.

_x000D_
_x000D_
var data = [_x000D_
    {value : 100, color : 'rgba(226,151,093,1)', highlight : 'rgba(226,151,093,0.75)', label : "Sector 1"},_x000D_
    {value : 100, color : 'rgba(214,113,088,1)', highlight : 'rgba(214,113,088,0.75)', label : "Sector 2"},_x000D_
    {value : 100, color : 'rgba(202,097,096,1)', highlight : 'rgba(202,097,096,0.75)', label : "Sector 3"}_x000D_
]_x000D_
_x000D_
var options = { showTooltips : true };_x000D_
     _x000D_
var total = 0;_x000D_
for (i = 0; i < data.length; i++) {_x000D_
     total = total + data[i].value;_x000D_
}_x000D_
_x000D_
var chartCtx = $("#canvas").get(0).getContext("2d");_x000D_
var chart = new Chart(chartCtx).Doughnut(data, options);_x000D_
_x000D_
var textCtx = $("#text").get(0).getContext("2d");_x000D_
textCtx.textAlign = "center";_x000D_
textCtx.textBaseline = "middle";_x000D_
textCtx.font = "30px sans-serif";_x000D_
textCtx.fillText(total, 150, 150);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>_x000D_
<html>_x000D_
<body>_x000D_
<div style="position: relative; width:300px; height:300px;">_x000D_
    <canvas id="text" _x000D_
            style="z-index: 1; _x000D_
                   position: absolute;_x000D_
                   left: 0px; _x000D_
                   top: 0px;" _x000D_
            height="300" _x000D_
            width="300"></canvas>_x000D_
    <canvas id="canvas" _x000D_
            style="z-index: 2; _x000D_
                   position: absolute;_x000D_
                   left: 0px; _x000D_
                   top: 0px;" _x000D_
            height="300" _x000D_
            width="300"></canvas>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Here's the jsfiddle: https://jsfiddle.net/68vxqyak/1/

Squash my last X commits together using Git

To avoid having to resolve any merge conflicts when rebasing onto a commit in the same branch, you can use the following command

git rebase -i <last commit id before your changes start> -s recursive -X ours

To squash all commits into one, when you are prompted to edit commits to be merged (-i flag), update all but first action from pick to squash as recommended in other answers too.

Here, we use the merge strategy (-s flag) recursive and strategy option (-X) ours to make sure that the later commits in the history win any merge conflicts.

NOTE: Do not confuse this with git rebase -s ours which does something else.

Reference: git rebase recursive merge strategy

T-SQL and the WHERE LIKE %Parameter% clause

The correct answer is, that, because the '%'-sign is part of your search expression, it should be part of your VALUE, so whereever you SET @LastName (be it from a programming language or from TSQL) you should set it to '%' + [userinput] + '%'

or, in your example:

DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%' + @LastName + '%'

Descending order by date filter in AngularJs

According to documentation you can use the reverse argument.

filter:orderBy(array, expression[, reverse]);

Change your filter to:

orderBy: 'created_at':true

Git fetch remote branch

If you would like to fetch all remote branches, please type just:

git fetch --all

How do you create a Distinct query in HQL

I had some problems with result transformers combined with HQL queries. When I tried

final ResultTransformer trans = new DistinctRootEntityResultTransformer();
qry.setResultTransformer(trans);

it didn't work. I had to transform manually like this:

final List found = trans.transformList(qry.list());

With Criteria API transformers worked just fine.

How do I debug "Error: spawn ENOENT" on node.js?

If you're on Windows Node.js does some funny business when handling quotes that may result in you issuing a command that you know works from the console, but does not when run in Node. For example the following should work:

spawn('ping', ['"8.8.8.8"'], {});

but fails. There's a fantastically undocumented option windowsVerbatimArguments for handling quotes/similar that seems to do the trick, just be sure to add the following to your opts object:

const opts = {
    windowsVerbatimArguments: true
};

and your command should be back in business.

 spawn('ping', ['"8.8.8.8"'], { windowsVerbatimArguments: true });

Convert wchar_t to char

Technically, 'char' could have the same range as either 'signed char' or 'unsigned char'. For the unsigned characters, your range is correct; theoretically, for signed characters, your condition is wrong. In practice, very few compilers will object - and the result will be the same.

Nitpick: the last && in the assert is a syntax error.

Whether the assertion is appropriate depends on whether you can afford to crash when the code gets to the customer, and what you could or should do if the assertion condition is violated but the assertion is not compiled into the code. For debug work, it seems fine, but you might want an active test after it for run-time checking too.

Return a "NULL" object if search result not found

You can try this:

return &Type();

Can we call the function written in one JavaScript in another JS file?

Here's a more descriptive example with a CodePen snippet attached:

1.js

function fn1() {
  document.getElementById("result").innerHTML += "fn1 gets called";
}

2.js

function clickedTheButton() {
  fn1();
} 

index.html

<html>
  <head>
  </head>
  <body>
    <button onclick="clickedTheButton()">Click me</button>
    <script type="text/javascript" src="1.js"></script>
    <script type="text/javascript" src="2.js"></script>
  </body>
 </html>

output

Output. Button + Result

Try this CodePen snippet: link .

How can I print to the same line?

Format your string like so:

[#                    ] 1%\r

Note the \r character. It is the so-called carriage return that will move the cursor back to the beginning of the line.

Finally, make sure you use

System.out.print()

and not

System.out.println()

SyntaxError: unexpected EOF while parsing

You're missing a closing parenthesis ) in print():

print('{0}+{1}={2}'.format(n1,n2,t1))

and you're also not storing the returned value from int(), so z is still a string.

z = input('?')
z = int(z)

or simply:

z = int(input('?'))

Visual Studio 2015 installer hangs during install?

In my case the Graphics Tools Windows feature installation was hanging forever. I've installed the Optional Windows Feature manually and restarted the setup of VS 2015.

Get and Set a Single Cookie with Node.js HTTP Server

If you're using the express library, as many node.js developers do, there is an easier way. Check the Express.js documentation page for more information.

The parsing example above works but express gives you a nice function to take care of that:

app.use(express.cookieParser());

To set a cookie:

res.cookie('cookiename', 'cookievalue', { maxAge: 900000, httpOnly: true });

To clear the cookie:

res.clearCookie('cookiename');

Django datetime issues (default=datetime.now())

From the Python language reference, under Function definitions:

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call.

Fortunately, Django has a way to do what you want, if you use the auto_now argument for the DateTimeField:

date = models.DateTimeField(auto_now=True)

See the Django docs for DateTimeField.

Why would $_FILES be empty when uploading files to PHP?

I was struggling with the same problem and testing everything, not getting error reporting and nothing seemed to be wrong. I had error_reporting(E_ALL) But suddenly I realized that I had not checked the apache log and voilà! There was a syntax error on the script...! (a missing "}" )

So, even though this is something evident to be checked, it can be forgotten... In my case (linux) it is at:

/var/log/apache2/error.log

Run JavaScript in Visual Studio Code

The shortcut for the integrated terminal is ctrl + `, then type node <filename>.

Alternatively you can create a task. This is the only code in my tasks.json:

{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "node",
"isShellCommand": true,
"args": ["${file}"],
"showOutput": "always"
}

From here create a shortcut. This is my keybindings.json:

// Place your key bindings in this file to overwrite the defaults
[
{   "key": "cmd+r",
"command": "workbench.action.tasks.runTask"
},
{   "key": "cmd+e",
"command": "workbench.action.output.toggleOutput"
}
]

This will open 'run' in the Command Pallete, but you still have to type or select with the mouse the task you want to run, in this case node. The second shortcut toggles the output panel, there's already a shortcut for it but these keys are next to each other and easier to work with.

JFrame Maximize window

@kgiannakakis answer is fully correct, but if someone stuck into this problem and uses Java 6 on Linux (by example, Mint 19 Cinnamon), MAXIMIZED_BOTH state is sometimes not applied.

You could try to call pack() method after setting this state.

Code example:

public MainFrame() {
    setContentPane(contentPanel); //some JPanel is here
    setPreferredSize(new Dimension(1200, 800));
    setMinimumSize(new Dimension(1200, 800));
    setSize(new Dimension(1200, 800));
    setExtendedState(JFrame.MAXIMIZED_BOTH);
    pack();
}

This is not necessary if you are using Java 7+ or Java 6 on Windows.

browser.msie error after update to jQuery 1.9.1

For simple IE detection I tend to use:

(/msie|trident/i).test(navigator.userAgent)

Visit the Microsoft Developer Network to learn about the IE useragent: http://msdn.microsoft.com/library/ms537503.aspx

Thymeleaf using path variables to th:href

You can use like

  1. My table is bellow like..

    <table>
       <thead>
        <tr>
            <th>Details</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="user: ${staffList}">
            <td><a th:href="@{'/details-view/'+ ${user.userId}}">Details</a></td>
        </tr>
     </tbody>
    </table>
    
  2. Here is my controller ..

    @GetMapping(value = "/details-view/{userId}")
    public String details(@PathVariable String userId) { 
    
        Logger.getLogger(getClass().getName()).info("userId-->" + userId);
    
     return "user-details";
    }
    

HTML Agility pack - parsing tables

I know this is a pretty old question but this was my solution that helped with visualizing the table so you can create a class structure. This is also using the HTML Agility Pack

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
var table = doc.DocumentNode.SelectSingleNode("//table");
var tableRows = table.SelectNodes("tr");
var columns = tableRows[0].SelectNodes("th/text()");
for (int i = 1; i < tableRows.Count; i++)
{
    for (int e = 0; e < columns.Count; e++)
    {
        var value = tableRows[i].SelectSingleNode($"td[{e + 1}]");
        Console.Write(columns[e].InnerText + ":" + value.InnerText);
    }
Console.WriteLine();
}

How to apply color in Markdown?

TL;DR

Markdown doesn't support color but you can inline HTML inside Markdown, e.g.:

<span style="color:blue">some *blue* text</span>.

Longer answer

As the original/official syntax rules state (emphasis added):

Markdown’s syntax is intended for one purpose: to be used as a format for writing for the web.

Markdown is not a replacement for HTML, or even close to it. Its syntax is very small, corresponding only to a very small subset of HTML tags. The idea is not to create a syntax that makes it easier to insert HTML tags. In my opinion, HTML tags are already easy to insert. The idea for Markdown is to make it easy to read, write, and edit prose. HTML is a publishing format; Markdown is a writing format. Thus, Markdown’s formatting syntax only addresses issues that can be conveyed in plain text.

For any markup that is not covered by Markdown’s syntax, you simply use HTML itself.

As it is not a "publishing format," providing a way to color your text is out-of-scope for Markdown. That said, it is not impossible as you can include raw HTML (and HTML is a publishing format). For example, the following Markdown text (as suggested by @scoa in a comment):

Some Markdown text with <span style="color:blue">some *blue* text</span>.

Would result in the following HTML:

<p>Some Markdown text with <span style="color:blue">some <em>blue</em> text</span>.</p>

Now, StackOverflow (and probably GitHub) will strip the raw HTML out (as a security measure) so you lose the color here, but it should work on any standard Markdown implementation.

Another possibility is to use the non-standard Attribute Lists originally introduced by the Markuru implementation of Markdown and later adopted by a few others (there may be more, or slightly different implementations of the same idea, like div and span attributes in pandoc). In that case, you could assign a class to a paragraph or inline element, and then use CSS to define a color for a class. However, you absolutely must be using one of the few implementations which actually support the non-standard feature and your documents are no longer portable to other systems.

How can I define a composite primary key in SQL?

Just for clarification: a table can have at most one primary key. A primary key consists of one or more columns (from that table). If a primary key consists of two or more columns it is called a composite primary key. It is defined as follows:

CREATE TABLE voting (
  QuestionID NUMERIC,
  MemberID NUMERIC,
  PRIMARY KEY (QuestionID, MemberID)
);

The pair (QuestionID,MemberID) must then be unique for the table and neither value can be NULL. If you do a query like this:

SELECT * FROM voting WHERE QuestionID = 7

it will use the primary key's index. If however you do this:

SELECT * FROM voting WHERE MemberID = 7

it won't because to use a composite index requires using all the keys from the "left". If an index is on fields (A,B,C) and your criteria is on B and C then that index is of no use to you for that query. So choose from (QuestionID,MemberID) and (MemberID,QuestionID) whichever is most appropriate for how you will use the table.

If necessary, add an index on the other:

CREATE UNIQUE INDEX idx1 ON voting (MemberID, QuestionID);

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Syntax:

CASE value WHEN [compare_value] THEN result 
[WHEN [compare_value] THEN result ...] 
[ELSE result] 
END

Alternative: CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]

mysql> SELECT CASE  WHEN 2>3 THEN 'this is true' ELSE 'this is false' END; 
+-------------------------------------------------------------+
| CASE  WHEN 2>3 THEN 'this is true' ELSE 'this is false' END |
+-------------------------------------------------------------+
| this is false                                               | 
+-------------------------------------------------------------+

I am use:

SELECT  act.*,
    CASE 
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NULL) THEN lises.location_id
        WHEN (lises.session_date IS NULL AND ses.session_date IS NOT NULL) THEN ses.location_id
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date>ses.session_date) THEN ses.location_id
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date<ses.session_date) THEN lises.location_id
    END AS location_id
FROM activity AS act
LEFT JOIN li_sessions AS lises ON lises.activity_id = act.id AND  lises.session_date >= now()
LEFT JOIN session AS ses ON  ses.activity_id = act.id AND  ses.session_date >= now()
WHERE act.id

Best way to generate a random float in C#

I prefer using the following code to generate a decimal number up to fist decimal point. you can copy paste the 3rd line to add more numbers after decimal point by appending that number in string "combined". You can set the minimum and maximum value by changing the 0 and 9 to your preferred value.

Random r = new Random();
string beforePoint = r.Next(0, 9).ToString();//number before decimal point
string afterPoint = r.Next(0,9).ToString();//1st decimal point
//string secondDP = r.Next(0, 9).ToString();//2nd decimal point
string combined = beforePoint+"."+afterPoint;
decimalNumber= float.Parse(combined);
Console.WriteLine(decimalNumber);

I hope that it helped you.

Sort columns of a dataframe by column name

If you only want one or more columns in the front and don't care about the order of the rest:

require(dplyr)
test %>%
  select(B, everything())

Why is super.super.method(); not allowed in Java?

public class A {

     @Override
     public String toString() {
          return "A";
     }

}


public class B extends A {

     @Override
     public String toString() {
          return "B";
     }

}

public class C extends B {

     @Override
     public String toString() {
          return "C";
     }

}


public class D extends C {

     @Override
     public String toString() {
          String result = "";
          try {
                result = this.getClass().getSuperclass().getSuperclass().getSuperclass().newInstance().toString();
          } catch (InstantiationException ex) {
                Logger.getLogger(D.class.getName()).log(Level.SEVERE, null, ex);
          } catch (IllegalAccessException ex) {
                Logger.getLogger(D.class.getName()).log(Level.SEVERE, null, ex);
          }
          return result;
     }

}

public class Main {

     public static void main(String... args) {
          D d = new D();
          System.out.println(d);

     }
}

run: A BUILD SUCCESSFUL (total time: 0 seconds)

How do I authenticate a WebClient request?

This helped me to call API that was using cookie authentication. I have passed authorization in header like this:

request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));

complete code:

// utility method to read the cookie value:
        public static string ReadCookie(string cookieName)
        {
            var cookies = HttpContext.Current.Request.Cookies;
            var cookie = cookies.Get(cookieName);
            if (cookie != null)
                return cookie.Value;
            return null;
        }

// using statements where you are creating your webclient
using System.Web.Script.Serialization;
using System.Net;
using System.IO;

// WebClient:

var requestUrl = "<API_url>";
var postRequest = new ClassRoom { name = "kushal seth" };

using (var webClient = new WebClient()) {
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      byte[] requestData = Encoding.ASCII.GetBytes(serializer.Serialize(postRequest));
      HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
      request.Method = "POST";
      request.ContentType = "application/json";                        
      request.ContentLength = requestData.Length;
      request.ContentType = "application/json";
      request.Expect = "application/json";
      request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));
      request.GetRequestStream().Write(requestData, 0, requestData.Length);

      using (var response = (HttpWebResponse)request.GetResponse()) {
         var reader = new StreamReader(response.GetResponseStream());
         var objText = reader.ReadToEnd(); // objText will have the value
      }
}


Detecting iOS / Android Operating system

This issue has already been resolved here : What is the best way to detect a mobile device in jQuery?.

On the accepted answer, they basically test if it's an iPhone, an iPod, an Android device or whatever to return true. Just keep the ones you want for instance if( /Android/i.test(navigator.userAgent) ) { // some code.. } will return true only for Android user-agents.

However, user-agents are not really reliable since they can be changed. The best thing is still to develop something universal for all mobile platforms.

when I run mockito test occurs WrongTypeOfReturnValue Exception

According to https://groups.google.com/forum/?fromgroups#!topic/mockito/9WUvkhZUy90, you should rephrase your

when(bar.getFoo()).thenReturn(fooBar)

to

doReturn(fooBar).when(bar).getFoo()

Converting string to byte array in C#

Building off Ali's answer, I would recommend an extension method that allows you to optionally pass in the encoding you want to use:

using System.Text;
public static class StringExtensions
{
    /// <summary>
    /// Creates a byte array from the string, using the 
    /// System.Text.Encoding.Default encoding unless another is specified.
    /// </summary>
    public static byte[] ToByteArray(this string str, Encoding encoding = Encoding.Default)
    {
        return encoding.GetBytes(str);
    }
}

And use it like below:

string foo = "bla bla";

// default encoding
byte[] default = foo.ToByteArray();

// custom encoding
byte[] unicode = foo.ToByteArray(Encoding.Unicode);

Align button to the right

The bootstrap 4.0.0 file you are getting from cdn doesn't have a pull-right (or pull-left) class. The v4 is in alpha, so there are many issues like that.

There are 2 options:

1) Reverse to bootstrap 3.3.7

2) Write your own CSS.

Use jQuery to change a second select list based on the first select list option

I wanted to make a version of this that uses $.getJSON() from a separate JSON file.

Demo: here

JavaScript:

$(document).ready(function () {
    "use strict";

    var selectData, $states;

    function updateSelects() {
        var cities = $.map(selectData[this.value], function (city) {
            return $("<option />").text(city);
        });
        $("#city_names").empty().append(cities);
    }

    $.getJSON("updateSelect.json", function (data) {
        var state;
        selectData = data;
        $states = $("#us_states").on("change", updateSelects);
        for (state in selectData) {
            $("<option />").text(state).appendTo($states);
        }
        $states.change();
    });
});

HTML:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
    <select id="us_states"></select>
    <select id="city_names"></select>
    <script type="text/javascript" src="updateSelect.js"></script>
</body>
</html>

JSON:

{
    "NE": [
        "Smallville",
        "Bigville"
    ],
    "CA": [
        "Sunnyvale",
        "Druryburg",
        "Vickslake"
    ],
    "MI": [
        "Lakeside",
        "Fireside",
        "Chatsville"
    ]
}

Make new column in Panda dataframe by adding values from other columns

As of Pandas version 0.16.0 you can use assign as follows:

df = pd.DataFrame({"A": [1,2,3], "B": [4,6,9]})
df.assign(C = df.A + df.B)

# Out[383]: 
#    A  B   C
# 0  1  4   5
# 1  2  6   8
# 2  3  9  12

You can add multiple columns this way as follows:

df.assign(C = df.A + df.B,
          Diff = df.B - df.A,
          Mult = df.A * df.B)
# Out[379]: 
#    A  B   C  Diff  Mult
# 0  1  4   5     3     4
# 1  2  6   8     4    12
# 2  3  9  12     6    27

How to change legend title in ggplot

None of the above code worked for me.

Here's what I found and it worked.

labs(color = "sale year")

You can also give a space between the title and the display by adding \n at the end.

labs(color = 'sale year\n")

How to find index of an object by key and value in an javascript array

Using jQuery .each()

_x000D_
_x000D_
var peoples = [_x000D_
  { "attr1": "bob", "attr2": "pizza" },_x000D_
  { "attr1": "john", "attr2": "sushi" },_x000D_
  { "attr1": "larry", "attr2": "hummus" }_x000D_
];_x000D_
_x000D_
$.each(peoples, function(index, obj) {_x000D_
   $.each(obj, function(attr, value) {_x000D_
      console.log( attr + ' == ' + value );_x000D_
   });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Using for-loop:

_x000D_
_x000D_
var peoples = [_x000D_
  { "attr1": "bob", "attr2": "pizza" },_x000D_
  { "attr1": "john", "attr2": "sushi" },_x000D_
  { "attr1": "larry", "attr2": "hummus" }_x000D_
];_x000D_
_x000D_
for (var i = 0; i < peoples.length; i++) {_x000D_
  for (var key in peoples[i]) {_x000D_
    console.log(key + ' == ' + peoples[i][key]);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

d3.select("#element") not working when code above the html element

<script>$(function(){var svg = d3.select("#chart").append("svg:svg");});</script>
<div id="chart"></div>

In other words, it's not happening because you can't query against something that doesn't exist yet-- so just do it after the page loads (here via jquery).

Btw, its recommended that you place your JS files before the close of your body tag.

How do you turn a Mongoose document into a plain object?

the fast way if the property is not in the model :

document.set( key,value, { strict: false });

Sum rows in data.frame or matrix

I came here hoping to find a way to get the sum across all columns in a data table and run into issues implementing the above solutions. A way to add a column with the sum across all columns uses the cbind function:

cbind(data, total = rowSums(data))

This method adds a total column to the data and avoids the alignment issue yielded when trying to sum across ALL columns using the above solutions (see the post below for a discussion of this issue).

Adding a new column to matrix error

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

PHP multiline string with PHP

Another option would be to use the if with a colon and an endif instead of the brackets:

<?php if ( has_post_thumbnail() ): ?>
    <div class="gridly-image">
        <a href="<?php the_permalink(); ?>">
        <?php the_post_thumbnail('summary-image', array('class' => 'overlay', 'title'=> the_title('Read Article ',' now',false) )); ?>
        </a>
    </div>
<?php endif; ?>

<div class="date">
    <span class="day"><?php the_time('d'); ?></span>
    <div class="holder">
        <span class="month"><?php the_time('M'); ?></span>
        <span class="year"><?php the_time('Y'); ?></span>
    </div>
</div>

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

How to search a list of tuples in Python

[i for i, v in enumerate(L) if v[0] == 53]

Select top 2 rows in Hive

Here I think it's worth mentioning SORT BY and ORDER BY both clauses and why they different,

SELECT * FROM <table_name> SORT BY <column_name> DESC LIMIT 2

If you are using SORT BY clause it sort data per reducer which means if you have more than one MapReduce task it will result partially ordered data. On the other hand, the ORDER BY clause will result in ordered data for the final Reduce task. To understand more please refer to this link.

SELECT * FROM <table_name> ORDER BY <column_name> DESC LIMIT 2

Note: Finally, Even though the accepted answer contains SORT BY clause, I mostly prefer to use ORDER BY clause for the general use case to avoid any data loss.

react button onClick redirect page

update:

React Router v5 with hooks:

import React from 'react';
import { useHistory } from "react-router-dom";
function LoginLayout() {

  const history = useHistory();

  const routeChange = () =>{ 
    let path = `newPath`; 
    history.push(path);
  }

  return (
      <div className="app flex-row align-items-center">
        <Container>
          ...
          <Row>
            <Col xs="6">                      
              <Button color="primary" className="px-4"
                onClick={routeChange}
                  >
                  Login
                </Button>
            </Col>
            <Col xs="6" className="text-right">
              <Button color="link" className="px-0">Forgot password?</Button>
            </Col>
          </Row>
          ...
        </Container>
      </div>
  );
}
export default LoginLayout;

with React Router v5:

import { useHistory } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row, NavLink  } from 'reactstrap';

class LoginLayout extends Component {

  routeChange=()=> {
    let path = `newPath`;
    let history = useHistory();
    history.push(path);
  }

  render() {
    return (
      <div className="app flex-row align-items-center">
        <Container>
          ...
          <Row>
            <Col xs="6">                      
              <Button color="primary" className="px-4"
                onClick={this.routeChange}
                  >
                  Login
                </Button>
            </Col>
            <Col xs="6" className="text-right">
              <Button color="link" className="px-0">Forgot password?</Button>
            </Col>
          </Row>
          ...
        </Container>
      </div>
    );
  }
}

export default LoginLayout;

with React Router v4:

import { withRouter } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row, NavLink  } from 'reactstrap';

class LoginLayout extends Component {
  constuctor() {
    this.routeChange = this.routeChange.bind(this);
  }

  routeChange() {
    let path = `newPath`;
    this.props.history.push(path);
  }

  render() {
    return (
      <div className="app flex-row align-items-center">
        <Container>
          ...
          <Row>
            <Col xs="6">                      
              <Button color="primary" className="px-4"
                onClick={this.routeChange}
                  >
                  Login
                </Button>
            </Col>
            <Col xs="6" className="text-right">
              <Button color="link" className="px-0">Forgot password?</Button>
            </Col>
          </Row>
          ...
        </Container>
      </div>
    );
  }
}

export default withRouter(LoginLayout);

Using jquery to delete all elements with a given id

As already said, only one element can have a specific ID. Use classes instead. Here is jQuery-free version to remove the nodes:

var form = document.getElementById('your-form-id');
var spans = form.getElementsByTagName('span');

for(var i = spans.length; i--;) {
    var span = spans[i];
    if(span.className.match(/\btheclass\b/)) {
        span.parentNode.removeChild(span);
    }
}

getElementsByTagName is the most cross-browser-compatible method that can be used here. getElementsByClassName would be much better, but is not supported by Internet Explorer <= IE 8.

Working Demo

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

Removing white space around a saved image in matplotlib

The most straightforward method is to use plt.tight_layout transformation which is actually more preferable as it doesn't do unnecessary cropping when using plt.savefig

import matplotlib as plt    
plt.plot([1,2,3], [1,2,3])
plt.tight_layout(pad=0)
plt.savefig('plot.png')

However, this may not be preferable for complex plots that modifies the figure. Refer to Johannes S's answer that uses plt.subplots_adjust if that's the case.

What does "both" mean in <div style="clear:both">

Both means "every item in a set of two things". The two things being "left" and "right"

Defining a `required` field in Bootstrap

To make a field required, use required or required="true"

I think required="required" has been deprecated in version 3 of bootstrap.

Django development IDE

You guys should checkout PyCharm! It is the first decent Django IDE.

What is JSONP, and why was it created?

JSONP is really a simple trick to overcome the XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

So - instead of using XMLHttpRequest we have to use script HTML tags, the ones you usually use to load js files, in order for js to get data from another domain. Sounds weird?

Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:

script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data';

You will end up with a script segment that looks like this after it loads the data:

<script>
{['some string 1', 'some data', 'whatever data']}
</script>

However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better(and it is):

script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data?callback=my_callback';

Notice the my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain js array it'll return this:

my_callback({['some string 1', 'some data', 'whatever data']});

See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data.
That's all there is to know about JSONP: it's a callback and script tags.

NOTE: these are simple examples of JSONP usage, these are not production ready scripts.

Basic JavaScript example (simple Twitter feed using JSONP)

<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>

Basic jQuery example (simple Twitter feed using JSONP)

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>


JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

Convert seconds value to hours minutes seconds?

If you want the units h, min and sec for a duration you can use this:

public static String convertSeconds(int seconds) {
    int h = seconds/ 3600;
    int m = (seconds % 3600) / 60;
    int s = seconds % 60;
    String sh = (h > 0 ? String.valueOf(h) + " " + "h" : "");
    String sm = (m < 10 && m > 0 && h > 0 ? "0" : "") + (m > 0 ? (h > 0 && s == 0 ? String.valueOf(m) : String.valueOf(m) + " " + "min") : "");
    String ss = (s == 0 && (h > 0 || m > 0) ? "" : (s < 10 && (h > 0 || m > 0) ? "0" : "") + String.valueOf(s) + " " + "sec");
    return sh + (h > 0 ? " " : "") + sm + (m > 0 ? " " : "") + ss;
}

int seconds = 3661;
String duration = convertSeconds(seconds);

That's a lot of conditional operators. The method will return those strings:

0    -> 0 sec
5    -> 5 sec
60   -> 1 min
65   -> 1 min 05 sec
3600 -> 1 h
3601 -> 1 h 01 sec
3660 -> 1 h 01
3661 -> 1 h 01 min 01 sec
108000 -> 30 h

Check if option is selected with jQuery, if not select a default

Easy! The default should be the first option. Done! That would lead you to unobtrusive JavaScript, because JavaScript isn't needed :)

Unobtrusive JavaScript

Pythonic way to print list items

OP's question is: does something like following exists, if not then why

print(p) for p in myList # doesn't work, OP's intuition

answer is, it does exist which is:

[p for p in myList] #works perfectly

Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this