Programs & Examples On #Fbx

FBX is an Autodesk proprietary file format (.fbx) used to provide interoperability between digital content creation applications like 3ds Max, Maya, MotionBuilder.

Extract Google Drive zip from Google colab notebook

Instead of GetContentString(), use GetContentFile() instead. It will save the file instead of returning the string.

downloaded.GetContentFile('images.zip') 

Then you can unzip it later with unzip.

How to enable PHP's openssl extension to install Composer?

you need to enable the openssl extension in

C:\wamp\bin\php\php5.4.12\php.ini 

that is the php configuration file that has it type has "configuration settings" with a driver-notepad like icon.

  1. open it either with notepad or any editor,
  2. search for openssl "your ctrl + F " would do.
  3. there is a semi-colon before the openssl extension

    ;extension=php_openssl.dll
    

    remove the semi-colon and you'll have

    extension=php_openssl.dll
    
  4. save the file and restart your WAMP server after that you're good to go. re-install the application again that should work.

Java - Convert image to Base64

To begin with, this line of code:

while ((bytesRead = fis.read(byteArray)) != -1)

is equivalent to

while ((bytesRead = fis.read(byteArray, 0, byteArray.length)) != -1)

So it's writing into the byteArray from offset 0, rather than from where you wrote to before.

You need something like this:

int offset = 0;
int bytesRead = 0;

while ((bytesRead = fis.read(byteArray, offset, byteArray.length - offset) != -1) {
    offset += bytesRead;
}

After you have read the data (bytes) in then, you can convert it to Base64.

There are bigger problems though - you're using a fixed size array, so files that are too big won't be converted correctly, and the code is tricker because of it too.

I would ditch the byte array and go with something like this:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// commons-io IOUtils
IOUtils.copy(fis, buffer);
byte [] data = buffer.toByteArray();
Base64.encode(data);

Or condense it further as Thilo has with FileUtils.

How to get current page URL in MVC 3

For me the issue was when I tried to access HTTPContext in the Controller's constructor while HTTPContext is not ready yet. When moved inside Index method it worked:

var uri = new Uri(Request.Url.AbsoluteUri);
url = uri.Scheme + "://" + uri.Host + "/";enter code here

what does this mean ? image/png;base64?

That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).

Return a `struct` from a function in C

You can return a structure from a function (or use the = operator) without any problems. It's a well-defined part of the language. The only problem with struct b = a is that you didn't provide a complete type. struct MyObj b = a will work just fine. You can pass structures to functions as well - a structure is exactly the same as any built-in type for purposes of parameter passing, return values, and assignment.

Here's a simple demonstration program that does all three - passes a structure as a parameter, returns a structure from a function, and uses structures in assignment statements:

#include <stdio.h>

struct a {
   int i;
};

struct a f(struct a x)
{
   struct a r = x;
   return r;
}

int main(void)
{
   struct a x = { 12 };
   struct a y = f(x);
   printf("%d\n", y.i);
   return 0;
}

The next example is pretty much exactly the same, but uses the built-in int type for demonstration purposes. The two programs have the same behaviour with respect to pass-by-value for parameter passing, assignment, etc.:

#include <stdio.h>

int f(int x) 
{
  int r = x;
  return r;
}

int main(void)
{
  int x = 12;
  int y = f(x);
  printf("%d\n", y);
  return 0;
}

How to quit a java app from within the program

System.exit() is usually not the best way, but it depends on your application.

The usual way of ending an application is by exiting the main() method. This does not work when there are other non-deamon threads running, as is usual for applications with a graphical user interface (AWT, Swing etc.). For these applications, you either find a way to end the GUI event loop (don't know if that is possible with the AWT or Swing), or invoke System.exit().

Swift Alamofire: How to get the HTTP response status code

For Swift 2.0 users with Alamofire > 2.0

Alamofire.request(.GET, url)
  .responseString { _, response, result in
    if response?.statusCode == 200{
      //Do something with result
    }
}

could not extract ResultSet in hibernate

I was using Spring Data JPA with PostgreSql and during UPDATE call it was showing errors-

  • 'could not extract ResultSet' and another one.
  • org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query. (Showing Transactional required.)

Actually, I was missing two required Annotations.

  • @Transactional and
  • @Modifying

With-

@Query(vlaue = " UPDATE DB.TABLE SET Col1 = ?1 WHERE id = ?2 ", nativeQuery = true)
void updateCol1(String value, long id);

A weighted version of random.choice

There is lecture on this by Sebastien Thurn in the free Udacity course AI for Robotics. Basically he makes a circular array of the indexed weights using the mod operator %, sets a variable beta to 0, randomly chooses an index, for loops through N where N is the number of indices and in the for loop firstly increments beta by the formula:

beta = beta + uniform sample from {0...2* Weight_max}

and then nested in the for loop, a while loop per below:

while w[index] < beta:
    beta = beta - w[index]
    index = index + 1

select p[index]

Then on to the next index to resample based on the probabilities (or normalized probability in the case presented in the course).

The lecture link: https://classroom.udacity.com/courses/cs373/lessons/48704330/concepts/487480820923

I am logged into Udacity with my school account so if the link does not work, it is Lesson 8, video number 21 of Artificial Intelligence for Robotics where he is lecturing on particle filters.

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

You can take a look at source-code-wordle.de, I have analyzed there the most frequently used suffixes of class names of the .NET framework and some other libraries.

The top 20 are:

  • attribute
  • type
  • helper
  • collection
  • converter
  • handler
  • info
  • provider
  • exception
  • service
  • element
  • manager
  • node
  • option
  • factory
  • context
  • item
  • designer
  • base
  • editor

PHP Excel Header

The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.

I know i came in late but it can help future readers of this post.

How to use a wildcard in the classpath to add multiple jars?

Basename wild cards were introduced in Java 6; i.e. "foo/*" means all ".jar" files in the "foo" directory.

In earlier versions of Java that do not support wildcard classpaths, I have resorted to using a shell wrapper script to assemble a Classpath by 'globbing' a pattern and mangling the results to insert ':' characters at the appropriate points. This would be hard to do in a BAT file ...

How can I access "static" class variables within class methods in Python?

Instead of bar use self.bar or Foo.bar. Assigning to Foo.bar will create a static variable, and assigning to self.bar will create an instance variable.

Selenium WebDriver and DropDown Boxes

Just wrap your WebElement into Select Object as shown below

Select dropdown = new Select(driver.findElement(By.id("identifier")));

Once this is done you can select the required value in 3 ways. Consider an HTML file like this

<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>

Now to identify dropdown do

Select dropdown = new Select(driver.findElement(By.id("designation")));

To select its option say 'Programmer' you can do

dropdown.selectByVisibleText("Programmer ");

or

 dropdown.selectByIndex(1);

or

 dropdown.selectByValue("prog");

Happy Coding :)

Copy multiple files in Python

You can use os.listdir() to get the files in the source directory, os.path.isfile() to see if they are regular files (including symbolic links on *nix systems), and shutil.copy to do the copying.

The following code copies only the regular files from the source directory into the destination directory (I'm assuming you don't want any sub-directories copied).

import os
import shutil
src_files = os.listdir(src)
for file_name in src_files:
    full_file_name = os.path.join(src, file_name)
    if os.path.isfile(full_file_name):
        shutil.copy(full_file_name, dest)

ASP.NET MVC: No parameterless constructor defined for this object

I had a similar problem, and basically the point is that there are some arguments in the action method that were not supplied by the Model Binding process, (and in other words these fields were not submitted by the submitting page).

This problem will come up even if all arguments but one are supplied, and even if the one missing is a nullable type.

The problem might also be a result of a typo, in which the name of the argument and name of the form field will not be identical.

The solution is to 1) verify that the names match up 2) provide a default value for the argument 3) or provide another action method without this argument.

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

Complementing YvesgereY's great answer, I found this visualization extremely helpful:

Padding visualization

Padding 'valid' is the first figure. The filter window stays inside the image.

Padding 'same' is the third figure. The output is the same size.


Found it on this article

Visualization credits: vdumoulin@GitHub

How to convert int to float in python?

The answers provided above are absolutely correct and worth to read but I just wanted to give a straight forward answer to the question.

The question asked is just a type conversion question and here its conversion from int data type to float data type and for that you can do it by the function :

float()

And for more details you can visit this page.

Python: Adding element to list while iterating

Alternate solution :

reduce(lambda x,newObj : x +[newObj] if somecond else x,myarr,myarr)

How do I request and receive user input in a .bat and use it to run a certain program?

If the input is, say, N, your IF lines evaluate like this:

If N=="y" goto yes 
If N=="n" goto no
…

That is, you are comparing N with "y", then "n" etc. including "N". You are never going to get a match unless the user somehow decides to input "N" or "y" (i.e. either of the four characters, but enclosed in double quotes).

So you need either to remove " from around y, n, Y and N or put them around %INPUT% in your conditional statements. I would recommend the latter, because that way you would be escaping at least some of the characters that have special meaning in batch scripts (if the user managed to type them in). So, this is what you should get:

If "%INPUT%"=="y" goto yes 
If "%INPUT%"=="n" goto no
If "%INPUT%"=="Y" goto yes
If "%INPUT%"=="N" goto no

By the way, you could reduce the number of conditions by applying the /I switch to the IF statement, like this:

If /I "%INPUT%"=="y" goto yes 
If /I "%INPUT%"=="n" goto no

The /I switch makes the comparisons case-insensitive, and so you don't need separate checks for different-case strings.

One other issue is that, after the development mode command is executed, there's no jumping over the other command, and so, if the user agrees to run Java in the development mode, he'll get it run both in the development mode and the non-development mode. So maybe you need to add something like this to your script:

...
:yes
java -jar lib/RSBot-4030.jar -dev
echo Starting RSbot in developer mode
goto cont
:no
java -jar lib/RSBot-4030.jar
echo Starting RSbot in regular mode
:cont
pause

Finally, to address the issue of processing incorrect input, you could simply add another (unconditional) goto command just after the conditional statements, just before the yes label, namely goto Ask, to return to the beginning of your script where the prompt is displayed and the input is requested, or you could also add another ECHO command before the jump, explaining that the input was incorrect, something like this:

@echo off
:Ask
echo Would you like to use developer mode?(Y/N)
set INPUT=
set /P INPUT=Type input: %=%
If /I "%INPUT%"=="y" goto yes 
If /I "%INPUT%"=="n" goto no
echo Incorrect input & goto Ask
:yes
...

Note: Some of the issues mentioned here have also been addressed by @xmjx in their answer, which I fully acknowledge.

Run javascript function when user finishes typing instead of on key up?

agree with the @going 's answer. Another similar solution that worked for me is the one below. The only difference is that I am using .on("input"...) instead of keyup. This only captures changes in the input. other keys like Ctrl, Shift etc. are ignored

var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms (5 seconds)

//on input change, start the countdown

$('#myInput').on("input", function() {    
    clearTimeout(typingTimer);
    typingTimer = setTimeout(function(){
        // doSomething...
    }, doneTypingInterval);
});

Spring Boot access static resources missing scr/main/resources

You can use following code to read file in String from resource folder.

final Resource resource = new ClassPathResource("public.key");
String publicKey = null;
try {
     publicKey = new String(Files.readAllBytes(resource.getFile().toPath()), StandardCharsets.UTF_8);
} catch (IOException e) {
     e.printStackTrace();
}

Can you write virtual functions / methods in Java?

Yes, you can write virtual "functions" in Java.

Disable Rails SQL logging in console

This might not be a suitable solution for the console, but Rails has a method for this problem: Logger#silence

ActiveRecord::Base.logger.silence do
  # the stuff you want to be silenced
end

Count Vowels in String Python

from collections import defaultdict


def count_vowels(word):
    vowels = 'aeiouAEIOU'
    count = defaultdict(int)   # init counter
    for char in word:
        if char in vowels:
            count[char] += 1
    return count

A pythonic way to count vowels in a word, not like in java or c++, actually no need to preprocess the word string, no need for str.strip() or str.lower(). But if you'd like to count vowels case-insensitively, then before go into the for-loop, use str.lower().

Pure CSS animation visibility with delay

Unfortunately you can't animate the display property. For a full list of what you can animate, try this CSS animation list by w3 Schools.

If you want to retain it's visual position on the page, you should try animating either it's height (which will still affect the position of other elements), or opacity (how transparent it is). You could even try animating the z-index, which is the position on the z axis (depth), by putting an element over the top of it, and then rearranging what's on top. However, I'd suggest using opacity, as it retains the vertical space where the element is.

I've updated the fiddle to show an example.

Good luck!

Clean up a fork and restart it from the upstream

The simplest solution would be (using 'upstream' as the remote name referencing the original repo forked):

git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master  
git push origin master --force 

(Similar to this GitHub page, section "What should I do if I’m in a bad situation?")

Be aware that you can lose changes done on the master branch (both locally, because of the reset --hard, and on the remote side, because of the push --force).

An alternative would be, if you want to preserve your commits on master, to replay those commits on top of the current upstream/master.
Replace the reset part by a git rebase upstream/master. You will then still need to force push.
See also "What should I do if I’m in a bad situation?"


A more complete solution, backing up your current work (just in case) is detailed in "Cleanup git master branch and move some commit to new branch".

See also "Pull new updates from original GitHub repository into forked GitHub repository" for illustrating what "upstream" is.

upstream


Note: recent GitHub repos do protect the master branch against push --force.
So you will have to un-protect master first (see picture below), and then re-protect it after force-pushing).

enter image description here


Note: on GitHub specifically, there is now (February 2019) a shortcut to delete forked repos for pull requests that have been merged upstream.

Binding ComboBox SelectedItem using MVVM

<!-- xaml code-->
    <Grid>
        <ComboBox Name="cmbData"    SelectedItem="{Binding SelectedstudentInfo, Mode=OneWayToSource}" HorizontalAlignment="Left" Margin="225,150,0,0" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
        <Button VerticalAlignment="Center" Margin="0,0,150,0" Height="40" Width="70" Click="Button_Click">OK</Button>
    </Grid>



        //student Class
        public class Student
        {
            public  int Id { set; get; }
            public string name { set; get; }
        }

        //set 2 properties in MainWindow.xaml.cs Class
        public ObservableCollection<Student> studentInfo { set; get; }
        public Student SelectedstudentInfo { set; get; }

        //MainWindow.xaml.cs Constructor
        public MainWindow()
        {
            InitializeComponent();
            bindCombo();
            this.DataContext = this;
            cmbData.ItemsSource = studentInfo;

        }

        //method to bind cobobox or you can fetch data from database in MainWindow.xaml.cs
        public void bindCombo()
        {
            ObservableCollection<Student> studentList = new ObservableCollection<Student>();
            studentList.Add(new Student { Id=0 ,name="==Select=="});
            studentList.Add(new Student { Id = 1, name = "zoyeb" });
            studentList.Add(new Student { Id = 2, name = "siddiq" });
            studentList.Add(new Student { Id = 3, name = "James" });

              studentInfo=studentList;

        }

        //button click to get selected student MainWindow.xaml.cs
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Student student = SelectedstudentInfo;
            if(student.Id ==0)
            {
                MessageBox.Show("select name from dropdown");
            }
            else
            {
                MessageBox.Show("Name :"+student.name + "Id :"+student.Id);
            }
        }

Min/Max of dates in an array?

The above answers do not handle blank/undefined values to fix this I used the below code and replaced blanks with NA :

function getMax(dateArray, filler) {
      filler= filler?filler:"";
      if (!dateArray.length) {
        return filler;
      }
      var max = "";
      dateArray.forEach(function(date) {
        if (date) {
          var d = new Date(date);
          if (max && d.valueOf()>max.valueOf()) {
            max = d;
          } else if (!max) {
            max = d;
          }
        }
      });
      return max;
    };
console.log(getMax([],"NA"));
console.log(getMax(datesArray,"NA"));
console.log(getMax(datesArray));

function getMin(dateArray, filler) {
 filler = filler ? filler : "";
  if (!dateArray.length) {
    return filler;
  }
  var min = "";
  dateArray.forEach(function(date) {
    if (date) {
      var d = new Date(date);
      if (min && d.valueOf() < min.valueOf()) {
        min = d;
      } else if (!min) {
        min = d;
      }
    }
  });
  return min;
}

console.log(getMin([], "NA"));
console.log(getMin(datesArray, "NA"));
console.log(getMin(datesArray));

I have added a plain javascript demo here and used it as a filter with AngularJS in this codepen

Abstract variables in Java?

I think your confusion is with C# properties vs. fields/variables. In C# you cannot define abstract fields, even in an abstract class. You can, however, define abstract properties as these are effectively methods (e.g. compiled to get_TAG() and set_TAG(...)).

As some have reminded, you should never have public fields/variables in your classes, even in C#. Several answers have hinted at what I would recommend, but have not made it clear. You should translate your idea into Java as a JavaBean property, using getTAG(). Then your sub-classes will have to implement this (I also have written a project with table classes that do this).

So you can have an abstract class defined like this...

public abstract class AbstractTable {

    public abstract String getTag();
    public abstract void init();

    ...
}

Then, in any concrete subclasses you would need to define a static final variable (constant) and return that from the getTag(), something like this:

public class SalesTable extends AbstractTable {

    private static final String TABLE_NAME = "Sales";

    public String getTag() {
        return TABLE_NAME;
    }

    public void init() {
        ...
        String tableName = getTag();
        ...
    }

}

EDIT:

You cannot override inherited fields (in either C# or Java). Nor can you override static members, whether they are fields or methods. So this also is the best solution for that. I changed my init method example above to show how this would be used - again, think of the getXXX method as a property.

Android Studio - UNEXPECTED TOP-LEVEL EXCEPTION:

Make sure you have downloaded Support Repository to use support library dependency in build.gradle.

enter image description here

If these all are there already installed sync your project with gradle once using the button available.

sync button

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

Try putting anchor tag inside and adding a{display:block;}....it will work fine

Capturing window.onbeforeunload

To pop a message when the user is leaving the page to confirm leaving, you just do:

<script>
    window.onbeforeunload = function(e) {
      return 'Are you sure you want to leave this page?  You will lose any unsaved data.';
    };
</script>

To call a function:

<script>
    window.onbeforeunload = function(e) {
       callSomeFunction();
       return null;
    };
</script>

How to Configure SSL for Amazon S3 bucket

As mentioned before, you cannot create free certificates for S3 buckets. However, you can create Cloud Front distribution and then assign the certificate for the Cloud Front instead. You request the certificate for your domain and then just assign it to the Cloud Front distribution in the Cloud Front settings. I've used this method to serve static websites via SSL as well as serve static files.

For static website creation Amazon is the go to place. It is really affordable to get a static website with SSL.

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.


The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

FIFO based Queue implementations?

Queue is an interface that extends Collection in Java. It has all the functions needed to support FIFO architecture.

For concrete implementation you may use LinkedList. LinkedList implements Deque which in turn implements Queue. All of these are a part of java.util package.

For details about method with sample example you can refer FIFO based Queue implementation in Java.

PS: Above link goes to my personal blog that has additional details on this.

How to trigger Jenkins builds remotely and to pass parameters

You can trigger Jenkins builds remotely and to pass parameters by using the following query.

JENKINS_URL/job/job-name/buildWithParameters?token=TOKEN_NAME&param_name1=value&param_name1=value

JENKINS_URL (can be) = https://<your domain name or server address>

TOKE_NAME can be created using configure tab

How to retrieve the current version of a MySQL database management system (DBMS)?

Here two more methods:

Linux: Mysql view version: from PHP

From a PHP function, we can see the version used:

mysql_get_server_info ([resource $ link_identifier = NULL]): string

Linux: Mysql view version: Package version

For RedHat / CentOS operating systems:

rpm -qa | grep mysql

For Debian / Ubuntu operating systems:

rpm -qa | grep mysql

Extracted from: https://www.sysadmit.com/2019/03/linux-mysql-ver-version.html

Angular2: custom pipe could not be found

I take no issue with the accepted answer as it certainly helped me. However, after implementing it, I still got the same error.

Turns out this was because I was calling the pipes incorrectly in my component as well:

My custom-pipe.ts file:

@Pipe({ name: 'doSomething' })
export class doSomethingPipe implements PipeTransform {
    transform(input: string): string {
        // Do something
    }
}

So far, so good, but in my component.html file I was calling the pipes as follows:

{{ myData | doSomethingPipe }}

This will again throw the error that the pipe is not found. This is because Angular looks up the pipes by the name defined in the Pipe decorator. So in my example, the pipe should instead be called like this:

{{ myData | doSomething }}

Silly mistake, but it cost me a fair amount of time. Hope this helps!

SQL Format as of Round off removing decimals

CAST(Round(MySum * 20.0 /100, 0) AS INT)

FYI

MySum * 20 /100, I get 11

This is because when all 3 operands are INTs, SQL Server will do perform integer maths, from left to right, truncating all intermediate results.

58 * 20 / 100 => 1160 / 100 => 11 (truncated from 11.6)

Also for the record ROUND(m,n) returns the result to n decimal places, not n significant figures.

Curl : connection refused

Make sure you have a service started and listening on the port.

netstat -ln | grep 8080

and

sudo netstat -tulpn

MySQL Error: #1142 - SELECT command denied to user

This error also arises for a syntax error occurred due to aliasing tablename.

For instance, when executed below query,

select * from a.table1, b.table2 where a.table1= b.table2

below error occurs:

MySQL Error: #1142. Response form the database. SELECT command denied to user "username@ip" for table "table1"

Solution : Syntax to alias tablename should be used proper, syntax solution for above instance >select * from table1 a, table2 b where a.table1= b.table2

How do I keep Python print from adding newlines or spaces?

Or use a +, i.e.:

>>> print 'me'+'no'+'likee'+'spacees'+'pls'
menolikeespaceespls

Just make sure all are concatenate-able objects.

How to download and save a file from Internet using Java?

Simpler nio usage:

URL website = new URL("http://www.website.com/information.asp");
try (InputStream in = website.openStream()) {
    Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
}

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

Use startForegroundService() instead of startService() and don't forget to create startForeground(1,new Notification()); in your service within 5 seconds of starting service.

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

I found some slides about this issue.

http://de.slideshare.net/DroidConTLV/android-crash-analysis-and-the-dalvik-garbage-collector-tools-and-tips

In this slides the author tells that it seems to be a problem with GC, if there are a lot of objects or huge objects in heap. The slide also include a reference to a sample app and a python script to analyze this issue.

https://github.com/oba2cat3/GCTest

https://github.com/oba2cat3/logcat2memorygraph

Furthermore I found a hint in comment #3 on this side: https://code.google.com/p/android/issues/detail?id=53418#c3

Convert javascript array to string

not sure if this is what you wanted but

var arr = ["A", "B", "C"];
var arrString = arr.join(", ");

This results in the following output:

A, B, C

How to create a file in memory for user to download, but not through server?

Based on @Rick answer which was really helpful.

You have to scape the string data if you want to share it this way:

$('a.download').attr('href', 'data:application/csv;charset=utf-8,'+ encodeURI(data));

` Sorry I can not comment on @Rick's answer due to my current low reputation in StackOverflow.

An edit suggestion was shared and rejected.

XML to CSV Using XSLT

Here is a version with configurable parameters that you can set programmatically:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="utf-8" />

  <xsl:param name="delim" select="','" />
  <xsl:param name="quote" select="'&quot;'" />
  <xsl:param name="break" select="'&#xA;'" />

  <xsl:template match="/">
    <xsl:apply-templates select="projects/project" />
  </xsl:template>

  <xsl:template match="project">
    <xsl:apply-templates />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$break" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="*">
    <!-- remove normalize-space() if you want keep white-space at it is --> 
    <xsl:value-of select="concat($quote, normalize-space(), $quote)" />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$delim" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="text()" />
</xsl:stylesheet>

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

As @swanliu pointed out it is due to a bad connection.
However before adjusting the server timing and client timeout , I would first try and use a better connection pooling strategy.

Connection Pooling

Hibernate itself admits that its connection pooling strategy is minimal

Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0.
As stated in Reference : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html

I personally use C3P0. however there are other alternatives available including DBCP.
Check out

Below is a minimal configuration of C3P0 used in my application:

<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.acquire_increment">1</property> 
<property name="c3p0.idle_test_period">100</property> <!-- seconds --> 
<property name="c3p0.max_size">100</property> 
<property name="c3p0.max_statements">0</property> 
<property name="c3p0.min_size">10</property> 
<property name="c3p0.timeout">1800</property> <!-- seconds --> 

By default, pools will never expire Connections. If you wish Connections to be expired over time in order to maintain "freshness", set maxIdleTime and/or maxConnectionAge. maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool. maxConnectionAge forces the pool to cull any Connections that were acquired from the database more than the set number of seconds in the past.
As stated in Reference : http://www.mchange.com/projects/c3p0/index.html#managing_pool_size

Edit:
I updated the configuration file (Reference), as I had just copy pasted the one for my project earlier. The timeout should ideally solve the problem, If that doesn't work for you there is an expensive solution which I think you could have a look at:

Create a file “c3p0.properties” which must be in the root of the classpath (i.e. no way to override it for particular parts of the application). (Reference)

# c3p0.properties
c3p0.testConnectionOnCheckout=true

With this configuration each connection is tested before being used. It however might affect the performance of the site.

How to change heatmap.2 color range in R?

Here's another option for those not using heatmap.2 (aheatmap is good!)

Make a sequential vector of 100 values from min to max of your input matrix, find value closest to 0 in that, make two vector of colours to and from desired midpoint, combine and use them:

breaks <- seq(from=min(range(inputMatrix)), to=max(range(inputMatrix)), length.out=100)
midpoint <- which.min(abs(breaks - 0))
rampCol1 <- colorRampPalette(c("forestgreen", "darkgreen", "black"))(midpoint)
rampCol2 <- colorRampPalette(c("black", "darkred", "red"))(100-(midpoint+1))
rampCols <- c(rampCol1,rampCol2)

The requested URL /about was not found on this server

I found a very simple solution.

  1. Go to Permalink Settings
  2. Use Plain for URL
  3. Press Save button

Now, all pages URLs in WordPress should work perfectly.

You can return the URL to the previous setting and the WordPress will re-generate the URL correctly. I choose Post name in my case and it works fine.

What is the standard Python docstring format?

As apparantly no one mentioned it: you can also use the Numpy Docstring Standard. It is widely used in the scientific community.

The Napolean sphinx extension to parse Google-style docstrings (recommended in the answer of @Nathan) also supports Numpy-style docstring, and makes a short comparison of both.

And last a basic example to give an idea how it looks like:

def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Parameters
    ----------
    arg1 : int
        Description of arg1
    arg2 : str
        Description of arg2

    Returns
    -------
    bool
        Description of return value

    See Also
    --------
    otherfunc : some related other function

    Examples
    --------
    These are written in doctest format, and should illustrate how to
    use the function.

    >>> a=[1,2,3]
    >>> print [x + 3 for x in a]
    [4, 5, 6]
    """
    return True

Failed to run sdkmanager --list with Java 9

When having java 11 in the system, the solutions provided are not valid.

This -XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee or--add-modules java.xml.bind do not work with Java 11 on Mac OS.

For that reason you have to downgrade java version to version 8 from here: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

List Java versions installed

/usr/libexec/java_home -V

Java 11

export JAVA_HOME=$(/usr/libexec/java_home -v 11)

Java 1.8

export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

Then go to

cd ~/Library/Android/sdk/tools/bin

and

./sdkmanager --licenses

How can I disable mod_security in .htaccess file?

Just to update this question for mod_security 2.7.0+ - they turned off the ability to mitigate modsec via htaccess unless you compile it with the --enable-htaccess-config flag. Most hosts do not use this compiler option since it allows too lax security. Instead, vhosts in httpd.conf are your go-to option for controlling modsec.

Even if you do compile modsec with htaccess mitigation, there are less directives available. SecRuleEngine can no longer be used there for example. Here is a list that is available to use by default in htaccess if allowed (keep in mind a host may further limit this list with AllowOverride):

    - SecAction
    - SecRule

    - SecRuleRemoveByMsg
    - SecRuleRemoveByTag
    - SecRuleRemoveById

    - SecRuleUpdateActionById
    - SecRuleUpdateTargetById
    - SecRuleUpdateTargetByTag
    - SecRuleUpdateTargetByMsg

More info on the official modsec wiki

As an additional note for 2.x users: the IfModule should now look for mod_security2.c instead of the older mod_security.c

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

How do you calculate the variance, median, and standard deviation in C++ or Java?

public class Statistics {
    double[] data;
    int size;   

    public Statistics(double[] data) {
        this.data = data;
        size = data.length;
    }   

    double getMean() {
        double sum = 0.0;
        for(double a : data)
            sum += a;
        return sum/size;
    }

    double getVariance() {
        double mean = getMean();
        double temp = 0;
        for(double a :data)
            temp += (a-mean)*(a-mean);
        return temp/(size-1);
    }

    double getStdDev() {
        return Math.sqrt(getVariance());
    }

    public double median() {
       Arrays.sort(data);
       if (data.length % 2 == 0)
          return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
       return data[data.length / 2];
    }
}

Error in installation a R package

After using the wrong quotation mark characters in install.packages(), correcting the quote marks yielded the "cannot remove prior installation" error. Closing and restarting R worked.

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

You can use localStorage to save the data for later use, but you can not save to a file using JavaScript (in the browser).

To be comprehensive: You can not store something into a file using JavaScript in the Browser, but using HTML5, you can read files.

Write-back vs Write-Through caching?

Write-back and write-through describe policies when a write hit occurs, that is when the cache has the requested information. In these examples, we assume a single processor is writing to main memory with a cache.

Write-through: The information is written to the cache and memory, and the write finishes when both have finished. This has the advantage of being simpler to implement, and the main memory is always consistent (in sync) with the cache (for the uniprocessor case - if some other device modifies main memory, then this policy is not enough), and a read miss never results in writes to main memory. The obvious disadvantage is that every write hit has to do two writes, one of which accesses slower main memory.

Write-back: The information is written to a block in the cache. The modified cache block is only written to memory when it is replaced (in effect, a lazy write). A special bit for each cache block, the dirty bit, marks whether or not the cache block has been modified while in the cache. If the dirty bit is not set, the cache block is "clean" and a write miss does not have to write the block to memory.

The advantage is that writes can occur at the speed of the cache, and if writing within the same block only one write to main memory is needed (when the previous block is being replaced). The disadvantages are that this protocol is harder to implement, main memory can be not consistent (not in sync) with the cache, and reads that result in replacement may cause writes of dirty blocks to main memory.

The policies for a write miss are detailed in my first link.

These protocols don't take care of the cases with multiple processors and multiple caches, as is common in modern processors. For this, more complicated cache coherence mechanisms are required. Write-through caches have simpler protocols since a write to the cache is immediately reflected in memory.

Good resources:

Programmatically switching between tabs within Swift

Swift 5

//MARK:- if you are in UITabBarController 
self.selectedIndex = 1

or

tabBarController?.selectedIndex = 1

Trying to create a file in Android: open failed: EROFS (Read-only file system)

To use internal storage for the application, you don't need permission, but you may need to use: File directory = getApplication().getCacheDir(); to get the allowed directory for the app.

Or:
getCashDir(); <-- should work
context.getCashDir(); (if in a broadcast receiver)
getDataDir(); <--Api 24

Finding all possible permutations of a given string in python

def perm(string):
   res=[]
   for j in range(0,len(string)):
       if(len(string)>1):
           for i in perm(string[1:]):
               res.append(string[0]+i)
       else:
           return [string];
       string=string[1:]+string[0];
   return res;
l=set(perm("abcde"))

This is one way to generate permutations with recursion, you can understand the code easily by taking strings 'a','ab' & 'abc' as input.

You get all N! permutations with this, without duplicates.

How to implement class constants?

For me none of earlier answer works. I did need to convert my static class to enum. Like this:

export enum MyConstants {
  MyFirstConstant = 'MyFirstConstant',
  MySecondConstant = 'MySecondConstant'
}

Then in my component I add new property as suggested in other answers

export class MyComponent {
public MY_CONTANTS = MyConstans;
constructor() { }
}

Then in my component's template I use it this way

<div [myDirective]="MY_CONTANTS.MyFirstConstant"> </div>

EDIT: Sorry. My problem was different than OP's. I still leave this here if someelse have same problem than I.

Simple and clean way to convert JSON string to Object in Swift

I like RDC's response, but why limit the JSON returned to have only arrays at the top level? I needed to allow a dictionary at the top level, so I modified it thus:

extension String
{
    var parseJSONString: AnyObject?
    {
        let data = self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

        if let jsonData = data
        {
            // Will return an object or nil if JSON decoding fails
            do
            {
                let message = try NSJSONSerialization.JSONObjectWithData(jsonData, options:.MutableContainers)
                if let jsonResult = message as? NSMutableArray {
                    return jsonResult //Will return the json array output
                } else if let jsonResult = message as? NSMutableDictionary {
                    return jsonResult //Will return the json dictionary output
                } else {
                    return nil
                }
            }
            catch let error as NSError
            {
                print("An error occurred: \(error)")
                return nil
            }
        }
        else
        {
            // Lossless conversion of the string was not possible
            return nil
        }
    }

Regexp Java for password validation

Password Requirement :

  • Password should be at least eight (8) characters in length where the system can support it.
  • Passwords must include characters from at least two (2) of these groupings: alpha, numeric, and special characters.

    ^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z])|(?=.{8,})(?=.*\d)(?=.*[!@#$%^&])|(?=.{8,})(?=.*[a-zA-Z])(?=.*[!@#$%^&]).*$
    

I tested it and it works

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

I faced a similar problem, here's how I solved in my case. I verify if the task already is RUNNING or FINISHED because an task can run only once. Below you will see a partial and adapted code from my solution.

public class MyActivity... {
    private MyTask task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       // your code
       task = new MyTask();
       setList();
    }

    private void setList() {
    if (task != null)
        if (task.getStatus().equals(AsyncTask.Status.RUNNING)){
            task.cancel(true);
            task = new MyTask();
            task.execute();         
        } else if (task.getStatus().equals(AsyncTask.Status.FINISHED)) {
            task = new MyTask();
            task.execute();
        } else 
            task.execute();
    }

    class MyTask extends AsyncTask<Void, Item, Void>{
       List<Item> Itens;

       @Override
       protected void onPreExecute() {

        //your code

        list.setVisibility(View.GONE);
        adapterItem= new MyListAdapter(MyActivity.this, R.layout.item, new ArrayList<Item>());
        list.setAdapter(adapterItem);

        adapterItem.notifyDataSetChanged();
    }

    @Override
    protected Void doInBackground(Void... params) {

        Itens = getItens();
        for (Item item : Itens) {
            publishProgress(item );
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Item ... item ) {           
        adapterItem.add(item[0]);
    }

    @Override
    protected void onPostExecute(Void result) {
        //your code
        adapterItem.notifyDataSetChanged();     
        list.setVisibility(View.VISIBLE);
    }

}

}

Open terminal here in Mac OS finder

This:

https://github.com/jbtule/cdto#cd-to

It's a small app that you drag into the Finder toolbar, the icon fits in very nicely. It works with Terminal, xterm (under X11), iterm.

Android: Proper Way to use onBackPressed() with Toast

If you want to exit your application from direct Second Activity without going to First Activity then try this code..`

In Second Activity put this code..

 @Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
            .setTitle("Really Exit?")
            .setMessage("Are you sure you want to exit?")
            .setNegativeButton(android.R.string.no, null)
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface arg0, int arg1) {
                    setResult(RESULT_OK, new Intent().putExtra("EXIT", true));
                    finish();
                }

            }).create().show();
}

And Your First Activity Put this code.....

public class FirstActivity extends AppCompatActivity {

Button next;
private final static int EXIT_CODE = 100;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    next = (Button) findViewById(R.id.next);
    next.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            startActivityForResult(new Intent(FirstActivity.this, SecondActivity.class), EXIT_CODE);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == EXIT_CODE) {
        if (resultCode == RESULT_OK) {
            if (data.getBooleanExtra("EXIT", true)) {
                finish();
            }
        }
    }
}

}

Examples of good gotos in C or C++

I don't use goto's myself, however I did work with a person once that would use them in specific cases. If I remember correctly, his rationale was around performance issues - he also had specific rules for how. Always in the same function, and the label was always BELOW the goto statement.

Copying a rsa public key to clipboard

Another alternative solution:

cat  ~/.ssh/id_rsa.pub |  xsel -i -b

From man xsel :

-i, --input

read standard input into the selection.

-b, --clipboard

operate on the CLIPBOARD selection.

"Cannot update paths and switch to branch at the same time"

You could follow these steps when you stumble upon this issue:

  1. Run the following command to list the branches known for your local repository.

git remote show origin

which outputs this:

 remote origin
  Fetch URL: <your_git_path>
  Push  URL: <your_git_path>
  HEAD branch: development
  Remote branches:
    development                             tracked
    Feature2                                tracked
    master                                  tracked
    refs/remotes/origin/Feature1         stale (use 'git remote prune' to remove)
  Local branches configured for 'git pull':
    Feature2     merges with remote Feature2
    development  merges with remote development
    master       merges with remote master
  Local refs configured for 'git push':
    Feature2     pushes to Feature2     (up to date)
    development  pushes to development (up to date)
    master       pushes to master      (local out of date)
  1. After verifying the details like (fetch URL, etc), run this command to fetch any new branch(i.e. which you may want to checkout in your local repo) that exist in the remote but not in your local.
» git remote update

Fetching origin
From gitlab.domain.local:ProjectGroupName/ProjectName
 * [new branch]      Feature3    -> Feature3

As you can see the new branch has been fetched from remote.
3. Finally, checkout the branch with this command

» git checkout -b Feature3 origin/Feature3

Branch Feature3 set up to track remote branch Feature3 from origin.
Switched to a new branch 'Feature3'

It is not necessary to explicitly tell Git to track(using --track) the branch with remote.

The above command will set the local branch to track the remote branch from origin.

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

How to write a link like <a href="#id"> which link to the same page in PHP?

Edit:

Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs


See the working example: http://jsfiddle.net/U6aKT/

<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>

React-Router: No Not Found Route?

In newer versions of react-router you want to wrap the routes in a Switch which only renders the first matched component. Otherwise you would see multiple components rendered.

For example:

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Route,
  browserHistory,
  Switch
} from 'react-router-dom';

import App from './app/App';
import Welcome from './app/Welcome';
import NotFound from './app/NotFound';

const Root = () => (
  <Router history={browserHistory}>
    <Switch>
      <Route exact path="/" component={App}/>
      <Route path="/welcome" component={Welcome}/>
      <Route component={NotFound}/>
    </Switch>
  </Router>
);

ReactDOM.render(
  <Root/>,
  document.getElementById('root')
);

Strtotime() doesn't work with dd/mm/YYYY format

I haven't found a better solution. You can use explode(), preg_match_all(), etc.

I have a static helper function like this

class Date {

    public static function ausStrToTime($str) {
        $dateTokens = explode('/', $str);
        return strtotime($dateTokens[1] . '/' . $dateTokens[0] . '/' . $dateTokens[2]); 

    }

}

There is probably a better name for that, but I use ausStrToTime() because it works with Australian dates (which I often deal with, being an Australian). A better name would probably be the standardised name, but I'm not sure what that is.

Standard deviation of a list

In Python 2.7.1, you may calculate standard deviation using numpy.std() for:

  • Population std: Just use numpy.std() with no additional arguments besides to your data list.
  • Sample std: You need to pass ddof (i.e. Delta Degrees of Freedom) set to 1, as in the following example:

numpy.std(< your-list >, ddof=1)

The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

It calculates sample std rather than population std.

Maven Unable to locate the Javac Compiler in:

If you we are doing all above steps that may be confused and our problem is just missing tools.jre so just add tools.jre by the following steps and problem is solved.

Step 1 : In eclipse go to Windows -> preferences

Step 2 : Java -> Installed JREs (Double click on it)

Step 3 : Click Edit button -> Click Add External JARs

Step 4 : Now select tools.jar path

now apply changes and it works fine.

Here is screenshoot

How to effectively work with multiple files in Vim

You can be an absolute madman and alias vim to vim -p by adding in your .bashrc:

alias vim="vim -p"

This will result in opening multiple files from the shell in tabs, without having to invoke :tab ball from within vim afterwards.

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

Try:

Install all the required tools and configurations using Microsoft's windows-build-tools by running npm install -g windows-build-tools from an elevated PowerShell (run as Administrator).

https://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#environment-setup-and-configuration

jQuery Keypress Arrow Keys

You can check wether an arrow key is pressed by:

$(document).keydown(function(e){
    if (e.keyCode > 36 && e.keyCode < 41) 
      alert( "arrowkey pressed" );          
});

jsfiddle demo

Java: Getting a substring from a string starting after a particular character

This can also get the filename

import java.nio.file.Paths;
import java.nio.file.Path;
Path path = Paths.get("/abc/def/ghfj.doc");
System.out.println(path.getFileName().toString());

Will print ghfj.doc

Check if string contains a value in array

$string = 'my domain name is website3.com';
$a = array('website1.com','website2.com','website3.com');

$result = count(array_filter($a, create_function('$e','return strstr("'.$string.'", $e);')))>0; 
var_dump($result );

output

bool(true)

Do we have router.reload in vue-router?

this.$router.go() does exactly this; if no arguments are specified, the router navigates to current location, refreshing the page.

note: current implementation of router and its history components don't mark the param as optional, but IMVHO it's either a bug or an omission on Evan You's part, since the spec explicitly allows it. I've filed an issue report about it. If you're really concerned with current TS annotations, just use the equivalent this.$router.go(0)

As to 'why is it so': go internally passes its arguments to window.history.go, so its equal to windows.history.go() - which, in turn, reloads the page, as per MDN doc.

note: since this executes a "soft" reload on regular desktop (non-portable) Firefox, a bunch of strange quirks may appear if you use it but in fact you require a true reload; using the window.location.reload(true); (https://developer.mozilla.org/en-US/docs/Web/API/Location/reload) mentioned by OP instead may help - it certainly did solve my problems on FF.

Integrating CSS star rating into an HTML form

Here is how to integrate CSS star rating into an HTML form without using javascript (only html and css):

CSS:

.txt-center {
    text-align: center;
}
.hide {
    display: none;
}

.clear {
    float: none;
    clear: both;
}

.rating {
    width: 90px;
    unicode-bidi: bidi-override;
    direction: rtl;
    text-align: center;
    position: relative;
}

.rating > label {
    float: right;
    display: inline;
    padding: 0;
    margin: 0;
    position: relative;
    width: 1.1em;
    cursor: pointer;
    color: #000;
}

.rating > label:hover,
.rating > label:hover ~ label,
.rating > input.radio-btn:checked ~ label {
    color: transparent;
}

.rating > label:hover:before,
.rating > label:hover ~ label:before,
.rating > input.radio-btn:checked ~ label:before,
.rating > input.radio-btn:checked ~ label:before {
    content: "\2605";
    position: absolute;
    left: 0;
    color: #FFD700;
}

HTML:

<div class="txt-center">
    <form>
        <div class="rating">
            <input id="star5" name="star" type="radio" value="5" class="radio-btn hide" />
            <label for="star5">?</label>
            <input id="star4" name="star" type="radio" value="4" class="radio-btn hide" />
            <label for="star4">?</label>
            <input id="star3" name="star" type="radio" value="3" class="radio-btn hide" />
            <label for="star3">?</label>
            <input id="star2" name="star" type="radio" value="2" class="radio-btn hide" />
            <label for="star2">?</label>
            <input id="star1" name="star" type="radio" value="1" class="radio-btn hide" />
            <label for="star1">?</label>
            <div class="clear"></div>
        </div>
    </form>
</div>

Please check the demo

font size in html code

There are a couple of answers posted here that will give you the text effects you want, but...

The thing about tables is that they are organized collections of labels and data. Having both a label ("Datum") and the value that it labels in the same cell is oh so very wrong. The label should be in a <th> element, with the value in a <td> either in the same row or the same column (depending on the data arrangement you are trying to achieve). You can have <th> elements running either vertically or horizontally or both, but if you don't have heading cells (which is what <th> means), you don't have a table, you just have a meaningless grid of text. It would be preferable, too, to have a <caption> element to label the table as a whole (you don't have to display the caption, but it should be there for accessibility) and have a summary="blah blah blah" attribute in the table tag, again for accessibility. So your HTML should probably look a lot more like this:

<html>
  <head>
    <title>Test page with Table<title>
    <style type="text/css">
      th {
        font-size: 35px;
        font-weight: bold;
        padding-left: 5px;
        padding-bottom: 3px;
      }
    </style>
  </head>
  <body>
    <table id="table_1" summary="This table has both labels and values">
      <caption>Table of Stuff</caption>
      <tr>
        <th>Datum</th>
        <td>November 2010</td>
      </tr>
    </table>
  </body>
</html>

That may not be exactly what you want -- it's hard to tell whether November 2010 is a data point or a label from what you've posted, and "Datum" isn't a helpful label in any case. Play with it a bit, but make sure that when your table is finished it actually has some kind of semantic meaning. If it's not a real table of data, then don't use a <table> to lay it out.

How much overhead does SSL impose?

Order of magnitude: zero.

In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the "duplicate" question focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.

The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.


Here's an interesting anecdote. When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.

How to delete a remote tag?

To remove the tag from the remote repository:

git push --delete origin TAGNAME

You may also want to delete the tag locally:

git tag -d TAGNAME

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

You did not need

Options Indexes FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order Allow,Deny
Allow from all
Require all granted

the only thing what you need is...

Require all granted

...inside the directory section.

See Apache 2.4 upgrading side:

http://httpd.apache.org/docs/2.4/upgrading.html

Javascript : get <img> src and set as variable?

If you don't have an id on the image but have a parent div this is also a technique you can use.

<div id="myDiv"><img src="http://www.example.com/image.png"></div>

var myVar = document.querySelectorAll('#myDiv img')[0].src

Getting an element from a Set

With Java 8 you can do:

Foo foo = set.stream().filter(item->item.equals(theItemYouAreLookingFor)).findFirst().get();

But be careful, .get() throws a NoSuchElementException, or you can manipulate a Optional item.

Find what 2 numbers add to something and multiply to something

Come on guys, there is no need to loop, just use simple math to solve this equation system:

a*b = i;

a+b = j;

a = j/b;

a = i-b;

j/b = i-b; so:

b + j/b + i = 0

b^2 + i*b + j = 0

From here, its a quadratic equation, and it's trivial to find b (just implement the quadratic equation formula) and from there get the value for a.

EDIT:

There you go:

function finder($add,$product)
{

 $inside_root = $add*$add - 4*$product;

 if($inside_root >=0)
 {

     $b = ($add + sqrt($inside_root))/2;
     $a = $add - $b;

     echo "$a+$b = $add and $a*$b=$product\n";

 }else
 {
   echo "No real solution\n";
 }
}

Real live action:

http://codepad.org/JBxMgHBd

How to count frequency of characters in a string?

String s = "aaaabbbbcccddddd";
Map<Character, Integer> map = new HashMap<>();

Using one line in Java8

s.chars().forEach(e->map.put((char)e, map.getOrDefault((char)e, 0) + 1));

Create an empty object in JavaScript with {} or new Object()?

Objects

There is no benefit to using new Object(); - whereas {}; can make your code more compact, and more readable.

For defining empty objects they're technically the same. The {} syntax is shorter, neater (less Java-ish), and allows you to instantly populate the object inline - like so:

var myObject = {
        title:  'Frog',
        url:    '/img/picture.jpg',
        width:  300,
        height: 200
      };

Arrays

For arrays, there's similarly almost no benefit to ever using new Array(); over []; - with one minor exception:

var emptyArray = new Array(100);

creates a 100 item long array with all slots containing undefined - which may be nice/useful in certain situations (such as (new Array(9)).join('Na-Na ') + 'Batman!').

My recommendation

  1. Never use new Object(); - it's clunkier than {}; and looks silly.
  2. Always use []; - except when you need to quickly create an "empty" array with a predefined length.

Log all requests from the python-requests module

I'm using a logger_config.yaml file to configure my logging, and to get those logs to show up, all I had to do was to add a disable_existing_loggers: False to the end of it.

My logging setup is rather extensive and confusing, so I don't even know a good way to explain it here, but if someone's also using a YAML file to configure their logging, this might help.

https://docs.python.org/3/howto/logging.html#configuring-logging

How to find all occurrences of a substring?

Again, old thread, but here's my solution using a generator and plain str.find.

def findall(p, s):
    '''Yields all the positions of
    the pattern p in the string s.'''
    i = s.find(p)
    while i != -1:
        yield i
        i = s.find(p, i+1)

Example

x = 'banananassantana'
[(i, x[i:i+2]) for i in findall('na', x)]

returns

[(2, 'na'), (4, 'na'), (6, 'na'), (14, 'na')]

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

Is there a unique Android device ID?

Also you might consider the Wi-Fi adapter's MAC address. Retrieved like this:

WifiManager wm = (WifiManager)Ctxt.getSystemService(Context.WIFI_SERVICE);
return wm.getConnectionInfo().getMacAddress();

Requires permission android.permission.ACCESS_WIFI_STATE in the manifest.

Reported to be available even when Wi-Fi is not connected. If Joe from the answer above gives this one a try on his many devices, that'd be nice.

On some devices, it's not available when Wi-Fi is turned off.

NOTE: From Android 6.x, it returns consistent fake mac address: 02:00:00:00:00:00

How to express a One-To-Many relationship in Django

While rolling stone's answer is good, straightforward and functional, I think there are two things it does not solve.

  1. If OP wanted to enforce a phone number cannot belong to both a Dude and a Business
  2. The inescapable feeling of sadness as a result of defining the relationship on the PhoneNumber model and not on the Dude/Business models. When extra terrestrials come to Earth, and we want to add an Alien model, we need to modify the PhoneNumber (assuming the ETs have phone numbers) instead of simply adding a "phone_numbers" field to the Alien model.

Introduce the content types framework, which exposes some objects that allow us to create a "generic foreign key" on the PhoneNumber model. Then, we can define the reverse relationship on Dude and Business

from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models

class PhoneNumber(models.Model):
    number = models.CharField()

    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    owner = GenericForeignKey()

class Dude(models.Model):
    numbers = GenericRelation(PhoneNumber)

class Business(models.Model):
    numbers = GenericRelation(PhoneNumber)

See the docs for details, and perhaps check out this article for a quick tutorial.

Also, here is an article that argues against the use of Generic FKs.

Android: Clear the back stack

I tried all solutions and none worked individually for me. My Solution is :

Declare Activity A as SingleTop by using [android:launchMode="singleTop"] in Android manifest.

Now add the following flags while launching A from anywhere. It will clear the stack.

Intent in = new Intent(mContext, A.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK );
startActivity(in);
finish();

Convert timestamp to date in Oracle SQL

CAST(timestamp_expression AS DATE)

For example, The query is : SELECT CAST(SYSTIMESTAMP AS DATE) FROM dual;

Ubuntu: OpenJDK 8 - Unable to locate package

I'm getting OpenJDK 8 from the official Debian repositories, rather than some random PPA or non-free Oracle binary. Here's how I did it:

sudo apt-get install debian-keyring debian-archive-keyring

Make /etc/apt/sources.list.d/debian-jessie-backports.list:

deb http://httpredir.debian.org/debian/ jessie-backports main

Make /etc/apt/preferences.d/debian-jessie-backports:

Package: *
Pin: release o=Debian,a=jessie-backports
Pin-Priority: -200

Then finally do the install:

sudo apt-get update
sudo apt-get -t jessie-backports install openjdk-8-jdk

Add items to comboBox in WPF

With OleDBConnection -> connect to Oracle

OleDbConnection con = new OleDbConnection();
            con.ConnectionString = "Provider=MSDAORA;Data Source=oracle;Persist Security Info=True;User ID=system;Password=**********;Unicode=True";

            OleDbCommand comd1 = new OleDbCommand("select name from table", con);
            OleDbDataReader DR = comd1.ExecuteReader();
            while (DR.Read())
            {
                comboBox_delete.Items.Add(DR[0]);
            }
            con.Close();

That's all :)

Windows command to convert Unix line endings?

I'm taking an AWS course and have frequently had to copy from text boxes in the AWS web forms to Windows Notepad. So I get the LF-delimited text only on my clipboard. I accidentally discovered that pasting it into my Delphi editor, and then hitting Ctrl+K+W will write the text to a file with CR+LF delimiters. (I'll bet many other IDE editors would do the same).

How to update RecyclerView Adapter Data?

I've solved the same problem in a different way. I don't have data I waiting for it from the background thread so start with an emty list.

        mAdapter = new ModelAdapter(getContext(),new ArrayList<Model>());
   // then when i get data

        mAdapter.update(response.getModelList());
  //  and update is in my adapter

        public void update(ArrayList<Model> modelList){
            adapterModelList.clear(); 
            for (Product model: modelList) {
                adapterModelList.add(model); 
            }
           mAdapter.notifyDataSetChanged();
        }

That's it.

Axios get in url works but with second parameter as object it doesn't

axios.get accepts a request config as the second parameter (not query string params).

You can use the params config option to set query string params as follows:

axios.get('/api', {
  params: {
    foo: 'bar'
  }
});

How to check for null in Twig?

How to set default values in twig: http://twig.sensiolabs.org/doc/filters/default.html

{{ my_var | default("my_var doesn't exist") }}

Or if you don't want it to display when null:

{{ my_var | default("") }}

How to unpack an .asar file?

From the asar documentation

(the use of npx here is to avoid to install the asar tool globally with npm install -g asar)

Extract the whole archive:

npx asar extract app.asar destfolder 

Extract a particular file:

npx asar extract-file app.asar main.js

How to append to the end of an empty list?

I personally prefer the + operator than append:

for i in range(0, n):

    list1 += [[i]]

But this is creating a new list every time, so might not be the best if performance is critical.

Java - No enclosing instance of type Foo is accessible

static class Thing will make your program work.

As it is, you've got Thing as an inner class, which (by definition) is associated with a particular instance of Hello (even if it never uses or refers to it), which means it's an error to say new Thing(); without having a particular Hello instance in scope.

If you declare it as a static class instead, then it's a "nested" class, which doesn't need a particular Hello instance.

Failed to authenticate on SMTP server error using gmail

This is how I solved this issue:

  1. Change the .env file as follow

Screenshot Reference

  1. Never forget to restart the server after you change the .env file

Send FormData with other field in AngularJS

This never gonna work, you can't stringify your FormData object.

You should do this:

this.uploadFileToUrl = function(file, title, text, uploadUrl){
   var fd = new FormData();
   fd.append('title', title);
   fd.append('text', text);
   fd.append('file', file);

     $http.post(uploadUrl, obj, {
       transformRequest: angular.identity,
       headers: {'Content-Type': undefined}
     })
  .success(function(){
    blockUI.stop();
  })
  .error(function(error){
    toaster.pop('error', 'Errore', error);
  });
}

jquery save json data object in cookie

It is not good practice to save the value that is returned from JSON.stringify(userData) to a cookie; it can lead to a bug in some browsers.

Before using it, you should convert it to base64 (using btoa), and when reading it, convert from base64 (using atob).

val = JSON.stringify(userData)
val = btoa(val)

write_cookie(val)

Uncompress tar.gz file

Use -C option of tar:

tar zxvf <yourfile>.tar.gz -C /usr/src/

and then, the content of the tar should be in:

/usr/src/<yourfile>

Get file name from URL

If you don't need to get rid of the file extension, here's a way to do it without resorting to error-prone String manipulation and without using external libraries. Works with Java 1.7+:

import java.net.URI
import java.nio.file.Paths

String url = "http://example.org/file?p=foo&q=bar"
String filename = Paths.get(new URI(url).getPath()).getFileName().toString()

Using Django time/date widgets in custom form

What about just assigning a class to your widget and then binding that class to the JQuery datepicker?

Django forms.py:

class MyForm(forms.ModelForm):

  class Meta:
    model = MyModel

  def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['my_date_field'].widget.attrs['class'] = 'datepicker'

And some JavaScript for the template:

  $(".datepicker").datepicker();

Automatically plot different colored lines

Actually, a decent shortcut method for getting the colors to cycle is to use hold all; in place of hold on;. Each successive plot will rotate (automatically for you) through MATLAB's default colormap.

From the MATLAB site on hold:

hold all holds the plot and the current line color and line style so that subsequent plotting commands do not reset the ColorOrder and LineStyleOrder property values to the beginning of the list. Plotting commands continue cycling through the predefined colors and linestyles from where the last plot stopped in the list.

summing two columns in a pandas dataframe

Same think can be done using lambda function. Here I am reading the data from a xlsx file.

import pandas as pd
df = pd.read_excel("data.xlsx", sheet_name = 4)
print df

Output:

  cluster Unnamed: 1      date  budget  actual
0       a 2014-01-01  00:00:00   11000   10000
1       a 2014-02-01  00:00:00    1200    1000
2       a 2014-03-01  00:00:00     200     100
3       b 2014-04-01  00:00:00     200     300
4       b 2014-05-01  00:00:00     400     450
5       c 2014-06-01  00:00:00     700    1000
6       c 2014-07-01  00:00:00    1200    1000
7       c 2014-08-01  00:00:00     200     100
8       c 2014-09-01  00:00:00     200     300

Sum two columns into 3rd new one.

df['variance'] = df.apply(lambda x: x['budget'] + x['actual'], axis=1)
print df

Output:

  cluster Unnamed: 1      date  budget  actual  variance
0       a 2014-01-01  00:00:00   11000   10000     21000
1       a 2014-02-01  00:00:00    1200    1000      2200
2       a 2014-03-01  00:00:00     200     100       300
3       b 2014-04-01  00:00:00     200     300       500
4       b 2014-05-01  00:00:00     400     450       850
5       c 2014-06-01  00:00:00     700    1000      1700
6       c 2014-07-01  00:00:00    1200    1000      2200
7       c 2014-08-01  00:00:00     200     100       300
8       c 2014-09-01  00:00:00     200     300       500

How to compare Boolean?

Using direct conditions (like ==, !=, !condition) will have a slight performance improvement over the .equals(condition) as in one case you are calling the method from an object whereas direct comparisons are performed directly.

how can select from drop down menu and call javascript function

<script type="text/javascript">
function report(func)
{
    func();
}

function daily()
{
    alert('daily');
}

function monthly()
{
    alert('monthly');
}
</script>

Rails.env vs RAILS_ENV

Strange behaviour while debugging my app: require "active_support/notifications" (rdb:1) p ENV['RAILS_ENV'] "test" (rdb:1) p Rails.env "development"

I would say that you should stick to one or another (and preferably Rails.env)

Error inflating class android.support.v7.widget.Toolbar?

In the case of Xamarin in VS, you must add

Theme = "@style/MyThemesss"

to youractivity.cs.

I add this and go on.

HTML input - name vs. id

Adding some actual references to W3 docs that authoritatively explain the role of the 'name' attribute on form elements. (For what it's worth, I arrived here while exploring exactly how Stripe.js works to implement safe interaction with payment gateway Stripe. In particular, what causes a form input element to get submitted back to the server, or prevents it from being submitted?)

The following W3 docs are relevent:

HTML 4: https://www.w3.org/TR/html401/interact/forms.html#control-name Section 17.2 Controls

HTML 5: https://www.w3.org/TR/html5/forms.html#form-submission-0 and https://www.w3.org/TR/html5/forms.html#constructing-the-form-data-set Section 4.10.22.4 Constructing the form data set.

As explained therein, an input element will be submitted by the browser if and only if it has a valid 'name' attribute.

As others have noted, the 'id' attribute uniquely identifies DOM elements, but is not involved in normal form submission. (Though 'id' or other attributes can of course be used by javascript to obtain form values, which javascript could then use for AJAX submissions and so on.)

One oddity regarding previous answers/commenters concern about id's values and name's values being in the same namespace. So far as I can tell from the specs, this applied to some deprecated uses of the name attribute (not on form elements). For example https://www.w3.org/TR/html5/obsolete.html:

"Authors should not specify the name attribute on a elements. If the attribute is present, its value must not be the empty string and must neither be equal to the value of any of the IDs in the element's home subtree other than the element's own ID, if any, nor be equal to the value of any of the other name attributes on a elements in the element's home subtree. If this attribute is present and the element has an ID, then the attribute's value must be equal to the element's ID. In earlier versions of the language, this attribute was intended as a way to specify possible targets for fragment identifiers in URLs. The id attribute should be used instead."

Clearly in this special case there's some overlap between id and name values for 'a' tags. But this seems to be a peculiarity of processing for fragment ids, not due to general sharing of namespace of ids and names.

REST API Best practice: How to accept list of parameter values as input

The standard way to pass a list of values as URL parameters is to repeat them:

http://our.api.com/Product?id=101404&id=7267261

Most server code will interpret this as a list of values, although many have single value simplifications so you may have to go looking.

Delimited values are also okay.

If you are needing to send JSON to the server, I don't like seeing it in in the URL (which is a different format). In particular, URLs have a size limitation (in practice if not in theory).

The way I have seen some do a complicated query RESTfully is in two steps:

  1. POST your query requirements, receiving back an ID (essentially creating a search criteria resource)
  2. GET the search, referencing the above ID
  3. optionally DELETE the query requirements if needed, but note that they requirements are available for reuse.

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

Just use

y_pred = (y_pred > 0.5)
accuracy_score(y_true, y_pred, normalize=False)

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

  1. Go to Sql Server Management Studio >
  2. Object Explorer >
  3. Databases >
  4. Choose and expand your Database.
  5. Under your database right click on "Database Diagrams" and select "New Database Diagram".
  6. It will a open a new window. Choose tables to include in ER-Diagram (to select multiple tables press "ctrl" or "shift" button and select tables).
  7. Click add.
  8. Wait for it to complete. Done!

You can save generated diagram for future use.

screenshot

jQuery: count number of rows in a table

Well, I get the attr rows from the table and get the length for that collection:

$("#myTable").attr('rows').length;

I think that jQuery works less.

What is key=lambda

A lambda is an anonymous function:

>>> f = lambda: 'foo'
>>> print f()
foo

It is often used in functions such as sorted() that take a callable as a parameter (often the key keyword parameter). You could provide an existing function instead of a lambda there too, as long as it is a callable object.

Take the sorted() function as an example. It'll return the given iterable in sorted order:

>>> sorted(['Some', 'words', 'sort', 'differently'])
['Some', 'differently', 'sort', 'words']

but that sorts uppercased words before words that are lowercased. Using the key keyword you can change each entry so it'll be sorted differently. We could lowercase all the words before sorting, for example:

>>> def lowercased(word): return word.lower()
...
>>> lowercased('Some')
'some'
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lowercased)
['differently', 'Some', 'sort', 'words']

We had to create a separate function for that, we could not inline the def lowercased() line into the sorted() expression:

>>> sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
  File "<stdin>", line 1
    sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
                                                           ^
SyntaxError: invalid syntax

A lambda on the other hand, can be specified directly, inline in the sorted() expression:

 >>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
['differently', 'Some', 'sort', 'words']

Lambdas are limited to one expression only, the result of which is the return value.

There are loads of places in the Python library, including built-in functions, that take a callable as keyword or positional argument. There are too many to name here, and they often play a different role.

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

There is a package called eclipse-cdt in the Ubuntu 12.10 repositories, this is what you want. If you haven't got g++ already, you need to install that as well, so all you need is:

sudo apt-get install eclipse eclipse-cdt g++

Whether you messed up your system with your previous installation attempts depends heavily on how you did it. If you did it the safe way for trying out new packages not from repositories (i.e., only installed in your home folder, no sudos blindly copied from installation manuals...) you're definitely fine. Otherwise, you may well have thousands of stray files all over your file system now. In that case, run all uninstall scripts you can find for the things you installed, then install using apt-get and hope for the best.

Using querySelectorAll to retrieve direct children

I am just doing this without even trying it. Would this work?

myDiv = getElementById("myDiv");
myDiv.querySelectorAll(this.id + " > .foo");

Give it a try, maybe it works maybe not. Apolovies, but I am not on a computer now to try it (responding from my iPhone).

There is already an open DataReader associated with this Command which must be closed first

This is extracted from a real world scenario:

  • Code works well in a Stage environment with MultipleActiveResultSets is set in the connection string
  • Code published to Production environment without MultipleActiveResultSets=true
  • So many pages/calls work while a single one is failing
  • Looking closer at the call, there is an unnecessary call made to the db and needs to be removed
  • Set MultipleActiveResultSets=true in Production and publish cleaned up code, everything works well and, efficiently

In conclusion, without forgetting about MultipleActiveResultSets, the code might have run for a long time before discovering a redundant db call that could be very costly, and I suggest not to fully depend on setting the MultipleActiveResultSets attribute but also find out why the code needs it where it failed.

Ajax - 500 Internal Server Error

One must use behavior: JsonRequestBehavior.AllowGet in Post Json Return in C#

OracleCommand SQL Parameters Binding

string strConn = "Data Source=ORCL134; User ID=user; Password=psd;";

System.Data.OracleClient.OracleConnection con = newSystem.Data.OracleClient.OracleConnection(strConn);
    con.Open();

    System.Data.OracleClient.OracleCommand Cmd = 
        new System.Data.OracleClient.OracleCommand(
            "SELECT * FROM TBLE_Name WHERE ColumnName_year= :year", con);

//for oracle..it is :object_name and for sql it s @object_name
    Cmd.Parameters.Add(new System.Data.OracleClient.OracleParameter("year", (txtFinYear.Text).ToString()));

    System.Data.OracleClient.OracleDataAdapter da = new System.Data.OracleClient.OracleDataAdapter(Cmd);
    DataSet myDS = new DataSet();
    da.Fill(myDS);
    try
    {
        lblBatch.Text = "Batch Number is : " + Convert.ToString(myDS.Tables[0].Rows[0][19]);
        lblBatch.ForeColor = System.Drawing.Color.Green;
        lblBatch.Visible = true;
    }
    catch 
    {
        lblBatch.Text = "No Data Found for the Year : " + txtFinYear.Text;
        lblBatch.ForeColor = System.Drawing.Color.Red;
        lblBatch.Visible = true;   
    }
    da.Dispose();
    con.Close();

nvm is not compatible with the npm config "prefix" option:

Note:
to remove, delete, or uninstall nvm - just remove the $NVM_DIR folder (usually ~/.nvm)
you can try :
rm -rf ~/.nvm

Sharing link on WhatsApp from mobile website (not application) for Android

LATEST UPDATE

Now you can use the latest API from whatsapp https://wa.me/ without worrying about the user agent, the API will do the user agent handling.

Share pre-filled text with contact selection option in respective whatsapp client (Android / iOS / Webapp):

https://wa.me/?text=urlencodedtext

Open Chat Dialog for a particular whatsapp user in respective whatsapp client (Android / iOS / Webapp):

https://wa.me/whatsappphonenumber

Share pre-filled text with a particular user (Combine above two):

https://wa.me/whatsappphonenumber/?text=urlencodedtext

Note : whatsappphonenumber should be full phone number in international format. Omit any zeroes, brackets or dashes when adding the phone number in international format.

For official documentation visit https://faq.whatsapp.com/en/general/26000030

How can I execute a python script from an html button?

There are various ways to make it done, very simple technique with security peace in mind, here might help you


1. First you need to install Flask
pip install flask
in your command prompt, which is a python microframework, don't be afraid that you need to have another prior knowledge to learn that, it's really simple and just a few line of code. If you wish you learn Flask quickly for complete novice here is the tutorial that I also learn from Flask Tutorial for beginner (YouTube)

2.Create a new folder
- 1st file will be server.py

_x000D_
_x000D_
from flask import Flask, render_template_x000D_
app = Flask(__name__)_x000D_
_x000D_
@app.route('/')_x000D_
def index():_x000D_
  return render_template('index.html')_x000D_
_x000D_
@app.route('/my-link/')_x000D_
def my_link():_x000D_
  print ('I got clicked!')_x000D_
_x000D_
  return 'Click.'_x000D_
_x000D_
if __name__ == '__main__':_x000D_
  app.run(debug=True)
_x000D_
_x000D_
_x000D_

-2nd create another subfolder inside previous folder and name it as templates file will be your html file
index.html

_x000D_
_x000D_
<!doctype html>_x000D_
_x000D_
_x000D_
<head><title>Test</title> _x000D_
    <meta charset=utf-8> </head>_x000D_
    <body>_x000D_
        <h1>My Website</h1>_x000D_
        <form action="/my-link/">_x000D_
            <input type="submit" value="Click me" />_x000D_
        </form>_x000D_
        _x000D_
        <button> <a href="/my-link/">Click me</a></button>_x000D_
_x000D_
    </body>
_x000D_
_x000D_
_x000D_

3.. To run, open command prompt to the New folder directory, type python server.py to run the script, then go to browser type localhost:5000, then you will see button. You can click and route to destination script file you created.

Hope this helpful. thank you.

How to handle the click event in Listview in android?

Error is coming in your code from this statement as you said

Intent intent = new Intent(context, SendMessage.class);

This is due to you are providing context of OnItemClickListener anonymous class into the Intent constructor but according to constructor of Intent

android.content.Intent.Intent(Context packageContext, Class<?> cls)

You have to provide context of you activity in which you are using intent that is the MainActivity class context. so your statement which is giving error will be converted to

Intent intent = new Intent(MainActivity.this, SendMessage.class);

Also for sending your message from this MainActivity to SendMessage class please see below code

lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
                Intent intent = new Intent(MainActivity.this, SendMessage.class);
                intent.putExtra(EXTRA_MESSAGE, entry.getMessage());
                startActivity(intent);
            }
        });

Please let me know if this helps you

EDIT:- If you are finding some issue to get the value of list do one thing declear your array list

ArrayList<ListEntry> members = new ArrayList<ListEntry>();

globally i.e. before oncreate and change your listener as below

 lv.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {
                    Intent intent = new Intent(MainActivity.this, SendMessage.class);
                    intent.putExtra(EXTRA_MESSAGE, members.get(position));
                    startActivity(intent);
                }
            });

So your whole code will look as

public class MainActivity extends Activity {
    public final static String EXTRA_MESSAGE = "com.example.ListViewTest.MESSAGE";
ArrayList<ListEntry> members = new ArrayList<ListEntry>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        members.add(new ListEntry("BBB","AAA",R.drawable.tab1_hdpi));
        members.add(new ListEntry("ccc","ddd",R.drawable.tab2_hdpi));
        members.add(new ListEntry("assa","cxv",R.drawable.tab3_hdpi));
        members.add(new ListEntry("BcxsadvBB","AcxdxvAA"));
        members.add(new ListEntry("BcxvadsBB","AcxzvAA"));
        members.add(new ListEntry("BcxvBB","AcxvAA"));
        members.add(new ListEntry("BvBB","AcxsvAA"));
        members.add(new ListEntry("BcxvBB","AcxsvzAA"));
        members.add(new ListEntry("Bcxadv","AcsxvAA"));
        members.add(new ListEntry("BcxcxB","AcxsvAA"));
        ListView lv = (ListView)findViewById(R.id.listView1);
        Log.i("testTag","before start adapter");
        StringArrayAdapter ad = new StringArrayAdapter (members,this);
        Log.i("testTag","after start adapter");
        Log.i("testTag","set adapter");
        lv.setAdapter(ad);
        lv.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
                        Intent intent = new Intent(MainActivity.this, SendMessage.class);
                        intent.putExtra(EXTRA_MESSAGE, members.get(position).getMessage());
                        startActivity(intent);
                    }
                });
    }

Where getMessage() will be a getter method specified in your ListEntry class which you are using to get message which was previously set.

Java function for arrays like PHP's join()?

My spin.

public static String join(Object[] objects, String delimiter) {
  if (objects.length == 0) {
    return "";
  }
  int capacityGuess = (objects.length * objects[0].toString().length())
      + ((objects.length - 1) * delimiter.length());
  StringBuilder ret = new StringBuilder(capacityGuess);
  ret.append(objects[0]);
  for (int i = 1; i < objects.length; i++) {
    ret.append(delimiter);
    ret.append(objects[i]);
  }
  return ret.toString();
}

public static String join(Object... objects) {
  return join(objects, "");
}

How to start activity in another application?

If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:

Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);

Hope it helps.

OnItemCLickListener not working in listview

you need to do 2 steps in your listview_item.xml

  1. set the root layout with: android:descendantFocusability="blocksDescendants"
  2. set any focusable or clickable view in this item with:
    android:clickable="false"
    android:focusable="false"
    android:focusableInTouchMode="false"

Here is an example: listview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:descendantFocusability="blocksDescendants">

    <RadioButton
        android:id="@+id/script_name_radio_btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textColor="#000"
        android:padding="5dp"
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false"
        />

</LinearLayout>

How to create .ipa file using Xcode?

In Xcode Version 10.0


  1. Go to Window -> Organizer
  2. Then select your app archive from archives
  3. Then click the "Distribute App" button on right panel

enter image description here

  1. Then follow the below steps

Step 1

enter image description here

Step 2

enter image description here

Step 3

enter image description here

Step 4

enter image description here

Step 5

enter image description here

Step 6 : Finally select the place you want to save the .ipa file

enter image description here

In Xcode Version 9.2


  1. Go to Window -> Organizer
  2. Then select your app archive from archives
  3. Then click the "Upload to App Store" button on right panel
  4. Then follow the following steps

Step 1 enter image description here

Step 2 enter image description here

Step 3 enter image description here

Step 4 Finally select the place you want to save the .ipa file

enter image description here

How to easily get network path to the file you are working on?

Answer to my own question. The only way I have found that works consistently and instantaneously is to:

1) Create a link in my "Favorites" to the directory I use

2) Update the properties on that favorite to be an absolute path (\\ads\IT-DEPT-DFS\Data\MAILROOM)

3) When saving a new file, I navigate to that directory only via the Favorites directory created above (or you can use any Shortcut with an absolute path)

4) After saving, go to the File tab and the full path can be copied from the top of the Info (default) section

Creating a constant Dictionary in C#

Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.

There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case tables are compiled to constant hash jump tables. That is, they are constant dictionaries, not a series of if-else statements. So consider a switch-case statement like this:

switch (myString)
{
   case "cat": return 0;
   case "dog": return 1;
   case "elephant": return 3;
}

This is exactly what you want. And yes, I know, it's ugly.

Database, Table and Column Naming Conventions?

our preference:

  1. Should table names be plural?
    Never. The arguments for it being a collection make sense, but you never know what the table is going to contain (0,1 or many items). Plural rules make the naming unnecessarily complicated. 1 House, 2 houses, mouse vs mice, person vs people, and we haven't even looked at any other languages.

    Update person set property = 'value' acts on each person in the table.
    Select * from person where person.name = 'Greg' returns a collection/rowset of person rows.

  2. Should column names be singular?
    Usually, yes, except where you are breaking normalisation rules.

  3. Should I prefix tables or columns?
    Mostly a platform preference. We prefer to prefix columns with the table name. We don't prefix tables, but we do prefix views (v_) and stored_procedures (sp_ or f_ (function)). That helps people who want to try to upday v_person.age which is actually a calculated field in a view (which can't be UPDATEd anyway).

    It is also a great way to avoid keyword collision (delivery.from breaks, but delivery_from does not).

    It does make the code more verbose, but often aids in readability.

    bob = new person()
    bob.person_name = 'Bob'
    bob.person_dob = '1958-12-21'
    ... is very readable and explicit. This can get out of hand though:

    customer.customer_customer_type_id

    indicates a relationship between customer and the customer_type table, indicates the primary key on the customer_type table (customer_type_id) and if you ever see 'customer_customer_type_id' whilst debugging a query, you know instantly where it is from (customer table).

    or where you have a M-M relationship between customer_type and customer_category (only certain types are available to certain categories)

    customer_category_customer_type_id

    ... is a little (!) on the long side.

  4. Should I use any case in naming items? Yes - lower case :), with underscores. These are very readable and cross platform. Together with 3 above it also makes sense.

    Most of these are preferences though. - As long as you are consistent, it should be predictable for anyone that has to read it.

Complex numbers usage in python

The following example for complex numbers should be self explanatory including the error message at the end

>>> x=complex(1,2)
>>> print x
(1+2j)
>>> y=complex(3,4)
>>> print y
(3+4j)
>>> z=x+y
>>> print x
(1+2j)
>>> print z
(4+6j)
>>> z=x*y
>>> print z
(-5+10j)
>>> z=x/y
>>> print z
(0.44+0.08j)
>>> print x.conjugate()
(1-2j)
>>> print x.imag
2.0
>>> print x.real
1.0
>>> print x>y

Traceback (most recent call last):
  File "<pyshell#149>", line 1, in <module>
    print x>y
TypeError: no ordering relation is defined for complex numbers
>>> print x==y
False
>>> 

HTML Entity Decode

jQuery provides a way to encode and decode html entities.

If you use a "<div/>" tag, it will strip out all the html.

function htmlDecode(value) {
    return $("<div/>").html(value).text();
}

function htmlEncode(value) {
    return $('<div/>').text(value).html();
}

If you use a "<textarea/>" tag, it will preserve the html tags.

function htmlDecode(value) {
    return $("<textarea/>").html(value).text();
}

function htmlEncode(value) {
    return $('<textarea/>').text(value).html();
}

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

I know this has been already answered a long time ago but the answer didnt fix it for me but, I just removed everything from the sources in the buildpath settings and re-added them

SQL Insert into table only if record doesn't exist

This might be a simple solution to achieve this:

INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
  FROM dual
 WHERE NOT EXISTS (SELECT 1 
                     FROM funds 
                    WHERE ID = 23
                      AND date = DATE('2013-02-12'));

p.s. alternatively (if ID a primary key):

 INSERT INTO funds (ID, date, price)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need

see this Fiddle.

TypeError: unsupported operand type(s) for /: 'str' and 'str'

I would have written:

percent = 100
while True:
     try:
        pyc = int(input('enter pyc :'))
        tpy = int(input('enter tpy:'))
        percent = (pyc / tpy) * percent
        break
     except ZeroDivisionError as detail:
        print 'Handling run-time error:', detail

Updating version numbers of modules in a multi-module Maven project

The given answer assumes that the project in question use project inheritance in addition to module aggregation. In fact those are distinct concepts:

https://maven.apache.org/guides/introduction/introduction-to-the-pom.html#Project_Inheritance_vs_Project_Aggregation

Some projects may be an aggregation of modules, yet not have a parent-child relationship between aggregator POM and the aggregated modules. (There may be no parent-child relationship at all, or the child modules may use a separate POM altogether as the "parent".) In these situations the given answer will not work.

After much reading and experimentation, it turns out there is a way to use the Versions Maven Plugin to update not only the aggregator POM but also all aggregated modules as well; it is the processAllModules option. The following command must be done in the directory of the aggregator project:

mvn versions:set -DnewVersion=2.50.1-SNAPSHOT -DprocessAllModules

The Versions Maven Plugin will not only update the versions of all contained modules, it will also update inter-module dependencies!!!! This is a huge win and will save a lot of time and prevent all sorts of problems.

Of course don't forget to commit the changes in all modules, which you can also do with the same switch:

mvn versions:commit -DprocessAllModules

You may decide to dispense with the backup POMS altogether and do everything in one command:

mvn versions:set -DnewVersion=2.50.1-SNAPSHOT -DprocessAllModules -DgenerateBackupPoms=false

Resize iframe height according to content height in it

You can do this with JavaScript.

document.getElementById('foo').height = document.getElementById('foo').contentWindow.document.body.scrollHeight + "px";

Common elements in two lists

Why reinvent the wheel? Use Commons Collections:

CollectionUtils.intersection(java.util.Collection a, java.util.Collection b)

How can I merge two commits into one if I already started rebase?

$ git rebase --abort

Run this code at any time if you want to undo the git rebase

$ git rebase -i HEAD~2

To reapply last two commits. The above command will open a code editor

  • [ The latest commit will be at the bottom ]. Change the last commit to squash(s). Since squash will meld with previous commit.
  • Then press esc key and type :wq to save and close

After :wq you will be in active rebase mode

Note: You'll get another editor if no warning/error messages, If there is an error or warning another editor will not show, you may abort by runnning $ git rebase --abort if you see an error or warning else just continue by running $ git rebase --continue

You will see your 2 commit message. Choose one or write your own commit message, save and quit [:wq]

Note 2: You may need to force push your changes to the remote repo if you run rebase command

$ git push -f

$ git push -f origin master

Span inside anchor or anchor inside span or doesn't matter?

It depends on what the span is for. If it refers to the text of the link, and not the fact that it is a link, choose #1. If the span refers to the link as a whole, then choose #2. Unless you explain what the span represents, there's not much more of an answer than that. They're both inline elements, can be syntactically nested in any order.

Search input with an icon Bootstrap 4

you can also do in this way using input-group

<div class="input-group">
  <input class="form-control"
         placeholder="I can help you to find anything you want!">
  <div class="input-group-addon" ><i class="fa fa-search"></i></div>
</div>

codeply

How to get cumulative sum

A CTE version, just for fun:

;
WITH  abcd
        AS ( SELECT id
                   ,SomeNumt
                   ,SomeNumt AS MySum
             FROM   @t
             WHERE  id = 1
             UNION ALL
             SELECT t.id
                   ,t.SomeNumt
                   ,t.SomeNumt + a.MySum AS MySum
             FROM   @t AS t
                    JOIN abcd AS a ON a.id = t.id - 1
           )
  SELECT  *  FROM    abcd
OPTION  ( MAXRECURSION 1000 ) -- limit recursion here, or 0 for no limit.

Returns:

id          SomeNumt    MySum
----------- ----------- -----------
1           10          10
2           12          22
3           3           25
4           15          40
5           23          63

How do you check whether a number is divisible by another number (Python)?

a = 1400
a1 = 5
a2 = 3

b= str(a/a1)
b1 = str(a/a2)
c =b[(len(b)-2):len(b)]
c1 =b[(len(b1)-2):len(b1)]
if c == ".0":
    print("yeah for 5!")
if c1 == ".0":
    print("yeah for 3!")

How to pre-populate the sms body text via an html link

For iOS 8, try this:

<a href="sms:/* phone number here */&body=/* body text here */">Link</a>

Switching the ";" with a "&" worked for me.

Easiest way to read/write a file's content in Python

This is same as above but does not handle errors:

s = open(filename, 'r').read()

Regular expression to match a word or its prefix

Square brackets are meant for character class, and you're actually trying to match any one of: s, |, s (again), e, a, s (again), o and n.

Use parentheses instead for grouping:

(s|season)

or non-capturing group:

(?:s|season)

Note: Non-capture groups tell the engine that it doesn't need to store the match, while the other one (capturing group does). For small stuff, either works, for 'heavy duty' stuff, you might want to see first if you need the match or not. If you don't, better use the non-capture group to allocate more memory for calculation instead of storing something you will never need to use.

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

How Can I Truncate A String In jQuery?

From: jQuery text truncation (read more style)

Try this:

var title = "This is your title";

var shortText = jQuery.trim(title).substring(0, 10)
    .split(" ").slice(0, -1).join(" ") + "...";

And you can also use a plugin:

As a extension of String

String.prototype.trimToLength = function(m) {
  return (this.length > m) 
    ? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
    : this;
};

Use as

"This is your title".trimToLength(10);

ExecJS and could not find a JavaScript runtime

Don't Use RubyRacer as it is bad on memory. Installing Node.js as suggested by some people here is a better idea.

This list of available runtimes that can be used by ExecJs Library also documents the use of Node.js

https://github.com/sstephenson/execjs

So, Node.js is not an overkill, and much better solution than using the RubyRacer.

What is the Difference Between Mercurial and Git?

Git is a platform, Mercurial is “just” an application. Git is a versioned filesystem platform that happens to ship with a DVCS app in the box, but as normal for platform apps, it is more complex and has rougher edges than focused apps do. But this also means git’s VCS is immensely flexible, and there is a huge depth of non-source-control things you can do with git.

That is the essence of the difference.

Git is best understood from the ground up – from the repository format up. Scott Chacon’s Git Talk is an excellent primer for this. If you try to use git without knowing what’s happening under the hood, you’ll end up confused at some point (unless you stick to only very basic functionality). This may sound stupid when all you want is a DVCS for your daily programming routine, but the genius of git is that the repository format is actually very simple and you can understand git’s entire operation quite easily.

For some more technicality-oriented comparisons, the best articles I have personally seen are Dustin Sallings’:

He has actually used both DVCSs extensively and understands them both well – and ended up preferring git.

What do I use for a max-heap implementation in Python?

Allowing you to chose an arbitrary amount of largest or smallest items

import heapq
heap = [23, 7, -4, 18, 23, 42, 37, 2, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
heapq.heapify(heap)
print(heapq.nlargest(3, heap))  # [42, 42, 37]
print(heapq.nsmallest(3, heap)) # [-4, -4, 2]

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

This can easily happen when you have 2 different databases and specially 2 different databases from 2 different servers. Best option is to change it to a common collection and do the join or comparison.

SELECT 
   *
FROM sd
INNER JOIN pd ON sd.SCaseflowID COLLATE Latin1_General_CS_AS = pd.PDebt_code COLLATE Latin1_General_CS_AS

remote rejected master -> master (pre-receive hook declined)

If you run $ heroku logs you may get a "hint" to what the problem is. For me, Heroku could not detect what type of app I was creating. It required me to set the buildpack. Since I was creating a Node.js app, I just had to run $ heroku buildpacks:set https://github.com/heroku/heroku-buildpack-nodejs. You can read more about it here: https://devcenter.heroku.com/articles/buildpacks. No pushing issues after that.

I know this is an old question, but still posting this here incase someone else gets stuck.

What regex will match every character except comma ',' or semi-colon ';'?

[^,;]+         

You haven't specified the regex implementation you are using. Most of them have a Split method that takes delimiters and split by them. You might want to use that one with a "normal" (without ^) character class:

[,;]+

How to run PowerShell in CMD

I'd like to add the following to Shay Levy's correct answer: You can make your life easier if you create a little batch script run.cmd to launch your powershell script:

@echo off & setlocal
set batchPath=%~dp0
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" "MY-PC"

Put it in the same path as SQLExecutor.ps1 and from now on you can run it by simply double-clicking on run.cmd.


Note:

  • If you require command line arguments inside the run.cmd batch, simply pass them as %1 ... %9 (or use %* to pass all parameters) to the powershell script, i.e.
    powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" %*

  • The variable batchPath contains the executing path of the batch file itself (this is what the expression %~dp0 is used for). So you just put the powershell script in the same path as the calling batch file.

How do I write a correct micro-benchmark in Java?

If you are trying to compare two algorithms, do at least two benchmarks for each, alternating the order. i.e.:

for(i=1..n)
  alg1();
for(i=1..n)
  alg2();
for(i=1..n)
  alg2();
for(i=1..n)
  alg1();

I have found some noticeable differences (5-10% sometimes) in the runtime of the same algorithm in different passes..

Also, make sure that n is very large, so that the runtime of each loop is at the very least 10 seconds or so. The more iterations, the more significant figures in your benchmark time and the more reliable that data is.

Git, fatal: The remote end hung up unexpectedly

Based on the protocol you are using to push to your repo

HTTP

git config --global http.postBuffer 157286400

References:

SSH

Add the following in ~/.ssh/config file in your linux machine

Host your-gitlab-server.com
  ServerAliveInterval 60
  ServerAliveCountMax 5
  IPQoS throughput

References:

How to redirect to logon page when session State time out is completed in asp.net mvc

One way is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Login page.

But this is very hectic method To over come this you need to create your own ActionFilterAttribute which will do this, you just need to add this attribute in every action method.

Here is the Class which overrides ActionFilterAttribute.

public class SessionExpireFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;

            // check if session is supported
            CurrentCustomer objCurrentCustomer = new CurrentCustomer();
            objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
            if (objCurrentCustomer == null)
            {
                // check if a new session id was generated
                filterContext.Result = new RedirectResult("~/Users/Login");
                return;
            }

            base.OnActionExecuting(filterContext);
        }
    }

Then in action just add this attribute like so:

[SessionExpire]
public ActionResult Index()
{
     return Index();
}

This will do you work.

JPA Native Query select and cast object

You might want to try one of the following ways:

  • Using the method createNativeQuery(sqlString, resultClass)

    Native queries can also be defined dynamically using the EntityManager.createNativeQuery() API.

    String sql = "SELECT USER.* FROM USER_ AS USER WHERE ID = ?";
    
    Query query = em.createNativeQuery(sql, User.class);
    query.setParameter(1, id);
    User user = (User) query.getSingleResult();
    
  • Using the annotation @NamedNativeQuery

    Native queries are defined through the @NamedNativeQuery and @NamedNativeQueries annotations, or <named-native-query> XML element.

    @NamedNativeQuery(
        name="complexQuery",
        query="SELECT USER.* FROM USER_ AS USER WHERE ID = ?",
        resultClass=User.class
    )
    public class User { ... }
    
    Query query = em.createNamedQuery("complexQuery", User.class);
    query.setParameter(1, id);
    User user = (User) query.getSingleResult();
    

You can read more in the excellent open book Java Persistence (available in PDF).

-------
NOTE: With regard to use of getSingleResult(), see Why you should never use getSingleResult() in JPA.

using CASE in the WHERE clause

This is working Oracle example but it should work in MySQL too.

You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value.

SELECT empno, ename, job
  FROM scott.emp
 WHERE (CASE WHEN job = 'MANAGER' THEN '1'  
         WHEN job = 'CLERK'   THEN '2' 
         ELSE '0'  END) IN (1, 2)

How to put two divs side by side

I am just giving the code for two responsive divs side by side

_x000D_
_x000D_
*{
  margin: 0;
  padding: 0;
}

#parent {
  display: flex;
  justify-content: space-around;
}

#left {
  border: 1px solid lightgray;
  background-color: red;
  width: 40%;
}

#right {
  border: 1px solid lightgray;
  background-color: green;
  width: 40%;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="parent">
        <div id="left">
        lorem ipsum dolor sit emet
        </div>
        <div id="right">
        lorem ipsum dolor sit emet
        </div>
    </div>
</body>
</html>
_x000D_
_x000D_
_x000D_

Ansible: create a user with sudo privileges

Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.

Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.

The answer to my question is at Ansible: best practice for maintaining list of sudoers.

The Ansible playbook code fragment looks like this from my problem:

- name: Make sure we have a 'wheel' group
  group:
    name: wheel
    state: present

- name: Allow 'wheel' group to have passwordless sudo
  lineinfile:
    dest: /etc/sudoers
    state: present
    regexp: '^%wheel'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'
    validate: 'visudo -cf %s'

- name: Add sudoers users to wheel group
  user:
    name=deployer
    groups=wheel
    append=yes
    state=present
    createhome=yes

- name: Set up authorized keys for the deployer user
  authorized_key: user=deployer key="{{item}}"
  with_file:
    - /home/railsdev/.ssh/id_rsa.pub

And the best part is that the solution is idempotent. It doesn't add the line

%wheel ALL=(ALL) NOPASSWD: ALL

to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

Matching an empty input box using CSS

If only the field is required you could go with input:valid

_x000D_
_x000D_
#foo-thing:valid + .msg { visibility: visible!important; }      
_x000D_
 <input type="text" id="foo-thing" required="required">_x000D_
 <span class="msg" style="visibility: hidden;">Yay not empty</span>
_x000D_
_x000D_
_x000D_

See live on jsFiddle

OR negate using #foo-thing:invalid (credit to @SamGoody)

Adding elements to an xml file in C#

You need to create a new XAttribute instead of XElement. Try something like this:

public static void Test()
{
    var xdoc = XDocument.Parse(@"
        <Snippets>

          <Snippet name='abc'>
            <SnippetCode>
              testcode1
            </SnippetCode>
          </Snippet>

          <Snippet name='xyz'>
            <SnippetCode>      
             testcode2
            </SnippetCode>
          </Snippet>

        </Snippets>");

    xdoc.Root.Add(
        new XElement("Snippet",
            new XAttribute("name", "name goes here"),
            new XElement("SnippetCode", "SnippetCode"))
    );
    xdoc.Save(@"C:\TEMP\FOO.XML");
}

This generates the output:

<?xml version="1.0" encoding="utf-8"?>
<Snippets>
  <Snippet name="abc">
    <SnippetCode>
      testcode1
    </SnippetCode>
  </Snippet>
  <Snippet name="xyz">
    <SnippetCode>      
     testcode2
    </SnippetCode>
  </Snippet>
  <Snippet name="name goes here">
    <SnippetCode>SnippetCode</SnippetCode>
  </Snippet>
</Snippets>

How to check if "Radiobutton" is checked?

You can also maintain a flag value based on listener,

 radioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {

                //handle the boolean flag here. 
                  if(arg1==true)
                         //Do something

                else 
                    //do something else

            }
        });

Or simply isChecked() can also be used to check the state of your RadioButton.

Here is a link to a sample,

http://www.mkyong.com/android/android-radio-buttons-example/

And then based on the flag you can execute your function.

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

Here is where you went wrong:

this.result = http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result.json());

it should be:

http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result);

or

http.get('friends.json')
                  .subscribe(result => this.result =result.json());

You have made two mistakes:

1- You assigned the observable itself to this.result. When you actually wanted to assign the list of friends to this.result. The correct way to do it is:

  • you subscribe to the observable. .subscribe is the function that actually executes the observable. It takes three callback parameters as follow:

    .subscribe(success, failure, complete);

for example:

.subscribe(
    function(response) { console.log("Success Response" + response)},
    function(error) { console.log("Error happened" + error)},
    function() { console.log("the subscription is completed")}
);

Usually, you take the results from the success callback and assign it to your variable. the error callback is self explanatory. the complete callback is used to determine that you have received the last results without any errors. On your plunker, the complete callback will always be called after either the success or the error callback.

2- The second mistake, you called .json() on .map(res => res.json()), then you called it again on the success callback of the observable. .map() is a transformer that will transform the result to whatever you return (in your case .json()) before it's passed to the success callback you should called it once on either one of them.

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

I had this same issue when working on an Ubuntu server.

I was getting the following error:

deploy@my-comp:~$ docker login -u my-username -p my-password
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Error response from daemon: Get https://registry-1.docker.io/v2/: dial tcp 35.175.83.85:443: connect: connection refused

Here are the things I tried that did not work:

  • Restarting the docker service using sudo docker systemctl restart docker
  • Powering off and restarting the Ubuntu server.
  • Changing the name server to 8.8.8.8 in the /etc/resolv.conf file

Here's what worked for me:

I tried checking if the server has access to the internet using the following netcat command:

nc -vz google.com 443

And it returned this output:

nc: connect to google.com port 443 (tcp) failed: Connection refused
nc: connect to google.com port 443 (tcp) failed: Network is unreachable

Instead of something like this:

Ncat: Version 7.70 ( https://nmap.org/ncat )
Ncat: Connected to 172.217.166.110:443.
Ncat: 0 bytes sent, 0 bytes received in 0.07 seconds.

I tried checking again if the server has access to the internet using the following wget command:

wget -q --spider http://google.com ; echo $?

And it returned:

4

Instead of:

0

Note: Anything other than 0 in the output means your system is not connected to the internet

I then tried the last time if the server has access to the internet using the following Nmap command:

nmap -p 443 google.com

And it returned:

Starting Nmap 7.01 ( https://nmap.org ) at 2021-02-16 11:50 WAT
Nmap scan report for google.com (216.58.223.238)
Host is up (0.00052s latency).
Other addresses for google.com (not scanned): 2c0f:fb50:4003:802::200e
rDNS record for 216.58.223.238: los02s04-in-f14.1e100.net
PORT    STATE  SERVICE
443/tcp closed https

Nmap done: 1 IP address (1 host up) scanned in 1.21 seconds

Instead something like this:

Starting Nmap 7.01 ( https://nmap.org ) at 2021-02-16 11:50 WAT
Nmap scan report for google.com (216.58.223.238)
Host is up (0.00052s latency).
Other addresses for google.com (not scanned): 2c0f:fb50:4003:802::200e
rDNS record for 216.58.223.238: los02s04-in-f14.1e100.net
PORT    STATE  SERVICE
443/tcp open https

Nmap done: 1 IP address (1 host up) scanned in 1.21 seconds

Note: The state of port 443/tcp is closed instead of open

All this was enough to make me realize that connections to the internet were not allowed on the server.

All I had to do was speak with the team in charge of infrastructure to fix the network connectivity issue to the internet on the server. And once that was fixed my docker command started working fine.

Resources: 9 commands to check if connected to internet with shell script examples

That's all.

I hope this helps

Python Decimals format

If you have Python 2.6 or newer, use format:

'{0:.3g}'.format(num)

For Python 2.5 or older:

'%.3g'%(num)

Explanation:

{0}tells format to print the first argument -- in this case, num.

Everything after the colon (:) specifies the format_spec.

.3 sets the precision to 3.

g removes insignificant zeros. See http://en.wikipedia.org/wiki/Printf#fprintf

For example:

tests=[(1.00, '1'),
       (1.2, '1.2'),
       (1.23, '1.23'),
       (1.234, '1.23'),
       (1.2345, '1.23')]

for num, answer in tests:
    result = '{0:.3g}'.format(num)
    if result != answer:
        print('Error: {0} --> {1} != {2}'.format(num, result, answer))
        exit()
    else:
        print('{0} --> {1}'.format(num,result))

yields

1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23

Using Python 3.6 or newer, you could use f-strings:

In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'

How to pop an alert message box using PHP?

You need some JS to achieve this by simply adding alert('Your message') within your PHP code.

See example below

     <?php 

//my other php code here
        
        function function_alert() { 
              
            // Display the alert box; note the Js tags within echo, it performs the magic
            echo "<script>alert('Your message Here');</script>"; 
        } 
        
        ?> 

when you visit your browser using the route supposed to triger your function_alert, you will see the alert box with your message displayed on your screen.

Read more at https://www.geeksforgeeks.org/how-to-pop-an-alert-message-box-using-php/

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

tl;dr

The answer is NEVER! (unless you really know what you're doing)

9/10 times the solution can be resolved with a proper understanding of encoding/decoding.

1/10 people have an incorrectly defined locale or environment and need to set:

PYTHONIOENCODING="UTF-8"  

in their environment to fix console printing problems.

What does it do?

sys.setdefaultencoding("utf-8") (struck through to avoid re-use) changes the default encoding/decoding used whenever Python 2.x needs to convert a Unicode() to a str() (and vice-versa) and the encoding is not given. I.e:

str(u"\u20AC")
unicode("€")
"{}".format(u"\u20AC") 

In Python 2.x, the default encoding is set to ASCII and the above examples will fail with:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

(My console is configured as UTF-8, so "€" = '\xe2\x82\xac', hence exception on \xe2)

or

UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)

sys.setdefaultencoding("utf-8") will allow these to work for me, but won't necessarily work for people who don't use UTF-8. The default of ASCII ensures that assumptions of encoding are not baked into code

Console

sys.setdefaultencoding("utf-8") also has a side effect of appearing to fix sys.stdout.encoding, used when printing characters to the console. Python uses the user's locale (Linux/OS X/Un*x) or codepage (Windows) to set this. Occasionally, a user's locale is broken and just requires PYTHONIOENCODING to fix the console encoding.

Example:

$ export LANG=en_GB.gibberish
$ python
>>> import sys
>>> sys.stdout.encoding
'ANSI_X3.4-1968'
>>> print u"\u20AC"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
>>> exit()

$ PYTHONIOENCODING=UTF-8 python
>>> import sys
>>> sys.stdout.encoding
'UTF-8'
>>> print u"\u20AC"
€

What's so bad with sys.setdefaultencoding("utf-8")?

People have been developing against Python 2.x for 16 years on the understanding that the default encoding is ASCII. UnicodeError exception handling methods have been written to handle string to Unicode conversions on strings that are found to contain non-ASCII.

From https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/

def welcome_message(byte_string):
    try:
        return u"%s runs your business" % byte_string
    except UnicodeError:
        return u"%s runs your business" % unicode(byte_string,
            encoding=detect_encoding(byte_string))

print(welcome_message(u"Angstrom (Å®)".encode("latin-1"))

Previous to setting defaultencoding this code would be unable to decode the “Å” in the ascii encoding and then would enter the exception handler to guess the encoding and properly turn it into unicode. Printing: Angstrom (Å®) runs your business. Once you’ve set the defaultencoding to utf-8 the code will find that the byte_string can be interpreted as utf-8 and so it will mangle the data and return this instead: Angstrom (U) runs your business.

Changing what should be a constant will have dramatic effects on modules you depend upon. It's better to just fix the data coming in and out of your code.

Example problem

While the setting of defaultencoding to UTF-8 isn't the root cause in the following example, it shows how problems are masked and how, when the input encoding changes, the code breaks in an unobvious way: UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte

Succeeded installing but could not start apache 2.4 on my windows 7 system

I have the same problem too, after upgrading win7 to win10. then I check services.msc and found "World Wide Web Publishing Service" was running automatically by default. So then I disabled it, and running the Apache service again.

MySQL: Check if the user exists and drop it

I wrote this procedure inspired by Cherian's answer. The difference is that in my version the user name is an argument of the procedure ( and not hard coded ) . I'm also doing a much necessary FLUSH PRIVILEGES after dropping the user.

DROP PROCEDURE IF EXISTS DropUserIfExists;
DELIMITER $$
CREATE PROCEDURE DropUserIfExists(MyUserName VARCHAR(100))
BEGIN
  DECLARE foo BIGINT DEFAULT 0 ;
  SELECT COUNT(*)
  INTO foo
    FROM mysql.user
      WHERE User = MyUserName ;
   IF foo > 0 THEN
         SET @A = (SELECT Result FROM (SELECT GROUP_CONCAT("DROP USER"," ",MyUserName,"@'%'") AS Result) AS Q LIMIT 1);
         PREPARE STMT FROM @A;
         EXECUTE STMT;
         FLUSH PRIVILEGES;
   END IF;
END ;$$
DELIMITER ;

I also posted this code on the CodeReview website ( https://codereview.stackexchange.com/questions/15716/mysql-drop-user-if-exists )

JQuery style display value

Well, for one thing your epression can be simplified:

$("#pDetails").attr("style")

since there should only be one element for any given ID and the ID selector will be much faster than the attribute id selector you're using.

If you just want to return the display value or something, use css():

$("#pDetails").css("display")

If you want to search for elements that have display none, that's a lot harder to do reliably. This is a rough example that won't be 100%:

$("[style*='display: none']")

but if you just want to find things that are hidden, use this:

$(":hidden")

How to use UIVisualEffectView to Blur Image?

Just put this blur view on the imageView. Here is an example in Objective-C:

UIVisualEffect *blurEffect;
blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];

UIVisualEffectView *visualEffectView;
visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];

visualEffectView.frame = imageView.bounds;
[imageView addSubview:visualEffectView];

and Swift:

var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))    

visualEffectView.frame = imageView.bounds

imageView.addSubview(visualEffectView)

HTML form readonly SELECT tag/input

If you disable a form field, this won't be sent when form is submitted. So if you need a readonly that works like disabled but sending values do this :

After any change in readonly properties of an element.

$('select.readonly option:not(:selected)').attr('disabled',true);

$('select:not([readonly]) option').removeAttr('disabled');

Logical operator in a handlebars.js {{#if}} conditional

I can understand why you would want to create a helper for situations where you have a large number of varied comparisons to perform within your template, but for a relatively small number of comparisons (or even one, which was what brought me to this page in the first place), it would probably just be easier to define a new handlebars variable in your view-rendering function call, like:

Pass to handlebars on render:

var context= {
    'section1' : section1,
    'section2' : section2,
    'section1or2' : (section1)||(section2)
};

and then within your handlebars template:

{{#if section1or2}}
    .. content
{{/if}}

I mention this for simplicity's sake, and also because it's an answer that may be quick and helpful while still complying with the logicless nature of Handlebars.

Reasons for using the set.seed function

Just adding some addition aspects. Need for setting seed: In the academic world, if one claims that his algorithm achieves, say 98.05% performance in one simulation, others need to be able to reproduce it.

?set.seed

Going through the help file of this function, these are some interesting facts:

(1) set.seed() returns NULL, invisible

(2) "Initially, there is no seed; a new one is created from the current time and the process ID when one is required. Hence different sessions will give different simulation results, by default. However, the seed might be restored from a previous session if a previously saved workspace is restored.", this is why you would want to call set.seed() with same integer values the next time you want a same sequence of random sequence.

How to prevent line-break in a column of a table cell (not a single cell)?

There are a few ways to do this; none of them are the easy, obvious way.

Applying white-space:nowrap to a <col> won't work; only four CSS properties work on <col> elements - background-color, width, border, and visibility. IE7 and earlier used to support all properties, but that's because they used a strange table model. IE8 now matches everyone else.

So, how do you solve this?

Well, if you can ignore IE (including IE8), you can use the :nth-child() pseudoclass to select particular <td>s from each row. You'd use td:nth-child(2) { white-space:nowrap; }. (This works for this example, but would break if you had any rowspans or colspans involved.)

If you have to support IE, then you've got to go the long way around and apply a class to every <td> that you want to affect. It sucks, but them's the breaks.

In the long run, there are proposals to fix this lack in CSS, so that you can more easily apply styles to all the cells in a column. You'll be able to do something like td:nth-col(2) { white-space:nowrap; } and it would do what you want.

How do I convert a String to a BigInteger?

Using the constructor

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

Javadoc

Another Repeated column in mapping for entity error

If you are stuck with a legacy database where someone already placed JPA annotations on but did NOT define the relationships and you are now trying to define them for use in your code, then you might NOT be able to delete the customerId @Column since other code may directly reference it already. In that case, define the relationships as follows:

@ManyToOne(optional=false)
@JoinColumn(name="productId",referencedColumnName="id_product", insertable=false, updatable=false)
private Product product;

@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer", insertable=false, updatable=false)
private Customer customer;

This allows you to access the relationships. However, to add/update to the relationships you will have to manipulate the foreign keys directly via their defined @Column values. It's not an ideal situation, but if you are handed this sort of situation, at least you can define the relationships so that you can use JPQL successfully.

How to get Chrome to allow mixed content?

The shield icon that is being mentioned was not in the sidebar for me either, however I solved it doing the following:

Find the shield icon located in the far right of the URL input bar,

Once clicked, the following popup should appear wherein you can click Load unsafe scripts,

That should result in a page refresh and the scripts should start working. What used to be an error,

is now merely a warning,

OS: Windows 10

Chrome Version: 76.0.3809.132 (Official Build) (64-bit)


Edit #1

On version 66.0.3359.117, the shield icon is still available:

Notice how the popup design has changed, so this is Chrome on version 66.0.3359.117.

Note: The shield icon will only appear when you try to load insecure content (content from http) while on https.

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

I had a similar problem recently, and needed to change the permissions of my vendor folder

By running following commands :

  1. php artisan cache:clear
  2. chmod -R 777 storage vendor
  3. composer dump-autoload

I need to give all the permissions required to open and write vendor files to solve this issue

Mocha / Chai expect.to.throw not catching thrown errors

examples from doc... ;)

because you rely on this context:

  • which is lost when the function is invoked by .throw
  • there’s no way for it to know what this is supposed to be

you have to use one of these options:

  • wrap the method or function call inside of another function
  • bind the context

    // wrap the method or function call inside of another function
    expect(function () { cat.meow(); }).to.throw();  // Function expression
    expect(() => cat.meow()).to.throw();             // ES6 arrow function
    
    // bind the context
    expect(cat.meow.bind(cat)).to.throw();           // Bind
    

Resizing an iframe based on content

iGoogle gadgets have to actively implement resizing, so my guess is in a cross-domain model you can't do this without the remote content taking part in some way. If your content can send a message with the new size to the container page using typical cross-domain communication techniques, then the rest is simple.

How can I disable the default console handler, while using the java logging API?

Do a reset of the configuration and set the root level to OFF

LogManager.getLogManager().reset();
Logger globalLogger = Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
globalLogger.setLevel(java.util.logging.Level.OFF);