Programs & Examples On #Color scheme

A color scheme is a set of colors used by an IDE.

How to get the list of all installed color schemes in Vim?

If you are willing to install a plugin, I recommend https://github.com/vim-scripts/CycleColor.

to cycle through all installed colorschemes. Nice way to easily choose a colorscheme.

How to set default vim colorscheme

You can just use the one-liner

echo colorscheme koehler >> ~/.vimrc

and replace koehler with any other available colorscheme. Imho, all of them are better than default.

How to automatically generate N "distinct" colors?

I have written a package for R called qualpalr that is designed specifically for this purpose. I recommend you look at the vignette to find out how it works, but I will try to summarize the main points.

qualpalr takes a specification of colors in the HSL color space (which was described previously in this thread), projects it to the DIN99d color space (which is perceptually uniform) and find the n that maximize the minimum distance between any oif them.

# Create a palette of 4 colors of hues from 0 to 360, saturations between
# 0.1 and 0.5, and lightness from 0.6 to 0.85
pal <- qualpal(n = 4, list(h = c(0, 360), s = c(0.1, 0.5), l = c(0.6, 0.85)))

# Look at the colors in hex format
pal$hex
#> [1] "#6F75CE" "#CC6B76" "#CAC16A" "#76D0D0"

# Create a palette using one of the predefined color subspaces
pal2 <- qualpal(n = 4, colorspace = "pretty")

# Distance matrix of the DIN99d color differences
pal2$de_DIN99d
#>        #69A3CC #6ECC6E #CA6BC4
#> 6ECC6E      22                
#> CA6BC4      21      30        
#> CD976B      24      21      21

plot(pal2)

enter image description here

Qt Creator color scheme

My Dark Color scheme for QtCreator is at:

https://github.com/borzh/qt-creator-css/blob/master/qt-creator.css

To use with Vim (dark) scheme.

Hope it is useful for someone.

How do I install a color theme for IntelliJ IDEA 7.0.x

Step 1: Do File -> Import Settings... and select the settings jar file

Step 2: Go to Settings -> Editor -> Colors and Fonts to choose the theme you just installed.

How to Sort Multi-dimensional Array by Value?

Use array_multisort(), array_map()

array_multisort(array_map(function($element) {
      return $element['order'];
  }, $array), SORT_ASC, $array);

print_r($array);

DEMO

How to get the category title in a post in Wordpress?

Use get_the_category() like this:

<?php
foreach((get_the_category()) as $category) { 
    echo $category->cat_name . ' '; 
} 
?>

It returns a list because a post can have more than one category.

The documentation also explains how to do this from outside the loop.

How to remove files and directories quickly via terminal (bash shell)

rm -rf some_dir

-r "recursive" -f "force" (suppress confirmation messages)

Be careful!

How do I mock a static method that returns void with PowerMock?

To mock a static method that return void for e.g. Fileutils.forceMKdir(File file),

Sample code:

File file =PowerMockito.mock(File.class);
PowerMockito.doNothing().when(FileUtils.class,"forceMkdir",file);

How to schedule a periodic task in Java?

Try this way ->

Firstly create a class TimeTask that run your task, it looks like:

public class CustomTask extends TimerTask  {

   public CustomTask(){

     //Constructor

   }

   public void run() {
       try {

         // Your task process

       } catch (Exception ex) {
           System.out.println("error running thread " + ex.getMessage());
       }
    }
}

then in main class you instantiate the task and run it periodically started by a specified date:

 public void runTask() {

        Calendar calendar = Calendar.getInstance();
        calendar.set(
           Calendar.DAY_OF_WEEK,
           Calendar.MONDAY
        );
        calendar.set(Calendar.HOUR_OF_DAY, 15);
        calendar.set(Calendar.MINUTE, 40);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);



        Timer time = new Timer(); // Instantiate Timer Object

        // Start running the task on Monday at 15:40:00, period is set to 8 hours
        // if you want to run the task immediately, set the 2nd parameter to 0
        time.schedule(new CustomTask(), calendar.getTime(), TimeUnit.HOURS.toMillis(8));
}

An existing connection was forcibly closed by the remote host

If Running In A .Net 4.5.2 Service

For me the issue was compounded because the call was running in a .Net 4.5.2 service. I followed @willmaz suggestion but got a new error.

In running the service with logging turned on, I viewed the handshaking with the target site would initiate ok (and send the bearer token) but on the following step to process the Post call, it would seem to drop the auth token and the site would reply with Unauthorized.

Solution

It turned out that the service pool credentials did not have rights to change TLS (?) and when I put in my local admin account into the pool, it all worked.

What is secret key for JWT based authentication and how to generate it?

What is the secret key does, you may have already known till now. It is basically HMAC SH256 (Secure Hash). The Secret is a symmetrical key.

Using the same key you can generate, & reverify, edit, etc.

For more secure, you can go with private, public key (asymmetric way). Private key to create token, public key to verify at client level.

Coming to secret key what to give You can give anything, "sudsif", "sdfn2173", any length

you can use online generator, or manually write

I prefer using openssl

C:\Users\xyz\Desktop>openssl rand -base64 12
65JymYzDDqqLW8Eg

generate, then encode with base 64

C:\Users\xyz\Desktop>openssl rand -out openssl-secret.txt -hex 20

The generated value is saved inside the file named "openssl-secret.txt"

generate, & store into a file.

One thing is giving 12 will generate, 12 characters only, but since it is base 64 encoded, it will be (4/3*n) ceiling value.

I recommend reading this article

https://auth0.com/blog/brute-forcing-hs256-is-possible-the-importance-of-using-strong-keys-to-sign-jwts/

show all tags in git log

git log --no-walk --tags --pretty="%h %d %s" --decorate=full

This version will print the commit message as well:

 $ git log --no-walk --tags --pretty="%h %d %s" --decorate=full
3713f3f  (tag: refs/tags/1.0.0, tag: refs/tags/0.6.0, refs/remotes/origin/master, refs/heads/master) SP-144/ISP-177: Updating the package.json with 0.6.0 version and the README.md.
00a3762  (tag: refs/tags/0.5.0) ISP-144/ISP-205: Update logger to save files with optional port number if defined/passed: Version 0.5.0
d8db998  (tag: refs/tags/0.4.2) ISP-141/ISP-184/ISP-187: Fixing the bug when loading the app with Gulp and Grunt for 0.4.2
3652484  (tag: refs/tags/0.4.1) ISP-141/ISP-184: Missing the package.json and README.md updates with the 0.4.1 version
c55eee7  (tag: refs/tags/0.4.0) ISP-141/ISP-184/ISP-187: Updating the README.md file with the latest 1.3.0 version.
6963d0b  (tag: refs/tags/0.3.0) ISP-141/ISP-184: Add support for custom serializers: README update
4afdbbe  (tag: refs/tags/0.2.0) ISP-141/ISP-143/ISP-144: Fixing a bug with the creation of the logs
e1513f1  (tag: refs/tags/0.1.0) ISP-141/ISP-143: Betterr refactoring of the Loggers, no dependencies, self-configuration for missing settings.

Delete specific values from column with where condition?

You don't want to delete if you're wanting to leave the row itself intact. You want to update the row, and change the column value.

The general form for this would be an UPDATE statement:

UPDATE <table name>
SET
    ColumnA = <NULL, or '', or whatever else is suitable for the new value for the column>
WHERE
    ColumnA = <bad value> /* or any other search conditions */

An object reference is required to access a non-static member

I'm guessing you get the error on accessing audioSounds and minTime, right?

The problem is you can't access instance members from static methods. What this means is that, a static method is a method that exists only once and can be used by all other objects (if its access modifier permits it).

Instance members, on the other hand, are created for every instance of the object. So if you create ten instances, how would the runtime know out of all these instances, which audioSounds list it should access?

Like others said, make your audioSounds and minTime static, or you could make your method an instance method, if your design permits it.

Open CSV file via VBA (performance)

I have the same issue, I'm not able to open a CSV file in Excel. I've found a solution that worked for me in this question Opening a file in excel via Workbooks.OpenText

That question helped me to figure out a code that works for me. The code looks more or less like this:

Private Sub OpenCSVFile(filename as String)
    Dim datasourceFilename As String
    Dim currentPath As String

    datasourceFilename = "\" & filename & ".csv"
    currentPath = ActiveWorkbook.Path

    Workbooks.OpenText Filename:=currentPath & datasourceFilename, _
                       Origin:=xlWindows, _
                       StartRow:=1, _
                       DataType:=xlDelimited, _
                       TextQualifier:=xlDoubleQuote, _
                       ConsecutiveDelimiter:=False, _
                       Tab:=False, _
                       Semicolon:=False, _
                       Comma:=True, _
                       Space:=False, _
                       Other:=False, _
                       FieldInfo:=Array(Array(1, 1), Array(2, 1)), _
                       DecimalSeparator:=".", _
                       ThousandsSeparator:=",", _
                       TrailingMinusNumbers:=True
End Sub

At least, it helped me to know about lots of parameters I can use with Workbooks.OpenText method.

Spring Boot War deployed to Tomcat

Solution for people using Gradle

Add plugin to build.gradle

apply plugin: 'war'

Add provided dependency to tomcat

dependencies {
    // other dependencies
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
}

Compare 2 arrays which returns difference

In this way you don't need to worry about if the first array is smaller than the second one.

var arr1 = [1, 2, 3, 4, 5, 6,10],
    arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function array_diff(array1, array2){
    var difference = $.grep(array1, function(el) { return $.inArray(el,array2) < 0});
    return difference.concat($.grep(array2, function(el) { return $.inArray(el,array1) < 0}));;
}

console.log(array_diff(arr1, arr2));

Jquery UI datepicker. Disable array of Dates

beforeShowDate didn't work for me, so I went ahead and developed my own solution:

$('#embeded_calendar').datepicker({
               minDate: date,
                localToday:datePlusOne,
               changeDate: true,
               changeMonth: true,
               changeYear: true,
               yearRange: "-120:+1",
               onSelect: function(selectedDateFormatted){

                     var selectedDate = $("#embeded_calendar").datepicker('getDate');

                    deactivateDates(selectedDate);
                   }

           });


              var excludedDates = [ "10-20-2017","10-21-2016", "11-21-2016"];

              deactivateDates(new Date());

            function deactivateDates(selectedDate){
                setTimeout(function(){ 
                      var thisMonthExcludedDates = thisMonthDates(selectedDate);
                      thisMonthExcludedDates = getDaysfromDate(thisMonthExcludedDates);
                       var excludedTDs = page.find('td[data-handler="selectDay"]').filter(function(){
                           return $.inArray( $(this).text(), thisMonthExcludedDates) >= 0
                       });

                       excludedTDs.unbind('click').addClass('ui-datepicker-unselectable');
                   }, 10);
            }

            function thisMonthDates(date){
              return $.grep( excludedDates, function( n){
                var dateParts = n.split("-");
                return dateParts[0] == date.getMonth() + 1  && dateParts[2] == date.getYear() + 1900;
            });
            }

            function getDaysfromDate(datesArray){
                  return  $.map( datesArray, function( n){
                    return n.split("-")[1]; 
                });
             }

How to know the version of pip itself

You can do this:

pip -V

or:

pip --version

R memory management / cannot allocate vector of size n Mb

I encountered a similar problem, and I used 2 flash drives as 'ReadyBoost'. The two drives gave additional 8GB boost of memory (for cache) and it solved the problem and also increased the speed of the system as a whole. To use Readyboost, right click on the drive, go to properties and select 'ReadyBoost' and select 'use this device' radio button and click apply or ok to configure.

How to dynamically change a web page's title?

One way that comes to mind that may help with SEO and still have your tab pages as they are would be to use named anchors that correspond to each tab, as in:

http://www.example.com/mypage#tab1, http://www.example.com/mypage#tab2, etc.

You would need to have server side processing to parse the url and set the initial page title when the browser renders the page. I would also go ahead and make that tab the "active" one. Once the page is loaded and an actual user is switching tabs you would use javascript to change document.title as other users have stated.

Cannot open local file - Chrome: Not allowed to load local resource

If you could do this, it will represent a big security problem, as you can access your filesystem, and potentially act on the data available there... Luckily it's not possible to do what you're trying to do.

If you need local resources to be accessed, you can try to start a web server on your machine, and in this case your method will work. Other workarounds are possible, such as acting on Chrome settings, but I always prefer the clean way, installing a local web server, maybe on a different port (no, it's not so difficult!).

See also:

What is the difference between “int” and “uint” / “long” and “ulong”?

u means unsigned, so ulong is a large number without sign. You can store a bigger value in ulong than long, but no negative numbers allowed.

A long value is stored in 64-bit,with its first digit to show if it's a positive/negative number. while ulong is also 64-bit, with all 64 bit to store the number. so the maximum of ulong is 2(64)-1, while long is 2(63)-1.

set gvim font in .vimrc file

When I try:

set guifont=Consolas:h16

I get: Warning: Font "Consolas" reports bad fixed pitch metrics

and the following is work, and don't show the waring.

autocmd vimenter * GuiFont! Consolas:h16

by the way, if you want to use the mouse wheel to control the font-size, then you can add:

function! AdjustFontSize(amount)
    let s:font_size = s:font_size + a:amount
    :execute "GuiFont! Consolas:h" . s:font_size
endfunction

noremap <C-ScrollWheelUp> :call AdjustFontSize(1)<CR>
noremap <C-ScrollWheelDown> :call AdjustFontSize(-1)<CR>

and if you want to pick the font, you can set

set guifont=*

will bring up a font requester, where you can pick the font you want.

enter image description here

CSS center content inside div

do like this :

child{
    position:absolute;
    margin: auto;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

What is a stack pointer used for in microprocessors?

The stack pointer holds the address to the top of the stack. A stack allows functions to pass arguments stored on the stack to each other, and to create scoped variables. Scope in this context means that the variable is popped of the stack when the stack frame is gone, and/or when the function returns. Without a stack, you would need to use explicit memory addresses for everything. That would make it impossible (or at least severely difficult) to design high-level programming languages for the architecture. Also, each CPU mode usually have its own banked stack pointer. So when exceptions occur (interrupts for example), the exception handler routine can use its own stack without corrupting the user process.

How do I attach events to dynamic HTML elements with jQuery?

If your on jQuery 1.3+ then use .live()

Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.

HTML to PDF with Node.js

You can also use pdf node creator package

Package URL - https://www.npmjs.com/package/pdf-creator-node

When to use: Java 8+ interface default method, vs. abstract method

Default methods in Java interface enables interface evolution.

Given an existing interface, if you wish to add a method to it without breaking the binary compatibility with older versions of the interface, you have two options at hands: add a default or a static method. Indeed, any abstract method added to the interface would have to be impleted by the classes or interfaces implementing this interface.

A static method is unique to a class. A default method is unique to an instance of the class.

If you add a default method to an existing interface, classes and interfaces which implement this interface do not need to implement it. They can

  • implement the default method, and it overrides the implementation in implemented interface.
  • re-declare the method (without implementation) which makes it abstract.
  • do nothing (then the default method from implemented interface is simply inherited).

More on the topic here.

Push JSON Objects to array in localStorage

Putting a whole array into one localStorage entry is very inefficient: the whole thing needs to be re-encoded every time you add something to the array or change one entry.

An alternative is to use http://rhaboo.org which stores any JS object, however deeply nested, using a separate localStorage entry for each terminal value. Arrays are restored much more faithfully, including non-numeric properties and various types of sparseness, object prototypes/constructors are restored in standard cases and the API is ludicrously simple:

var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);

store.write('somethingfancy', {
  one: ['man', 'went'],
  2: 'mow',
  went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
});  
store.somethingfancy.went[1].mow.write(1, 'lawn');

BTW, I wrote it.

Check that Field Exists with MongoDB

db.<COLLECTION NAME>.find({ "<FIELD NAME>": { $exists: true, $ne: null } })

Silent installation of a MSI package

You should be able to use the /quiet or /qn options with msiexec to perform a silent install.

MSI packages export public properties, which you can set with the PROPERTY=value syntax on the end of the msiexec parameters.

For example, this command installs a package with no UI and no reboot, with a log and two properties:

msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2

You can read the options for msiexec by just running it with no options from Start -> Run.

How to select data where a field has a min value in MySQL?

This also works:

SELECT
  pieces.*
FROM
  pieces inner join (select min(price) as minprice from pieces) mn
  on pieces.price = mn.minprice

(since this version doesn't have a where condition with a subquery, it could be used if you need to UPDATE the table, but if you just need to SELECT i would reccommend to use John Woo solution)

Segmentation Fault - C

Even better

#include <stdio.h>
int
main(void)
{
  char *line = NULL;
  size_t count;
  char *dup_line;

  getline(&line,&count, stdin);
  dup_line=strdup(line);

  puts(dup_line);

  free(dup_line);
  free(line);

  return 0;
}

What encoding/code page is cmd.exe using?

In Java I used encoding "IBM850" to write the file. That solved the problem.

How to remove the hash from window.location (URL) with JavaScript without page refresh?

How about the following?

window.location.hash=' '

Please note that am setting the hash to a single space and not an empty string.


Setting the hash to an invalid anchor does not cause a refresh either. Such as,

window.location.hash='invalidtag'

But, I find above solution to be misleading. This seems to indicate that there is an anchor on the given position with the given name although there isn't one. At the same time, using an empty string causes page to move to the top which can be unacceptable at times. Using a space also ensures that whenever the URL is copied and bookmarked and visited again, the page will usually be at the top and the space will be ignored.

And, hey, this is my first answer on StackOverflow. Hope someone finds it useful and it matches the community standards.

git stash -> merge stashed change with current changes

What I want is a way to merge my stashed changes with the current changes

Here is another option to do it:

git stash show -p|git apply
git stash drop

git stash show -p will show the patch of last saved stash. git apply will apply it. After the merge is done, merged stash can be dropped with git stash drop.

What does [object Object] mean? (JavaScript)

Alerts aren't the best for displaying objects. Try console.log? If you still see Object Object in the console, use JSON.parse like this > var obj = JSON.parse(yourObject); console.log(obj)

How to serialize Joda DateTime with Jackson JSON processor?

The easy solution

I have encountered similar problem and my solution is much clear than above.

I simply used the pattern in @JsonFormat annotation

Basically my class has a DateTime field, so I put an annotation around the getter:

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public DateTime getDate() {
    return date;
}

I serialize the class with ObjectMapper

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    ObjectWriter ow = mapper.writer();
    try {
        String logStr = ow.writeValueAsString(log);
        outLogger.info(logStr);
    } catch (IOException e) {
        logger.warn("JSON mapping exception", e);
    }

We use Jackson 2.5.4

Creating folders inside a GitHub repository without using Git

When creating a file, use slashes to specify the directory. For example:

Name the file:

repositoryname/newfoldername/filename

GitHub will automatically create a folder with the name newfoldername.

How can I install Visual Studio Code extensions offline?

If you have a specific (legacy) version of VSCode on your offline instance, pulling the latest extensions might not properly integrate.

To make sure that VSCode and the extensions work together, they must all be installed together on the online machine. This resolves any dependencies (with specific versions), and ensures the exact configuration of the offline instance.

Quick steps:

Install the VSCode version, turn off updating, and install the extensions. Copy the extensions from the installed location and place them on the target machine.

Detailed steps:

Install the exact version of VSCode on online machine. Then turn off updates by going to File -> Preferences -> Settings. In the Settings window, under User Settings -> Application, go to Update section, and change the parameter for Channel to none. This prevents VSCode from reaching out to the internet and auto-updating your versions to the latest.

Then go to the VSCode extensions section and install all of your desired extensions. Copy the installed extensions from their install location (with windows its C:\Users\<username>\.vscode\extensions) to the same location on the target machine.

Works perfectly.

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

Converting a Date object to a calendar object

Here's your method:

public static Calendar toCalendar(Date date){ 
  Calendar cal = Calendar.getInstance();
  cal.setTime(date);
  return cal;
}

Everything else you are doing is both wrong and unnecessary.

BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar or toCalendar (as shown).


OK, let's milk your code, shall we?

DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString()); 

DateFormat is used to convert Strings to Dates (parse()) or Dates to Strings (format()). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?

How to Convert datetime value to yyyymmddhhmmss in SQL server?

Another option I have googled, but contains several replace ...

SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '') 

What is the meaning of "int(a[::-1])" in Python?

Assuming a is a string. The Slice notation in python has the syntax -

list[<start>:<stop>:<step>]

So, when you do a[::-1], it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.

Example -

>>> a = '1234'
>>> a[::-1]
'4321'

Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.

Triangle Draw Method

You can use Processing library: https://processing.org/reference/PGraphics.html

There is a method called triangle():

g.triangle(x1,y1,x2,y2,x3,y3)

PKIX path building failed in Java application

On Windows you can try these steps:

  1. Download a root CA certificate from the website.
  2. Find a file jssecacerts in the directory /lib/security with JRE (you can use a comand System.out.println(System.getProperty("java.home"); to find the folder with the current JRE). Make a backup of the file.
  3. Download a program portecle.
  4. Open the jssecacerts file in portecle.
  5. Enter the password: changeit.
  6. Import the downloaded certificate with porticle (Tools > Import Trusted Certificate).
  7. Click Save.
  8. Replace the original file jssecacerts.

How to call servlet through a JSP page

there isn't method to call Servlet. You should make mapping in web.xml and then trigger this mapping.

Example: web.xml:

  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>test.HelloServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

This mapping means that every call to http://yoursite/yourwebapp/hello trigger this servlet For example this jsp:

<jsp:forward page="/hello"/> 

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

You should use Java's built in serialization mechanism. To use it, you need to do the following:

  1. Declare the Club class as implementing Serializable:

    public class Club implements Serializable {
        ...
    }
    

    This tells the JVM that the class can be serialized to a stream. You don't have to implement any method, since this is a marker interface.

  2. To write your list to a file do the following:

    FileOutputStream fos = new FileOutputStream("t.tmp");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(clubs);
    oos.close();
    
  3. To read the list from a file, do the following:

    FileInputStream fis = new FileInputStream("t.tmp");
    ObjectInputStream ois = new ObjectInputStream(fis);
    List<Club> clubs = (List<Club>) ois.readObject();
    ois.close();
    

How to exit from ForEach-Object in PowerShell

Since ForEach-Object is a cmdlet, break and continue will behave differently here than with the foreach keyword. Both will stop the loop but will also terminate the entire script:

break:

0..3 | foreach {
    if ($_ -eq 2) { break }
    $_
}
echo "Never printed"

# OUTPUT:
# 0
# 1

continue:

0..3 | foreach {
    if ($_ -eq 2) { continue }
    $_
}
echo "Never printed"

# OUTPUT:
# 0
# 1

So far, I have not found a "good" way to break a foreach script block without breaking the script, except "abusing" exceptions:

throw:

try {
    0..3 | foreach {
        if ($_ -eq 2) { throw }
        $_
    }
} catch { }
echo "End"

# OUTPUT:
# 0
# 1
# End

The alternative (which is not always possible) would be to use the foreach keyword:

foreach:

foreach ($_ in (0..3)) {
    if ($_ -eq 2) { break }
    $_
}
echo "End"

# OUTPUT:
# 0
# 1
# End

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

I think this represents a good answer.

APK Signature Scheme v2 verification

  1. Locate the APK Signing Block and verify that:
    1. Two size fields of APK Signing Block contain the same value.
    2. ZIP Central Directory is immediately followed by ZIP End of Central Directory record.
    3. ZIP End of Central Directory is not followed by more data.
  2. Locate the first APK Signature Scheme v2 Block inside the APK Signing Block. If the v2 Block if present, proceed to step 3. Otherwise, fall back to verifying the APK using v1 scheme.
  3. For each signer in the APK Signature Scheme v2 Block:
    1. Choose the strongest supported signature algorithm ID from signatures. The strength ordering is up to each implementation/platform version.
    2. Verify the corresponding signature from signatures against signed data using public key. (It is now safe to parse signed data.)
    3. Verify that the ordered list of signature algorithm IDs in digests and signatures is identical. (This is to prevent signature stripping/addition.)
    4. Compute the digest of APK contents using the same digest algorithm as the digest algorithm used by the signature algorithm.
    5. Verify that the computed digest is identical to the corresponding digest from digests.
    6. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical to public key.
  4. Verification succeeds if at least one signer was found and step 3 succeeded for each found signer.

Note: APK must not be verified using the v1 scheme if a failure occurs in step 3 or 4.

JAR-signed APK verification (v1 scheme)

The JAR-signed APK is a standard signed JAR, which must contain exactly the entries listed in META-INF/MANIFEST.MF and where all entries must be signed by the same set of signers. Its integrity is verified as follows:

  1. Each signer is represented by a META-INF/<signer>.SF and META-INF/<signer>.(RSA|DSA|EC) JAR entry.
  2. <signer>.(RSA|DSA|EC) is a PKCS #7 CMS ContentInfo with SignedData structure whose signature is verified over the <signer>.SF file.
  3. <signer>.SF file contains a whole-file digest of the META-INF/MANIFEST.MF and digests of each section of META-INF/MANIFEST.MF. The whole-file digest of the MANIFEST.MF is verified. If that fails, the digest of each MANIFEST.MF section is verified instead.
  4. META-INF/MANIFEST.MF contains, for each integrity-protected JAR entry, a correspondingly named section containing the digest of the entry’s uncompressed contents. All these digests are verified.
  5. APK verification fails if the APK contains JAR entries which are not listed in the MANIFEST.MF and are not part of JAR signature. The protection chain is thus <signer>.(RSA|DSA|EC) ? <signer>.SF ? MANIFEST.MF ? contents of each integrity-protected JAR entry.

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

Function passed as template argument

Came here with the additional requirement, that also parameter/return types should vary. Following Ben Supnik this would be for some type T

typedef T(*binary_T_op)(T, T);

instead of

typedef int(*binary_int_op)(int, int);

The solution here is to put the function type definition and the function template into a surrounding struct template.

template <typename T> struct BinOp
{
    typedef T(*binary_T_op )(T, T); // signature for all valid template params
    template<binary_T_op op>
    T do_op(T a, T b)
    {
       return op(a,b);
    }
};


double mulDouble(double a, double b)
{
    return a * b;
}


BinOp<double> doubleBinOp;

double res = doubleBinOp.do_op<&mulDouble>(4, 5);

Alternatively BinOp could be a class with static method template do_op(...), then called as

double res = BinOp<double>::do_op<&mulDouble>(4, 5);

Marker in leaflet, click event

Here's a jsfiddle with a function call: https://jsfiddle.net/8282emwn/

var marker = new L.Marker([46.947, 7.4448]).on('click', markerOnClick).addTo(map);

function markerOnClick(e)
{
  alert("hi. you clicked the marker at " + e.latlng);
}

How to zoom div content using jquery?

Used zoom-master/jquery.zoom.js. The zoom for the image worked perfectly. Here is a link to the page. http://www.jacklmoore.com/zoom/

 <script>
    $(document).ready(function(){
        $('#ex1').zoom();

    });
</script>

Android appcompat v7:23

Original answer:

I too tried to change the support library to "23". When I changed the targetSdkVersion to 23, Android Studio reported the following error:

This support library should not use a lower version (22) than the targetSdkVersion (23)

I simply changed:

compile 'com.android.support:appcompat-v7:23.0.0'

to

compile 'com.android.support:appcompat-v7:+'

Although this fixed my issue, you should not use dynamic versions. After a few hours the new support repository was available and it is currently 23.0.1.


Pro tip:

You can use double quotes and create a ${supportLibVersion} variable for simplicity. Example:

ext {
    supportLibVersion = '23.1.1'
}

compile "com.android.support:appcompat-v7:${supportLibVersion}"
compile "com.android.support:design:${supportLibVersion}"
compile "com.android.support:palette-v7:${supportLibVersion}"
compile "com.android.support:customtabs:${supportLibVersion}"
compile "com.android.support:gridlayout-v7:${supportLibVersion}"

source: https://twitter.com/manidesto/status/669195097947377664

What causes java.lang.IncompatibleClassChangeError?

While these answers are all correct, resolving the problem is often more difficult. It's generally the result of two mildly different versions of the same dependency on the classpath, and is almost always caused by either a different superclass than was originally compiled against being on the classpath or some import of the transitive closure being different, but generally at class instantiation and constructor invocation. (After successful class loading and ctor invocation, you'll get NoSuchMethodException or whatnot.)

If the behavior appears random, it's likely the result of a multithreaded program classloading different transitive dependencies based on what code got hit first.

To resolve these, try launching the VM with -verbose as an argument, then look at the classes that were being loaded when the exception occurs. You should see some surprising information. For instance, having multiple copies of the same dependency and versions you never expected or would have accepted if you knew they were being included.

Resolving duplicate jars with Maven is best done with a combination of the maven-dependency-plugin and maven-enforcer-plugin under Maven (or SBT's Dependency Graph Plugin, then adding those jars to a section of your top-level POM or as imported dependency elements in SBT (to remove those dependencies).

Good luck!

Convert to date format dd/mm/yyyy

There is also the DateTime object if you want to go that way: http://www.php.net/manual/en/datetime.construct.php

Cannot open Windows.h in Microsoft Visual Studio

I got this error fatal error lnk1104: cannot open file 'kernel32.lib'. this error is getting because there is no path in VC++ directories. To solve this problem

Open Visual Studio 2008

  1. go to Tools-options-Projects and Solutions-VC++ directories-*
  2. then at right corner select Library files
  3. here you need to add path of kernel132.lib

In my case It is C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib

Jquery - animate height toggle

Very late but I apologize. Sorry if this is "inefficient" but if you found all the above not working, do try this. Works for above 1.10 also

<script>
  $(document).ready(function() {
    var position='expanded';

    $("#topbar").click(function() {
      if (position=='expanded') {
        $(this).animate({height:'200px'});
        position='collapsed';
      } else {
        $(this).animate({height:'400px'});
        position='expanded';
      }
    });
   });
</script>

Django set field value after a form is initialized

Since you're not passing in POST data, I'll assume that what you are trying to do is set an initial value that will be displayed in the form. The way you do this is with the initial keyword.

form = CustomForm(initial={'Email': GetEmailString()})

See the Django Form docs for more explanation.

If you are trying to change a value after the form was submitted, you can use something like:

if form.is_valid():
    form.cleaned_data['Email'] = GetEmailString()

Check the referenced docs above for more on using cleaned_data

jQuery - Detect value change on hidden input field

It is possible to use Object.defineProperty() in order to redefine the 'value' property of the input element and do anything during its changing.

Object.defineProperty() allows us to define a getter and setter for a property, thus controlling it.

replaceWithWrapper($("#hid1")[0], "value", function(obj, property, value) { 
  console.log("new value:", value)
});

function replaceWithWrapper(obj, property, callback) {
  Object.defineProperty(obj, property, new function() {
    var _value = obj[property];
    return {
      set: function(value) {
        _value = value;
        callback(obj, property, value)
      },
      get: function() {
        return _value;
      }
    }
  });
}

$("#hid1").val(4);

https://jsfiddle.net/bvvmhvfk/

Import file size limit in PHPMyAdmin

Find the file called: php.ini on your server and follow below steps

With apache2 and php5 installed you need to make three changes in the php.ini file. First open the file for editing, e.g.:

sudo gedit /etc/php5/apache2/php.ini

OR

sudo gedit /etc/php/7.0/apache2/php.ini

Next, search for the post_max_size entry, and enter a larger number than the size of your database (15M in this case), for example:

post_max_size = 25M

Next edit the entry for memory_limit and give it a larger value than the one given to post_max_size.

Then ensure the value of upload_max_filesize is smaller than post_max_size.

The order from biggest to smallest should be:

    memory_limit
    post_max_size
    upload_max_filesize

After saving the file, restart apache (e.g. sudo /etc/init.d/apache2 restart) and you are set.

Don't forget to Restart Apache Services for changes to be applied.

For further details, click here.

How to switch to the new browser window, which opens after click on the button?

 main you can do :

 String mainTab = page.goToNewTab ();
 //do what you want
 page.backToMainPage(mainTab);  

 What you need to have in order to use the main   

        private static Set<String> windows;

            //get all open windows 
            //return current window
            public String initWindows() {
                windows = new HashSet<String>();
                driver.getWindowHandles().stream().forEach(n ->   windows.add(n));
                return driver.getWindowHandle();
            }

            public String getNewWindow() {
                List<String> newWindow = driver.getWindowHandles().stream().filter(n -> windows.contains(n) == false)
                        .collect(Collectors.toList());
                logger.info(newWindow.get(0));
                return newWindow.get(0);
            }


            public String goToNewTab() {
                String startWindow = driver.initWindows();
                driver.findElement(By.cssSelector("XX")).click();
                String newWindow = driver.getNewWindow();
                driver.switchTo().window(newWindow);
                return startWindow;
            }

            public void backToMainPage(String startWindow) {
                driver.close();
                driver.switchTo().window(startWindow);
            }

Microsoft Excel mangles Diacritics in .csv files?

The answer for all combinations of Excel versions (2003 + 2007) and file types

Most other answers here concern their Excel version only and will not necessarily help you, because their answer just might not be true for your version of Excel.

For example, adding the BOM character introduces problems with automatic column separator recognition, but not with every Excel version.

There are 3 variables that determines if it works in most Excel versions:

  • Encoding
  • BOM character presence
  • Cell separator

Somebody stoic at SAP tried every combination and reported the outcome. End result? Use UTF16le with BOM and tab character as separator to have it work in most Excel versions.

You don't believe me? I wouldn't either, but read here and weep: http://wiki.sdn.sap.com/wiki/display/ABAP/CSV+tests+of+encoding+and+column+separator

Testing if a checkbox is checked with jQuery

// use ternary operators
$("#ans").is(':checked') ? 1 : 0;

Create or update mapping in elasticsearch

In later Elasticsearch versions (7.x), types were removed. Updating a mapping can becomes:

curl -XPUT "http://localhost:9200/test/_mapping" -H 'Content-Type: application/json' -d'{
  "properties": {
    "new_geo_field": {
      "type": "geo_point"
    }
  }
}'

As others have pointed out, if the field exists, you typically have to reindex. There are exceptions, such as adding a new sub-field or changing analysis settings.

You can't "create a mapping", as the mapping is created with the index. Typically, you'd define the mapping when creating the index (or via index templates):

curl -XPUT "http://localhost:9200/test" -H 'Content-Type: application/json' -d'{
  "mappings": {
    "properties": {
      "foo_field": {
        "type": "text"
      }
    }
  }
}'

That's because, in production at least, you'd want to avoid letting Elasticsearch "guess" new fields. Which is what generated this question: geo data was read as an array of long values.

Authentication plugin 'caching_sha2_password' is not supported

I ran into the same problem as well. My problem was, that I accidentally installed the wrong connector version. Delete your currently installed version from your file system (my path looks like this: C:\Program Files\Python36\Lib\site-packages) and then execute "pip install mysql-connector-python". This should solve your problem

Android SDK installation doesn't find JDK

I have the jdk installed on my D: drive. None of the other answers worked for me. I got it to install by creating a symbolic link from the C: drive to the installed location:

    c:
    cd "Program Files"
    mklink /d Java "d:\Program Files\Java"  

Note that the jdk (and jre) install directories are subdirectories of "Java" so upgrading is not a problem even though the name changes with the release.

Calling a Sub and returning a value

Private Sub Main()
    Dim value = getValue()
    'do something with value
End Sub

Private Function getValue() As Integer
    Return 3
End Function

TypeError: 'float' object is not subscriptable

PriceList[0] is a float. PriceList[0][1] is trying to access the first element of a float. Instead, do

PriceList[0] = PriceList[1] = ...code omitted... = PriceList[6] = PizzaChange

or

PriceList[0:7] = [PizzaChange]*7

Remove empty lines in a text file via grep

If you want to know what the total lines of code is in your Xcode project and you are not interested in listing the count for each swift file then this will give you the answer. It removes lines with no code at all and removes lines that are prefixed with the comment //

Run it at the root level of your Xcode project.

find . \( -iname \*.swift \) -exec grep -v '^[[:space:]]*$' \+ | grep -v -e '//' | wc -l

If you have comment blocks in your code beginning with /* and ending with */ such as:

/*
 This is an comment block 
*/

then these will get included in the count. (Too hard).

JSON.net: how to deserialize without using the default constructor?

The default behaviour of Newtonsoft.Json is going to find the public constructors. If your default constructor is only used in containing class or the same assembly, you can reduce the access level to protected or internal so that Newtonsoft.Json will pick your desired public constructor.

Admittedly, this solution is rather very limited to specific cases.

internal Result() { }

public Result(int? code, string format, Dictionary<string, string> details = null)
{
    Code = code ?? ERROR_CODE;
    Format = format;

    if (details == null)
        Details = new Dictionary<string, string>();
    else
        Details = details;
}

How does one capture a Mac's command key via JavaScript?

Basing on Ilya's data, I wrote a Vanilla JS library for supporting modifier keys on Mac: https://github.com/MichaelZelensky/jsLibraries/blob/master/macKeys.js

Just use it like this, e.g.:

document.onclick = function (event) {
  if (event.shiftKey || macKeys.shiftKey) {
    //do something interesting
  }
}

Tested on Chrome, Safari, Firefox, Opera on Mac. Please check if it works for you.

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Preventing SQL injection in Node.js

The library has a section in the readme about escaping. It's Javascript-native, so I do not suggest switching to node-mysql-native. The documentation states these guidelines for escaping:

Edit: node-mysql-native is also a pure-Javascript solution.

  • Numbers are left untouched
  • Booleans are converted to true / false strings
  • Date objects are converted to YYYY-mm-dd HH:ii:ss strings
  • Buffers are converted to hex strings, e.g. X'0fa5'
  • Strings are safely escaped
  • Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
  • Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')
  • Objects are turned into key = 'val' pairs. Nested objects are cast to strings.
  • undefined / null are converted to NULL
  • NaN / Infinity are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.

This allows for you to do things like so:

var userId = 5;
var query = connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  //query.sql returns SELECT * FROM users WHERE id = '5'
});

As well as this:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  //query.sql returns INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
});

Aside from those functions, you can also use the escape functions:

connection.escape(query);
mysql.escape(query);

To escape query identifiers:

mysql.escapeId(identifier);

And as a response to your comment on prepared statements:

From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements.

The prepared statements are on the todo list for this connector, but this module at least allows you to specify custom formats that can be very similar to prepared statements. Here's an example from the readme:

connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
};

This changes the query format of the connection so you can use queries like this:

connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
//equivalent to
connection.query("UPDATE posts SET title = " + mysql.escape("Hello MySQL");

Remove the newline character in a list read from a file

You can use the strip() function to remove trailing (and leading) whitespace; passing it an argument will let you specify which whitespace:

for i in range(len(lists)):
    grades.append(lists[i].strip('\n'))

It looks like you can just simplify the whole block though, since if your file stores one ID per line grades is just lists with newlines stripped:

Before

lists = files.readlines()
grades = []

for i in range(len(lists)):
    grades.append(lists[i].split(","))

After

grades = [x.strip() for x in files.readlines()]

(the above is a list comprehension)


Finally, you can loop over a list directly, instead of using an index:

Before

for i in range(len(grades)):
    # do something with grades[i]

After

for thisGrade in grades:
    # do something with thisGrade

How to construct a relative path in Java from two absolute paths (or URLs)?

I'm assuming you have fromPath (an absolute path for a folder), and toPath (an absolute path for a folder/file), and your're looking for a path that with represent the file/folder in toPath as a relative path from fromPath (your current working directory is fromPath) then something like this should work:

public static String getRelativePath(String fromPath, String toPath) {

  // This weirdness is because a separator of '/' messes with String.split()
  String regexCharacter = File.separator;
  if (File.separatorChar == '\\') {
    regexCharacter = "\\\\";
  }

  String[] fromSplit = fromPath.split(regexCharacter);
  String[] toSplit = toPath.split(regexCharacter);

  // Find the common path
  int common = 0;
  while (fromSplit[common].equals(toSplit[common])) {
    common++;
  }

  StringBuffer result = new StringBuffer(".");

  // Work your way up the FROM path to common ground
  for (int i = common; i < fromSplit.length; i++) {
    result.append(File.separatorChar).append("..");
  }

  // Work your way down the TO path
  for (int i = common; i < toSplit.length; i++) {
    result.append(File.separatorChar).append(toSplit[i]);
  }

  return result.toString();
}

INNER JOIN same table

Perhaps this should be the select (if I understand the question correctly)

select user.user_fname, user.user_lname, parent.user_fname, parent.user_lname
... As before

Loop through JSON object List

It's close! Try this:

for (var prop in result) {
    if (result.hasOwnProperty(prop)) {
        alert(result[prop]);
    }
}

Update:

If your result is truly is an array of one object, then you might have to do this:

for (var prop in result[0]) {
    if (result[0].hasOwnProperty(prop)) {
        alert(result[0][prop]);
    }
}

Or if you want to loop through each result in the array if there are more, try:

for (var i = 0; i < results.length; i++) {
    for (var prop in result[i]) {
        if (result[i].hasOwnProperty(prop)) {
            alert(result[i][prop]);
        }
    }
}

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

Filter an array using a formula (without VBA)

This will do it if you only want the first "B" value, you can sub a cell address for "B" if you want to make it more generic.

=INDEX(A2:A6,SUMPRODUCT(MATCH(TRUE,(B2:B6)="B",0)),1)

To use this based on two columns, just concatenate inside the match:

=INDEX(A2:A6,SUMPRODUCT(MATCH(TRUE,(A2:A6&B2:B6)=("3"&"B"),0)),1)

How can one run multiple versions of PHP 5.x on a development LAMP server?

Rasmus Lerdorf, who created PHP, is maintaining an active Vagrant solution that seems to solve your needs. It allows for quickly switching between PHP versions, currently supporting more than 20 different versions. It comes out of the box with an nginx server, but can easily be switched to apache2 with a preconfigured setting. It also supports MySQL out of the box.

This way you will have access to all versions of PHP, deployable on two of the main web servers, in a nice vagrant box, maintained by the big man behind PHP.

For more information I would like to refer to the talk given by mr. Lerdorf at https://youtu.be/6XnysJAyThs?t=2864

The github repository containing the Vagrant solution is found at https://github.com/rlerdorf/php7dev

Failed to run sdkmanager --list with Java 9

The only working solution for me is to use the java shipped with the Android studio.

set the JAVA_HOME to /Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home

in .bashrc

set JAVA_HOME="/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home"

If you are using fish shel, put this in ~/.config/fish/config.fish

set -gx JAVA_HOME /Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home

(This is for mac, but I am sure it should work with linux and windows by setting the correct path)

Python: How to create a unique file name?

You can use the datetime module

import datetime
uniq_filename = str(datetime.datetime.now().date()) + '_' + str(datetime.datetime.now().time()).replace(':', '.')

Note that: I am using replace since the colons are not allowed in filenames in many operating systems.

That's it, this will give you a unique filename every single time.

How to get selected value from Dropdown list in JavaScript

Hope it's working for you

 function GetSelectedItem()
 {
     var index = document.getElementById(select1).selectedIndex;

     alert("value =" + document.getElementById(select1).value); // show selected value
     alert("text =" + document.getElementById(select1).options[index].text); // show selected text 
 }

Change one value based on another value in pandas

This question might still be visited often enough that it's worth offering an addendum to Mr Kassies' answer. The dict built-in class can be sub-classed so that a default is returned for 'missing' keys. This mechanism works well for pandas. But see below.

In this way it's possible to avoid key errors.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> class SurnameMap(dict):
...     def __missing__(self, key):
...         return ''
...     
>>> surnamemap = SurnameMap()
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap[x])
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

The same thing can be done more simply in the following way. The use of the 'default' argument for the get method of a dict object makes it unnecessary to subclass a dict.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> surnamemap = {}
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap.get(x, ''))
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

Trying to mock datetime.date.today(), but not working

CPython actually implements the datetime module using both a pure-Python Lib/datetime.py and a C-optimized Modules/_datetimemodule.c. The C-optimized version cannot be patched but the pure-Python version can.

At the bottom of the pure-Python implementation in Lib/datetime.py is this code:

try:
    from _datetime import *  # <-- Import from C-optimized module.
except ImportError:
    pass

This code imports all the C-optimized definitions and effectively replaces all the pure-Python definitions. We can force CPython to use the pure-Python implementation of the datetime module by doing:

import datetime
import importlib
import sys

sys.modules["_datetime"] = None
importlib.reload(datetime)

By setting sys.modules["_datetime"] = None, we tell Python to ignore the C-optimized module. Then we reload the module which causes the import from _datetime to fail. Now the pure-Python definitions remain and can be patched normally.

If you're using Pytest then include the snippet above in conftest.py and you can patch datetime objects normally.

xpath find if node exists

<xsl:if test="xpath-expression">...</xsl:if>

so for example

<xsl:if test="/html/body">body node exists</xsl:if>
<xsl:if test="not(/html/body)">body node missing</xsl:if>

C# winforms combobox dynamic autocomplete

This was a major pain to get working. I hit a bunch of dead ends, but the final result is reasonably straight forward. Hopefully it can be of benefit to someone. It may need a little spit and polish that's all.

Note: _addressFinder.CompleteAsync returns a list of KeyValuePairs.

public partial class MyForm : Form
{
    private readonly AddressFinder _addressFinder;
    private readonly AddressSuggestionsUpdatedEventHandler _addressSuggestionsUpdated;

    private delegate void AddressSuggestionsUpdatedEventHandler(object sender, AddressSuggestionsUpdatedEventArgs e);

    public MyForm()
    {
        InitializeComponent();

        _addressFinder = new AddressFinder(new AddressFinderConfigurationProvider());

        _addressSuggestionsUpdated += AddressSuggestions_Updated;

        MyComboBox.DropDownStyle = ComboBoxStyle.DropDown;
        MyComboBox.DisplayMember = "Value";
        MyComboBox.ValueMember = "Key";
    }

    private void MyComboBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (char.IsControl(e.KeyChar))
        {
            return;
        }

        var searchString = ThreadingHelpers.GetText(MyComboBox);

        if (searchString.Length > 1)
        {
            Task.Run(() => GetAddressSuggestions(searchString));
        }
    }

    private async Task GetAddressSuggestions(string searchString)
    {
        var addressSuggestions = await _addressFinder.CompleteAsync(searchString).ConfigureAwait(false);

        if (_addressSuggestionsUpdated.IsNotNull())
        {
            _addressSuggestionsUpdated.Invoke(this, new AddressSuggestionsUpdatedEventArgs(addressSuggestions));
        }
    }

    private void AddressSuggestions_Updated(object sender, AddressSuggestionsUpdatedEventArgs eventArgs)
    {
        try
        {
            ThreadingHelpers.BeginUpdate(MyComboBox);

            var text = ThreadingHelpers.GetText(MyComboBox);

            ThreadingHelpers.ClearItems(MyComboBox);

            foreach (var addressSuggestions in eventArgs.AddressSuggestions)
            {
                ThreadingHelpers.AddItem(MyComboBox, addressSuggestions);
            }

            ThreadingHelpers.SetDroppedDown(MyComboBox, true);

            ThreadingHelpers.ClearSelection(MyComboBox);
            ThreadingHelpers.SetText(MyComboBox, text);
            ThreadingHelpers.SetSelectionStart(MyComboBox, text.Length);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        finally
        {
            ThreadingHelpers.EndUpdate(MyComboBox);
        }
    }

    private class AddressSuggestionsUpdatedEventArgs : EventArgs
    {
        public IList<KeyValuePair<string, string>> AddressSuggestions { get; private set; }

        public AddressSuggestionsUpdatedEventArgs(IList<KeyValuePair<string, string>> addressSuggestions)
        {
            AddressSuggestions = addressSuggestions;
        }
    }
}

ThreadingHelpers is just a set of static methods of the form:

    public static string GetText(ComboBox comboBox)
    {
        if (comboBox.InvokeRequired)
        {
            return (string)comboBox.Invoke(new Func<string>(() => GetText(comboBox)));
        }

        lock (comboBox)
        {
            return comboBox.Text;
        }
    }

    public static void SetText(ComboBox comboBox, string text)
    {
        if (comboBox.InvokeRequired)
        {
            comboBox.Invoke(new Action(() => SetText(comboBox, text)));
            return;
        }

        lock (comboBox)
        {
            comboBox.Text = text;
        }
    }

Is there a unique Android device ID?

String SERIAL_NUMER = Build.SERIAL;

Returns SERIAL NUMBER as a string which unique in each device.

Get the Year/Month/Day from a datetime in php?

Try below code if you want to use php loop to display

<span>
  <select name="birth_month">
    <?php for( $m=1; $m<=12; ++$m ) { 
      $month_label = date('F', mktime(0, 0, 0, $m, 1));
    ?>
      <option value="<?php echo $month_label; ?>"><?php echo $month_label; ?></option>
    <?php } ?>
  </select> 
</span>
<span>
  <select name="birth_day">
    <?php 
      $start_date = 1;
      $end_date   = 31;
      for( $j=$start_date; $j<=$end_date; $j++ ) {
        echo '<option value='.$j.'>'.$j.'</option>';
      }
    ?>
  </select>
</span>
<span>
  <select name="birth_year">
    <?php 
      $year = date('Y');
      $min = $year - 60;
      $max = $year;
      for( $i=$max; $i>=$min; $i-- ) {
        echo '<option value='.$i.'>'.$i.'</option>';
      }
    ?>
  </select>
</span>

How to remove line breaks from a file in Java?

str = str.replaceAll("\\r\\n|\\r|\\n", " ");

Worked perfectly for me after searching a lot, having failed with every other line.

Excel: Use a cell value as a parameter for a SQL query

If you are using microsoft query, you can add "?" to your query...

select name from user where id= ?

that will popup a small window asking for the cell/data/etc when you go back to excel.

In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.

How to find the size of a table in SQL?

You may refer the answer by Marc_s in another thread, Very useful.

Get size of all tables in database

replace \n and \r\n with <br /> in java

Since my account is new I can't up-vote Nino van Hooff's answer. If your strings are coming from a Windows based source such as an aspx based server, this solution does work:

rawText.replaceAll("(\\\\r\\\\n|\\\\n)", "<br />");

Seems to be a weird character set issue as the double back-slashes are being interpreted as single slash escape characters. Hence the need for the quadruple slashes above.

Again, under most circumstances "(\\r\\n|\\n)" should work, but if your strings are coming from a Windows based source try the above.

Just an FYI tried everything to correct the issue I was having replacing those line endings. Thought at first was failed conversion from Windows-1252 to UTF-8. But that didn't working either. This solution is what finally did the trick. :)

How do I pull files from remote without overwriting local files?

You can stash your local changes first, then pull, then pop the stash.

git stash
git pull origin master
git stash pop

Anything that overrides changes from remote will have conflicts which you will have to manually resolve.

How to use refs in React with Typescript

One way (which I've been doing) is to setup manually :

refs: {
    [string: string]: any;
    stepInput:any;
}

then you can even wrap this up in a nicer getter function (e.g. here):

stepInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.stepInput);

How does numpy.histogram() work?

Another useful thing to do with numpy.histogram is to plot the output as the x and y coordinates on a linegraph. For example:

arr = np.random.randint(1, 51, 500)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()

enter image description here

This can be a useful way to visualize histograms where you would like a higher level of granularity without bars everywhere. Very useful in image histograms for identifying extreme pixel values.

Use Ant for running program with command line arguments

The only effective mechanism for passing parameters into a build is to use Java properties:

ant -Done=1 -Dtwo=2

The following example demonstrates how you can check and ensure the expected parameters have been passed into the script

<project name="check" default="build">

    <condition property="params.set">
        <and>
            <isset property="one"/>
            <isset property="two"/>
        </and>
    </condition>

    <target name="check">
        <fail unless="params.set">
        Must specify the parameters: one, two
        </fail>
    </target>

    <target name="build" depends="check">
        <echo>
        one = ${one}
        two = ${two}
        </echo>
    </target>

</project>

How to turn NaN from parseInt into 0 for an empty string?

var s = '';

var num = parseInt(s) || 0;

When not used with boolean values, the logical OR (||) operator returns the first expression (parseInt(s)) if it can be evaluated to true, otherwise it returns the second expression (0). The return value of parseInt('') is NaN. NaN evaluates to false, so num ends up being set to 0.

How to set thymeleaf th:field value from other variable

You could approach this method.

Instead of using th:field use html id & name. Set value using th:value

<input class="form-control"
           type="text"
           th:value="${client.name}" id="clientName" name="clientName" />

Hope this will help you

How to access parent Iframe from JavaScript

Simply call window.frameElement from your framed page. If the page is not in a frame then frameElement will be null.

The other way (getting the window element inside a frame is less trivial) but for sake of completeness:

/**
 * @param f, iframe or frame element
 * @return Window object inside the given frame
 * @effect will append f to document.body if f not yet part of the DOM
 * @see Window.frameElement
 * @usage myFrame.document = getFramedWindow(myFrame).document;
 */
function getFramedWindow(f)
{
    if(f.parentNode == null)
        f = document.body.appendChild(f);
    var w = (f.contentWindow || f.contentDocument);
    if(w && w.nodeType && w.nodeType==9)
        w = (w.defaultView || w.parentWindow);
    return w;
}

Reading CSV files using C#

Another one to this list, Cinchoo ETL - an open source library to read and write CSV files

For a sample CSV file below

Id, Name
1, Tom
2, Mark

Quickly you can load them using library as below

using (var reader = new ChoCSVReader("test.csv").WithFirstLineHeader())
{
   foreach (dynamic item in reader)
   {
      Console.WriteLine(item.Id);
      Console.WriteLine(item.Name);
   }
}

If you have POCO class matching the CSV file

public class Employee
{
   public int Id { get; set; }
   public string Name { get; set; }
}

You can use it to load the CSV file as below

using (var reader = new ChoCSVReader<Employee>("test.csv").WithFirstLineHeader())
{
   foreach (var item in reader)
   {
      Console.WriteLine(item.Id);
      Console.WriteLine(item.Name);
   }
}

Please check out articles at CodeProject on how to use it.

Disclaimer: I'm the author of this library

What do .c and .h file extensions mean to C?

The .c is the source file and .h is the header file.

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

Since the syntaxes are equivalent (in MySQL anyhow), I prefer the INSERT INTO table SET x=1, y=2 syntax, since it is easier to modify and easier to catch errors in the statement, especially when inserting lots of columns. If you have to insert 10 or 15 or more columns, it's really easy to mix something up using the (x, y) VALUES (1,2) syntax, in my opinion.

If portability between different SQL standards is an issue, then maybe INSERT INTO table (x, y) VALUES (1,2) would be preferred.

And if you want to insert multiple records in a single query, it doesn't seem like the INSERT INTO ... SET syntax will work, whereas the other one will. But in most practical cases, you're looping through a set of records to do inserts anyhow, though there could be some cases where maybe constructing one large query to insert a bunch of rows into a table in one query, vs. a query for each row, might have a performance improvement. Really don't know.

How to check date of last change in stored procedure or function in SQL server

In latest version(2012 or more) we can get modified stored procedure detail by using this query

SELECT create_date, modify_date, name FROM sys.procedures 
ORDER BY modify_date DESC

How to pass parameters using ui-sref in ui-router to controller

You simply misspelled $stateParam, it should be $stateParams (with an s). That's why you get undefined ;)

Failed to resolve: com.android.support:appcompat-v7:26.0.0

My issue got resolved with the help of following steps:

For gradle 3.0.0 and above version

  1. add google() below jcenter()
  2. Change the compileSdkVersion to 26 and buildToolsVersion to 26.0.2
  3. Change to gradle-4.2.1-all.zip in the gradle_wrapper.properties file

How to markdown nested list items in Bitbucket?

4 spaces do the trick even inside definition list:

Endpoint
: `/listAgencies`

Method
: `GET`

Arguments
:   * `level` - bla-bla.
    * `withDisabled` - should we include disabled `AGENT`s.
    * `userId` - bla-bla.

I am documenting API using BitBucket Wiki and Markdown proprietary extension for definition list is most pleasing (MD's table syntax is awful, imaging multiline and embedding requirements...).

Unfamiliar symbol in algorithm: what does ? mean?

The upside-down A symbol is the universal quantifier from predicate logic. (Also see the more complete discussion of the first-order predicate calculus.) As others noted, it means that the stated assertions holds "for all instances" of the given variable (here, s). You'll soon run into its sibling, the backwards capital E, which is the existential quantifier, meaning "there exists at least one" of the given variable conforming to the related assertion.

If you're interested in logic, you might enjoy the book Logic and Databases: The Roots of Relational Theory by C.J. Date. There are several chapters covering these quantifiers and their logical implications. You don't have to be working with databases to benefit from this book's coverage of logic.

How to make a page redirect using JavaScript?

You can call a JavaScript function and use window.location = 'url';:

http://www.pageresource.com/jscript/jredir.htm

How to make html table vertically scrollable

I fought with this one for a while. My goal was to have a table with headers where the widths of the each header column was the the same as the corresponding body column and was the minimum size necessary to fit the data. also the body data was scrollable underneath header.

I solved this by using divs and not tables. Each "table" was a div with the header being a div of divs and the body being a div of divs. I used the style as indicated by @sushil above. I added a bit of javascript/jQuery to balance the columns. Maybe 20-30 lines.

Unfortunately I lost the code and have to rebuild it. I know this is a bit old, but maybe it will help someone else.

Convert string to Date in java

it went OK when i used Locale.US parametre in SimpleDateFormat

String dateString = "15 May 2013 17:38:34 +0300";
System.out.println(dateString);

SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.US);
DateFormat targetFormat = new SimpleDateFormat("dd MMM yyyy HH:mm", Locale.getDefault());
String formattedDate = null;
Date convertedDate = new Date();
try {
     convertedDate = dateFormat.parse(dateString);
System.out.println(dateString);
formattedDate = targetFormat.format(convertedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 System.out.println(convertedDate);

ValueError: all the input arrays must have same number of dimensions

If I start with a 3x4 array, and concatenate a 3x1 array, with axis 1, I get a 3x5 array:

In [911]: x = np.arange(12).reshape(3,4)
In [912]: np.concatenate([x,x[:,-1:]], axis=1)
Out[912]: 
array([[ 0,  1,  2,  3,  3],
       [ 4,  5,  6,  7,  7],
       [ 8,  9, 10, 11, 11]])
In [913]: x.shape,x[:,-1:].shape
Out[913]: ((3, 4), (3, 1))

Note that both inputs to concatenate have 2 dimensions.

Omit the :, and x[:,-1] is (3,) shape - it is 1d, and hence the error:

In [914]: np.concatenate([x,x[:,-1]], axis=1)
...
ValueError: all the input arrays must have same number of dimensions

The code for np.append is (in this case where axis is specified)

return concatenate((arr, values), axis=axis)

So with a slight change of syntax append works. Instead of a list it takes 2 arguments. It imitates the list append is syntax, but should not be confused with that list method.

In [916]: np.append(x, x[:,-1:], axis=1)
Out[916]: 
array([[ 0,  1,  2,  3,  3],
       [ 4,  5,  6,  7,  7],
       [ 8,  9, 10, 11, 11]])

np.hstack first makes sure all inputs are atleast_1d, and then does concatenate:

return np.concatenate([np.atleast_1d(a) for a in arrs], 1)

So it requires the same x[:,-1:] input. Essentially the same action.

np.column_stack also does a concatenate on axis 1. But first it passes 1d inputs through

array(arr, copy=False, subok=True, ndmin=2).T

This is a general way of turning that (3,) array into a (3,1) array.

In [922]: np.array(x[:,-1], copy=False, subok=True, ndmin=2).T
Out[922]: 
array([[ 3],
       [ 7],
       [11]])
In [923]: np.column_stack([x,x[:,-1]])
Out[923]: 
array([[ 0,  1,  2,  3,  3],
       [ 4,  5,  6,  7,  7],
       [ 8,  9, 10, 11, 11]])

All these 'stacks' can be convenient, but in the long run, it's important to understand dimensions and the base np.concatenate. Also know how to look up the code for functions like this. I use the ipython ?? magic a lot.

And in time tests, the np.concatenate is noticeably faster - with a small array like this the extra layers of function calls makes a big time difference.

Detect rotation of Android phone in the browser with JavaScript

The actual behavior across different devices is inconsistent. The resize and orientationChange events can fire in a different sequence with varying frequency. Also, some values (e.g. screen.width and window.orientation) don't always change when you expect. Avoid screen.width -- it doesn't change when rotating in iOS.

The reliable approach is to listen to both resize and orientationChange events (with some polling as a safety catch), and you'll eventually get a valid value for the orientation. In my testing, Android devices occasionally fail to fire events when rotating a full 180 degrees, so I've also included a setInterval to poll the orientation.

var previousOrientation = window.orientation;
var checkOrientation = function(){
    if(window.orientation !== previousOrientation){
        previousOrientation = window.orientation;
        // orientation changed, do your magic here
    }
};

window.addEventListener("resize", checkOrientation, false);
window.addEventListener("orientationchange", checkOrientation, false);

// (optional) Android doesn't always fire orientationChange on 180 degree turns
setInterval(checkOrientation, 2000);

Here are the results from the four devices that I've tested (sorry for the ASCII table, but it seemed like the easiest way to present the results). Aside from the consistency between the iOS devices, there is a lot of variety across devices. NOTE: The events are listed in the order that they fired.

|==============================================================================|
|     Device     | Events Fired      | orientation | innerWidth | screen.width |
|==============================================================================|
| iPad 2         | resize            | 0           | 1024       | 768          |
| (to landscape) | orientationchange | 90          | 1024       | 768          |
|----------------+-------------------+-------------+------------+--------------|
| iPad 2         | resize            | 90          | 768        | 768          |
| (to portrait)  | orientationchange | 0           | 768        | 768          |
|----------------+-------------------+-------------+------------+--------------|
| iPhone 4       | resize            | 0           | 480        | 320          |
| (to landscape) | orientationchange | 90          | 480        | 320          |
|----------------+-------------------+-------------+------------+--------------|
| iPhone 4       | resize            | 90          | 320        | 320          |
| (to portrait)  | orientationchange | 0           | 320        | 320          |
|----------------+-------------------+-------------+------------+--------------|
| Droid phone    | orientationchange | 90          | 320        | 320          |
| (to landscape) | resize            | 90          | 569        | 569          |
|----------------+-------------------+-------------+------------+--------------|
| Droid phone    | orientationchange | 0           | 569        | 569          |
| (to portrait)  | resize            | 0           | 320        | 320          |
|----------------+-------------------+-------------+------------+--------------|
| Samsung Galaxy | orientationchange | 0           | 400        | 400          |
| Tablet         | orientationchange | 90          | 400        | 400          |
| (to landscape) | orientationchange | 90          | 400        | 400          |
|                | resize            | 90          | 683        | 683          |
|                | orientationchange | 90          | 683        | 683          |
|----------------+-------------------+-------------+------------+--------------|
| Samsung Galaxy | orientationchange | 90          | 683        | 683          |
| Tablet         | orientationchange | 0           | 683        | 683          |
| (to portrait)  | orientationchange | 0           | 683        | 683          |
|                | resize            | 0           | 400        | 400          |
|                | orientationchange | 0           | 400        | 400          |
|----------------+-------------------+-------------+------------+--------------|

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

With C++11 and std::chrono::high_resolution_clock you can do this:

#include <iostream>
#include <chrono>
#include <thread>
typedef std::chrono::high_resolution_clock Clock;

int main()
{
    std::chrono::milliseconds three_milliseconds{3};

    auto t1 = Clock::now();
    std::this_thread::sleep_for(three_milliseconds);
    auto t2 = Clock::now();

    std::cout << "Delta t2-t1: " 
              << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count()
              << " milliseconds" << std::endl;
}

Output:

Delta t2-t1: 3 milliseconds

Link to demo: http://cpp.sh/2zdtu

JQuery: How to get selected radio button value?

$('input[name=myradiobutton]:radio:checked') will get you the selected radio button $('input[name=myradiobutton]:radio:not(:checked)') will get you the unselected radio buttons

Using this you can do this

$('input[name=myradiobutton]:radio:not(:checked)').val("0");

Update: After reading your Update I think I understand You will want to do something like this

var myRadioValue;

function radioValue(jqRadioButton){
  if (jqRadioButton.length) {
    myRadioValue = jqRadioButton.val();
  }
  else {
    myRadioValue = 0;
  }
}

$(document).ready(function () {
  $('input[name=myradiobutton]:radio').click(function () {   //Hook the click event for selected elements
    radioValue($('input[name=myradiobutton]:radio:checked'));
  });

  radioValue($('input[name=myradiobutton]:radio:checked')); //check for value on page load
});

How to get ° character in a string in python?

just use \xb0 (in a string); python will convert it automatically

Run a command over SSH with JSch

I am using JSCH since about 2000 and still find it a good library to use. I agree it is not documented well enough but the provided examples seem good enough to understand that is required in several minutes, and user friendly Swing, while this is quite original approach, allows to test the example quickly to make sure it actually works. It is not always true that every good project needs three times more documentation than the amount of code written, and even when such is present, this not always helps to write faster a working prototype of your concept.

How to Install pip for python 3.7 on Ubuntu 18?

pip3 not pip. You can create an alias like you did with python3 if you like.

Find and replace Android studio

On Windows:

Find : Ctrl+F

Find And Replace In Single Class: Ctrl+R

Find And Replace In Whole Project: Ctrl+Shift+R

on OS X ,it is similar, just replace Ctrl with Command

OpenSSL and error in reading openssl.conf file

Just create an openssl.cnf file yourself like this in step 4: http://www.flatmtn.com/article/setting-openssl-create-certificates

Edit after link stopped working The content of the openssl.cnf file was the following:

#
# OpenSSL configuration file.
#

# Establish working directory.

dir                 = .

[ ca ]
default_ca              = CA_default

[ CA_default ]
serial                  = $dir/serial
database                = $dir/certindex.txt
new_certs_dir               = $dir/certs
certificate             = $dir/cacert.pem
private_key             = $dir/private/cakey.pem
default_days                = 365
default_md              = md5
preserve                = no
email_in_dn             = no
nameopt                 = default_ca
certopt                 = default_ca
policy                  = policy_match

[ policy_match ]
countryName             = match
stateOrProvinceName         = match
organizationName            = match
organizationalUnitName          = optional
commonName              = supplied
emailAddress                = optional

[ req ]
default_bits                = 1024          # Size of keys
default_keyfile             = key.pem       # name of generated keys
default_md              = md5               # message digest algorithm
string_mask             = nombstr       # permitted characters
distinguished_name          = req_distinguished_name
req_extensions              = v3_req

[ req_distinguished_name ]
# Variable name             Prompt string
#-------------------------    ----------------------------------
0.organizationName          = Organization Name (company)
organizationalUnitName          = Organizational Unit Name (department, division)
emailAddress                = Email Address
emailAddress_max            = 40
localityName                = Locality Name (city, district)
stateOrProvinceName         = State or Province Name (full name)
countryName             = Country Name (2 letter code)
countryName_min             = 2
countryName_max             = 2
commonName              = Common Name (hostname, IP, or your name)
commonName_max              = 64

# Default values for the above, for consistency and less typing.
# Variable name             Value
#------------------------     ------------------------------
0.organizationName_default      = My Company
localityName_default            = My Town
stateOrProvinceName_default     = State or Providence
countryName_default         = US

[ v3_ca ]
basicConstraints            = CA:TRUE
subjectKeyIdentifier            = hash
authorityKeyIdentifier          = keyid:always,issuer:always

[ v3_req ]
basicConstraints            = CA:FALSE
subjectKeyIdentifier            = hash

Remove rows with all or some NAs (missing values) in data.frame

delete.dirt <- function(DF, dart=c('NA')) {
  dirty_rows <- apply(DF, 1, function(r) !any(r %in% dart))
  DF <- DF[dirty_rows, ]
}

mydata <- delete.dirt(mydata)

Above function deletes all the rows from the data frame that has 'NA' in any column and returns the resultant data. If you want to check for multiple values like NA and ? change dart=c('NA') in function param to dart=c('NA', '?')

How do I run a file on localhost?

I'm not really sure what you mean, so I'll start simply:

If the file you're trying to "run" is static content, like HTML or even Javascript, you don't need to run it on "localhost"... you should just be able to open it from wherever it is on your machine in your browser.

If it is a piece of server-side code (ASP[.NET], php, whatever else, uou need to be running either a web server, or if you're using Visual Studio, start the development server for your application (F5 to debug, or CTRL+F5 to start without debugging).

If you're using a web server, you'll need to have a web site configured with the home directory set to the directory the file is in (or, just put the file in whatever home directory is configured).

If you're using Visual Studio, the file just needs to be in your project.

How can I output a UTF-8 CSV in PHP that Excel will read properly?

Add:

fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));

Or:

fprintf($file, "\xEF\xBB\xBF");

Before writing any content to CSV file.

Example:

<?php
$file = fopen( "file.csv", "w");
fprintf( $file, "\xEF\xBB\xBF");
fputcsv( $file, ["english", 122, "?????"]);
fclose($file);

C# Encoding a text string with line breaks

Try \n\n , it will work! :)

public async Task AjudaAsync(IDialogContext context, LuisResult result){
await context.PostAsync("How can I help you? \n\n 1.To Schedule \n\n 2.Consult");
context.Wait(MessageReceived);
}

Dark Theme for Visual Studio 2010 With Productivity Power Tools

  1. Install the Visual Studio Color Theme Editor extension:
  2. Make your own color scheme or try: The Dark Expression Blend Color Theme (preview below)
  3. Once you have that, you'll want schemes for the text editor as well. This site has several, including the VS2012 "dark" theme implemented for VS2010.

Visual Studio 2010 with Dark Theme

CSS force new line

or you can use:

a {
    display: inline-block;
  }

How to launch Windows Scheduler by command-line?

You can make a new shortcut to:

control schedtasks

Name it something easy like "tsks.lnk" and then save it in c:\windows\system32.

You can now press Windows Key + R, then type "tsks" and press Enter and voila. No mouse necessary at that point.
Or in Windows Vista/7/2008, just press Windows Key, then type "tsks" and press Enter.

removing new line character from incoming stream using sed

This might work for you:

printf "{new\nto\nlinux}" | paste -sd' '            
{new to linux}

or:

printf "{new\nto\nlinux}" | tr '\n' ' '            
{new to linux}

or:

printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}

Limit to 2 decimal places with a simple pipe

Currency pipe uses the number one internally for number formatting. So you can use it like this:

{{ number | number : '1.2-2'}}

How can I make my own event in C#?

You can declare an event with the following code:

public event EventHandler MyOwnEvent;

A custom delegate type instead of EventHandler can be used if needed.

You can find detailed information/tutorials on the use of events in .NET in the article Events Tutorial (MSDN).

What column type/length should I use for storing a Bcrypt hashed password in a Database?

If you are using PHP's password_hash() with the PASSWORD_DEFAULT algorithm to generate the bcrypt hash (which I would assume is a large percentage of people reading this question) be sure to keep in mind that in the future password_hash() might use a different algorithm as the default and this could therefore affect the length of the hash (but it may not necessarily be longer).

From the manual page:

Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).

Using bcrypt, even if you have 1 billion users (i.e. you're currently competing with facebook) to store 255 byte password hashes it would only ~255 GB of data - about the size of a smallish SSD hard drive. It is extremely unlikely that storing the password hash is going to be the bottleneck in your application. However in the off chance that storage space really is an issue for some reason, you can use PASSWORD_BCRYPT to force password_hash() to use bcrypt, even if that's not the default. Just be sure to stay informed about any vulnerabilities found in bcrypt and review the release notes every time a new PHP version is released. If the default algorithm is ever changed it would be good to review why and make an informed decision whether to use the new algorithm or not.

Get input value from TextField in iOS alert in Swift

Updated for Swift 3 and above:

//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)

//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
    textField.text = "Some default text"
}

// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
    let textField = alert.textFields![0] // Force unwrapping because we know it exists.
    print("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.present(alert, animated: true, completion: nil)

Swift 2.x

Assuming you want an action alert on iOS:

//1. Create the alert controller.            
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
    textField.text = "Some default text."
})

//3. Grab the value from the text field, and print it when the user clicks OK. 
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [weak alert] (action) -> Void in
    let textField = alert.textFields![0] as UITextField
    println("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)

How can I convert my Java program to an .exe file?

I would say launch4j is the best tool for converting a java source code(.java) to .exe file You can even bundle a jre with it for distribution and the exe can even be iconified. Although the size of application increases, it makes sure that the application will work perfectly even if the user does not have a jre installed. It also makes sure that you are able to provide the specific jre required for your app without the user having to install it separately. But unfortunately, java loses its importance. Its multi platform support is totally ignored and the final app is only supported for windows. But that is not a big deal, if you are catering only to windows users.

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

Another solution to know why exactly nothing works (from Microsoft connect):

  1. Add this code to the project:

    foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
    {
        asm.GetTypes();
    }
    
  2. Turn off generation serialization assemblies.

  3. Build and execute.

How to jquery alert confirm box "yes" & "no"

See following snippet :

_x000D_
_x000D_
$(document).on("click", "a.deleteText", function() {_x000D_
    if (confirm('Are you sure ?')) {_x000D_
        $(this).prev('span.text').remove();_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
    <span class="text">some text</span>_x000D_
    <a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

.Net picking wrong referenced assembly version

Its almost like you have to wipe out your computer to get rid of the old dll. I have already tried everything above and then I went the extra step of just deleting every instance of the .DLL file that was on my computer and removing every reference from the application. However, it still compiles just fine and when it runs it is referencing the dll functions just fine. I'm starting to wonder if it is referencing it from a network drive somehwere.

CSS: how to position element in lower right?

Lets say your HTML looks something like this:

<div class="box">
    <!-- stuff -->
    <p class="bet_time">Bet 5 days ago</p>
</div>

Then, with CSS, you can make that text appear in the bottom right like so:

.box {
    position:relative;
}
.bet_time {
    position:absolute;
    bottom:0;
    right:0;
}

The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time positions its right edge to the right edge of .box and its bottom edge to the bottom edge of .box

PLS-00103: Encountered the symbol "CREATE"

At line 5 there is a / missing.

There is a good answer on the differences between ; and / here.

Basically, when running a CREATE block via script, you need to use / to let SQLPlus know when the block ends, since a PL/SQL block can contain many instances of ;.

Get the ID of a drawable in ImageView

I think if I understand correctly this is what you are doing.

ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        ImageView imageView = (ImageView) view;
        assert(R.id.someImage == imageView.getId());

        switch(getDrawableId(imageView)) {
            case R.drawable.foo:
                imageView.setDrawableResource(R.drawable.bar);
                break;
            case R.drawable.bar:
            default:
                imageView.setDrawableResource(R.drawable.foo);
            break;
        }
    });

Right? So that function getDrawableId() doesn't exist. You can't get a the id that a drawable was instantiated from because the id is just a reference to the location of data on the device on how to construct a drawable. Once the drawable is constructed it doesn't have a way to get back the resourceId that was used to create it. But you could make it work something like this using tags

ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        ImageView imageView = (ImageView) view;
        assert(R.id.someImage == imageView.getId());

        // See here
        Integer integer = (Integer) imageView.getTag();
        integer = integer == null ? 0 : integer;

        switch(integer) {
        case R.drawable.foo:
            imageView.setDrawableResource(R.drawable.bar);
            imageView.setTag(R.drawable.bar);
            break;
        case R.drawable.bar:
        default:
            imageView.setDrawableResource(R.drawable.foo);
            imageView.setTag(R.drawable.foo);
            break;
        }
    });

Disable text input history

<input type="text" autocomplete="off" />

How to check whether a Storage item is set?

For TRUE

localStorage.infiniteScrollEnabled = 1;

FOR FALSE

localStorage.removeItem("infiniteScrollEnabled")

CHECK EXISTANCE

if (localStorage[""infiniteScrollEnabled""]) {
  //CODE IF ENABLED
}

Linux command line howto accept pairing for bluetooth device without pin

~ $ hciconfig noauth

This should do the trick (I'm using bluez 5.23 and there's no more simple-egent and blue-utils). However, I'm trying to look for a way to make changes hciconfig permanent because after power out and then power on, authentication is needed again. So far, the changes in hciconfig still stays the same when you reboot it. it reverts back only when power out. If anybody has found a way to make hciconfig permanent, do let me know!

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

In my case I used the binaries from Shining Light and the environment variables were already updated. But still had the issue until I ran a command window with elevated privileges.

When you open the CMD window be sure to run it as Administrator. (Right click the Command Prompt in Start menu and choose "Run as administrator")

I think it can't read the files due to User Account Control.

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

I needed to do this because I have an ajax login form. When users login successfully I redirect to a new page and end the previous request because the other page handles redirecting back to the relying party (because it's a STS SSO System).

However, I also wanted it to work with javascript disabled, being the central login hop and all, so I came up with this,

    public static string EnsureUrlEndsWithSlash(string url)
    {
        if (string.IsNullOrEmpty(url))
            throw new ArgumentNullException("url");
        if (!url.EndsWith("/"))
            return string.Concat(url, "/");
        return url;
    }

    public static string GetQueryStringFromArray(KeyValuePair<string, string>[] values)
    {
        Dictionary<string, string> dValues = new Dictionary<string,string>();
        foreach(var pair in values)            
            dValues.Add(pair.Key, pair.Value);            
        var array = (from key in dValues.Keys select string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(dValues[key]))).ToArray();
        return "?" + string.Join("&", array);
    }

    public static void RedirectTo(this HttpRequestBase request, string url, params KeyValuePair<string, string>[] queryParameters)
    {            
        string redirectUrl = string.Concat(EnsureUrlEndsWithSlash(url), GetQueryStringFromArray(queryParameters));
        if (request.IsAjaxRequest())
            HttpContext.Current.Response.Write(string.Format("<script type=\"text/javascript\">window.location='{0}';</script>", redirectUrl));
        else
            HttpContext.Current.Response.Redirect(redirectUrl, true);

    }

Superscript in markdown (Github flavored)?

Use the <sup></sup>tag (<sub></sub> is the equivalent for subscripts). See this gist for an example.

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

For me, the solution was to ensure all projects were building for the same CPU - in my case x86

Better way to find control in ASP.NET

https://blog.codinghorror.com/recursive-pagefindcontrol/

Page.FindControl("DataList1:_ctl0:TextBox3");

OR

private Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
    {
        return root;
    }
    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null)
        {
            return t;
        }
    }
    return null;
}

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

ohh, Thank @kimbaudi, i followed this tuts

https://dotnettutorials.net/lesson/generic-repository-pattern-csharp-mvc/

and got the same error as your. But after read your code i found out my solution was adding

services.AddScoped(IGenericRepository, GenericRepository);

into ConfigureServices method in StartUp.cs file =))

Convert String XML fragment to Document Node in Java

...and if you're using purely XOM, something like this:

    String xml = "<fakeRoot>" + xml + "</fakeRoot>";
    Document doc = new Builder( false ).build( xml, null );
    Nodes children = doc.getRootElement().removeChildren();
    for( int ix = 0; ix < children.size(); ix++ ) {
        otherDocumentElement.appendChild( children.get( ix ) );
    }

XOM uses fakeRoot internally to do pretty much the same, so it should be safe, if not exactly elegant.

When to use a View instead of a Table?

You should design your table WITHOUT considering the views.
Apart from saving joins and conditions, Views do have a performance advantage: SQL Server may calculate and save its execution plan in the view, and therefore make it faster than "on the fly" SQL statements.
View may also ease your work regarding user access at field level.

Seaborn plots not showing up

This worked for me

import matplotlib.pyplot as plt
import seaborn as sns
.
.
.
plt.show(sns)

Get source JARs from Maven repository

Maven repositories do provide simple way to download sources jar.

I will explain it using a demonstration for "spring-boot-actuator-autoconfigure".

  1. Go to maven repository - https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-actuator-autoconfigure
  2. The page lists various versions. Click-on to desired one, let's say, 2.1.6.RELEASE - https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-actuator-autoconfigure/2.1.6.RELEASE
  3. The page have link "View All" next to "Files". Click it - https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-actuator-autoconfigure/2.1.6.RELEASE/
  4. The page lists various files including the one for sources - https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-actuator-autoconfigure/2.1.6.RELEASE/spring-boot-actuator-autoconfigure-2.1.6.RELEASE-sources.jar

Otherwise, you can always "git clone" the repo from github, if its there and get the specific code.

As explained by others, you can use "mvn dependency:sources" command the get and generate sources jar for the dependency you are using.

Note: Some dependencies will not have sources.jar, as those contains no source code but a pom file. e.g. spring-boot-starter-actuator. As in this case:

Starter POMs are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy paste loads of dependency descriptors.

Reference: Intro to Spring Boot Starters

ASP.NET MVC Global Variables

You can put them in the Application:

Application["GlobalVar"] = 1234;

They are only global within the current IIS / Virtual applicition. This means, on a webfarm they are local to the server, and within the virtual directory that is the root of the application.

Get user input from textarea

I think you should not use spaces between the [(ngModel)] the = and the str. Then you should use a button or something like this with a click function and in this function you can use the values of your inputfields.

<input id="str" [(ngModel)]="str"/>
<button (click)="sendValues()">Send</button>

and in your component file

str: string;
sendValues(): void {
//do sth with the str e.g. console.log(this.str);
}

Hope I can help you.

how to get vlc logs?

Or you can use the more obvious solution, right in the GUI: Tools -> Messages (set verbosity to 2)...

jquery to loop through table rows and cells, where checkob is checked, concatenate

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...
        });
    });
}

How to get the difference between two arrays of objects in JavaScript

import differenceBy from 'lodash/differenceBy'

const myDifferences = differenceBy(Result1, Result2, 'value')

This will return the difference between two arrays of objects, using the key value to compare them. Note two things with the same value will not be returned, as the other keys are ignored.

This is a part of lodash.

Set session variable in laravel

in Laravel 5.4

use this method:

Session::put('variableName', $value);

Removing white space around a saved image in matplotlib

You may try this. It solved my issue.

import matplotlib.image as mpimg
img = mpimg.imread("src.png")
mpimg.imsave("out.png", img, cmap=cmap)

python xlrd unsupported format, or corrupt file.

Worked on the same issue , finally done this is top for the question so just putting what i did.

Observation - 1 -The file was not actually XLS i renamed to txt and noticed HTML text in file.

2 - Renamed the file to html and tried reading pd.read_html, Failed.

3- Added as it was not there in txt file, removed style to ensure that table is displaying in browser from local, and WORKED.

Below is the code may help someone..

import pandas as pd
import os
import shutil
import html5lib
import requests
from bs4 import BeautifulSoup
import re
import time

shutil.copy('your.xls','file.html')
shutil.copy('file.html','file.txt')
time.sleep(2)

txt = open('file.txt','r').read()

# Modify the text to ensure the data display in html page, delete style

txt = str(txt).replace('<style> .text { mso-number-format:\@; } </script>','')

# Add head and body if it is not there in HTML text

txt_with_head = '<html><head></head><body>'+txt+'</body></html>'

# Save the file as HTML

html_file = open('output.html','w')
html_file.write(txt_with_head)

# Use beautiful soup to read

url = r"C:\Users\hitesh kumar\PycharmProjects\OEM ML\output.html"
page = open(url)
soup = BeautifulSoup(page.read(), features="lxml")
my_table = soup.find("table",attrs={'border': '1'})

frame = pd.read_html(str(my_table))[0]
print(frame.head())
frame.to_excel('testoutput.xlsx',sheet_name='sheet1', index=False)

How to Apply global font to whole HTML document

You should be able to utilize the asterisk and !important elements within CSS.

html *
{
   font-size: 1em !important;
   color: #000 !important;
   font-family: Arial !important;
}

The asterisk matches everything (you could probably get away without the html too).

The !important ensures that nothing can override what you've set in this style (unless it is also important). (this is to help with your requirement that it should "ignore inner formatting of text" - which I took to mean that other styles could not overwrite these)

The rest of the style within the braces is just like any other styling and you can do whatever you'd like to in there. I chose to change the font size, color and family as an example.

check if file exists on remote host with ssh

You're missing ;s. The general syntax if you put it all in one line would be:

if thing ; then ... ; else ... ; fi

The thing can be pretty much anything that returns an exit code. The then branch is taken if that thing returns 0, the else branch otherwise.

[ isn't syntax, it's the test program (check out ls /bin/[, it actually exists, man test for the docs – although can also have a built-in version with different/additional features.) which is used to test various common conditions on files and variables. (Note that [[ on the other hand is syntax and is handled by your shell, if it supports it).

For your case, you don't want to use test directly, you want to test something on the remote host. So try something like:

if ssh user@host test -e "$file" ; then ... ; else ... ; fi

C# catch a stack overflow exception

You can't. The CLR won't let you. A stack overflow is a fatal error and can't be recovered from.

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

I suppose your dictMap is of type HashMap, which makes it default to HashMap<Object, Object>. If you want it to be more specific, declare it as HashMap<String, ArrayList>, or even better, as HashMap<String, ArrayList<T>>

Removing object properties with Lodash

Lodash unset is suitable for removing a few unwanted keys.

_x000D_
_x000D_
const myObj = {
    keyOne: "hello",
    keyTwo: "world"
}

unset(myObj, "keyTwo");

console.log(myObj); /// myObj = { keyOne: "hello" }
_x000D_
_x000D_
_x000D_

Why Is `Export Default Const` invalid?

The answer shared by Paul is the best one. To expand more,

There can be only one default export per file. Whereas there can be more than one const exports. The default variable can be imported with any name, whereas const variable can be imported with it's particular name.

var message2 = 'I am exported';
export default message2;
export const message = 'I am also exported'

At the imports side we need to import it like this:

import { message } from './test';

or

import message from './test';

With the first import, the const variable is imported whereas, with the second one, the default one will be imported.

Aren't Python strings immutable? Then why does a + " " + b work?

A variable is just a label pointing to an object. The object is immutable, but you can make the label point to a completely different object if you want to.

'LIKE ('%this%' OR '%that%') and something=else' not working

It would be nice if you could, but you can't use that syntax in SQL.

Try this:

(column1 LIKE '%this%' OR column1 LIKE '%that%') AND something = else

Note the use of brackets! You need them around the OR expression.
Without brackets, it will be parsed as A OR (B AND C),which won't give you the results you expect.

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

I had a somewhat similar problem - on my first attempt to enter MySQL, as root, it told me access denied. Turns out I forgot to use the sudo...

So, if you fail on root first attempt, try:

sudo mysql -u root -p

and then enter your password, this should work.

Reading e-mails from Outlook with Python through MAPI

I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)

class CheckMailer:

        def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
            self.f = FileWriter(filename)
            self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
            self.inbox = self.outlook.Folders(folderindex)


        def check(self):                
        #===============================================================================
        # for i in xrange(1,100):                           #Uncomment this section if index 3 does not work for you
        #     try:
        #         self.inbox = self.outlook.Folders(i)     # "6" refers to the index of inbox for Default User Mailbox
        #         print "%i %s" % (i,self.inbox)            # "3" refers to the index of inbox for Another user's mailbox
        #     except:
        #         print "%i does not work"%i
        #===============================================================================

                self.f.pl(time.strftime("%H:%M:%S"))
                tot = 0                
                messages = self.inbox.Items
                message = messages.GetFirst()
                while message:
                    self.f.pl (message.Subject)
                    message = messages.GetNext()
                    tot += 1
                self.f.pl("Total Messages found: %i" % tot)
                self.f.pl("-" * 80)
                self.f.flush()

if __name__ == "__main__":
    mail = CheckMailer()
    for i in xrange(320):  # this is 10.6 hours approximately
            mail.check()
            time.sleep(120.00)

For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because trying to pipe UTF8 to a file in windows did not work.

class FileWriter(object):
    '''
    convenient file wrapper for writing to files
    '''


    def __init__(self, filename):
        '''
        Constructor
        '''
        self.file = open(filename, "w")

    def pl(self, a_string):
        str_uni = a_string.encode('utf-8')
        self.file.write(str_uni)
        self.file.write("\n")

    def flush(self):
        self.file.flush()

Convert pandas.Series from dtype object to float, and errors to nans

Use pd.to_numeric with errors='coerce'

# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s

0    1
1    2
2    3
3    4
4    .
dtype: object

pd.to_numeric(s, errors='coerce')

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

If you need the NaNs filled in, use Series.fillna.

pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')

0    1
1    2
2    3
3    4
4    0
dtype: float64

Note, downcast='infer' will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.

From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use

pd.__version__
# '0.24.1'

pd.to_numeric(s, errors='coerce').astype('Int32')

0      1
1      2
2      3
3      4
4    NaN
dtype: Int32

There are other options to choose from as well, read the docs for more.


Extension for DataFrames

If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply.

# Setup.
np.random.seed(0)
df = pd.DataFrame({
    'A' : np.random.choice(10, 5), 
    'C' : np.random.choice(10, 5), 
    'B' : ['1', '###', '...', 50, '234'], 
    'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df

   A    B  C    D
0  5    1  9   23
1  0  ###  3    1
2  3  ...  5  ...
3  3   50  2  268
4  7  234  4   $$

df.dtypes

A     int64
B    object
C     int64
D    object
dtype: object

df2 = df.apply(pd.to_numeric, errors='coerce')
df2

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

df2.dtypes

A      int64
B    float64
C      int64
D    float64
dtype: object

You can also do this with DataFrame.transform; although my tests indicate this is marginally slower:

df.transform(pd.to_numeric, errors='coerce')

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric on the non-numeric columns only.

df.dtypes.eq(object)

A    False
B     True
C    False
D     True
dtype: bool

cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')

df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
#     df[c] = pd.to_numeric(df[c], errors='coerce')

df

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

Applying pd.to_numeric along the columns (i.e., axis=0, the default) should be slightly faster for long DataFrames.

Deep copy vs Shallow Copy

The quintessential example of this is an array of pointers to structs or objects (that are mutable).

A shallow copy copies the array and maintains references to the original objects.

A deep copy will copy (clone) the objects too so they bear no relation to the original. Implicit in this is that the object themselves are deep copied. This is where it gets hard because there's no real way to know if something was deep copied or not.

The copy constructor is used to initilize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory.

In order to read the details with complete examples and explanations you could see the article Constructors and destructors.

The default copy constructor is shallow. You can make your own copy constructors deep or shallow, as appropriate. See C++ Notes: OOP: Copy Constructors.

Powershell v3 Invoke-WebRequest HTTPS error

I tried searching for documentation on the EM7 OpenSource REST API. No luck so far.

http://blog.sciencelogic.com/sciencelogic-em7-the-next-generation/05/2011

There's a lot of talk about OpenSource REST API, but no link to the actual API or any documentation. Maybe I was impatient.

Here are few things you can try out

$a = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert 
$a.Results | ConvertFrom-Json

Try this to see if you can filter out the columns that you are getting from the API

$a.Results | ft

or, you can try using this also

$b = Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert 
$b.Content | ConvertFrom-Json

Curl Style Headers

$b.Headers

I tested the IRM / IWR with the twitter JSON api.

$a = Invoke-RestMethod http://search.twitter.com/search.json?q=PowerShell 

Hope this helps.

What’s the difference between Response.Write() andResponse.Output.Write()?

Response.write() is used to display the normal text and Response.output.write() is used to display the formated text.

How to remove duplicate white spaces in string using Java?

Though it is too late, I have found a better solution (that works for me) that will replace all consecutive same type white spaces with one white space of its type. That is:

   Hello!\n\n\nMy    World  

will be

 Hello!\nMy World 

Notice there are still leading and trailing white spaces. So my complete solution is:

str = str.trim().replaceAll("(\\s)+", "$1"));

Here, trim() replaces all leading and trailing white space strings with "". (\\s) is for capturing \\s (that is white spaces such as ' ', '\n', '\t') in group #1. + sign is for matching 1 or more preceding token. So (\\s)+ can be consecutive characters (1 or more) among any single white space characters (' ', '\n' or '\t'). $1 is for replacing the matching strings with the group #1 string (which only contains 1 white space character) of the matching type (that is the single white space character which has matched). The above solution will change like this:

   Hello!\n\n\nMy    World  

will be

Hello!\nMy World

I have not found my above solution here so I have posted it.

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

Html.fromHtml deprecated in Android N

fromHtml

This method was deprecated in API level 24.

You should use FROM_HTML_MODE_LEGACY

Separate block-level elements with blank lines (two newline characters) in between. This is the legacy behavior prior to N.

Code

if (Build.VERSION.SDK_INT >= 24)
        {
            etOBJ.setText(Html.fromHtml("Intellij \n Amiyo",Html.FROM_HTML_MODE_LEGACY));

         }
 else
        {
           etOBJ.setText(Html.fromHtml("Intellij \n Amiyo"));
        }

For Kotlin

fun setTextHTML(html: String): Spanned
    {
        val result: Spanned = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
        } else {
            Html.fromHtml(html)
        }
        return result
    }

Call

 txt_OBJ.text  = setTextHTML("IIT Amiyo")

How can I convert an Integer to localized month name in Java?

I would use SimpleDateFormat. Someone correct me if there is an easier way to make a monthed calendar though, I do this in code now and I'm not so sure.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;


public String formatMonth(int month, Locale locale) {
    DateFormat formatter = new SimpleDateFormat("MMMM", locale);
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.set(Calendar.MONTH, month-1);
    return formatter.format(calendar.getTime());
}

Jquery check if element is visible in viewport

You can see this example.

// Is this element visible onscreen?
var visible = $(#element).visible( detectPartial );

detectPartial :

  • True : the entire element is visible
  • false : part of the element is visible

visible is boolean variable which indicates if the element is visible or not.

What causing this "Invalid length for a Base-64 char array"

As others have mentioned this can be caused when some firewalls and proxies prevent access to pages containing a large amount of ViewState data.

ASP.NET 2.0 introduced the ViewState Chunking mechanism which breaks the ViewState up into manageable chunks, allowing the ViewState to pass through the proxy / firewall without issue.

To enable this feature simply add the following line to your web.config file.

<pages maxPageStateFieldLength="4000">

This should not be used as an alternative to reducing your ViewState size but it can be an effective backstop against the "Invalid length for a Base-64 char array" error resulting from aggressive proxies and the like.

How to import Swagger APIs into Postman?

The accepted answer is correct but I will rewrite complete steps for java.

I am currently using Swagger V2 with Spring Boot 2 and it's straightforward 3 step process.

Step 1: Add required dependencies in pom.xml file. The second dependency is optional use it only if you need Swagger UI.

        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

Step 2: Add configuration class

@Configuration
@EnableSwagger2
public class SwaggerConfig {

     public static final Contact DEFAULT_CONTACT = new Contact("Usama Amjad", "https://stackoverflow.com/users/4704510/usamaamjad", "[email protected]");
      public static final ApiInfo DEFAULT_API_INFO = new ApiInfo("Article API", "Article API documentation sample", "1.0", "urn:tos",
              DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList<VendorExtension>());

    @Bean
    public Docket api() {
        Set<String> producesAndConsumes = new HashSet<>();
        producesAndConsumes.add("application/json");
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(DEFAULT_API_INFO)
                .produces(producesAndConsumes)
                .consumes(producesAndConsumes);

    }
}

Step 3: Setup complete and now you need to document APIs in controllers

    @ApiOperation(value = "Returns a list Articles for a given Author", response = Article.class, responseContainer = "List")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
            @ApiResponse(code = 404, message = "The resource you were trying to reach is not found") })
    @GetMapping(path = "/articles/users/{userId}")
    public List<Article> getArticlesByUser() {
       // Do your code
    }

Usage:

You can access your Documentation from http://localhost:8080/v2/api-docs just copy it and paste in Postman to import collection.

enter image description here

Optional Swagger UI: You can also use standalone UI without any other rest client via http://localhost:8080/swagger-ui.html and it's pretty good, you can host your documentation without any hassle.

enter image description here

Calling Java from Python

I've been integrating a lot of stuff into Python lately, including Java. The most robust method I've found is to use IKVM and a C# wrapper.

IKVM has a neat little application that allows you to take any Java JAR, and convert it directly to .Net DLL. It simply translates the JVM bytecode to CLR bytecode. See http://sourceforge.net/p/ikvm/wiki/Ikvmc/ for details.

The converted library behaves just like a native C# library, and you can use it without needing the JVM. You can then create a C# DLL wrapper project, and add a reference to the converted DLL.

You can now create some wrapper stubs that call the methods that you want to expose, and mark those methods as DllEport. See https://stackoverflow.com/a/29854281/1977538 for details.

The wrapper DLL acts just like a native C library, with the exported methods looking just like exported C methods. You can connect to them using ctype as usual.

I've tried it with Python 2.7, but it should work with 3.0 as well. Works on Windows and the Linuxes

If you happen to use C#, then this is probably the best approach to try when integrating almost anything into python.

How do I run a batch file from my Java Application?

Process p = Runtime.getRuntime().exec( 
  new String[]{"cmd", "/C", "orgreg.bat"},
  null, 
  new File("D://TEST//home//libs//"));

tested with jdk1.5 and jdk1.6

This was working fine for me, hope it helps others too. to get this i have struggled more days. :(

Experimental decorators warning in TypeScript compilation

You can also try with ng build. I've just rebuilt the app and now it's not complying.

What does the C++ standard state the size of int, long type to be?

You can use:

cout << "size of datatype = " << sizeof(datatype) << endl;

datatype = int, long int etc. You will be able to see the size for whichever datatype you type.

Get index of element as child relative to parent

There's no need to require a big library like jQuery to accomplish this, if you don't want to. To achieve this with built-in DOM manipulation, get a collection of the li siblings in an array, and on click, check the indexOf the clicked element in that array.

_x000D_
_x000D_
const lis = [...document.querySelectorAll('#wizard > li')];_x000D_
lis.forEach((li) => {_x000D_
  li.addEventListener('click', () => {_x000D_
    const index = lis.indexOf(li);_x000D_
    console.log(index);_x000D_
  });_x000D_
});
_x000D_
<ul id="wizard">_x000D_
    <li>Step 1</li>_x000D_
    <li>Step 2</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Or, with event delegation:

_x000D_
_x000D_
const lis = [...document.querySelectorAll('#wizard li')];_x000D_
document.querySelector('#wizard').addEventListener('click', ({ target }) => {_x000D_
  // Make sure the clicked element is a <li> which is a child of wizard:_x000D_
  if (!target.matches('#wizard > li')) return;_x000D_
  _x000D_
  const index = lis.indexOf(target);_x000D_
  console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
    <li>Step 1</li>_x000D_
    <li>Step 2</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Or, if the child elements may change dynamically (like with a todo list), then you'll have to construct the array of lis on every click, rather than beforehand:

_x000D_
_x000D_
const wizard = document.querySelector('#wizard');_x000D_
wizard.addEventListener('click', ({ target }) => {_x000D_
  // Make sure the clicked element is a <li>_x000D_
  if (!target.matches('li')) return;_x000D_
  _x000D_
  const lis = [...wizard.children];_x000D_
  const index = lis.indexOf(target);_x000D_
  console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
    <li>Step 1</li>_x000D_
    <li>Step 2</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

How to read a CSV file into a .NET Datatable

The best option I have found, and it resolves issues where you may have different versions of Office installed, and also 32/64-bit issues like Chuck Bevitt mentioned, is FileHelpers.

It can be added to your project references using NuGet and it provides a one-liner solution:

CommonEngine.CsvToDataTable(path, "ImportRecord", ',', true);

remove item from stored array in angular 2

Use splice() to remove item from the array its refresh the array index to be consequence.

delete will remove the item from the array but its not refresh the array index which means if you want to remove third item from four array items the index of elements will be after delete the element 0,1,4

this.data.splice(this.data.indexOf(msg), 1)

Where can I find the API KEY for Firebase Cloud Messaging?

Please add new api key from Firebase -> Project Settings -> Cloud Messaging -> Legacy Server Key to the workspace file i.e google-services.json

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

CASE WHEN statement for ORDER BY clause

CASE is an expression - it returns a single scalar value (per row). It can't return a complex part of the parse tree of something else, like an ORDER BY clause of a SELECT statement.

It looks like you just need:

ORDER BY 
CASE WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount END desc,
CASE WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount END desc, 
Case WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount END DESC,
CASE WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount END DESC,
Case WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount END DESC,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC

Or possibly:

ORDER BY 
CASE
   WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
   WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
   WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
   WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
   WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC

It's a little tricky to tell which of the above (or something else) is what you're looking for because you've a) not explained what actual sort order you're trying to achieve, and b) not supplied any sample data and expected results, from which we could attempt to deduce the actual sort order you're trying to achieve.


This may be the answer we're looking for:

ORDER BY 
CASE
   WHEN TblList.PinRequestCount <> 0 THEN 5
   WHEN TblList.HighCallAlertCount <> 0 THEN 4
   WHEN TblList.HighAlertCount <> 0 THEN 3
   WHEN TblList.MediumCallAlertCount <> 0 THEN 2
   WHEN TblList.MediumAlertCount <> 0 THEN 1
END desc,
CASE
   WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
   WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
   WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
   WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
   WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC

Select 2 columns in one and combine them

Your syntax should work, maybe add a space between the colums like

SELECT something + ' ' + somethingElse as onlyOneColumn FROM someTable

tmux set -g mouse-mode on doesn't work

As @Graham42 said, from version 2.1 mouse options has been renamed but you can use the mouse with any version of tmux adding this to your ~/.tmux.conf:

Bash shells:

is_pre_2_1="[[ $(tmux -V | cut -d' ' -f2) < 2.1 ]] && echo true || echo false"
if-shell "$is_pre_2_1" "setw -g mode-mouse on; set -g mouse-resize-pane on;\
      set -g mouse-select-pane on; set -g mouse-select-window on" "set -g mouse on"

Sh (Bourne shell) shells:

is_pre_2_1="tmux -V | cut -d' ' -f2 | awk '{print ($0 < 2.1) ? "true" : "false"}'"
if-shell "$is_pre_2_1" "setw -g mode-mouse on; set -g mouse-resize-pane on;\
      set -g mouse-select-pane on; set -g mouse-select-window on" "set -g mouse on"

Hope this helps

How to replace a string in an existing file in Perl?

It can be done using a single line:

perl -pi.back -e 's/oldString/newString/g;' inputFileName

Pay attention that oldString is processed as a Regular Expression.
In case the string contains any of {}[]()^$.|*+? (The special characters for Regular Expression syntax) make sure to escape them unless you want it to be processed as a regular expression.
Escaping it is done by \, so \[.

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

For Windows Users (and maybe others)

Rubygems.org has a guide that not only explains how to fix this problem, but also why so many people are having it: SSL Certificate Update The reason for the problem is rubygems.org switched to a more secure SSL certificate (SHA-2 which use 256bit encryption). The rubygems command line tool bundles the reference to the correct certificate. Therefore rubygems itself can’t be updated using an older version of rubygems. Rubygems must first be updated manually.

First find out what rubygems you have:

rubygems –v

Depending on whether you have a 1.8.x, 2.0.x or 2.2.x, you will need to download an update gem, named “rubygems-update-X.Y.Z.gem”, where X.Y.Z is the version you need. Running 1.8.x: download: https://github.com/rubygems/rubygems/releases/tag/v1.8.30 Running 2.0.x: download: https://github.com/rubygems/rubygems/releases/tag/v2.0.15 Running 2.2.x: download: https://github.com/rubygems/rubygems/releases/tag/v2.2.3

Install update gem:

gem install –-local full_path_to_the_gem_file

Run update gem:

update_rubygems --no-ri --no-rdoc

Check that rubygems was updated:

rubygems –v

Uninstall update gem:

gem uninstall rubygems-update -x

At this point, you may be OK. But it is possible that you do not have the latest public key file for the new certificate. To do this:

Download the latest certificate, (currently AddTrustExternalCARoot-2048.pem) from https://rubygems.org/pages/download. All of the certs are also located at: https://github.com/rubygems/rubygems/tree/master/lib/rubygems/ssl_certs

Find out where to put it:

gem which rubygems

Put this file in the “rubygems\ssl_certs” directory at this location.

As per rubygems commit, the certificates are moved to more specific directories. Thus, currently the certificate(AddTrustExternalCARoot-2048.pem) is expected to be on the following path lib/rubygems/ssl_certs/rubygems.org/AddTrustExternalCARoot-2048.pem