Programs & Examples On #Icustomtypedescriptor

cartesian product in pandas

If you have no overlapping columns, don't want to add one, and the indices of the data frames can be discarded, this may be easier:

df1.index[:] = df2.index[:] = 0
df_cartesian = df1.join(df2, how='outer')
df_cartesian.index[:] = range(len(df_cartesian))

What range of values can integer types store in C++

The minimum ranges you can rely on are:

  • short int and int: -32,767 to 32,767
  • unsigned short int and unsigned int: 0 to 65,535
  • long int: -2,147,483,647 to 2,147,483,647
  • unsigned long int: 0 to 4,294,967,295

This means that no, long int cannot be relied upon to store any 10 digit number. However, a larger type long long int was introduced to C in C99 and C++ in C++11 (this type is also often supported as an extension by compilers built for older standards that did not include it). The minimum range for this type, if your compiler supports it, is:

  • long long int: -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807
  • unsigned long long int: 0 to 18,446,744,073,709,551,615

So that type will be big enough (again, if you have it available).


A note for those who believe I've made a mistake with these lower bounds - I haven't. The C requirements for the ranges are written to allow for ones' complement or sign-magnitude integer representations, where the lowest representable value and the highest representable value differ only in sign. It is also allowed to have a two's complement representation where the value with sign bit 1 and all value bits 0 is a trap representation rather than a legal value. In other words, int is not required to be able to represent the value -32,768.

How to set label size in Bootstrap

In Bootstrap 3 they do not have separate classes for different styles of labels.

http://getbootstrap.com/components/

However, you can customize bootstrap classes that way. In your css file

.lb-sm {
  font-size: 12px;
}

.lb-md {
  font-size: 16px;
}

.lb-lg {
  font-size: 20px;
}

Alternatively, you can use header tags to change the sizes. For example, here is a medium sized label and a small-sized label

_x000D_
_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<h3>Example heading <span class="label label-default">New</span></h3>_x000D_
<h6>Example heading <span class="label label-default">New</span></h6>
_x000D_
_x000D_
_x000D_

They might add size classes for labels in future Bootstrap versions.

Float and double datatype in Java

You should use double instead of float for precise calculations, and float instead of double when using less accurate calculations. Float contains only decimal numbers, but double contains an IEEE754 double-precision floating point number, making it easier to contain and computate numbers more accurately. Hope this helps.

Facebook Access Token for Pages

The documentation for this is good if not a little difficult to find.

Facebook Graph API - Page Tokens

After initializing node's fbgraph, you can run:

var facebookAccountID = yourAccountIdHere 

graph
.setOptions(options)
.get(facebookAccountId + "/accounts", function(err, res) {
  console.log(res); 
});

and receive a JSON response with the token you want to grab, located at:

res.data[0].access_token

Clearing content of text file using php

Use 'w' and not, 'a'.

if (!$handle = fopen($file, 'w'))

Vbscript list all PDF files in folder and subfolders

Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Users\NOLA BOOTHE\My Documents\operating system"

Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files
For Each objFile in colFiles
    Wscript.Echo objFile.Name
Next

google console error `OR-IEH-01`

i found that my google payment account was not activated. i activated it and the error was solved. link for vitrification: google account verification

Given a class, see if instance has method (Ruby)

I think there is something wrong with method_defined? in Rails. It may be inconsistent or something, so if you use Rails, it's better to use something from attribute_method?(attribute).

"testing for method_defined? on ActiveRecord classes doesn't work until an instantiation" is a question about the inconsistency.

C++ - struct vs. class

1) It is the only difference in C++.

2) POD: plain old data Other classes -> not POD

How do I vertically align something inside a span tag?

Set padding-top to be an appropriate value to push the x down, then subtract the value you have for padding-top from the height.

How to convert a char to a String?

  char vIn = 'A';
  String vOut = Character.toString(vIn);

For these types of conversion, I have site bookmarked called https://www.converttypes.com/ It helps me quickly get the conversion code for most of the languages I use.

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

Maven error: Not authorized, ReasonPhrase:Unauthorized

You have an old password in the settings.xml. It is trying to connect to the repositories, but is not able to, since the password is not updated. Once you update and re-run the command, you should be good.

Best way to get whole number part of a Decimal number

Depends on what you're doing.

For instance:

//bankers' rounding - midpoint goes to nearest even
GetIntPart(2.5) >> 2
GetIntPart(5.5) >> 6
GetIntPart(-6.5) >> -6

or

//arithmetic rounding - midpoint goes away from zero
GetIntPart(2.5) >> 3
GetIntPart(5.5) >> 6
GetIntPart(-6.5) >> -7

The default is always the former, which can be a surprise but makes very good sense.

Your explicit cast will do:

int intPart = (int)343564564.5
// intPart will be 343564564

int intPart = (int)343564565.5
// intPart will be 343564566

From the way you've worded the question it sounds like this isn't what you want - you want to floor it every time.

I would do:

Math.Floor(Math.Abs(number));

Also check the size of your decimal - they can be quite big, so you may need to use a long.

How to overlay image with color in CSS?

If you don't mind using absolute positioning, you can position your background image, and then add an overlay using opacity.

div {
    width:50px;
    height:50px;
    background:   url('http://images1.wikia.nocookie.net/__cb20120626155442/adventuretimewithfinnandjake/images/6/67/Link.gif');
    position:absolute;
    left:0;
    top:0;
}

.overlay {
   background:red;
   opacity:.5;
}

See here: http://jsfiddle.net/4yh9L/

MySQL Daemon Failed to Start - centos 6

run this :

chown -R mysql:mysql /var/lib/mysql

and try again!

null terminating a string

Be very careful: NULL is a macro used mainly for pointers. The standard way of terminating a string is:

char *buffer;
...
buffer[end_position] = '\0';

This (below) works also but it is not a big difference between assigning an integer value to a int/short/long array and assigning a character value. This is why the first version is preferred and personally I like it better.

buffer[end_position] = 0; 

Laravel whereIn OR whereIn

$query = DB::table('dms_stakeholder_permissions');
$query->select(DB::raw('group_concat(dms_stakeholder_permissions.fid) as fid'),'dms_stakeholder_permissions.rights');
$query->where('dms_stakeholder_permissions.stakeholder_id','4');
$query->orWhere(function($subquery)  use ($stakeholderId){
            $subquery->where('dms_stakeholder_permissions.stakeholder_id',$stakeholderId);
            $subquery->whereIn('dms_stakeholder_permissions.rights',array('1','2','3'));
    });

 $result = $query->get();

return $result;

// OUTPUT @input $stakeholderId = 1

//select group_concat(dms_stakeholder_permissions.fid) as fid, dms_stakeholder_permissionss.rights from dms_stakeholder_permissions where dms_stakeholder_permissions.stakeholder_id = 4 or (dms_stakeholder_permissions.stakeholder_id = 1 and dms_stakeholder_permissions.rights in (1, 2, 3))

Session timeout in ASP.NET

You can find the setting here in IIS:

Settings

It can be found at the server level, web site level, or app level under "ASP".

I think you can set it at the web.config level here. Please confirm this for yourself.

<configuration>
   <system.web>

      <!-- Session Timeout in Minutes (Also in Global.asax) -->
       <sessionState timeout="1440"/>

   </system.web>
</configuration>

What's the best mock framework for Java?

I like JMock because you are able to set up expectations. This is totally different from checking if a method was called found in some mock libraries. Using JMock you can write very sophisticated expectations. See the jmock cheat-sheat.

How to search by key=>value in a multidimensional array in PHP

Be careful of linear search algorithms (the above are linear) in multiple dimensional arrays as they have compounded complexity as its depth increases the number of iterations required to traverse the entire array. Eg:

array(
    [0] => array ([0] => something, [1] => something_else))
    ...
    [100] => array ([0] => something100, [1] => something_else100))
)

would take at the most 200 iterations to find what you are looking for (if the needle were at [100][1]), with a suitable algorithm.

Linear algorithms in this case perform at O(n) (order total number of elements in entire array), this is poor, a million entries (eg a 1000x100x10 array) would take on average 500,000 iterations to find the needle. Also what would happen if you decided to change the structure of your multidimensional array? And PHP would kick out a recursive algorithm if your depth was more than 100. Computer science can do better:

Where possible, always use objects instead of multiple dimensional arrays:

ArrayObject(
   MyObject(something, something_else))
   ...
   MyObject(something100, something_else100))
)

and apply a custom comparator interface and function to sort and find them:

interface Comparable {
   public function compareTo(Comparable $o);
}

class MyObject implements Comparable {
   public function compareTo(Comparable $o){
      ...
   }
}

function myComp(Comparable $a, Comparable $b){
    return $a->compareTo($b);
}

You can use uasort() to utilize a custom comparator, if you're feeling adventurous you should implement your own collections for your objects that can sort and manage them (I always extend ArrayObject to include a search function at the very least).

$arrayObj->uasort("myComp");

Once they are sorted (uasort is O(n log n), which is as good as it gets over arbitrary data), binary search can do the operation in O(log n) time, ie a million entries only takes ~20 iterations to search. As far as I am aware custom comparator binary search is not implemented in PHP (array_search() uses natural ordering which works on object references not their properties), you would have to implement this your self like I do.

This approach is more efficient (there is no longer a depth) and more importantly universal (assuming you enforce comparability using interfaces) since objects define how they are sorted, so you can recycle the code infinitely. Much better =)

How to compare DateTime without time via LINQ?

The .Date answer is misleading since you get the error mentioned before. Another way to compare, other than mentioned DbFunctions.TruncateTime, may also be:

DateTime today = DateTime.Now.date;
var q = db.Games.Where(t => SqlFunctions.DateDiff("dayofyear", today, t.StartDate) <= 0
      && SqlFunctions.DateDiff("year", today, t.StartDate) <= 0)

It looks better(more readable) in the generated SQL query. But I admit it looks worse in the C# code XD. I was testing something and it seemed like TruncateTime was not working for me unfortunately the fault was between keyboard and chair, but in the meantime I found this alternative.

Windows equivalent of linux cksum command

Here is a C# implementation of the *nix cksum command line utility for windows https://cksum.codeplex.com/

How to say no to all "do you want to overwrite" prompts in a batch file copy?

Here's a workaround. If you want to copy everything from A that does not already exist in B:

Copy A to a new directory C. Copy B to C, overwriting anything that overlaps with A. Copy C to B.

SQL Server tables: what is the difference between @, # and ##?

#table refers to a local (visible to only the user who created it) temporary table.

##table refers to a global (visible to all users) temporary table.

@variableName refers to a variable which can hold values depending on its type.

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

C - freeing structs

free is not enough, free just marks the memory as unused, the struct data will be there until overwriting. For safety, set the pointer to NULL after free.

Ex:

if (testPerson) {
    free(testPerson);
    testPerson = NULL;
}

struct is similar like an array, it is a block of memory. You can access to struct member via its offset. The first struct's member is placed at offset 0 so the address of first struct's member is same as the address of struct.

Date minus 1 year?

Although there are many acceptable answers in response to this question, I don't see any examples of the sub method using the \Datetime object: https://www.php.net/manual/en/datetime.sub.php

So, for reference, you can also use a \DateInterval to modify a \Datetime object:

$date = new \DateTime('2009-01-01');
$date->sub(new \DateInterval('P1Y'));

echo $date->format('Y-m-d');

Which returns:

2008-01-01

For more information about \DateInterval, refer to the documentation: https://www.php.net/manual/en/class.dateinterval.php

How can I build a recursive function in python?

Let's say you want to build: u(n+1)=f(u(n)) with u(0)=u0

One solution is to define a simple recursive function:

u0 = ...

def f(x):
  ...

def u(n):
  if n==0: return u0
  return f(u(n-1))

Unfortunately, if you want to calculate high values of u, you will run into a stack overflow error.

Another solution is a simple loop:

def u(n):
  ux = u0
  for i in xrange(n):
    ux=f(ux)
  return ux

But if you want multiple values of u for different values of n, this is suboptimal. You could cache all values in an array, but you may run into an out of memory error. You may want to use generators instead:

def u(n):
  ux = u0
  for i in xrange(n):
    ux=f(ux)
  yield ux

for val in u(1000):
  print val

There are many other options, but I guess these are the main ones.

HTML5 placeholder css padding

Removing the line-height indeed makes your text align with your placeholder-text, but it doesn't properly solve your problem since you need to adapt your design to this flaw (it's not a bug). Adding vertical-align won't do the deal either. I haven't tried in all browsers, but it doesn't work in Safari 5.1.4 for sure.

I have heard of a jQuery fix for this, that is not cross-browser placeholder support (jQuery.placeholder), but for styling placeholders, but I haven't found it yet.

In the meantime, you can resolve to the table on this page which shows different browser support for different styles.

Edit: Found the plugin! jquery.placeholder.min.js provides you with both full styling capabilities and cross-browser support into the bargain.

How can I return pivot table output in MySQL?

select t3.name, sum(t3.prod_A) as Prod_A, sum(t3.prod_B) as Prod_B, sum(t3.prod_C) as    Prod_C, sum(t3.prod_D) as Prod_D, sum(t3.prod_E) as Prod_E  
from
(select t2.name as name, 
case when t2.prodid = 1 then t2.counts
else 0 end  prod_A, 

case when t2.prodid = 2 then t2.counts
else 0 end prod_B,

case when t2.prodid = 3 then t2.counts
else 0 end prod_C,

case when t2.prodid = 4 then t2.counts
else 0 end prod_D, 

case when t2.prodid = "5" then t2.counts
else 0 end prod_E

from 
(SELECT partners.name as name, sales.products_id as prodid, count(products.name) as counts
FROM test.sales left outer join test.partners on sales.partners_id = partners.id
left outer join test.products on sales.products_id = products.id 
where sales.partners_id = partners.id and sales.products_id = products.id group by partners.name, prodid) t2) t3

group by t3.name ;

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

How do you delete all text above a certain line

d1G = delete to top including current line (vi)

How to run a command in the background on Windows?

If you take 5 minutes to download visual studio and make a Console Application for this, your problem is solved.

using System;
using System.Linq;
using System.Diagnostics;
using System.IO;

namespace BgRunner
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting: " + String.Join(" ", args));
            String arguments = String.Join(" ", args.Skip(1).ToArray());
            String command = args[0];

            Process p = new Process();
            p.StartInfo = new ProcessStartInfo(command);
            p.StartInfo.Arguments = arguments;
            p.StartInfo.WorkingDirectory = Path.GetDirectoryName(command);
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.UseShellExecute = false;
            p.Start();
        }
    }
}

Examples of usage:

BgRunner.exe php/php-cgi -b 9999
BgRunner.exe redis/redis-server --port 3000
BgRunner.exe nginx/nginx

Error inflating class fragment

I did not have the androidx.fragment:fragment dependency.

You can get the latest version from the Jetpack/ AndroidX docs:

dependencies {
    def fragment_version = "1.2.5"

    // Java language implementation
    implementation "androidx.fragment:fragment:$fragment_version"
    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
    // Testing Fragments in Isolation
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}

Remove ALL styling/formatting from hyperlinks

You can just use an a selector in your stylesheet to define all states of an anchor/hyperlink. For example:

a {
    color: blue;
}

Would override all link styles and make all the states the colour blue.

Angular 2 - View not updating after model changes

In my case, I had a very similar problem. I was updating my view inside a function that was being called by a parent component, and in my parent component I forgot to use @ViewChild(NameOfMyChieldComponent). I lost at least 3 hours just for this stupid mistake. i.e: I didn't need to use any of those methods:

  • ChangeDetectorRef.detectChanges()
  • ChangeDetectorRef.markForCheck()
  • ApplicationRef.tick()

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

How to dismiss ViewController in Swift?

From you image it seems like you presented the ViewController using push

The dismissViewControllerAnimated is used to close ViewControllers that presented using modal

Swift 2

navigationController.popViewControllerAnimated(true)

Swift 4

navigationController?.popViewController(animated: true)

dismiss(animated: true, completion: nil)

Delete/Reset all entries in Core Data?

Here is combined solution for purging Core Data.

- (void)deleteAllObjectsInCoreData
{
    NSArray *allEntities = self.managedObjectModel.entities;
    for (NSEntityDescription *entityDescription in allEntities)
    {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        [fetchRequest setEntity:entityDescription];

        fetchRequest.includesPropertyValues = NO;
        fetchRequest.includesSubentities = NO;

        NSError *error;
        NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

        if (error) {
                NSLog(@"Error requesting items from Core Data: %@", [error localizedDescription]);
            }

        for (NSManagedObject *managedObject in items) {
            [self.managedObjectContext deleteObject:managedObject];
        }

        if (![self.managedObjectContext save:&error]) {
            NSLog(@"Error deleting %@ - error:%@", entityDescription, [error localizedDescription]);
        }
    }  
}

Set EditText cursor color

In Layout

<EditText  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textCursorDrawable="@drawable/color_cursor"
    />

Then create drawalble xml: color_cursor

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <size android:width="3dp" />
    <solid android:color="#FFFFFF"  />
</shape>

You have a white color cursor on EditText property.

update package.json version automatically

With Husky:

{
  "name": "demo-project",
  "version": "0.0.3",
  "husky": {
    "hooks": {
      "pre-commit": "npm --no-git-tag-version version patch && git add ."
    }
  }
}

How to create a data file for gnuplot?

I was having the exact same issue. The problem that I was having is that I hadn't saved the .plt file that I was typing into yet. The fix: I saved the .plt file in the same directory as the data that I was trying to plot and suddenly it worked! If they are in the same directory, you don't even need to specify a path, you can just put in the file name.

Below is exactly what was happening to me, and how I fixed it. The first line shows the problem we were both having. I saved in the second line, and the third line worked!

gnuplot> plot 'c:/Documents and Settings/User/Desktop/data.dat'
         warning: Skipping unreadable file c:/Documents and Settings/User/Desktop/data.dat
         No data in plot

gnuplot> save 'c:/Documents and Settings/User/Desktop/myfile.plt'

gnuplot> plot 'c:/Documents and Settings/User/Desktop/data.dat'

how do I create an array in jquery?

Here is the clear working example:

//creating new array
var custom_arr1 = [];


//storing value in array
custom_arr1.push("test");
custom_arr1.push("test1");

alert(custom_arr1);
//output will be  test,test1

how to get vlc logs?

I found the following command to run from command line:

vlc.exe --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

GetMemberName allows to get the string with the name of a member with compile time safety.

public static string GetMemberName<T, TResult>(
    this T anyObject, 
    Expression<Func<T, TResult>> expression)
{
    return ((MemberExpression)expression.Body).Member.Name;
}

Usage:

"blah".GetMemberName(x => x.Length); // returns "Length"

It comes together with a non-extension static method if you don't have a instance:

public static string GetMemberName<T, TReturn>(
    Expression<Func<T, TReturn>> expression)
    where T : class
{
    return ((MemberExpression)expression.Body).Member.Name;
}

But the call doesn't look as pretty of course:

ReflectionUtility.GetMemberName((string) s => s.Length); // returns "Length"

You can put it on Codeplex if you want.

How do you rotate a two dimensional array?

A couple of people have already put up examples which involve making a new array.

A few other things to consider:

(a) Instead of actually moving the data, simply traverse the "rotated" array differently.

(b) Doing the rotation in-place can be a little trickier. You'll need a bit of scratch place (probably roughly equal to one row or column in size). There's an ancient ACM paper about doing in-place transposes (http://doi.acm.org/10.1145/355719.355729), but their example code is nasty goto-laden FORTRAN.

Addendum:

http://doi.acm.org/10.1145/355611.355612 is another, supposedly superior, in-place transpose algorithm.

Print list without brackets in a single row

General solution, works on arrays of non-strings:

>>> print str(names)[1:-1]
'Sam', 'Peter', 'James', 'Julian', 'Ann'

Save multiple sheets to .pdf

Similar to Tim's answer - but with a check for 2007 (where the PDF export is not installed by default):

Public Sub subCreatePDF()

    If Not IsPDFLibraryInstalled Then
        'Better show this as a userform with a proper link:
        MsgBox "Please install the Addin to export to PDF. You can find it at http://www.microsoft.com/downloads/details.aspx?familyid=4d951911-3e7e-4ae6-b059-a2e79ed87041". 
        Exit Sub
    End If

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        Filename:=ActiveWorkbook.Path & Application.PathSeparator & _
        ActiveSheet.Name & " für " & Range("SelectedName").Value & ".pdf", _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub

Private Function IsPDFLibraryInstalled() As Boolean
'Credits go to Ron DeBruin (http://www.rondebruin.nl/pdf.htm)
    IsPDFLibraryInstalled = _
        (Dir(Environ("commonprogramfiles") & _
        "\Microsoft Shared\OFFICE" & _
        Format(Val(Application.Version), "00") & _
        "\EXP_PDF.DLL") <> "")
End Function

How to avoid "StaleElementReferenceException" in Selenium?

A solution in C# would be:

Helper class:

internal class DriverHelper
{

    private IWebDriver Driver { get; set; }
    private WebDriverWait Wait { get; set; }

    public DriverHelper(string driverUrl, int timeoutInSeconds)
    {
        Driver = new ChromeDriver();
        Driver.Url = driverUrl;
        Wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(timeoutInSeconds));
    }

    internal bool ClickElement(string cssSelector)
    {
        //Find the element
        IWebElement element = Wait.Until(d=>ExpectedConditions.ElementIsVisible(By.CssSelector(cssSelector)))(Driver);
        return Wait.Until(c => ClickElement(element, cssSelector));
    }

    private bool ClickElement(IWebElement element, string cssSelector)
    {
        try
        {
            //Check if element is still included in the dom
            //If the element has changed a the OpenQA.Selenium.StaleElementReferenceException is thrown.
            bool isDisplayed = element.Displayed;

            element.Click();
            return true;
        }
        catch (StaleElementReferenceException)
        {
            //wait until the element is visible again
            element = Wait.Until(d => ExpectedConditions.ElementIsVisible(By.CssSelector(cssSelector)))(Driver);
            return ClickElement(element, cssSelector);
        }
        catch (Exception)
        {
            return false;
        }
    }
}

Invocation:

        DriverHelper driverHelper = new DriverHelper("http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp", 10);
        driverHelper.ClickElement("input[value='csharp']:first-child");

Similarly can be used for Java.

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

Set time to 00:00:00

As Java8 add new Date functions, we can do this easily.


    // If you have instant, then:
    Instant instant1 = Instant.now();
    Instant day1 = instant1.truncatedTo(ChronoUnit.DAYS);
    System.out.println(day1); //2019-01-14T00:00:00Z

    // If you have Date, then:
    Date date = new Date();
    Instant instant2 = date.toInstant();
    Instant day2 = instant2.truncatedTo(ChronoUnit.DAYS);
    System.out.println(day2); //2019-01-14T00:00:00Z

    // If you have LocalDateTime, then:
    LocalDateTime dateTime = LocalDateTime.now();
    LocalDateTime day3 = dateTime.truncatedTo(ChronoUnit.DAYS);
    System.out.println(day3); //2019-01-14T00:00
    String format = day3.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    System.out.println(format);//2019-01-14T00:00:00


How to reset the bootstrap modal when it gets closed and open it fresh again?

Reset form inside the modal. Sample Code:

$('#myModal').on('hide.bs.modal', '#myModal', function (e) {
    $('#myModal form')[0].reset();
});

How to set a timeout on a http.request() in Node?

There is simpler method.

Instead of using setTimeout or working with socket directly,
We can use 'timeout' in the 'options' in client uses

Below is code of both server and client, in 3 parts.

Module and options part:

'use strict';

// Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js

const assert = require('assert');
const http = require('http');

const options = {
    host: '127.0.0.1', // server uses this
    port: 3000, // server uses this

    method: 'GET', // client uses this
    path: '/', // client uses this
    timeout: 2000 // client uses this, timesout in 2 seconds if server does not respond in time
};

Server part:

function startServer() {
    console.log('startServer');

    const server = http.createServer();
    server
            .listen(options.port, options.host, function () {
                console.log('Server listening on http://' + options.host + ':' + options.port);
                console.log('');

                // server is listening now
                // so, let's start the client

                startClient();
            });
}

Client part:

function startClient() {
    console.log('startClient');

    const req = http.request(options);

    req.on('close', function () {
        console.log("got closed!");
    });

    req.on('timeout', function () {
        console.log("timeout! " + (options.timeout / 1000) + " seconds expired");

        // Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js#L27
        req.destroy();
    });

    req.on('error', function (e) {
        // Source: https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js#L248
        if (req.connection.destroyed) {
            console.log("got error, req.destroy() was called!");
            return;
        }

        console.log("got error! ", e);
    });

    // Finish sending the request
    req.end();
}


startServer();

If you put all the above 3 parts in one file, "a.js", and then run:

node a.js

then, output will be:

startServer
Server listening on http://127.0.0.1:3000

startClient
timeout! 2 seconds expired
got closed!
got error, req.destroy() was called!

Hope that helps.

How to test that no exception is thrown?

JUnit 5 (Jupiter) provides three functions to check exception absence/presence:

? assertAll?()

Asserts that all supplied executables
  do not throw exceptions.

? assertDoesNotThrow?()

Asserts that execution of the
  supplied executable/supplier
does not throw any kind of exception.

  This function is available
  since JUnit 5.2.0 (29 April 2018).

? assertThrows?()

Asserts that execution of the supplied executable
throws an exception of the expectedType
  and returns the exception.

Example

package test.mycompany.myapp.mymodule;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class MyClassTest {

    @Test
    void when_string_has_been_constructed_then_myFunction_does_not_throw() {
        String myString = "this string has been constructed";
        assertAll(() -> MyClass.myFunction(myString));
    }

    @Test
    void when_string_has_been_constructed_then_myFunction_does_not_throw__junit_v520() {
        String myString = "this string has been constructed";
        assertDoesNotThrow(() -> MyClass.myFunction(myString));
    }

    @Test
    void when_string_is_null_then_myFunction_throws_IllegalArgumentException() {
        String myString = null;
        assertThrows(
            IllegalArgumentException.class,
            () -> MyClass.myFunction(myString));
    }

}

How do I install a module globally using npm?

If you want to install a npm module globally, make sure to use the new -g flag, for example:

npm install forever -g

The general recommendations concerning npm module installation since 1.0rc (taken from blog.nodejs.org):

  • If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your project.
  • If you’re installing something that you want to use in your shell, on the command line or something, install it globally, so that its binaries end up in your PATH environment variable.

I just recently used this recommendations and it went down pretty smoothly. I installed forever globally (since it is a command line tool) and all my application modules locally.

However, if you want to use some modules globally (i.e. express or mongodb), take this advice (also taken from blog.nodejs.org):

Of course, there are some cases where you want to do both. Coffee-script and Express both are good examples of apps that have a command line interface, as well as a library. In those cases, you can do one of the following:

  • Install it in both places. Seriously, are you that short on disk space? It’s fine, really. They’re tiny JavaScript programs.
  • Install it globally, and then npm link coffee-script or npm link express (if you’re on a platform that supports symbolic links.) Then you only need to update the global copy to update all the symlinks as well.

The first option is the best in my opinion. Simple, clear, explicit. The second is really handy if you are going to re-use the same library in a bunch of different projects. (More on npm link in a future installment.)

I did not test one of those variations, but they seem to be pretty straightforward.

Difference between string object and string literal

The long answer is available here, so I'll give you the short one.

When you do this:

String str = "abc";

You are calling the intern() method on String. This method references an internal pool of String objects. If the String you called intern() on already resides in the pool, then a reference to that String is assigned to str. If not, then the new String is placed in the pool, and a reference to it is then assigned to str.

Given the following code:

String str = "abc";
String str2 = "abc";
boolean identity = str == str2;

When you check for object identity by doing == (you are literally asking: do these two references point to the same object?), you get true.

However, you don't need to intern() Strings. You can force the creation on a new Object on the Heap by doing this:

String str = new String("abc");
String str2 = new String("abc");
boolean identity = str == str2;

In this instance, str and str2 are references to different Objects, neither of which have been interned, so that when you test for Object identity using ==, you will get false.

In terms of good coding practice: do not use == to check for String equality, use .equals() instead.

Exit/save edit to sudoers file? Putty SSH

Just open file by nano /file_name

Once done, press CTRL+O and then Enter to save. Then press CTRL+X to return.

Here CTRL+O : is CTRL and O for Orange Not 0 Zero

Java Map equivalent in C#

class Test
{
    Dictionary<int, string> entities;

    public string GetEntity(int code)
    {
        // java's get method returns null when the key has no mapping
        // so we'll do the same

        string val;
        if (entities.TryGetValue(code, out val))
            return val;
        else
            return null;
    }
}

Python ImportError: No module named wx

In fedora you can use following command to install wx

pip install -U \
  -f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-16.04 \
  wxPython

How to disable Hyper-V in command line?

Open a command prompt as admin and run this command:

bcdedit /set {current} hypervisorlaunchtype off

After a reboot, Hyper-V is still installed but the Hypervisor is no longer running. Now you can use VMware without any issues.

If you need Hyper-V again, open a command prompt as admin and run this command:

bcdedit /set {current} hypervisorlaunchtype auto

Creating a BLOB from a Base64 string in JavaScript

Here is a more minimal method without any dependencies or libraries.
It requires the new fetch API. (Can I use it?)

_x000D_
_x000D_
var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

fetch(url)
.then(res => res.blob())
.then(console.log)
_x000D_
_x000D_
_x000D_

With this method you can also easily get a ReadableStream, ArrayBuffer, text, and JSON.
(fyi this also works with node-fetch in Node)

As a function:

const b64toBlob = (base64, type = 'application/octet-stream') => 
  fetch(`data:${type};base64,${base64}`).then(res => res.blob())

I did a simple performance test towards Jeremy's ES6 sync version.
The sync version will block UI for a while. keeping the devtool open can slow the fetch performance

_x000D_
_x000D_
document.body.innerHTML += '<input autofocus placeholder="try writing">'
// get some dummy gradient image
var img=function(){var a=document.createElement("canvas"),b=a.getContext("2d"),c=b.createLinearGradient(0,0,1500,1500);a.width=a.height=3000;c.addColorStop(0,"red");c.addColorStop(1,"blue");b.fillStyle=c;b.fillRect(0,0,a.width,a.height);return a.toDataURL()}();


async function perf() {
  
  const blob = await fetch(img).then(res => res.blob())
  // turn it to a dataURI
  const url = img
  const b64Data = url.split(',')[1]

  // Jeremy Banks solution
  const b64toBlob = (b64Data, contentType = '', sliceSize=512) => {
    const byteCharacters = atob(b64Data);
    const byteArrays = [];
    
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      const slice = byteCharacters.slice(offset, offset + sliceSize);
      
      const byteNumbers = new Array(slice.length);
      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }
      
      const byteArray = new Uint8Array(byteNumbers);
      
      byteArrays.push(byteArray);
    }
    
    const blob = new Blob(byteArrays, {type: contentType});
    return blob;
  }

  // bench blocking method
  let i = 500
  console.time('blocking b64')
  while (i--) {
    await b64toBlob(b64Data)
  }
  console.timeEnd('blocking b64')
  
  // bench non blocking
  i = 500

  // so that the function is not reconstructed each time
  const toBlob = res => res.blob()
  console.time('fetch')
  while (i--) {
    await fetch(url).then(toBlob)
  }
  console.timeEnd('fetch')
  console.log('done')
}

perf()
_x000D_
_x000D_
_x000D_

Passing environment-dependent variables in webpack

You can directly use the EnvironmentPlugin available in webpack to have access to any environment variable during the transpilation.

You just have to declare the plugin in your webpack.config.js file:

var webpack = require('webpack');

module.exports = {
    /* ... */
    plugins = [
        new webpack.EnvironmentPlugin(['NODE_ENV'])
    ]
};

Note that you must declare explicitly the name of the environment variables you want to use.

Android Layout Right Align

The layout is extremely inefficient and bloated. You don't need that many LinearLayouts. In fact you don't need any LinearLayout at all.

Use only one RelativeLayout. Like this.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ImageButton android:background="@null"
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/back"
        android:padding="10dip"
        android:layout_alignParentLeft="true"/>
    <ImageButton android:background="@null"
        android:id="@+id/forward"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/forward"
        android:padding="10dip"
        android:layout_toRightOf="@id/back"/>
    <ImageButton android:background="@null"
        android:id="@+id/special"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/barcode"
        android:padding="10dip"
        android:layout_alignParentRight="true"/>
</RelativeLayout>

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

Write the function inline, and the interpreter is smart enough to know you're writing a function. Do it like this, and it assumes it's just a string (which it technically is).

How to remove stop words using nltk or python

Here is my take on this, in case you want to immediately get the answer into a string (instead of a list of filtered words):

STOPWORDS = set(stopwords.words('english'))
text =  ' '.join([word for word in text.split() if word not in STOPWORDS]) # delete stopwords from text

Node Version Manager (NVM) on Windows

As an node manager alternative you can use Volta from LinkedIn.

How do I select an element in jQuery by using a variable for the ID?

row = $("body").find('#' + row_id);

More importantly doing the additional body.find has no impact on performance. The proper way to do this is simply:

row = $('#' + row_id);

What is offsetHeight, clientHeight, scrollHeight?

My descriptions for the three:

  • offsetHeight: How much of the parent's "relative positioning" space is taken up by the element. (ie. it ignores the element's position: absolute descendents)
  • clientHeight: Same as offset-height, except it excludes the element's own border, margin, and the height of its horizontal scroll-bar (if it has one).
  • scrollHeight: How much space is needed to see all of the element's content/descendents (including position: absolute ones) without scrolling.

Then there is also:

Dependent DLL is not getting copied to the build output folder in Visual Studio

In my case, it was the stupidest thing, caused by a default behavior of TFS/VS that I disagree with.

Since adding the dll as a reference to the main project did not work, I decided to add it as an "Existing Item", with Copy Local = Always. Even then the file was not there.

Turns out that, even though the file is present on the VS Solution and everything compiled both locally and on the server, VS/TFS did not add actually add the file to source control. It was not included on the "Pending Changes" at all. I had to manually go to the Source Control Explorer and explicitly click on the "Add items to folder" icon.

Stupid because I've been developing for 15 years in VS. I've run into this before, I just did not remember and somehow I missed it because everything still compiled because of the file being a regular reference, but the file that was added as Existing Item was not being copied because it did not exist on the source control server.

I hope this saves someone some time, since I lost 2 days of my life to this.

How do I add a foreign key to an existing SQLite table?

If you are using the Firefox add-on sqlite-manager you can do the following:

Instead of dropping and creating the table again one can just modify it like this.

In the Columns text box, right click on the last column name listed to bring up the context menu and select Edit Column. Note that if the last column in the TABLE definition is the PRIMARY KEY then it will be necessary to first add a new column and then edit the column type of the new column in order to add the FOREIGN KEY definition. Within the Column Type box , append a comma and the

FOREIGN KEY (parent_id) REFERENCES parent(id)

definition after data type. Click on the Change button and then click the Yes button on the Dangerous Operation dialog box.

Reference: Sqlite Manager

Python, remove all non-alphabet chars from string

Try:

s = ''.join(filter(str.isalnum, s))

This will take every char from the string, keep only alphanumeric ones and build a string back from them.

Random Number Between 2 Double Numbers

Yes.

Random.NextDouble returns a double between 0 and 1. You then multiply that by the range you need to go into (difference between maximum and minimum) and then add that to the base (minimum).

public double GetRandomNumber(double minimum, double maximum)
{ 
    Random random = new Random();
    return random.NextDouble() * (maximum - minimum) + minimum;
}

Real code should have random be a static member. This will save the cost of creating the random number generator, and will enable you to call GetRandomNumber very frequently. Since we are initializing a new RNG with every call, if you call quick enough that the system time doesn't change between calls the RNG will get seeded with the exact same timestamp, and generate the same stream of random numbers.

How to overcome root domain CNAME restrictions?

You have to put a period at the end of the external domain so it doesn't think you mean customer1.mycompanydomain.com.localdomain;

So just change:

customer1.com IN CNAME customer1.mycompanydomain.com

To

customer1.com IN CNAME customer1.mycompanydomain.com.

Add column to SQL Server

Use this query:

ALTER TABLE tablename ADD columname DATATYPE(size);

And here is an example:

ALTER TABLE Customer ADD LastName VARCHAR(50);

How to dismiss AlertDialog in android

Here is How I close my alertDialog

lv_three.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                GetTalebeDataUser clickedObj = (GetTalebeDataUser) parent.getItemAtPosition(position);
                alertDialog.setTitle(clickedObj.getAd());
                alertDialog.setMessage("Ögrenci Bilgileri Güncelle?");
                alertDialog.setIcon(R.drawable.ic_info);
                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // User pressed YES button. Write Logic Here
                    }
                });
                alertDialog.setNegativeButton("Iptal", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //alertDialog.
                        alertDialog.setCancelable(true); // HERE

                    }
                });
                alertDialog.show();
                return true;
            }
        });

append new row to old csv file python

If the file exists and contains data, then it is possible to generate the fieldname parameter for csv.DictWriter automatically:

# read header automatically
with open(myFile, "r") as f:
    reader = csv.reader(f)
    for header in reader:
        break

# add row to CSV file
with open(myFile, "a", newline='') as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writerow(myDict)

How to make script execution wait until jquery is loaded

the easiest and safest way is to use something like this:

var waitForJQuery = setInterval(function () {
    if (typeof $ != 'undefined') {

        // place your code here.

        clearInterval(waitForJQuery);
    }
}, 10);

How to make 'submit' button disabled?

May be below code can help:

<button type="submit" [attr.disabled]="!ngForm.valid ? true : null">Submit</button>

Classpath including JAR within a JAR

You do NOT want to use those "explode JAR contents" solutions. They definitely make it harder to see stuff (since everything is exploded at the same level). Furthermore, there could be naming conflicts (should not happen if people use proper packages, but you cannot always control this).

The feature that you want is one of the top 25 Sun RFEs: RFE 4648386, which Sun, in their infinite wisdom, has designated as being of low priority. We can only hope that Sun wakes up...

In the meanwhile, the best solution that I have come across (which I wish that Sun would copy in the JDK) is to use the custom class loader JarClassLoader.

bash export command

Probably because it's trying to execute "export" as an external command, and it's a shell internal.

Replace all non-alphanumeric characters in a string

Use \W which is equivalent to [^a-zA-Z0-9_]. Check the documentation, https://docs.python.org/2/library/re.html

Import re
s =  'h^&ell`.,|o w]{+orld'
replaced_string = re.sub(r'\W+', '*', s)
output: 'h*ell*o*w*orld'

update: This solution will exclude underscore as well. If you want only alphabets and numbers to be excluded, then solution by nneonneo is more appropriate.

Error Running React Native App From Terminal (iOS)

In my case the problem was that Xcode was not installed.

How to rotate portrait/landscape Android emulator?

Officially it's Ctrl+F11 & Ctrl+F12 or KEYPAD 7 & KEYPAD 9.

In practise it's a bit quirky.

  1. Specifically it's Left Ctrl+F11 and Left Ctrl+F12 to switch to previous orientation and next orientation respectively.

  2. You have to release Ctrl before you can rotate again.

  3. KEYPAD 7 and KEYPAD 9 only work with Num Lock OFF (so they're acting as Home & PageUp rather than 7 & 9).

  4. The only orientations are vertically upright and rotated one quarter-turn anti-clockwise.

Maybe a bit too much info for such a simple question, but it drove me half-mad finding this out.

Note: This was tested on Android SDK R16 and a very old keyboard, modern keyboards may behave differently.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access

Why the error is raised:

JavaScript code is limited by the same-origin policy, meaning, from a page at www.example.com, you can only make (AJAX) requests to services located at exactly the same domain, in that case, exactly www.example.com (not example.com - without the www - or whatever.example.com).

In your case, your Ajax code is trying to reach a service in http://wordicious.com from a page located at http://www.wordicious.com.

Although very similar, they are not the same domain. And when they are not on the same domain, the request will only be successful if the target's respose contains a Access-Control-Allow-Origin header in it.

As your page/service at http://wordicious.com was never configured to present such header, that error message is shown.

Solution:

As said, the origin (where the page with JavaScript is at) and the target (where the JavaScript is trying to reach) domains must be the exact same.

Your case seems like a typo. Looks like http://wordicious.com and http://www.wordicious.com are actually the same server/domain. So to fix, type the target and the origin equally: make you Ajax code request pages/services to http://www.wordicious.com not http://wordicious.com. (Maybe place the target URL relatively, like '/login.php', without the domain).



On a more general note:

If the problem is not a typo like the one of this question seems to be, the solution would be to add the Access-Control-Allow-Origin to the target domain. To add it, depends, of course, of the server/language behind that address. Sometimes a configuration variable in the tool will do the trick. Other times you'll have to add the headers through code yourself.

What are projection and selection?

Projections and Selections are two unary operations in Relational Algebra and has practical applications in RDBMS (relational database management systems).

In practical sense, yes Projection means selecting specific columns (attributes) from a table and Selection means filtering rows (tuples). Also, for a conventional table, Projection and Selection can be termed as vertical and horizontal slicing or filtering.

Wikipedia provides more formal definitions of these with examples and they can be good for further reading on relational algebra:

A more useful statusline in vim?

What I've found useful is to know which copy/paste buffer (register) is currently active: %{v:register}. Otherwise, my complete status line looks almost exactly like the standard line.

:set statusline=%<%f\ %h%m%r\ %y%=%{v:register}\ %-14.(%l,%c%V%)\ %P

How to find out what type of a Mat object is with Mat::type() in OpenCV

This was answered by a few others but I found a solution that worked really well for me.

System.out.println(CvType.typeToString(yourMat.type()));

Determine if 2 lists have the same elements, regardless of order?

Determine if 2 lists have the same elements, regardless of order?

Inferring from your example:

x = ['a', 'b']
y = ['b', 'a']

that the elements of the lists won't be repeated (they are unique) as well as hashable (which strings and other certain immutable python objects are), the most direct and computationally efficient answer uses Python's builtin sets, (which are semantically like mathematical sets you may have learned about in school).

set(x) == set(y) # prefer this if elements are hashable

In the case that the elements are hashable, but non-unique, the collections.Counter also works semantically as a multiset, but it is far slower:

from collections import Counter
Counter(x) == Counter(y)

Prefer to use sorted:

sorted(x) == sorted(y) 

if the elements are orderable. This would account for non-unique or non-hashable circumstances, but this could be much slower than using sets.

Empirical Experiment

An empirical experiment concludes that one should prefer set, then sorted. Only opt for Counter if you need other things like counts or further usage as a multiset.

First setup:

import timeit
import random
from collections import Counter

data = [str(random.randint(0, 100000)) for i in xrange(100)]
data2 = data[:]     # copy the list into a new one

def sets_equal(): 
    return set(data) == set(data2)

def counters_equal(): 
    return Counter(data) == Counter(data2)

def sorted_lists_equal(): 
    return sorted(data) == sorted(data2)

And testing:

>>> min(timeit.repeat(sets_equal))
13.976069927215576
>>> min(timeit.repeat(counters_equal))
73.17287588119507
>>> min(timeit.repeat(sorted_lists_equal))
36.177085876464844

So we see that comparing sets is the fastest solution, and comparing sorted lists is second fastest.

How to find prime numbers between 0 - 100?

I have slightly modified the Sieve of Sundaram algorithm to cut the unnecessary iterations and it seems to be very fast.

This algorithm is actually two times faster than the most accepted @Ted Hopp's solution under this topic. Solving the 78498 primes between 0 - 1M takes like 20~25 msec in Chrome 55 and < 90 msec in FF 50.1. Also @vitaly-t's get next prime algorithm looks interesting but also results much slower.

This is the core algorithm. One could apply segmentation and threading to get superb results.

_x000D_
_x000D_
"use strict";_x000D_
function primeSieve(n){_x000D_
  var a = Array(n = n/2),_x000D_
      t = (Math.sqrt(4+8*n)-2)/4,_x000D_
      u = 0,_x000D_
      r = [];_x000D_
  for(var i = 1; i <= t; i++){_x000D_
    u = (n-i)/(1+2*i);_x000D_
    for(var j = i; j <= u; j++) a[i + j + 2*i*j] = true;_x000D_
  }_x000D_
  for(var i = 0; i<= n; i++) !a[i] && r.push(i*2+1);_x000D_
  return r;_x000D_
}_x000D_
_x000D_
var primes = [];_x000D_
console.time("primes");_x000D_
primes = primeSieve(1000000);_x000D_
console.timeEnd("primes");_x000D_
console.log(primes.length);
_x000D_
_x000D_
_x000D_

The loop limits explained:

Just like the Sieve of Erasthotenes, the Sieve of Sundaram algorithm also crosses out some selected integers from the list. To select which integers to cross out the rule is i + j + 2ij = n where i and j are two indices and n is the number of the total elements. Once we cross out every i + j + 2ij, the remaining numbers are doubled and oddified (2n+1) to reveal a list of prime numbers. The final stage is in fact the auto discounting of the even numbers. It's proof is beautifully explained here.

Sieve of Sundaram is only fast if the loop indices start and end limits are correctly selected such that there shall be no (or minimal) redundant (multiple) elimination of the non-primes. As we need i and j values to calculate the numbers to cross out, i + j + 2ij up to n let's see how we can approach.

i) So we have to find the the max value i and j can take when they are equal. Which is 2i + 2i^2 = n. We can easily solve the positive value for i by using the quadratic formula and that is the line with t = (Math.sqrt(4+8*n)-2)/4,

j) The inner loop index j should start from i and run up to the point it can go with the current i value. No more than that. Since we know that i + j + 2ij = n, this can easily be calculated as u = (n-i)/(1+2*i);

While this will not completely remove the redundant crossings it will "greatly" eliminate the redundancy. For instance for n = 50 (to check for primes up to 100) instead of doing 50 x 50 = 2500, we will do only 30 iterations in total. So clearly, this algorithm shouldn't be considered as an O(n^2) time complexity one.

i  j  v
1  1  4
1  2  7
1  3 10
1  4 13
1  5 16
1  6 19
1  7 22  <<
1  8 25
1  9 28
1 10 31  <<
1 11 34
1 12 37  <<
1 13 40  <<
1 14 43
1 15 46
1 16 49  <<
2  2 12
2  3 17
2  4 22  << dupe #1
2  5 27
2  6 32
2  7 37  << dupe #2
2  8 42
2  9 47
3  3 24
3  4 31  << dupe #3
3  5 38
3  6 45
4  4 40  << dupe #4
4  5 49  << dupe #5

among which there are only 5 duplicates. 22, 31, 37, 40, 49. The redundancy is around 20% for n = 100 however it increases to ~300% for n = 10M. Which means a further optimization of SoS bears the potentital to obtain the results even faster as n grows. So one idea might be segmentation and to keep n small all the time.

So OK.. I have decided to take this quest a little further.

After some careful examination of the repeated crossings I have come to the awareness of the fact that, by the exception of i === 1 case, if either one or both of the i or j index value is among 4,7,10,13,16,19... series, a duplicate crossing is generated. Then allowing the inner loop to turn only when i%3-1 !== 0, a further cut down like 35-40% from the total number of the loops is achieved. So for instance for 1M integers the nested loop's total turn count dropped to like 1M from 1.4M. Wow..! We are talking almost O(n) here.

I have just made a test. In JS, just an empty loop counting up to 1B takes like 4000ms. In the below modified algorithm, finding the primes up to 100M takes the same amount of time.

I have also implemented the segmentation part of this algorithm to push to the workers. So that we will be able to use multiple threads too. But that code will follow a little later.

So let me introduce you the modified Sieve of Sundaram probably at it's best when not segmented. It shall compute the primes between 0-1M in about 15-20ms with Chrome V8 and Edge ChakraCore.

_x000D_
_x000D_
"use strict";_x000D_
function primeSieve(n){_x000D_
  var a = Array(n = n/2),_x000D_
      t = (Math.sqrt(4+8*n)-2)/4,_x000D_
      u = 0,_x000D_
      r = [];_x000D_
  for(var i = 1; i < (n-1)/3; i++) a[1+3*i] = true;_x000D_
  for(var i = 2; i <= t; i++){_x000D_
    u = (n-i)/(1+2*i);_x000D_
    if (i%3-1) for(var j = i; j < u; j++) a[i + j + 2*i*j] = true;_x000D_
  }_x000D_
  for(var i = 0; i< n; i++) !a[i] && r.push(i*2+1);_x000D_
  return r;_x000D_
}_x000D_
_x000D_
var primes = [];_x000D_
console.time("primes");_x000D_
primes = primeSieve(1000000);_x000D_
console.timeEnd("primes");_x000D_
console.log(primes.length);
_x000D_
_x000D_
_x000D_

Well... finally I guess i have implemented a sieve (which is originated from the ingenious Sieve of Sundaram) such that it's the fastest JavaScript sieve that i could have found over the internet, including the "Odds only Sieve of Eratosthenes" or the "Sieve of Atkins". Also this is ready for the web workers, multi-threading.

Think it this way. In this humble AMD PC for a single thread, it takes 3,300 ms for JS just to count up to 10^9 and the following optimized segmented SoS will get me the 50847534 primes up to 10^9 only in 14,000 ms. Which means 4.25 times the operation of just counting. I think it's impressive.

You can test it for yourself;

_x000D_
_x000D_
console.time("tare");_x000D_
for (var i = 0; i < 1000000000; i++);_x000D_
console.timeEnd("tare");
_x000D_
_x000D_
_x000D_

And here i introduce you to the segmented Seieve of Sundaram at it's best.

_x000D_
_x000D_
"use strict";_x000D_
function findPrimes(n){_x000D_
  _x000D_
  function primeSieve(g,o,r){_x000D_
    var t = (Math.sqrt(4+8*(g+o))-2)/4,_x000D_
        e = 0,_x000D_
        s = 0;_x000D_
    _x000D_
    ar.fill(true);_x000D_
    if (o) {_x000D_
      for(var i = Math.ceil((o-1)/3); i < (g+o-1)/3; i++) ar[1+3*i-o] = false;_x000D_
      for(var i = 2; i < t; i++){_x000D_
        s = Math.ceil((o-i)/(1+2*i));_x000D_
        e = (g+o-i)/(1+2*i);_x000D_
        if (i%3-1) for(var j = s; j < e; j++) ar[i + j + 2*i*j-o] = false;_x000D_
      }_x000D_
    } else {_x000D_
        for(var i = 1; i < (g-1)/3; i++) ar[1+3*i] = false;_x000D_
        for(var i = 2; i < t; i++){_x000D_
          e = (g-i)/(1+2*i);_x000D_
          if (i%3-1) for(var j = i; j < e; j++) ar[i + j + 2*i*j] = false;_x000D_
        }_x000D_
      }_x000D_
    for(var i = 0; i < g; i++) ar[i] && r.push((i+o)*2+1);_x000D_
    return r;_x000D_
  }_x000D_
  _x000D_
  var cs = n <= 1e6 ? 7500_x000D_
                    : n <= 1e7 ? 60000_x000D_
                               : 100000, // chunk size_x000D_
      cc = ~~(n/cs),                     // chunk count_x000D_
      xs = n % cs,                       // excess after last chunk_x000D_
      ar = Array(cs/2),                  // array used as map_x000D_
  result = [];_x000D_
  _x000D_
  for(var i = 0; i < cc; i++) result = primeSieve(cs/2,i*cs/2,result);_x000D_
  result = xs ? primeSieve(xs/2,cc*cs/2,result) : result;_x000D_
  result[0] *=2;_x000D_
  return result;_x000D_
}_x000D_
_x000D_
_x000D_
var primes = [];_x000D_
console.time("primes");_x000D_
primes = findPrimes(1000000000);_x000D_
console.timeEnd("primes");_x000D_
console.log(primes.length);
_x000D_
_x000D_
_x000D_

I am not sure if it gets any better than this. I would love to hear your opinions.

Connect with SSH through a proxy

I was using the following lines in my .ssh/config (which can be replaced by suitable command line parameters) under Ubuntu

Host remhost
  HostName      my.host.com
  User          myuser
  ProxyCommand  nc -v -X 5 -x proxy-ip:1080 %h %p 2> ssh-err.log
  ServerAliveInterval 30
  ForwardX11 yes

When using it with Msys2, after installing gnu-netcat, file ssh-err.log showed that option -X does not exist. nc --help confirmed that, and seemed to show that there is no alternative option to handle proxies.

So I installed openbsd-netcat (pacman removed gnu-netcat after asking, since it conflicted with openbsd-netcat). On a first view, and checking the respective man pages, openbsd-netcat and Ubuntu netcat seem to very similar, in particular regarding options -X and -x. With this, I connected with no problems.

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.

function myFunction() {
    var data;  //The Values can be like as null, blank, undefined, zero you can test

    if(!(!(data)))
    {
        alert("data "+data);
    } 
    else 
    {
        alert("data is "+data);
    }
}

Node.js - EJS - including a partial

Works with Express 4.x :

The Correct way to include partials in the template according to this you should use:

<%- include('partials/youFileName.ejs') %>.

You are using:

<% include partials/yourFileName.ejs %>

which is deprecated.

What is the purpose of mvnw and mvnw.cmd files?

Command mvnw uses Maven that is by default downloaded to ~/.m2/wrapper on the first use.

URL with Maven is specified in each project at .mvn/wrapper/maven-wrapper.properties:

distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip

To update or change Maven version invoke the following (remember about --non-recursive for multi-module projects):

./mvnw io.takari:maven:wrapper -Dmaven=3.3.9 

or just modify .mvn/wrapper/maven-wrapper.properties manually.

To generate wrapper from scratch using Maven (you need to have it already in PATH run:

mvn io.takari:maven:wrapper -Dmaven=3.3.9 

CSS table td width - fixed, not flexible

It is not only the table cell which is growing, the table itself can grow, too. To avoid this you can assign a fixed width to the table which in return forces the cell width to be respected:

table {
  table-layout: fixed;
  width: 120px; /* Important */
}
td {
  width: 30px;
}

(Using overflow: hidden and/or text-overflow: ellipsis is optional but highly recommended for a better visual experience)

So if your situation allows you to assign a fixed width to your table, this solution might be a better alternative to the other given answers (which do work with or without a fixed width)

Hide axis values but keep axis tick labels in matplotlib

to remove tickmarks entirely use:

ax.set_yticks([])
ax.set_xticks([])

otherwise ax.set_yticklabels([]) and ax.set_xticklabels([]) will keep tickmarks.

Message Queue vs. Web Services?

When you use a web service you have a client and a server:

  1. If the server fails the client must take responsibility to handle the error.
  2. When the server is working again the client is responsible of resending it.
  3. If the server gives a response to the call and the client fails the operation is lost.
  4. You don't have contention, that is: if million of clients call a web service on one server in a second, most probably your server will go down.
  5. You can expect an immediate response from the server, but you can handle asynchronous calls too.

When you use a message queue like RabbitMQ, Beanstalkd, ActiveMQ, IBM MQ Series, Tuxedo you expect different and more fault tolerant results:

  1. If the server fails, the queue persist the message (optionally, even if the machine shutdown).
  2. When the server is working again, it receives the pending message.
  3. If the server gives a response to the call and the client fails, if the client didn't acknowledge the response the message is persisted.
  4. You have contention, you can decide how many requests are handled by the server (call it worker instead).
  5. You don't expect an immediate synchronous response, but you can implement/simulate synchronous calls.

Message Queues has a lot more features but this is some rule of thumb to decide if you want to handle error conditions yourself or leave them to the message queue.

Unit Tests not discovered in Visual Studio 2017

Solution was removing my app.config file from my unit test project. The tests will re-appear!

This file referenced some dll's in the bindingredirects that were not actually present in the project references. Re-add the assemblybindings that are strictly necessary for your project.

Matplotlib-Animation "No MovieWriters Available"

Had the same problem....managed to get it to work after a little while.

Thing to do is follow instructions on installing FFmpeg - which is (at least on windows) a bundle of executables you need to set a path to in your environment variables

http://www.wikihow.com/Install-FFmpeg-on-Windows

Download from ffmpeg.org

Hope this helps someone - even after a while after the question - good luck

Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException

The CosisEntities class is your DbContext. When you create a context in a using block, you're defining the boundaries for your data-oriented operation.

In your code, you're trying to emit the result of a query from a method and then end the context within the method. The operation you pass the result to then tries to access the entities in order to populate the grid view. Somewhere in the process of binding to the grid, a lazy-loaded property is being accessed and Entity Framework is trying to perform a lookup to obtain the values. It fails, because the associated context has already ended.

You have two problems:

  1. You're lazy-loading entities when you bind to the grid. This means that you're doing lots of separate query operations to SQL Server, which are going to slow everything down. You can fix this issue by either making the related properties eager-loaded by default, or asking Entity Framework to include them in the results of this query by using the Include extension method.

  2. You're ending your context prematurely: a DbContext should be available throughout the unit of work being performed, only disposing it when you're done with the work at hand. In the case of ASP.NET, a unit of work is typically the HTTP request being handled.

Python regex to match dates

I find the below RE working fine for Date in the following format;

  1. 14-11-2017
  2. 14.11.2017
  3. 14|11|2017

It can accept year from 2000-2099

Please do not forget to add $ at the end,if not it accept 14-11-201 or 20177

date="13-11-2017"

x=re.search("^([1-9] |1[0-9]| 2[0-9]|3[0-1])(.|-)([1-9] |1[0-2])(.|-|)20[0-9][0-9]$",date)

x.group()

output = '13-11-2017'

Python pandas insert list into a cell

df3.set_value(1, 'B', abc) works for any dataframe. Take care of the data type of column 'B'. Eg. a list can not be inserted into a float column, at that case df['B'] = df['B'].astype(object) can help.

android download pdf from url then open it with a pdf reader

This is the best method to download and view PDF file.You can just call it from anywhere as like

PDFTools.showPDFUrl(context, url);

here below put the code. It will works fine

public class PDFTools {
private static final String TAG = "PDFTools";
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";


public static void showPDFUrl(final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    //final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    String filename = "";
    try {
        filename = new GetFileInfo().execute(pdfUrl).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
    Log.e(TAG,"File Path:"+tempFile);
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        openPDF( context, Uri.fromFile( tempFile ) );
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    openPDF( context, Uri.fromFile( tempFile ) );
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}


public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}

public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}

public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
    i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}

// get File name from url
static class GetFileInfo extends AsyncTask<String, Integer, String>
{
    protected String doInBackground(String... urls)
    {
        URL url;
        String filename = null;
        try {
            url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            conn.setInstanceFollowRedirects(false);
            if(conn.getHeaderField("Content-Disposition")!=null){
                String depo = conn.getHeaderField("Content-Disposition");

                String depoSplit[] = depo.split("filename=");
                filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
            }else{
                filename = "download.pdf";
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
        }
        return filename;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // use result as file name
    }
}

}

try it. it will works, enjoy

Can I run javascript before the whole page is loaded?

Not only can you, but you have to make a special effort not to if you don't want to. :-)

When the browser encounters a classic script tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write calls to output markup that the parser should handle).

That's the default behavior, but you have a few options for delaying script execution:

  1. Use JavaScript modules. A type="module" script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:

    <script type="module" src="./my-code.js"></script>
    <!-- Or -->
    <script type="module">
    // Your code here
    </script>
    

    The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)

    This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.

  2. Use the defer attribute on a classic script tag:

    <script defer src="./my-code.js"></script>
    

    As with the module, the code in my-code.js will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer doesn't work with inline script content, only with external files referenced via src.

  3. I don't think it's what you want, but you can use the async attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module" tag, or use it instead of defer on a classic script tag.

  4. Put the script tag at the end of the document, just prior to the closing </body> tag:

    <!doctype html>
    <html>
    <!-- ... -->
    <body>
    <!-- The document's HTML goes here -->
    <script type="module" src="./my-code.js"></script><!-- Or inline script -->
    </body>
    </html>
    

    That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.

    It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer are better options.

The spec has a useful diagram showing a raw script tag, defer, async, type="module", and type="module" async and the timing of when the JavaScript code is fetched and run:

enter image description here

Here's an example of the default behavior, a raw script tag:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
    if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
        NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
    }_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

(See my answer here for details around that NodeList code.)

When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.

In contrast, here's a type="module" script:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer script with external content (but not inline content).

(There was no need for the NodeList check there because any modern browser supporting modules already has forEach on NodeList.)

In this modern world, there's no real value to the DOMContentLoaded event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script was in the head instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body, again back in the day.

PHP mailer multiple address

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

Deleting rows with MySQL LEFT JOIN

MySQL allows you to use the INNER JOIN clause in the DELETE statement to delete rows from a table and the matching rows in another table.

For example, to delete rows from both T1 and T2 tables that meet a specified condition, you use the following statement:

DELETE T1, T2
FROM T1
INNER JOIN T2 ON T1.key = T2.key
WHERE condition;

Notice that you put table names T1 and T2 between the DELETE and FROM keywords. If you omit T1 table, the DELETE statement only deletes rows in T2 table. Similarly, if you omitT2 table, the DELETE statement will delete only rows in T1 table.

Hope this help.

How can I check for existence of element in std::vector, in one line?

int elem = 42;
std::vector<int> v;
v.push_back(elem);
if(std::find(v.begin(), v.end(), elem) != v.end())
{
  //elem exists in the vector
} 

How do I check if an element is hidden in jQuery?

Often when checking if something is visible or not, you are going to go right ahead immediately and do something else with it. jQuery chaining makes this easy.

So if you have a selector and you want to perform some action on it only if is visible or hidden, you can use filter(":visible") or filter(":hidden") followed by chaining it with the action you want to take.

So instead of an if statement, like this:

if ($('#btnUpdate').is(":visible"))
{
     $('#btnUpdate').animate({ width: "toggle" });   // Hide button
}

Or more efficient, but even uglier:

var button = $('#btnUpdate');
if (button.is(":visible"))
{
     button.animate({ width: "toggle" });   // Hide button
}

You can do it all in one line:

$('#btnUpdate').filter(":visible").animate({ width: "toggle" });

MySQL CREATE FUNCTION Syntax

You have to override your ; delimiter with something like $$ to avoid this kind of error.

After your function definition, you can set the delimiter back to ;.

This should work:

DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal) 
RETURNS decimal
DETERMINISTIC
BEGIN 
  DECLARE dist decimal;
  SET dist = SQRT(x1 - y1);
  RETURN dist;
END$$
DELIMITER ;

Determining whether an object is a member of a collection in VBA

This is an old question. I have carefully reviewed all the answers and comments, tested the solutions for performance.

I came up with the fastest option for my environment which does not fail when a collection has objects as well as primitives.

Public Function ExistsInCollection(col As Collection, key As Variant) As Boolean
    On Error GoTo err
    ExistsInCollection = True
    IsObject(col.item(key))
    Exit Function
err:
    ExistsInCollection = False
End Function

In addition, this solution does not depend on hard-coded error values. So the parameter col As Collection can be substituted by some other collection type variable, and the function must still work. E.g., on my current project, I will have it as col As ListColumns.

Swift addsubview and remove it

I've a view inside my custom CollectionViewCell, and embedding a graph on that view. In order to refresh it, I've to check if there is already a graph placed on that view, remove it and then apply new. Here's the solution

cell.cellView.addSubview(graph)
graph.tag = 10

now, in code block where you want to remove it (in your case gestureRecognizerFunction)

if let removable = cell.cellView.viewWithTag(10){
   removable.removeFromSuperview()
}

to embed it again

cell.cellView.addSubview(graph)
graph.tag = 10

How to add a new row to an empty numpy array

In case of adding new rows for array in loop, Assign the array directly for firsttime in loop instead of initialising an empty array.

for i in range(0,len(0,100)):
    SOMECALCULATEDARRAY = .......
    if(i==0):
        finalArrayCollection = SOMECALCULATEDARRAY
    else:
        finalArrayCollection = np.vstack(finalArrayCollection,SOMECALCULATEDARRAY)

This is mainly useful when the shape of the array is unknown

Can I serve multiple clients using just Flask app.run() as standalone?

flask.Flask.run accepts additional keyword arguments (**options) that it forwards to werkzeug.serving.run_simple - two of those arguments are threaded (a boolean) and processes (which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).

threaded defaults to True as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True to enable this behaviour.

For example, you can do

if __name__ == '__main__':
    app.run(threaded=True)

to handle multiple clients using threads in a way compatible with old Flask versions, or

if __name__ == '__main__':
    app.run(threaded=False, processes=3)

to tell Werkzeug to spawn three processes to handle incoming requests, or just

if __name__ == '__main__':
    app.run()

to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.

That being said, Werkzeug's serving.run_simple wraps the standard library's wsgiref package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).

Make page to tell browser not to cache/preserve input values

Another approach would be to reset the form using JavaScript right after the form in the HTML:

<form id="myForm">
  <input type="text" value="" name="myTextInput" />
</form>

<script type="text/javascript">
  document.getElementById("myForm").reset();
</script>

Show dialog from fragment?

    public static void OpenDialog (Activity activity, DialogFragment fragment){

    final FragmentManager fm = ((FragmentActivity)activity).getSupportFragmentManager();

    fragment.show(fm, "tag");
}

How do you underline a text in Android XML?

If you want to compare text String or the text will change dynamically then you can created a view in Constraint layout it will adjust according to text length like this

 <android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/txt_Previous"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="8dp"
        android:gravity="center"
        android:text="Last Month Rankings"
        android:textColor="@color/colorBlue"
        android:textSize="15sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <View
        android:layout_width="0dp"
        android:layout_height="0.7dp"
        android:background="@color/colorBlue"
        app:layout_constraintEnd_toEndOf="@+id/txt_Previous"
        app:layout_constraintStart_toStartOf="@+id/txt_Previous"
        app:layout_constraintBottom_toBottomOf="@id/txt_Previous"/>


</android.support.constraint.ConstraintLayout>

How to set component default props on React component

If you're using a functional component, you can define defaults in the destructuring assignment, like so:

export default ({ children, id="menu", side="left", image={menu} }) => {
  ...
};

What's the difference between a single precision and double precision floating point operation?

Double precision means the numbers takes twice the word-length to store. On a 32-bit processor, the words are all 32 bits, so doubles are 64 bits. What this means in terms of performance is that operations on double precision numbers take a little longer to execute. So you get a better range, but there is a small hit on performance. This hit is mitigated a little by hardware floating point units, but its still there.

The N64 used a MIPS R4300i-based NEC VR4300 which is a 64 bit processor, but the processor communicates with the rest of the system over a 32-bit wide bus. So, most developers used 32 bit numbers because they are faster, and most games at the time did not need the additional precision (so they used floats not doubles).

All three systems can do single and double precision floating operations, but they might not because of performance. (although pretty much everything after the n64 used a 32 bit bus so...)

How do I pass parameters into a PHP script through a webpage?

$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter

If you want to all the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

<?php
if ($_GET) {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
} else {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
?>

To call from command line chmod 755 /var/www/webroot/index.php and use

/usr/bin/php /var/www/webroot/index.php arg1 arg2

To call from the browser, use

http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2

IE6/IE7 css border on select element

From my personal experience where we tryed to put the border red when an invalid entry was selected, it is impossible to put border red of select element in IE.

As stated before the ocntrols in internet explorer uses WindowsAPI to draw and render and you have nothing to solve this.

What was our solution was to put the background color of select element light red (for text to be readable). background color was working in every browser, but in IE we had a side effects that the element where the same background color as the select.

So to summarize the solution we putted :

select
{
  background-color:light-red;
  border: 2px solid red;
}
option
{
  background-color:white;
}

Note that color was set with hex code, I just don't remember which.

This solution was giving us the wanted effect in every browser except for the border red in IE.

Good luck

What do these operators mean (** , ^ , %, //)?

You can find all of those operators in the Python language reference, though you'll have to scroll around a bit to find them all. As other answers have said:

  • The ** operator does exponentiation. a ** b is a raised to the b power. The same ** symbol is also used in function argument and calling notations, with a different meaning (passing and receiving arbitrary keyword arguments).
  • The ^ operator does a binary xor. a ^ b will return a value with only the bits set in a or in b but not both. This one is simple!
  • The % operator is mostly to find the modulus of two integers. a % b returns the remainder after dividing a by b. Unlike the modulus operators in some other programming languages (such as C), in Python a modulus it will have the same sign as b, rather than the same sign as a. The same operator is also used for the "old" style of string formatting, so a % b can return a string if a is a format string and b is a value (or tuple of values) which can be inserted into a.
  • The // operator does Python's version of integer division. Python's integer division is not exactly the same as the integer division offered by some other languages (like C), since it rounds towards negative infinity, rather than towards zero. Together with the modulus operator, you can say that a == (a // b)*b + (a % b). In Python 2, floor division is the default behavior when you divide two integers (using the normal division operator /). Since this can be unexpected (especially when you're not picky about what types of numbers you get as arguments to a function), Python 3 has changed to make "true" (floating point) division the norm for division that would be rounded off otherwise, and it will do "floor" division only when explicitly requested. (You can also get the new behavior in Python 2 by putting from __future__ import division at the top of your files. I strongly recommend it!)

How to copy data from another workbook (excel)?

I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -

Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")

The Range("A1") in Sheet1 of Book1 now contains "A".

Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".

The Role Manager feature has not been enabled

If you got here because you're using the new ASP.NET Identity UserManager, what you're actually looking for is the RoleManager:

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

roleManager will give you access to see if the role exists, create, etc, plus it is created for the UserManager

Can't create handler inside thread that has not called Looper.prepare()

UPDATE - 2016

The best alternative is to use RxAndroid (specific bindings for RxJava) for the P in MVP to take charge fo data.

Start by returning Observable from your existing method.

private Observable<PojoObject> getObservableItems() {
    return Observable.create(subscriber -> {

        for (PojoObject pojoObject: pojoObjects) {
            subscriber.onNext(pojoObject);
        }
        subscriber.onCompleted();
    });
}

Use this Observable like this -

getObservableItems().
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread()).
subscribe(new Observer<PojoObject> () {
    @Override
    public void onCompleted() {
        // Print Toast on completion
    }

    @Override
    public void onError(Throwable e) {}

    @Override
    public void onNext(PojoObject pojoObject) {
        // Show Progress
    }
});
}

----------------------------------------------------------------------------------------------------------------------------------

I know I am a little late but here goes. Android basically works on two thread types namely UI thread and background thread. According to android documentation -

Do not access the Android UI toolkit from outside the UI thread to fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:

Activity.runOnUiThread(Runnable)  
View.post(Runnable)  
View.postDelayed(Runnable, long)

Now there are various methods to solve this problem.

I will explain it by code sample:

runOnUiThread

new Thread()
{
    public void run()
    {
        myactivity.this.runOnUiThread(new Runnable()
        {
            public void run()
            {
                //Do your UI operations like dialog opening or Toast here
            }
        });
    }
}.start();

LOOPER

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

class LooperThread extends Thread {
    public Handler mHandler;

    public void run() {
        Looper.prepare();

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // process incoming messages here
            }
        };

        Looper.loop();
    }
}

AsyncTask

AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

public void onClick(View v) {
    new CustomTask().execute((Void[])null);
}


private class CustomTask extends AsyncTask<Void, Void, Void> {

    protected Void doInBackground(Void... param) {
        //Do some work
        return null;
    }

    protected void onPostExecute(Void param) {
        //Print Toast or open dialog
    }
}

Handler

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.

Message msg = new Message();


new Thread()
{
    public void run()
    {
        msg.arg1=1;
        handler.sendMessage(msg);
    }
}.start();



Handler handler = new Handler(new Handler.Callback() {

    @Override
    public boolean handleMessage(Message msg) {
        if(msg.arg1==1)
        {
            //Print Toast or open dialog        
        }
        return false;
    }
});

IIS: Idle Timeout vs Recycle

From here:

One way to conserve system resources is to configure idle time-out settings for the worker processes in an application pool. When these settings are configured, a worker process will shut down after a specified period of inactivity. The default value for idle time-out is 20 minutes.

Also check Why is the IIS default app pool recycle set to 1740 minutes?

If you have a just a few sites on your server and you want them to always load fast then set this to zero. Otherwise, when you have 20 minutes without any traffic then the app pool will terminate so that it can start up again on the next visit. The problem is that the first visit to an app pool needs to create a new w3wp.exe worker process which is slow because the app pool needs to be created, ASP.NET or another framework needs to be loaded, and then your application needs to be loaded. That can take a few seconds. Therefore I set that to 0 every chance I have, unless it’s for a server that hosts a lot of sites that don’t always need to be running.

Angular 2 Unit Tests: Cannot find name 'describe'

I'm on Angular 6, Typescript 2.7, and I'm using Jest framework to unit test. I had @types/jest installed and added on typeRoots inside tsconfig.json

But still have the display error below (i.e: on terminal there is no errors)

cannot find name describe

And adding the import :

import {} from 'jest'; // in my case or jasmine if you're using jasmine

doesn't technically do anything, so I thought, that there is an import somewhere causing this problem, then I found, that if delete the file

tsconfig.spec.json

in the src/ folder, solved the problem for me. As @types is imported before inside the rootTypes.

I recommend you to do same and delete this file, no needed config is inside. (ps: if you're in the same case as I am)

PHP unable to load php_curl.dll extension

After having tried everything here I had to simply upgrade Apache to a newer version in order to make curl extension work.

I was upgrading PHP from 7.0.2 to 7.1.15 after which curl did not work. Only way to fix it was upgrade Apache (which was version 2.4.18) to the latest 2.4.29.

Didn't have to copy any of the lib/ssleay dll files to either Apache or Windows - possibly because I already have the PHP folder in my system path.

Running Windows 10, 64-bit, thread-safe versions, VC14.

How do I get indices of N maximum values in a NumPy array?

Newer NumPy versions (1.8 and up) have a function called argpartition for this. To get the indices of the four largest elements, do

>>> a = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
>>> a
array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
>>> ind = np.argpartition(a, -4)[-4:]
>>> ind
array([1, 5, 8, 0])
>>> a[ind]
array([4, 9, 6, 9])

Unlike argsort, this function runs in linear time in the worst case, but the returned indices are not sorted, as can be seen from the result of evaluating a[ind]. If you need that too, sort them afterwards:

>>> ind[np.argsort(a[ind])]
array([1, 8, 5, 0])

To get the top-k elements in sorted order in this way takes O(n + k log k) time.

Convert a python 'type' object to a string

print("My type is %s" % type(someObject)) # the type in python

or...

print("My type is %s" % type(someObject).__name__) # the object's type (the class you defined)

Streaming Audio from A URL in Android using MediaPlayer?

Android MediaPlayer doesn't support streaming of MP3 natively until 2.2. In older versions of the OS it appears to only stream 3GP natively. You can try the pocketjourney code, although it's old (there's a new version here) and I had trouble making it sticky — it would stutter whenever it refilled the buffer.

The NPR News app for Android is open source and uses a local proxy server to handle MP3 streaming in versions of the OS before 2.2. You can see the relevant code in lines 199-216 (r94) here: http://code.google.com/p/npr-android-app/source/browse/Npr/src/org/npr/android/news/PlaybackService.java?r=7cf2352b5c3c0fbcdc18a5a8c67d836577e7e8e3

And this is the StreamProxy class: http://code.google.com/p/npr-android-app/source/browse/Npr/src/org/npr/android/news/StreamProxy.java?r=e4984187f45c39a54ea6c88f71197762dbe10e72

The NPR app is also still getting the "error (-38, 0)" sometimes while streaming. This may be a threading issue or a network change issue. Check the issue tracker for updates.

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

I think the upgrade of Java will not help. You need to uninstall the old version and then install the latest java version to help you. Make sure that you restart the computer once you are done with the installation.

Hope it helps!

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

maybe you forget to add parameter dataType:'json' in your $.ajax

$.ajax({
   type: "POST",
   dataType: "json",
   url: url,
   data: { get_member: id },
   success: function( response ) 
   { 
     //some action here
   },
   error: function( error )
   {
     alert( error );
   }
});

What are intent-filters in Android?

Keep the first intent filter with keys MAIN and LAUNCHER and add another as ANY_NAME and DEFAULT.

Your LAUNCHER will be activity A and DEFAULT will be your activity B.

Laravel assets url

Besides put all your assets in the public folder, you can use the HTML::image() Method, and only needs an argument which is the path to the image, relative on the public folder, as well:

{{ HTML::image('imgs/picture.jpg') }}

Which generates the follow HTML code:

<img src="http://localhost:8000/imgs/picture.jpg">

The link to other elements of HTML::image() Method: http://laravel-recipes.com/recipes/185/generating-an-html-image-element

How to POST request using RestSharp

I added this helper method to handle my POST requests that return an object I care about.

For REST purists, I know, POSTs should not return anything besides a status. However, I had a large collection of ids that was too big for a query string parameter.

Helper Method:

    public TResponse Post<TResponse>(string relativeUri, object postBody) where TResponse : new()
    {
        //Note: Ideally the RestClient isn't created for each request. 
        var restClient = new RestClient("http://localhost:999");

        var restRequest = new RestRequest(relativeUri, Method.POST)
        {
            RequestFormat = DataFormat.Json
        };

        restRequest.AddBody(postBody);

        var result = restClient.Post<TResponse>(restRequest);

        if (!result.IsSuccessful)
        {
            throw new HttpException($"Item not found: {result.ErrorMessage}");
        }

        return result.Data;
    }

Usage:

    public List<WhateverReturnType> GetFromApi()
    {
        var idsForLookup = new List<int> {1, 2, 3, 4, 5};

        var relativeUri = "/api/idLookup";

        var restResponse = Post<List<WhateverReturnType>>(relativeUri, idsForLookup);

        return restResponse;
    }

What does "Table does not support optimize, doing recreate + analyze instead" mean?

The better option is create a new table copy the rows to the destination table, drop the actual table and rename the newly created table . This method is good for small tables,

How to execute a Python script from the Django shell?

Note, this method has been deprecated for more recent versions of django! (> 1.3)

An alternative answer, you could add this to the top of my_script.py

from django.core.management import setup_environ
import settings
setup_environ(settings)

and execute my_script.py just with python in the directory where you have settings.py but this is a bit hacky.

$ python my_script.py

How to find specified name and its value in JSON-string from Java?

I agree that Google's Gson is clear and easy to use. But you should create a result class for getting an instance from JSON string. If you can't clarify the result class, use json-simple:

// import static org.hamcrest.CoreMatchers.is;
// import static org.junit.Assert.assertThat;
// import org.json.simple.JSONObject;
// import org.json.simple.JSONValue;
// import org.junit.Test;

@Test
public void json2Object() {
    // given
    String jsonString = "{\"name\" : \"John\",\"age\" : \"20\","
            + "\"address\" : \"some address\","
            + "\"someobject\" : {\"field\" : \"value\"}}";

    // when
    JSONObject object = (JSONObject) JSONValue.parse(jsonString);

    // then
    @SuppressWarnings("unchecked")
    Set<String> keySet = object.keySet();
    for (String key : keySet) {
        Object value = object.get(key);
        System.out.printf("%s=%s (%s)\n", key, value, value.getClass()
                .getSimpleName());
    }

    assertThat(object.get("age").toString(), is("20"));
}

Pros and cons of Gson and json-simple is pretty much like pros and cons of user-defined Java Object and Map. The object you define is clear for all fields (name and type), but less flexible than Map.

How do I get list of all tables in a database using TSQL?

select * from sysobjects where xtype='U'

How to display all elements in an arraylist?

Are you trying to make something like this?

public List<Car> getAll() {
    return new ArrayList<Car>(cars);
}

And then calling it:

List<Car> cars = c1.getAll();
for (Car item : cars) {   
    System.out.println(item.getMake() + " " + item.getReg());
}

How to set a Fragment tag by code?

You can also get all fragments like this:

For v4 fragmets

List<Fragment> allFragments = getSupportFragmentManager().getFragments();

For app.fragment

List<Fragment> allFragments = getFragmentManager().getFragments();

error opening trace file: No such file or directory (2)

You will not have access to your real sd card in emulator. You will have to follow the steps in this tutorial to direct your emulator to a directory on your development environment acting as your SD card.

How to Validate on Max File Size in Laravel?

Edit: Warning! This answer worked on my XAMPP OsX environment, but when I deployed it to AWS EC2 it did NOT prevent the upload attempt.

I was tempted to delete this answer as it is WRONG But instead I will explain what tripped me up

My file upload field is named 'upload' so I was getting "The upload failed to upload.". This message comes from this line in validation.php:

in resources/lang/en/validaton.php:

'uploaded' => 'The :attribute failed to upload.',

And this is the message displayed when the file is larger than the limit set by PHP.

I want to over-ride this message, which you normally can do by passing a third parameter $messages array to Validator::make() method.

However I can't do that as I am calling the POST from a React Component, which renders the form containing the csrf field and the upload field.

So instead, as a super-dodgy-hack, I chose to get into my view that displays the messages and replace that specific message with my friendly 'file too large' message.

Here is what works if the file to smaller than the PHP file size limit:

In case anyone else is using Laravel FormRequest class, here is what worked for me on Laravel 5.7:

This is how I set a custom error message and maximum file size:

I have an input field <input type="file" name="upload">. Note the CSRF token is required also in the form (google laravel csrf_field for what this means).

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
  ...
  ...
  public function rules() {
    return [
      'upload' => 'required|file|max:8192',
    ];
  }
  public function messages()
  {
    return [            
      'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
      'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
    ];
  }
}

Cannot read property 'push' of undefined when combining arrays

answer to your question is simple order is not a object make it an array. var order = new Array(); order.push(/item to push/); when ever this error appears just check the left of which property the error is in this case it is push which is order[] so it is undefined.

Submit form using a button outside the <form> tag

I had an issue where I was trying to hide the form from a table cell element, but still show the forms submit-button. The problem was that the form element was still taking up an extra blank space, making the format of my table cell look weird. The display:none and visibility:hidden attributes didn't work because it would hide the submit button as well, since it was contained within the form I was trying to hide. The simple answer was to set the forms height to barely nothing using CSS

So,

CSS -

    #formID {height:4px;}

worked for me.

Switch on Enum in Java

You might be using the enums incorrectly in the switch cases. In comparison with the above example by CoolBeans.. you might be doing the following:

switch(day) {
    case Day.MONDAY:
        // Something..
        break;
    case Day.FRIDAY:
        // Something friday
        break;
}

Make sure that you use the actual enum values instead of EnumType.EnumValue

Eclipse points out this mistake though..

How to find length of a string array?

In Java, we declare a String of arrays (eg. car) as

String []car;
String car[];

We create the array using new operator and by specifying its type:-

String []car=new String[];
String car[]=new String[];

This assigns a reference, to an array of Strings, to car. You can also create the array by initializing it:-

String []car={"Sedan","SUV","Hatchback","Convertible"};

Since you haven't initialized an array and you're trying to access it, a NullPointerException is thrown.

How to do IF NOT EXISTS in SQLite

If you want to ignore the insertion of existing value, there must be a Key field in your Table. Just create a table With Primary Key Field Like:

CREATE TABLE IF NOT EXISTS TblUsers (UserId INTEGER PRIMARY KEY, UserName varchar(100), ContactName varchar(100),Password varchar(100));

And Then Insert Or Replace / Insert Or Ignore Query on the Table Like:

INSERT OR REPLACE INTO TblUsers (UserId, UserName, ContactName ,Password) VALUES('1','UserName','ContactName','Password');

It Will Not Let it Re-Enter The Existing Primary key Value... This Is how you can Check Whether a Value exists in the table or not.

How to check if a text field is empty or not in swift

It's too late and its working fine in Xcode 7.3.1

if _txtfield1.text!.isEmpty || _txtfield2.text!.isEmpty {
        //is empty
    }

Change icon on click (toggle)

$("#togglebutton").click(function () {
  $(".fa-arrow-circle-left").toggleClass("fa-arrow-circle-right");
}

I have a button with the id "togglebutton" and an icon from FontAwesome . This can be a way to toggle it . from left arrow to right arrow icon

Is it really impossible to make a div fit its size to its content?

CSS display setting

It is of course possible - JSFiddle proof of concept where you can see all three possible solutions:

  • display: inline-block - this is the one you're not aware of

  • position: absolute

  • float: left/right

Select arrow style change

I wanna clear something that no one mention before I think.

  1. First get your svg image or icon
  2. There you will get some xml code like these <svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M4 10.127L12 18.127L20 10.127H4Z" fill="#8E8E93"/> </svg> try to find it.
  3. And past it after this code data:image/svg+xml;utf8,
  4. Replace the fill color fill="#8E8E93" to this fill="%238E8E93" If you want to add hexadecmal color you should change # to %23

Here is the html code:

              <fieldset>
                <label for="editName">Country</label>
                    <select class="ra-select">
                      <option value="bangladesh" selected>Bangladesh</option>
                      <option value="saudi arabia">Saudi Arabia</option>
                      <option value="us">Uinited State Of America</option>
                      <option value="india">India</option>
                    </select>
                </fieldset>

Here is the css code:

.ra-select {
   width: 30%;
   padding: 10px;
   /* Replace Default styling (arrow) */
   appearance: none;
   -webkit-appearance: none;
   -moz-appearance: none;
   background-image: url('data:image/svg+xml;utf8,<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 10.127L12 18.127L20 10.127H4Z" fill="%238E8E93"/></svg>');
   background-repeat: no-repeat;
   background-position-y: 50%;
   background-position-x: 98%;
}

.ra-select:focus,
.ra-select:hover {
   outline: none;
   border: 1px solid #bbb;
}

.ra-select option {
   background-color: #fff;
}

Best way to do Version Control for MS Excel

There is also a program called Beyond Compare that has a quite nice Excel file compare. I found a screenshot in chinese that briefly shows this:

Beyond Compare - comparing two excel files (Chinese)
Original image source

There is a 30 day trial on their page

What does %>% function mean in R?

The R packages dplyr and sf import the operator %>% from the R package magrittr.

Help is available by using the following command:

?'%>%'

Of course the package must be loaded before by using e.g.

library(sf)

The documentation of the magrittr forward-pipe operator gives a good example: When functions require only one argument, x %>% f is equivalent to f(x)

initialize a vector to zeros C++/C++11

You don't need initialization lists for that:

std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);

Load an image from a url into a PictureBox

If you are trying to load the image at your form_load, it's a better idea to use the code

pictureBox1.LoadAsync(@"http://google.com/test.png");

not only loading from web but also no lag in your form loading.

What is the effect of encoding an image in base64?

Encoding an image to base64 will make it about 30% bigger.

See the details in the wikipedia article about the Data URI scheme, where it states:

Base64-encoded data URIs are 1/3 larger in size than their binary equivalent. (However, this overhead is reduced to 2-3% if the HTTP server compresses the response using gzip)

Bash loop ping successful

Here's my one-liner solution:

screen -S internet-check -d -m -- bash -c 'while ! ping -c 1 google.com; do echo -; done; echo Google responding to ping | mail -s internet-back [email protected]'

This runs an infinite ping in a new screen session until there is a response, at which point it sends an e-mail to [email protected]. Useful in the age of e-mail sent to phones.

(You might want to check that mail is configured correctly by just running echo test | mail -s test [email protected] first. Of course you can do whatever you want from done; onwards, sound a bell, start a web browser, use your imagination.)

How do I fix a Git detached head?

Here's what I just did after I realized I was on a detached head and had already made some changes.

I committed the changes.

$ git commit -m "..."
[detached HEAD 1fe56ad] ...

I remembered the hash (1fe56ad) of the commit. Then I checked out the branch I should have been on.

$ git checkout master
Switched to branch 'master'

Finally I applied the changes of the commit to the branch.

$ git cherry-pick 1fe56ad
[master 0b05f1e] ...

I think this is a bit easier than creating a temporary branch.

Jquery change <p> text programmatically

"saving" is something wholly different from changing paragraph content with jquery.

If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").

Judging by your question, this is a topic on which you will have to do MUCH more research.

Input page (input.html):

<form action="/saveMyParagraph.php">
    <input name="pContent" type="text"></input>
</form>

Saving page (saveMyParagraph.php) and Ouput page (output.php):

Inserting Data Into a MySQL Database using PHP

How to suppress warnings globally in an R Script

I have replaced the printf calls with calls to warning in the C-code now. It will be effective in the version 2.17.2 which should be available tomorrow night. Then you should be able to avoid the warnings with suppressWarnings() or any of the other above mentioned methods.

suppressWarnings({ your code })

How to make scipy.interpolate give an extrapolated result beyond the input range?

The below code gives you the simple extrapolation module. k is the value to which the data set y has to be extrapolated based on the data set x. The numpy module is required.

 def extrapol(k,x,y):
        xm=np.mean(x);
        ym=np.mean(y);
        sumnr=0;
        sumdr=0;
        length=len(x);
        for i in range(0,length):
            sumnr=sumnr+((x[i]-xm)*(y[i]-ym));
            sumdr=sumdr+((x[i]-xm)*(x[i]-xm));

        m=sumnr/sumdr;
        c=ym-(m*xm);
        return((m*k)+c)

How do I set the classpath in NetBeans?

Maven

The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.

Dependency

Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.

Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.

Repository

Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).

Easy to Use

Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.

enter image description here

Adding a slide effect to bootstrap dropdown

Also it's possible to avoid using JavaScript for drop-down effect, and use CSS3 transition, by adding this small piece of code to your style:

.dropdown .dropdown-menu {
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    -ms-transition: all 0.3s;
    -o-transition: all 0.3s;
    transition: all 0.3s;

    max-height: 0;
    display: block;
    overflow: hidden;
    opacity: 0;
}

.dropdown.open .dropdown-menu { /* For Bootstrap 4, use .dropdown.show instead of .dropdown.open */
    max-height: 300px;
    opacity: 1;
}

The only problem with this way is that you should manually specify max-height. If you set a very big value, your animation will be very quick.

It works like a charm if you know the approximate height of your dropdowns, otherwise you still can use javascript to set a precise max-height value.

Here is small example: DEMO


! There is small bug with padding in this solution, check Jacob Stamm's comment with solution.

How Exactly Does @param Work - Java

You might miss @author and inside of @param you need to explain what's that parameter for, how to use it, etc.

How does Google calculate my location on a desktop?

Rejecting the WiFi networks idea!

Sorry folks... I don't see it. Using WiFi networks around you seems to be a highly inaccurate and ineffective method of collecting data. WiFi networks these days simply don't stay long in one place.

Think about it, the WiFi networks change every day. Not to mention MiFi and Adhoc networks which are "designed" to be mobile and travel with the users. Equipment breaks, network settings change, people move... Relying on "WiFi Networks" in your area seems highly inaccurate and in the end may not even offer a significant improvement in granularity over IP lookup.

I think the idea that iPhone users are "scanning and sending" the WiFi survey data back to google, and the wardriving, perhaps in conjunction with the Google Maps "Street View" mapping might seem like a very possible method of collecting this data however, in practicality, it does not work as a business model.

Oh and btw, I forgot to mention in my prior post... when I originally pulled my location the time I was pinpointed "precisely" on the map I was connecting to a router from my desktop over an ethernet connection. I don't have a WiFi card on my desktop.

So if that "nearby WiFi networks" theory was true... then I shouldn't have been able to pinpoint my location with such precision.

I'll call my ISP, SKyrim, and ask them as to whether they share their network topology to enable geolocation on their networks.

Create a List that contain each Line of a File

It's a lot easier than that:

List = open("filename.txt").readlines()

This returns a list of each line in the file.

Adding backslashes without escaping [Python]

>>> '\\&' == '\&'
True
>>> len('\\&')
2
>>> print('\\&')
\&

Or in other words: '\\&' only contains one backslash. It's just escaped in the python shell's output for clarity.

How to read HDF5 files in Python

from keras.models import load_model 

h= load_model('FILE_NAME.h5')

How do you determine what technology a website is built on?

yes there are some telltale signs for common CMSs like Drupal, Joomla, Pligg, and RoR etc .. .. ASP.NET stuff is easy to spot too .. but as the framework becomes more obscure it gets harder to deduce ..

What I usually is compare the site i am snooping with another site that I know is built using a particular tech. That sometimes works ..

Full Screen Theme for AppCompat

Issues arise among before and after versions of Android 4.0 (API level 14).

from here I created my own solution.

@SuppressLint("NewApi")
@Override
protected void onResume()
{
    super.onResume();

    if (Build.VERSION.SDK_INT < 16)
    {
        // Hide the status bar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // Hide the action bar
        getSupportActionBar().hide();
    }
    else
    {
        // Hide the status bar
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        / Hide the action bar
        getActionBar().hide();
    }
}

I write this code in onResume() method because if you exit from your app and then you reopen it, the action bar remains active! (and so this fix the problem)

I hope it was helpful ;)

How to create friendly URL in php?

It looks like you are talking about a RESTful webservice.

http://en.wikipedia.org/wiki/Representational_State_Transfer

The .htaccess file does rewrite all URIs to point to one controller, but that is more detailed then you want to get at this point. You may want to look at Recess

It's a RESTful framework all in PHP

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

Using Accept header is really easy to get the format json or xml from the REST service.

This is my Controller, take a look produces section.

@RequestMapping(value = "properties", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.GET)
    public UIProperty getProperties() {
        return uiProperty;
    }

In order to consume the REST service we can use the code below where header can be MediaType.APPLICATION_JSON_VALUE or MediaType.APPLICATION_XML_VALUE

HttpHeaders headers = new HttpHeaders();
headers.add("Accept", header);

HttpEntity entity = new HttpEntity(headers);

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/properties", HttpMethod.GET, entity,String.class);
return response.getBody();

Edit 01:

In order to work with application/xml, add this dependency

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

How to remove a build from itunes connect?

Choose the build

The answer is that you Mouse over the icon for your build and at the end of the line you'll see a little colored minus in a circle. This removes the build and you can now click on the + sign and choose a new build for submitting.

It is an unbelievably complicated web page with tricks and gizmos to do the thing you want. I'm sure Steve never saw this page or tried to use it.

Surely it's better practice to design the screen so that you can see the options all the time, not to have the screen change depending on whether you have an app in review or not!

Writing a dictionary to a csv file with one line for every 'key: value'

Easiest way is to ignore the csv module and format it yourself.

with open('my_file.csv', 'w') as f:
    [f.write('{0},{1}\n'.format(key, value)) for key, value in my_dict.items()]

Center an element with "absolute" position and undefined width in CSS?

Here's a useful jQuery plugin to do this. I found it here. I don't think it's possible purely with CSS.

/**
 * @author: Suissa
 * @name: Absolute Center
 * @date: 2007-10-09
 */
jQuery.fn.center = function() {
    return this.each(function(){
            var el = $(this);
            var h = el.height();
            var w = el.width();
            var w_box = $(window).width();
            var h_box = $(window).height();
            var w_total = (w_box - w)/2; //400
            var h_total = (h_box - h)/2;
            var css = {"position": 'absolute', "left": w_total + "px", "top":
h_total + "px"};
            el.css(css)
    });
};

How to prevent XSS with HTML/PHP?

<?php
function xss_clean($data)
{
// Fix &entity\n;
$data = str_replace(array('&amp;','&lt;','&gt;'), array('&amp;amp;','&amp;lt;','&amp;gt;'), $data);
$data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
$data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
$data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');

// Remove any attribute starting with "on" or xmlns
$data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);

// Remove javascript: and vbscript: protocols
$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);

// Only works in IE: <span style="width: expression(alert('Ping!'));"></span>
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);

// Remove namespaced elements (we do not need them)
$data = preg_replace('#</*\w+:\w[^>]*+>#i', '', $data);

do
{
    // Remove really unwanted tags
    $old_data = $data;
    $data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
}
while ($old_data !== $data);

// we are done...
return $data;
}

Capitalize first letter. MySQL

It's almost the same, you just have to change to use the CONCAT() function instead of the + operator :

UPDATE tb_Company
SET CompanyIndustry = CONCAT(UCASE(LEFT(CompanyIndustry, 1)), 
                             SUBSTRING(CompanyIndustry, 2));

This would turn hello to Hello, wOrLd to WOrLd, BLABLA to BLABLA, etc. If you want to upper-case the first letter and lower-case the other, you just have to use LCASE function :

UPDATE tb_Company
SET CompanyIndustry = CONCAT(UCASE(LEFT(CompanyIndustry, 1)), 
                             LCASE(SUBSTRING(CompanyIndustry, 2)));

Note that UPPER and UCASE do the same thing.

How to replace all spaces in a string

var result = replaceSpace.replace(/ /g, ";");

Here, / /g is a regex (regular expression). The flag g means global. It causes all matches to be replaced.

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

Main differences between SOAP and RESTful web services in Java

  1. REST has no WSDL (Web Description Language) interface definition.

  2. REST is over HTTP, but SOAP can be over any transport protocols such as HTTP, FTP, SMTP, JMS, etc.

Measuring execution time of a function in C++

If you want to safe time and lines of code you can make measuring the function execution time a one line macro:

a) Implement a time measuring class as already suggested above ( here is my implementation for android):

class MeasureExecutionTime{
private:
    const std::chrono::steady_clock::time_point begin;
    const std::string caller;
public:
    MeasureExecutionTime(const std::string& caller):caller(caller),begin(std::chrono::steady_clock::now()){}
    ~MeasureExecutionTime(){
        const auto duration=std::chrono::steady_clock::now()-begin;
        LOGD("ExecutionTime")<<"For "<<caller<<" is "<<std::chrono::duration_cast<std::chrono::milliseconds>(duration).count()<<"ms";
    }
};

b) Add a convenient macro that uses the current function name as TAG (using a macro here is important, else __FUNCTION__ will evaluate to MeasureExecutionTime instead of the function you wanto to measure

#ifndef MEASURE_FUNCTION_EXECUTION_TIME
#define MEASURE_FUNCTION_EXECUTION_TIME const MeasureExecutionTime measureExecutionTime(__FUNCTION__);
#endif

c) Write your macro at the begin of the function you want to measure. Example:

 void DecodeMJPEGtoANativeWindowBuffer(uvc_frame_t* frame_mjpeg,const ANativeWindow_Buffer& nativeWindowBuffer){
        MEASURE_FUNCTION_EXECUTION_TIME
        // Do some time-critical stuff 
}

Which will result int the following output:

ExecutionTime: For DecodeMJPEGtoANativeWindowBuffer is 54ms

Note that this (as all other suggested solutions) will measure the time between when your function was called and when it returned, not neccesarily the time your CPU was executing the function. However, if you don't give the scheduler any change to suspend your running code by calling sleep() or similar there is no difference between.

Catching multiple exception types in one catch block

As of PHP 7.1,

catch( AError | BError $e )
{
    handler1( $e )
}

interestingly, you can also:

catch( AError | BError $e )
{
    handler1( $e )
} catch (CError $e){
    handler2($e);
} catch(Exception $e){
    handler3($e);
}

and in earlier versions of PHP:

catch(Exception $ex){
    if($ex instanceof AError){
        //handle a AError
    } elseif($ex instanceof BError){
        //handle a BError
    } else {
       throw $ex;//an unknown exception occured, throw it further
    }
}

How to remove non UTF-8 characters from text file

This command:

iconv -f utf-8 -t utf-8 -c file.txt

will clean up your UTF-8 file, skipping all the invalid characters.

-f is the source format
-t the target format
-c skips any invalid sequence

How do I make a PHP form that submits to self?

I guess , you means $_SERVER['PHP_SELF']. And if so , you really shouldn't use it without sanitizing it first. This leaves you open to XSS attacks.

The if(isset($_POST['submit'])) condition should be above all the HTML output, and should contain a header() function with a redirect to current page again (only now , with some nice notice that "emails has been sent" .. or something ). For that you will have to use $_SESSION or $_COOKIE.

And please. Stop using $_REQUEST. It too poses a security threat.

Git fails when pushing commit to github

The Problem to push mostly is because of the size of the files that need to be pushed. I was trying to push some libraries of just size 2 mb, then too the push was giving error of RPC with result 7. The line is of 4 mbps and is working fine. Some subsequent tries to the push got me success. If such error comes, wait for few minutes and keep on trying.

I also found out that there are some RPC failures if the github is down or is getting unstable network at their side.

So keeping up trying after some intervals is the only option!

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

Convert row names into first column

Or by using DBIs sqlRownamesToColumn

library(DBI)
sqlRownamesToColumn(df)

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

It is being pointed out not directly in the file which is caused the error. But it is actually triggered in a controller file. It happens when a return value from a method defined inside in a controller file is set on a boolean value. It must not be set on a boolean type but on the other hand, it must be set or given a value of a string type. It can be shown as follows :

public function saveFormSummary(Request $request) {
      ... 
      $status = true;
      return $status;
}

Given the return value of a boolean type above in a method, to be able to solve the problem to handle the error specified. Just change the type of the return value into a string type

as follows :

public function saveFormSummary(Request $request) {
      ... 
      $status = "true";
      return $status;
}

Retrieving Data from SQL Using pyodbc

You are so close!

import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')
cursor = cnxn.cursor()

cursor.execute("SELECT WORK_ORDER.TYPE,WORK_ORDER.STATUS, WORK_ORDER.BASE_ID, WORK_ORDER.LOT_ID FROM WORK_ORDER")
for row in cursor.fetchall():
    print row

(the "columns()" function collects meta-data about the columns in the named table, as opposed to the actual data).

Find a string within a cell using VBA

For a search routine you should look to use Find, AutoFilter or variant array approaches. Range loops are nomally too slow, worse again if they use Select

The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2 which you can then further process

Option Explicit

Const strText As String = "%"

Sub ColSearch_DelRows()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range
    Dim cel1 As Range
    Dim cel2 As Range
    Dim strFirstAddress As String
    Dim lAppCalc As Long


    'Get working range from user
    On Error Resume Next
    Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
    On Error GoTo 0
    If rng1 Is Nothing Then Exit Sub

    With Application
        lAppCalc = .Calculation
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)

    'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
    If Not cel1 Is Nothing Then
        Set rng2 = cel1
        strFirstAddress = cel1.Address
        Do
            Set cel1 = rng1.FindNext(cel1)
            Set rng2 = Union(rng2, cel1)
        Loop While strFirstAddress <> cel1.Address
    End If

    If Not rng2 Is Nothing Then
        For Each cel2 In rng2
            Debug.Print cel2.Address & " contained " & strText
        Next
    Else
        MsgBox "No " & strText
    End If

    With Application
        .ScreenUpdating = True
        .Calculation = lAppCalc
    End With

End Sub

How to prevent vim from creating (and leaving) temporary files?

I'd strongly recommend to keep working with swap files (in case Vim crashes).

You can set the directory where the swap files are stored, so they don't clutter your normal directories:

set swapfile
set dir=~/tmp

See also

:help swap-file

Best way to repeat a character in C#

The answer really depends on the complexity you want. For example, I want to outline all my indents with a vertical bar, so my indent string is determined as follows:

return new string(Enumerable.Range(0, indentSize*indent).Select(
  n => n%4 == 0 ? '|' : ' ').ToArray());

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

Pyspark does include a dropDuplicates() method, which was introduced in 1.4. https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.dropDuplicates

>>> from pyspark.sql import Row
>>> df = sc.parallelize([ \
...     Row(name='Alice', age=5, height=80), \
...     Row(name='Alice', age=5, height=80), \
...     Row(name='Alice', age=10, height=80)]).toDF()
>>> df.dropDuplicates().show()
+---+------+-----+
|age|height| name|
+---+------+-----+
|  5|    80|Alice|
| 10|    80|Alice|
+---+------+-----+

>>> df.dropDuplicates(['name', 'height']).show()
+---+------+-----+
|age|height| name|
+---+------+-----+
|  5|    80|Alice|
+---+------+-----+