Programs & Examples On #Continuation passing

In functional programming, continuation-passing style (CPS) is a style of programming in which control is passed explicitly in the form of continuation function(s).

C# Java HashMap equivalent

the answer is

Dictionary

take look at my function, its simple add uses most important member functions inside Dictionary

this function return false if the list contain Duplicates items

 public static bool HasDuplicates<T>(IList<T> items)
    {
        Dictionary<T, bool> mp = new Dictionary<T, bool>();
        for (int i = 0; i < items.Count; i++)
        {
            if (mp.ContainsKey(items[i]))
            {
                return true; // has duplicates
            }
            mp.Add(items[i], true);
        }
        return false; // no duplicates
    }

Replace or delete certain characters from filenames of all files in a folder

Use PowerShell to do anything smarter for a DOS prompt. Here, I've shown how to batch rename all the files and directories in the current directory that contain spaces by replacing them with _ underscores.

Dir |
Rename-Item -NewName { $_.Name -replace " ","_" }

EDIT :
Optionally, the Where-Object command can be used to filter out ineligible objects for the successive cmdlet (command-let). The following are some examples to illustrate the flexibility it can afford you:

  • To skip any document files

    Dir |
    Where-Object { $_.Name -notmatch "\.(doc|xls|ppt)x?$" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    
  • To process only directories (pre-3.0 version)

    Dir |
    Where-Object { $_.Mode -match "^d" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

    PowerShell v3.0 introduced new Dir flags. You can also use Dir -Directory there.

  • To skip any files already containing an underscore (or some other character)

    Dir |
    Where-Object { -not $_.Name.Contains("_") } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

How do I use CREATE OR REPLACE?

You can use CORT (www.softcraftltd.co.uk/cort). This tool allows to CREATE OR REPLACE table in Oracle. It looks like:

create /*# or replace */ table MyTable(
  ... -- standard table definition
);

It preserves data.

MySQL Join Where Not Exists

I'd probably use a LEFT JOIN, which will return rows even if there's no match, and then you can select only the rows with no match by checking for NULLs.

So, something like:

SELECT V.*
FROM voter V LEFT JOIN elimination E ON V.id = E.voter_id
WHERE E.voter_id IS NULL

Whether that's more or less efficient than using a subquery depends on optimization, indexes, whether its possible to have more than one elimination per voter, etc.

Setting new value for an attribute using jQuery

Works fine for me

See example here. http://jsfiddle.net/blowsie/c6VAy/

Make sure your jquery is inside $(document).ready function or similar.

Also you can improve your code by using jquery data

$('#amount').data('min','1000');

<div id="amount" data-min=""></div>

Update,

A working example of your full code (pretty much) here. http://jsfiddle.net/blowsie/c6VAy/3/

Remove accents/diacritics in a string in JavaScript

Here's a very simple solution without too much code using a very simple map of diacritics that includes some or all that map to ascii equivalents containing more than one character, i.e. Æ => AE, ? => ffi, etc... Also included some very basic functional tests

var diacriticsMap = {
  '\u00C0': 'A',  // À => A
  '\u00C1': 'A',   // Á => A
  '\u00C2': 'A',   // Â => A
  '\u00C3': 'A',   // Ã => A
  '\u00C4': 'A',   // Ä => A
  '\u00C5': 'A',   // Å => A
  '\u00C6': 'AE', // Æ => AE
  '\u00C7': 'C',   // Ç => C
  '\u00C8': 'E',   // È => E
  '\u00C9': 'E',   // É => E
  '\u00CA': 'E',   // Ê => E
  '\u00CB': 'E',   // Ë => E
  '\u00CC': 'I',   // Ì => I
  '\u00CD': 'I',   // Í => I
  '\u00CE': 'I',   // Î => I
  '\u00CF': 'I',   // Ï => I
  '\u0132': 'IJ', // ? => IJ
  '\u00D0': 'D',   // Ð => D
  '\u00D1': 'N',   // Ñ => N
  '\u00D2': 'O',   // Ò => O
  '\u00D3': 'O',   // Ó => O
  '\u00D4': 'O',   // Ô => O
  '\u00D5': 'O',   // Õ => O
  '\u00D6': 'O',   // Ö => O
  '\u00D8': 'O',   // Ø => O
  '\u0152': 'OE', // Π=> OE
  '\u00DE': 'TH', // Þ => TH
  '\u00D9': 'U',   // Ù => U
  '\u00DA': 'U',   // Ú => U
  '\u00DB': 'U',   // Û => U
  '\u00DC': 'U',   // Ü => U
  '\u00DD': 'Y',   // Ý => Y
  '\u0178': 'Y',   // Ÿ => Y
  '\u00E0': 'a',   // à => a
  '\u00E1': 'a',   // á => a
  '\u00E2': 'a',   // â => a
  '\u00E3': 'a',   // ã => a
  '\u00E4': 'a',   // ä => a
  '\u00E5': 'a',   // å => a
  '\u00E6': 'ae', // æ => ae
  '\u00E7': 'c',   // ç => c
  '\u00E8': 'e',   // è => e
  '\u00E9': 'e',   // é => e
  '\u00EA': 'e',   // ê => e
  '\u00EB': 'e',   // ë => e
  '\u00EC': 'i',   // ì => i
  '\u00ED': 'i',   // í => i
  '\u00EE': 'i',   // î => i
  '\u00EF': 'i',   // ï => i
  '\u0133': 'ij', // ? => ij
  '\u00F0': 'd',   // ð => d
  '\u00F1': 'n',   // ñ => n
  '\u00F2': 'o',   // ò => o
  '\u00F3': 'o',   // ó => o
  '\u00F4': 'o',   // ô => o
  '\u00F5': 'o',   // õ => o
  '\u00F6': 'o',   // ö => o
  '\u00F8': 'o',   // ø => o
  '\u0153': 'oe', // œ => oe
  '\u00DF': 'ss', // ß => ss
  '\u00FE': 'th', // þ => th
  '\u00F9': 'u',   // ù => u
  '\u00FA': 'u',   // ú => u
  '\u00FB': 'u',   // û => u
  '\u00FC': 'u',   // ü => u
  '\u00FD': 'y',   // ý => y
  '\u00FF': 'y',   // ÿ => y
  '\uFB00': 'ff', // ? => ff
  '\uFB01': 'fi',   // ? => fi
  '\uFB02': 'fl', // ? => fl
  '\uFB03': 'ffi',  // ? => ffi
  '\uFB04': 'ffl',  // ? => ffl
  '\uFB05': 'ft', // ? => ft
  '\uFB06': 'st'  // ? => st
};

function replaceDiacritics(str) {
  var returnStr = '';
  if(str) {
    for (var i = 0; i < str.length; i++) {
      if (diacriticsMap[str[i]]) {
        returnStr += diacriticsMap[str[i]];
      } else {
        returnStr += str[i];
      }
    }
  }
  return returnStr;
}

function testStripDiacritics(input, expected) {
  var coChar = replaceDiacritics(input);
  console.log('The character passed in was ' + input);
  console.log('The character that came out was ' + coChar);
  console.log('The character expected was' + expected);
}

testStripDiacritics('À','A');
testStripDiacritics('A','A');
testStripDiacritics('Æ','AE');
testStripDiacritics('AE','AE');
testStripDiacritics('ÇhÀrlËšYŸZŽ','ChArlEsYYZZ');

What is a typedef enum in Objective-C?

typedef enum {
kCircle,
kRectangle,
kOblateSpheroid
} ShapeType;

then you can use it like :-

 ShapeType shape;

and

 enum {
    kCircle,
    kRectangle,
    kOblateSpheroid
} 
ShapeType;

now you can use it like:-

enum ShapeType shape;

How to change href attribute using JavaScript after opening the link in a new window?

You can change this in the page load.

My intention is that when the page comes to the load function, switch the links (the current link in the required one)

How to delete large data of table in SQL without log?

  1. If you are Deleting All the rows in that table the simplest option is to Truncate table, something like

    TRUNCATE TABLE LargeTable
    GO
    

    Truncate table will simply empty the table, you cannot use WHERE clause to limit the rows being deleted and no triggers will be fired.

  2. On the other hand if you are deleting more than 80-90 Percent of the data, say if you have total of 11 Million rows and you want to delete 10 million another way would be to Insert these 1 million rows (records you want to keep) to another staging table. Truncate this Large table and Insert back these 1 Million rows.

  3. Or if permissions/views or other objects which has this large table as their underlying table doesnt get affected by dropping this table you can get these relatively small amount of the rows into another table drop this table and create another table with same schema and import these rows back into this ex-Large table.

  4. One last option I can think of is to change your database's Recovery Mode to SIMPLE and then delete rows in smaller batches using a while loop something like this..

    DECLARE @Deleted_Rows INT;
    SET @Deleted_Rows = 1;
    
    
    WHILE (@Deleted_Rows > 0)
      BEGIN
       -- Delete some small number of rows at a time
         DELETE TOP (10000)  LargeTable 
         WHERE readTime < dateadd(MONTH,-7,GETDATE())
    
      SET @Deleted_Rows = @@ROWCOUNT;
    END
    

and dont forget to change the Recovery mode back to full and I think you have to take a backup to make it fully affective (the change or recovery modes).

What's the purpose of META-INF?

The META-INF folder is the home for the MANIFEST.MF file. This file contains meta data about the contents of the JAR. For example, there is an entry called Main-Class that specifies the name of the Java class with the static main() for executable JAR files.

How do I print the content of a .txt file in Python?

with open("filename.txt", "w+") as file:
  for line in file:
    print line

This with statement automatically opens and closes it for you and you can iterate over the lines of the file with a simple for loop

Copy data from another Workbook through VBA

I had the same question but applying the provided solutions changed the file to write in. Once I selected the new excel file, I was also writing in that file and not in my original file. My solution for this issue is below:

Sub GetData()

    Dim excelapp As Application
    Dim source As Workbook
    Dim srcSH1 As Worksheet
    Dim sh As Worksheet
    Dim path As String
    Dim nmr As Long
    Dim i As Long

    nmr = 20

    Set excelapp = New Application

    With Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = False
        .Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
        .Show
        path = .SelectedItems.Item(1)
    End With

    Set source = excelapp.Workbooks.Open(path)
    Set srcSH1 = source.Worksheets("Sheet1")
    Set sh = Sheets("Sheet1")

    For i = 1 To nmr
        sh.Cells(i, "A").Value = srcSH1.Cells(i, "A").Value
    Next i

End Sub

With excelapp a new application will be called. The with block sets the path for the external file. Finally, I set the external Workbook with source and srcSH1 as a Worksheet within the external sheet.

How do I call a specific Java method on a click/submit event of a specific button in JSP?

Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.

You only need to make sure that the button inputs have type="submit" as in <input type="submit"> and <button type="submit"> and not type="button", which only renders a "dead" button purely for onclick stuff and all.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
    <input type="submit" name="button2" value="Button 2" />
    <input type="submit" name="button3" value="Button 3" />
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();

        if (request.getParameter("button1") != null) {
            myClass.method1();
        } else if (request.getParameter("button2") != null) {
            myClass.method2();
        } else if (request.getParameter("button3") != null) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

Alternatively, use <button type="submit"> instead of <input type="submit">, then you can give them all the same name, but an unique value. The value of the <button> won't be used as label, you can just specify that yourself as child.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <button type="submit" name="button" value="button1">Button 1</button>
    <button type="submit" name="button" value="button2">Button 2</button>
    <button type="submit" name="button" value="button3">Button 3</button>
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();
        String button = request.getParameter("button");

        if ("button1".equals(button)) {
            myClass.method1();
        } else if ("button2".equals(button)) {
            myClass.method2();
        } else if ("button3".equals(button)) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

See also:

Change bootstrap navbar background color and font color

Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.

<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->

Otherwise, you can put !important at the end of your CSS like this: color:#ffffff!important; but I would advise against using !important at all costs.

How do I convert a IPython Notebook into a Python file via commandline?

If you don't want to output a Python script every time you save, or you don't want to restart the IPython kernel:

On the command line, you can use nbconvert:

$ jupyter nbconvert --to script [YOUR_NOTEBOOK].ipynb

As a bit of a hack, you can even call the above command in an IPython notebook by pre-pending ! (used for any command line argument). Inside a notebook:

!jupyter nbconvert --to script config_template.ipynb

Before --to script was added, the option was --to python or --to=python, but it was renamed in the move toward a language-agnostic notebook system.

What is the use of the %n format specifier in C?

It will store value of number of characters printed so far in that printf() function.

Example:

int a;
printf("Hello World %n \n", &a);
printf("Characters printed so far = %d",a);

The output of this program will be

Hello World
Characters printed so far = 12

Play audio from a stream using C#

Edit: Answer updated to reflect changes in recent versions of NAudio

It's possible using the NAudio open source .NET audio library I have written. It looks for an ACM codec on your PC to do the conversion. The Mp3FileReader supplied with NAudio currently expects to be able to reposition within the source stream (it builds an index of MP3 frames up front), so it is not appropriate for streaming over the network. However, you can still use the MP3Frame and AcmMp3FrameDecompressor classes in NAudio to decompress streamed MP3 on the fly.

I have posted an article on my blog explaining how to play back an MP3 stream using NAudio. Essentially you have one thread downloading MP3 frames, decompressing them and storing them in a BufferedWaveProvider. Another thread then plays back using the BufferedWaveProvider as an input.

Running Windows batch file commands asynchronously

There's a third (and potentially much easier) option. If you want to spin up multiple instances of a single program, using a Unix-style command processor like Xargs or GNU Parallel can make that a fairly straightforward process.

There's a win32 Xargs clone called PPX2 that makes this fairly straightforward.

For instance, if you wanted to transcode a directory of video files, you could run the command:

dir /b *.mpg |ppx2 -P 4 -I {} -L 1 ffmpeg.exe -i "{}" -quality:v 1 "{}.mp4"

Picking this apart, dir /b *.mpg grabs a list of .mpg files in my current directory, the | operator pipes this list into ppx2, which then builds a series of commands to be executed in parallel; 4 at a time, as specified here by the -P 4 operator. The -L 1 operator tells ppx2 to only send one line of our directory listing to ffmpeg at a time.

After that, you just write your command line (ffmpeg.exe -i "{}" -quality:v 1 "{}.mp4"), and {} gets automatically substituted for each line of your directory listing.

It's not universally applicable to every case, but is a whole lot easier than using the batch file workarounds detailed above. Of course, if you're not dealing with a list of files, you could also pipe the contents of a textfile or any other program into the input of pxx2.

jQuery 'input' event

I think 'input' simply works here the same way 'oninput' does in the DOM Level O Event Model.

Incidentally:

Just as silkfire commented it, I too googled for 'jQuery input event'. Thus I was led to here and astounded to learn that 'input' is an acceptable parameter to jquery's bind() command. In jQuery in Action (p. 102, 2008 ed.) 'input' is not mentionned as a possible event (against 20 others, from 'blur' to 'unload'). It is true that, on p. 92, the contrary could be surmised from rereading (i.e. from a reference to different string identifiers between Level 0 and Level 2 models). That is quite misleading.

This Activity already has an action bar supplied by the window decor

Use this inside your application tag in manifest or inside your Activity tag.

android:theme="@style/AppTheme.NoActionBar"

Parsing a comma-delimited std::string

simple structure, easily adaptable, easy maintenance.

std::string stringIn = "my,csv,,is 10233478,separated,by commas";
std::vector<std::string> commaSeparated(1);
int commaCounter = 0;
for (int i=0; i<stringIn.size(); i++) {
    if (stringIn[i] == ",") {
        commaSeparated.push_back("");
        commaCounter++;
    } else {
        commaSeparated.at(commaCounter) += stringIn[i];
    }
}

in the end you will have a vector of strings with every element in the sentence separated by spaces. empty strings are saved as separate items.

What is the difference between 'E', 'T', and '?' for Java generics?

The previous answers explain type parameters (T, E, etc.), but don't explain the wildcard, "?", or the differences between them, so I'll address that.

First, just to be clear: the wildcard and type parameters are not the same. Where type parameters define a sort of variable (e.g., T) that represents the type for a scope, the wildcard does not: the wildcard just defines a set of allowable types that you can use for a generic type. Without any bounding (extends or super), the wildcard means "use any type here".

The wildcard always come between angle brackets, and it only has meaning in the context of a generic type:

public void foo(List<?> listOfAnyType) {...}  // pass a List of any type

never

public <?> ? bar(? someType) {...}  // error. Must use type params here

or

public class MyGeneric ? {      // error
    public ? getFoo() { ... }   // error
    ...
}

It gets more confusing where they overlap. For example:

List<T> fooList;  // A list which will be of type T, when T is chosen.
                  // Requires T was defined above in this scope
List<?> barList;  // A list of some type, decided elsewhere. You can do
                  // this anywhere, no T required.

There's a lot of overlap in what's possible with method definitions. The following are, functionally, identical:

public <T> void foo(List<T> listOfT) {...}
public void bar(List<?> listOfSomething)  {...}

So, if there's overlap, why use one or the other? Sometimes, it's honestly just style: some people say that if you don't need a type param, you should use a wildcard just to make the code simpler/more readable. One main difference I explained above: type params define a type variable (e.g., T) which you can use elsewhere in the scope; the wildcard doesn't. Otherwise, there are two big differences between type params and the wildcard:

Type params can have multiple bounding classes; the wildcard cannot:

public class Foo <T extends Comparable<T> & Cloneable> {...}

The wildcard can have lower bounds; type params cannot:

public void bar(List<? super Integer> list) {...}

In the above the List<? super Integer> defines Integer as a lower bound on the wildcard, meaning that the List type must be Integer or a super-type of Integer. Generic type bounding is beyond what I want to cover in detail. In short, it allows you to define which types a generic type can be. This makes it possible to treat generics polymorphically. E.g. with:

public void foo(List<? extends Number> numbers) {...}

You can pass a List<Integer>, List<Float>, List<Byte>, etc. for numbers. Without type bounding, this won't work -- that's just how generics are.

Finally, here's a method definition which uses the wildcard to do something that I don't think you can do any other way:

public static <T extends Number> void adder(T elem, List<? super Number> numberSuper) {
    numberSuper.add(elem);
}

numberSuper can be a List of Number or any supertype of Number (e.g., List<Object>), and elem must be Number or any subtype. With all the bounding, the compiler can be certain that the .add() is typesafe.

Installing Apache Maven Plugin for Eclipse

Installing m2eclipse

All downloads are provided under the terms and conditions of the Eclipse Foundation Software User Agreement unless otherwise specified.

m2e is tested against Eclipse 4.2 (Juno) and 4.3 (Kepler).

See http://wiki.eclipse.org/M2E_updatesite_and_gittags for detailed information about available builds and m2e build repository layout.

m2e 1.3 and earlier version have been removed from the main m2e update site. These old releases are still available and can be installed from repositories documented in http://wiki.eclipse.org/M2E_updatesite_and_gittags

Please note that links below point at Eclipse p2 repositories; you must access them from Eclipse (see how). Update Sites Latest m2e release (recommended) http://download.eclipse.org/technology/m2e/releases m2e milestone builds towards version 1.5 http://download.eclipse.org/technology/m2e/milestones/1.5 Latest m2e 1.5 SNAPSHOT build (not tested, not hosted at eclipse.org) http://repository.takari.io:8081/nexus/content/sites/m2e.extras/m2e/1.5.0/N/LATEST/

JavaScript Object Id

If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a WeakMap:

// Note that object must be an object or array,
// NOT a primitive value like string, number, etc.
var objIdMap=new WeakMap, objectCount = 0;
function objectId(object){
  if (!objIdMap.has(object)) objIdMap.set(object,++objectCount);
  return objIdMap.get(object);
}

var o1={}, o2={}, o3={a:1}, o4={a:1};
console.log( objectId(o1) ) // 1
console.log( objectId(o2) ) // 2
console.log( objectId(o1) ) // 1
console.log( objectId(o3) ) // 3
console.log( objectId(o4) ) // 4
console.log( objectId(o3) ) // 3

Using a WeakMap instead of Map ensures that the objects can still be garbage-collected.

Create a list from two object lists with linq

Does the following code work for your problem? I've used a foreach with a bit of linq inside to do the combining of lists and assumed that people are equal if their names match, and it seems to print the expected values out when run. Resharper doesn't offer any suggestions to convert the foreach into linq so this is probably as good as it'll get doing it this way.

public class Person
{
   public string Name { get; set; }
   public int Value { get; set; }
   public int Change { get; set; }

   public Person(string name, int value)
   {
      Name = name;
      Value = value;
      Change = 0;
   }
}


class Program
{
   static void Main(string[] args)
   {
      List<Person> list1 = new List<Person>
                              {
                                 new Person("a", 1),
                                 new Person("b", 2),
                                 new Person("c", 3),
                                 new Person("d", 4)
                              };
      List<Person> list2 = new List<Person>
                              {
                                 new Person("a", 4),
                                 new Person("b", 5),
                                 new Person("e", 6),
                                 new Person("f", 7)
                              };

      List<Person> list3 = list2.ToList();

      foreach (var person in list1)
      {
         var existingPerson = list3.FirstOrDefault(x => x.Name == person.Name);
         if (existingPerson != null)
         {
            existingPerson.Change = existingPerson.Value - person.Value;
         }
         else
         {
            list3.Add(person);
         }
      }

      foreach (var person in list3)
      {
         Console.WriteLine("{0} {1} {2} ", person.Name,person.Value,person.Change);
      }
      Console.Read();
   }
}

How do I programmatically click on an element in JavaScript?

I used KooiInc's function listed above but I had to use two different input types one 'button' for IE and one 'submit' for FireFox. I am not exactly sure why but it works.

// HTML

<input type="button" id="btnEmailHidden" style="display:none" />
<input type="submit" id="btnEmailHidden2" style="display:none" />

// in JavaScript

var hiddenBtn = document.getElementById("btnEmailHidden");

if (hiddenBtn.fireEvent) {
    hiddenBtn.fireEvent('onclick');
    hiddenBtn[eType]();
}
else {
    // dispatch for firefox + others
    var evObj = document.createEvent('MouseEvent');
    evObj.initEvent(eType, true, true);
    var hiddenBtn2 = document.getElementById("btnEmailHidden2");
    hiddenBtn2.dispatchEvent(evObj);
}

I have search and tried many suggestions but this is what ended up working. If I had some more time I would have liked to investigate why submit works with FF and button with IE but that would be a luxury right now so on to the next problem.

Trying to get Laravel 5 email to work

I know it's working for you now @Vantheman6 but this is what worked for me in case it's the same for someone else.

I added to my .env file the details of the mail service I am using. So make sure the following details

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=MyPassword

in the .env file are accurate.

NOTE: Don't forget to restart your server after editing the .env file so it will pick the new data that you put in there.

Clear config cache with below command:

php artisan config:cache

If you don't restart your server, the .env file will still continue to present the old mail data to the app even though you have made changes that can cause this error.

Least common multiple for 3 or more numbers

In python:

def lcm(*args):
    """Calculates lcm of args"""
    biggest = max(args) #find the largest of numbers
    rest = [n for n in args if n != biggest] #the list of the numbers without the largest
    factor = 1 #to multiply with the biggest as long as the result is not divisble by all of the numbers in the rest
    while True:
        #check if biggest is divisble by all in the rest:
        ans = False in [(biggest * factor) % n == 0 for n in rest]
        #if so the clm is found break the loop and return it, otherwise increment factor by 1 and try again
        if not ans:
            break
        factor += 1
    biggest *= factor
    return "lcm of {0} is {1}".format(args, biggest)

>>> lcm(100,23,98)
'lcm of (100, 23, 98) is 112700'
>>> lcm(*range(1, 20))
'lcm of (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) is 232792560'

PostgreSQL: role is not permitted to log in

try to run

sudo su - postgres
psql
ALTER ROLE 'dbname'

svn: E155004: ..(path of resource).. is already locked

//Inside the folder,

svn cleanup

svn update

//If are viewing any conflicts,

svn revert --depth infinity conflicted_filename

svn update conflicted_filename

svn update

regex error - nothing to repeat

That is a Python bug between "*" and special characters.

Instead of

re.compile(r"\w*")

Try:

re.compile(r"[a-zA-Z0-9]*")

It works, however does not make the same regular expression.

This bug seems to have been fixed between 2.7.5 and 2.7.6.

How to convert an NSTimeInterval (seconds) into minutes

Since it's essentially a double...

Divide by 60.0 and extract the integral part and the fractional part.

The integral part will be the whole number of minutes.

Multiply the fractional part by 60.0 again.

The result will be the remaining seconds.

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

PHP find difference between two datetimes

The code below will show difference for found values only, i.e., if years = 0, then it will not show years.


$diffs = [
    'years' => 'y',
    'months' => 'm',
    'days' => 'd',
    'hours' => 'h',
    'minutes' => 'i',
    'seconds' => 's'
];

$interval = $timeout->diff($timein);
$diffArr = [];
foreach ($diffs as $k => $v) {
    $d = $interval->format('%' . $v);
    if ($d > 0) {
        $diffArr[] = $d . ' ' . $k;
    }
}    
$diffStr = implode(', ', $diffArr);
echo 'Difference: ' . ($diffStr == '' ? '0' : $diffStr) . PHP_EOL;

Can you have multiline HTML5 placeholder text in a <textarea>?

You can try using CSS, it works for me. The attribute placeholder=" " is required here.

<textarea id="myID" placeholder=" "></textarea>
<style>
#myID::-webkit-input-placeholder::before {
    content: "1st line...\A2nd line...\A3rd line...";
}
</style>

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

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

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

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

not:first-child selector

One of the versions you posted actually works for all modern browsers (where CSS selectors level 3 are supported):

div ul:not(:first-child) {
    background-color: #900;
}

If you need to support legacy browsers, or if you are hindered by the :not selector's limitation (it only accepts a simple selector as an argument) then you can use another technique:

Define a rule that has greater scope than what you intend and then "revoke" it conditionally, limiting its scope to what you do intend:

div ul {
    background-color: #900;  /* applies to every ul */
}

div ul:first-child {
    background-color: transparent; /* limits the scope of the previous rule */
}

When limiting the scope use the default value for each CSS attribute that you are setting.

How do I install Python packages on Windows?

The accepted answer is outdated. So first, pip is preferred over easy_install, (Why use pip over easy_install?). Then follow these steps to install pip on Windows, it's quite easy.

  1. Install setuptools:

    curl https://bootstrap.pypa.io/ez_setup.py | python
    
  2. Install pip:

    curl https://bootstrap.pypa.io/get-pip.py | python
    
  3. Optionally, you can add the path to your environment so that you can use pip anywhere. It's somewhere like C:\Python33\Scripts.

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

I worked on Access Denied for User 'root'@'localhost' (using password: YES) for several hours, I have found following solution,

The answer to this problem was that in the my.cnf located within
/etc/mysql/my.cnf

the line was either 
bind-address = 127.0.0.1 
            (or)
bind-address = localhost
            (or)
bind-address = 0.0.0.0

I should prefer that 127.0.0.1

I should also prefer 0.0.0.0, it is more flexible 
because which will allow all connections

Attach Authorization header for all axios requests

If you use "axios": "^0.17.1" version you can do like this:

Create instance of axios:

// Default config options
  const defaultOptions = {
    baseURL: <CHANGE-TO-URL>,
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

Then for any request the token will be select from localStorage and will be added to the request headers.

I'm using the same instance all over the app with this code:

import axios from 'axios';

const fetchClient = () => {
  const defaultOptions = {
    baseURL: process.env.REACT_APP_API_PATH,
    method: 'get',
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

  return instance;
};

export default fetchClient();

Good luck.

What does the [Flags] Enum Attribute mean in C#?

To add Mode.Write:

Mode = Mode | Mode.Write;

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

Correct use of transactions in SQL Server

At the beginning of stored procedure one should put SET XACT_ABORT ON to instruct Sql Server to automatically rollback transaction in case of error. If ommited or set to OFF one needs to test @@ERROR after each statement or use TRY ... CATCH rollback block.

Printf long long int in C with GCC?

You can try settings of code::block, there is a complier..., then you select in C mode.

enter image description here

How to install package from github repo in Yarn

For ssh style urls just add ssh before the url:

yarn add ssh://<whatever>@<xxx>#<branch,tag,commit>

Convert column classes in data.table

Here is the same way as @Nera suggested to check the class first but instead of using .SD is to use the fast loop of data.table with set as @Matt Dowle solution with added class check.

for (j in seq_len(ncol(DT))){
  if(class(DT[[j]]) == 'factor')
    set(DT, j = j, value = as.character(DT[[j]]))
}

String contains another two strings

So you want to know if one string contains two other strings?

You could use this extension which also allows to specify the comparison:

public static bool ContainsAll(this string text, StringComparison comparison = StringComparison.CurrentCulture, params string[]parts)
{
    return parts.All(p => text.IndexOf(p, comparison) > -1);
}

Use it in this way (you can also omit the StringComparison):

bool containsAll = d.ContainsAll(StringComparison.OrdinalIgnoreCase, a, b);

C# DateTime.ParseExact

That's because you have the Date in American format in line[i] and UK format in the FormatString.

11/20/2011
M / d/yyyy

I'm guessing you might need to change the FormatString to:

"M/d/yyyy h:mm"

MySQL default datetime through phpmyadmin

You can't set CURRENT_TIMESTAMP as default value with DATETIME.

But you can do it with TIMESTAMP.

See the difference here.

Words from this blog

The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.

This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE.

The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column.

pandas unique values multiple columns

An updated solution using numpy v1.13+ requires specifying the axis in np.unique if using multiple columns, otherwise the array is implicitly flattened.

import numpy as np

np.unique(df[['col1', 'col2']], axis=0)

This change was introduced Nov 2016: https://github.com/numpy/numpy/commit/1f764dbff7c496d6636dc0430f083ada9ff4e4be

Regular Expression Validation For Indian Phone Number and Mobile number

You can use regular expression like this.

/^[(]+\ ++\d{2}[)]+[^0]+\d{9}/

Is it possible to use JavaScript to change the meta-tags of the page?

var description=document.getElementsByTagName('h4')[0].innerHTML;
var link = document.createElement('meta');
  
link.setAttribute('name', 'description');
  
link.content = description;
  
document.getElementsByTagName('head')[0].appendChild(link);
var htwo=document.getElementsByTagName('h2');
var hthree=document.getElementsByTagName('h3');
var ls=[];
for(var i=0;i<hthree.length;i++){ls.push(htwo[i].innerHTML);}

for(var i=0;i<hthree.length;i++){ls.push(hthree[i].innerHTML);}

var keyword=ls.toString()
;
var keyw = document.createElement('meta');
  
keyw.setAttribute('name', 'keywords');
  
keyw.content = keyword;
  
document.getElementsByTagName('head')[0].appendChild(keyw);

in my case, I write this code and all my meta tags are working perfectly but we can not see the actual meta tag it will be hidden somewhere.

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

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

In my case, I had opened a query from data context, like

    Dim stores = DataContext.Stores _
        .Where(Function(d) filter.Contains(d.code)) _

... and then subsequently queried the same...

    Dim stores = DataContext.Stores _
        .Where(Function(d) filter.Contains(d.code)).ToList

Adding the .ToList to the first resolved my issue. I think it makes sense to wrap this in a property like:

Public ReadOnly Property Stores As List(Of Store)
    Get
        If _stores Is Nothing Then
            _stores = DataContext.Stores _
                .Where(Function(d) Filters.Contains(d.code)).ToList
        End If
        Return _stores
    End Get
End Property

Where _stores is a private variable, and Filters is also a readonly property that reads from AppSettings.

Safely limiting Ansible playbooks to a single machine?

There's also a cute little trick that lets you specify a single host on the command line (or multiple hosts, I guess), without an intermediary inventory:

ansible-playbook -i "imac1-local," user.yml

Note the comma (,) at the end; this signals that it's a list, not a file.

Now, this won't protect you if you accidentally pass a real inventory file in, so it may not be a good solution to this specific problem. But it's a handy trick to know!

Pandas split DataFrame by column value

You can use boolean indexing:

df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
   A  Sales
0  3     10
1  4     20
2  7     30
3  6     40
4  1     50

s = 30

df1 = df[df['Sales'] >= s]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

df2 = df[df['Sales'] < s]
print (df2)
   A  Sales
0  3     10
1  4     20

It's also possible to invert mask by ~:

mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

print (df2)
   A  Sales
0  3     10
1  4     20

print (mask)
0    False
1    False
2     True
3     True
4     True
Name: Sales, dtype: bool

print (~mask)
0     True
1     True
2    False
3    False
4    False
Name: Sales, dtype: bool

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

In the app function you have incorrectly spelled the word setpersonSate, missing the letter t, thus it should be setpersonState.

Error:

const app = props => { 
    const [personState, setPersonSate] = useState({....

Solution:

const app = props => { 
        const [personState, setPersonState] = useState({....

Recursive query in SQL Server

Try this:

;WITH CTE
AS
(
    SELECT DISTINCT
        M1.Product_ID Group_ID,
        M1.Product_ID
    FROM matches M1
        LEFT JOIN matches M2
            ON M1.Product_Id = M2.matching_Product_Id
    WHERE M2.matching_Product_Id IS NULL
    UNION ALL
    SELECT
        C.Group_ID,
        M.matching_Product_Id
    FROM CTE C
        JOIN matches M
            ON C.Product_ID = M.Product_ID
)
SELECT * FROM CTE ORDER BY Group_ID

You can use OPTION(MAXRECURSION n) to control recursion depth.

SQL FIDDLE DEMO

Iterate over object attributes in python

For python 3.6

class SomeClass:

    def attr_list(self, should_print=False):

        items = self.__dict__.items()
        if should_print:
            [print(f"attribute: {k}    value: {v}") for k, v in items]

        return items

DataTrigger where value is NOT null?

If you are looking for a solution that does not use IValueConverter, you can always go with below mechanism

       <StackPanel>
            <TextBlock Text="Border = Red when null value" />
            <Border x:Name="border_objectForNullValueTrigger" HorizontalAlignment="Stretch" Height="20"> 
                <Border.Style>
                    <Style TargetType="Border">
                        <Setter Property="Background" Value="Black" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding ObjectForNullValueTrigger}" Value="{x:Null}">
                                <Setter Property="Background" Value="Red" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Border.Style>
            </Border>
            <TextBlock Text="Border = Green when not null value" />
            <Border HorizontalAlignment="Stretch" Height="20">
                <Border.Style>
                    <Style TargetType="Border">
                        <Setter Property="Background" Value="Green" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Background, ElementName=border_objectForNullValueTrigger}" Value="Red">
                                <Setter Property="Background" Value="Black" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Border.Style>
            </Border>
            <Button Content="Invert Object state" Click="Button_Click_1"/>
        </StackPanel>

To show only file name without the entire directory path

just hoping to be helpful to someone as old problems seem to come back every now and again and I always find good tips here.

My problem was to list in a text file all the names of the "*.txt" files in a certain directory without path and without extension from a Datastage 7.5 sequence.

The solution we used is:

ls /home/user/new/*.txt | xargs -n 1 basename | cut -d '.' -f1 > name_list.txt

Using arrays or std::vectors in C++, what's the performance gap?

To respond to something Mehrdad said:

However, there might be cases where you still need arrays. When interfacing with low level code (i.e. assembly) or old libraries that require arrays, you might not be able to use vectors.

Not true at all. Vectors degrade nicely into arrays/pointers if you use:

vector<double> vector;
vector.push_back(42);

double *array = &(*vector.begin());

// pass the array to whatever low-level code you have

This works for all major STL implementations. In the next standard, it will be required to work (even though it does just fine today).

How to add New Column with Value to the Existing DataTable?

Add the column and update all rows in the DataTable, for example:

DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Name", typeof(string)));
for (Int32 i = 1; i <= 10; i++) {
    DataRow row = tbl.NewRow();
    row["ID"] = i;
    row["Name"] = i + ". row";
    tbl.Rows.Add(row);
}
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
tbl.Columns.Add(newCol);
foreach (DataRow row in tbl.Rows) {
    row["NewColumn"] = "You DropDownList value";
}
//if you don't want to allow null-values'
newCol.AllowDBNull = false;

Winforms issue - Error creating window handle

See this post of mine about "Error creating window handle" and how it relates to USER Objects and the Desktop Heap. I provide some solutions.

Differences between unique_ptr and shared_ptr

unique_ptr is the light-weight smart pointer of choice if you just have a dynamic object somewhere for which one consumer has sole (hence "unique") responsibility -- maybe a wrapper class that needs to maintain some dynamically allocated object. unique_ptr has very little overhead. It is not copyable, but movable. Its type is template <typename D, typename Deleter> class unique_ptr;, so it depends on two template parameters.

unique_ptr is also what auto_ptr wanted to be in the old C++ but couldn't because of that language's limitations.

shared_ptr on the other hand is a very different animal. The obvious difference is that you can have many consumers sharing responsibility for a dynamic object (hence "shared"), and the object will only be destroyed when all shared pointers have gone away. Additionally you can have observing weak pointers which will intelligently be informed if the shared pointer they're following has disappeared.

Internally, shared_ptr has a lot more going on: There is a reference count, which is updated atomically to allow the use in concurrent code. Also, there's plenty of allocation going on, one for an internal bookkeeping "reference control block", and another (often) for the actual member object.

But there's another big difference: The shared pointers type is always template <typename T> class shared_ptr;, and this is despite the fact that you can initialize it with custom deleters and with custom allocators. The deleter and allocator are tracked using type erasure and virtual function dispatch, which adds to the internal weight of the class, but has the enormous advantage that different sorts of shared pointers of type T are all compatible, no matter the deletion and allocation details. Thus they truly express the concept of "shared responsibility for T" without burdening the consumer with the details!

Both shared_ptr and unique_ptr are designed to be passed by value (with the obvious movability requirement for the unique pointer). Neither should make you worried about the overhead, since their power is truly astounding, but if you have a choice, prefer unique_ptr, and only use shared_ptr if you really need shared responsibility.

Python causing: IOError: [Errno 28] No space left on device: '../results/32766.html' on disk with lots of space

  1. Show where memory is allocated sudo du -x -h / | sort -h | tail -40
  2. Delete from either your /tmp or /home/user_name/.cache folder if these are taking up a lot of memory. You can do this by running sudo rm -R /path/to/folder

Step 2 outlines fairly common folders to delete from (/tmp and /home/user_name/.cache). If you get back other results when running the first command showing you have lots of memory being used elsewhere, I advise being a bit more cautious when deleting from those locations.

How to specify new GCC path for CMake

Export should be specific about which version of GCC/G++ to use, because if user had multiple compiler version, it would not compile successfully.

 export CC=path_of_gcc/gcc-version
 export CXX=path_of_g++/g++-version
 cmake  path_of_project_contain_CMakeList.txt
 make 

In case project use C++11 this can be handled by using -std=C++-11 flag in CMakeList.txt

How do I combine 2 javascript variables into a string

ES6 introduce template strings for concatenation. Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:

// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);

// => "Yo, Brendan!"

var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);

//=> JavaScript first appeared 20 years ago. Crazy!

ComboBox.SelectedText doesn't give me the SelectedText

Try this:

String status = "The status of my combobox is " + comboBoxTest.text;

PHP ternary operator vs null coalescing operator

Null Coalescing operator performs just two tasks: it checks whether the variable is set and whether it is null. Have a look at the following example:

<?php
# case 1:
$greeting = 'Hola';
echo $greeting ?? 'Hi There'; # outputs: 'Hola'

# case 2:
$greeting = null;
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'

# case 3:
unset($greeting);
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'

The above code example states that Null Coalescing operator treats a non-existing variable and a variable which is set to NULL in the same way.

Null Coalescing operator is an improvement over the ternary operator. Have a look at the following code snippet comparing the two:

<?php /* example: checking for the $_POST field that goes by the name of 'fullname'*/
# in ternary operator
echo "Welcome ", (isset($_POST['fullname']) && !is_null($_POST['fullname']) ? $_POST['fullname'] : 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.
# in null coalecing operator
echo "Welcome ", ($_POST['fullname'] ?? 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.

So, the difference between the two is that Null Coalescing operator operator is designed to handle undefined variables better than the ternary operator. Whereas, the ternary operator is a shorthand for if-else.

Null Coalescing operator is not meant to replace ternary operator, but in some use cases like in the above example, it allows you to write clean code with less hassle.

Credits: http://dwellupper.io/post/6/php7-null-coalescing-operator-usage-and-examples

Is there a simple way to convert C++ enum to string?

Note that your conversion function should ideally be returning a const char *.

If you can afford to put your enums in their separate header files, you could perhaps do something like this with macros (oh, this will be ugly):

#include "enum_def.h"
#include "colour.h"
#include "enum_conv.h"
#include "colour.h"

Where enum_def.h has:

#undef ENUM_START
#undef ENUM_ADD
#undef ENUM_END
#define ENUM_START(NAME) enum NAME {
#define ENUM_ADD(NAME, VALUE) NAME = VALUE,
#define ENUM_END };

And enum_conv.h has:

#undef ENUM_START
#undef ENUM_ADD
#undef ENUM_END
#define ENUM_START(NAME) const char *##NAME##_to_string(NAME val) { switch (val) {
#define ENUM_ADD(NAME, VALUE) case NAME: return #NAME;
#define ENUM_END default: return "Invalid value"; } }

And finally, colour.h has:

ENUM_START(colour)
ENUM_ADD(red,   0xff0000)
ENUM_ADD(green, 0x00ff00)
ENUM_ADD(blue,  0x0000ff)
ENUM_END

And you can use the conversion function as:

printf("%s", colour_to_string(colour::red));

This is ugly, but it's the only way (at the preprocessor level) that lets you define your enum just in a single place in your code. Your code is therefore not prone to errors due to modifications to the enum. Your enum definition and the conversion function will always be in sync. However, I repeat, this is ugly :)

Best Way to Refresh Adapter/ListView on Android

If nothing works, just create the adapter instance again with the new set of results or the updated set of results. Then you can see the new view.

XYZAdapter adbXzy = new XYZAdapter(context, 0, listData);
xyzListView.setAdapter(adbXzy);

adbXzy.notifyDataSetChanged();

CS0234: Mvc does not exist in the System.Web namespace

You need to include the reference to the assembly System.Web.Mvc in you project.

you may not have the System.Web.Mvc in your C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0

So you need to add it and then to include it as reference to your projrect

Variable length (Dynamic) Arrays in Java

How about using a List instead? For example, ArrayList<integer>

Difference between a theta join, equijoin and natural join

While the answers explaining the exact differences are fine, I want to show how the relational algebra is transformed to SQL and what the actual value of the 3 concepts is.

The key concept in your question is the idea of a join. To understand a join you need to understand a Cartesian Product (the example is based on SQL where the equivalent is called a cross join as onedaywhen points out);

This isn't very useful in practice. Consider this example.

Product(PName, Price)
====================
Laptop,   1500
Car,      20000
Airplane, 3000000


Component(PName, CName, Cost)
=============================
Laptop, CPU,    500
Laptop, hdd,    300
Laptop, case,   700
Car,    wheels, 1000

The Cartesian product Product x Component will be - bellow or sql fiddle. You can see there are 12 rows = 3 x 4. Obviously, rows like "Laptop" with "wheels" have no meaning, this is why in practice the Cartesian product is rarely used.

|    PNAME |   PRICE |  CNAME | COST |
--------------------------------------
|   Laptop |    1500 |    CPU |  500 |
|   Laptop |    1500 |    hdd |  300 |
|   Laptop |    1500 |   case |  700 |
|   Laptop |    1500 | wheels | 1000 |
|      Car |   20000 |    CPU |  500 |
|      Car |   20000 |    hdd |  300 |
|      Car |   20000 |   case |  700 |
|      Car |   20000 | wheels | 1000 |
| Airplane | 3000000 |    CPU |  500 |
| Airplane | 3000000 |    hdd |  300 |
| Airplane | 3000000 |   case |  700 |
| Airplane | 3000000 | wheels | 1000 |

JOINs are here to add more value to these products. What we really want is to "join" the product with its associated components, because each component belongs to a product. The way to do this is with a join:

Product JOIN Component ON Pname

The associated SQL query would be like this (you can play with all the examples here)

SELECT *
FROM Product
JOIN Component
  ON Product.Pname = Component.Pname

and the result:

|  PNAME | PRICE |  CNAME | COST |
----------------------------------
| Laptop |  1500 |    CPU |  500 |
| Laptop |  1500 |    hdd |  300 |
| Laptop |  1500 |   case |  700 |
|    Car | 20000 | wheels | 1000 |

Notice that the result has only 4 rows, because the Laptop has 3 components, the Car has 1 and the Airplane none. This is much more useful.

Getting back to your questions, all the joins you ask about are variations of the JOIN I just showed:

Natural Join = the join (the ON clause) is made on all columns with the same name; it removes duplicate columns from the result, as opposed to all other joins; most DBMS (database systems created by various vendors such as Microsoft's SQL Server, Oracle's MySQL etc. ) don't even bother supporting this, it is just bad practice (or purposely chose not to implement it). Imagine that a developer comes and changes the name of the second column in Product from Price to Cost. Then all the natural joins would be done on PName AND on Cost, resulting in 0 rows since no numbers match.

Theta Join = this is the general join everybody uses because it allows you to specify the condition (the ON clause in SQL). You can join on pretty much any condition you like, for example on Products that have the first 2 letters similar, or that have a different price. In practice, this is rarely the case - in 95% of the cases you will join on an equality condition, which leads us to:

Equi Join = the most common one used in practice. The example above is an equi join. Databases are optimized for this type of joins! The oposite of an equi join is a non-equi join, i.e. when you join on a condition other than "=". Databases are not optimized for this! Both of them are subsets of the general theta join. The natural join is also a theta join but the condition (the theta) is implicit.

Source of information: university + certified SQL Server developer + recently completed the MOO "Introduction to databases" from Stanford so I dare say I have relational algebra fresh in mind.

How to execute a java .class from the command line

With Java 11 you won't have to go through this rigmarole anymore!

Instead, you can do this:

> java MyApp.java

You don't have to compile beforehand, as it's all done in one step.

You can get the Java 11 JDK here: JDK 11 GA Release

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

In build.gradle change minSdkVersion 17 or later.

CSS Change List Item Background Color with Class

This is an issue of selector specificity. (The selector .selected is less specific than ul.nav li.)

To fix, use as much specificity in the overriding rule as in the original:

ul.nav li {
 background-color:blue;
}
ul.nav li.selected {
 background-color:red;
}

You might also consider nixing the ul, unless there will be other .navs. So:

.nav li {
 background-color:blue;
}
.nav li.selected {
 background-color:red;
}

That's a bit cleaner, less typing, and fewer bits.

jQuery to loop through elements with the same class

It's pretty simple to do this without jQuery these days.

Without jQuery:

Just select the elements and use the .forEach() method to iterate over them:

const elements = document.querySelectorAll('.testimonial');
Array.from(elements).forEach((element, index) => {
  // conditional logic here.. access element
});

In older browsers:

var testimonials = document.querySelectorAll('.testimonial');
Array.prototype.forEach.call(testimonials, function(element, index) {
  // conditional logic here.. access element
});

Simple way to query connected USB devices info in Python?

I can think of a quick code like this.

Since all USB ports can be accessed via /dev/bus/usb/< bus >/< device >

For the ID generated, even if you unplug the device and reattach it [ could be some other port ]. It will be the same.

import re
import subprocess
device_re = re.compile("Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>\w+:\w+)\s(?P<tag>.+)$", re.I)
df = subprocess.check_output("lsusb")
devices = []
for i in df.split('\n'):
    if i:
        info = device_re.match(i)
        if info:
            dinfo = info.groupdict()
            dinfo['device'] = '/dev/bus/usb/%s/%s' % (dinfo.pop('bus'), dinfo.pop('device'))
            devices.append(dinfo)
print devices

Sample output here will be:

[
{'device': '/dev/bus/usb/001/009', 'tag': 'Apple, Inc. Optical USB Mouse [Mitsumi]', 'id': '05ac:0304'},
{'device': '/dev/bus/usb/001/001', 'tag': 'Linux Foundation 2.0 root hub', 'id': '1d6b:0002'},
{'device': '/dev/bus/usb/001/002', 'tag': 'Intel Corp. Integrated Rate Matching Hub', 'id': '8087:0020'},
{'device': '/dev/bus/usb/001/004', 'tag': 'Microdia ', 'id': '0c45:641d'}
]

Code Updated for Python 3

import re
import subprocess
device_re = re.compile(b"Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>\w+:\w+)\s(?P<tag>.+)$", re.I)
df = subprocess.check_output("lsusb")
devices = []
for i in df.split(b'\n'):
    if i:
        info = device_re.match(i)
        if info:
            dinfo = info.groupdict()
            dinfo['device'] = '/dev/bus/usb/%s/%s' % (dinfo.pop('bus'), dinfo.pop('device'))
            devices.append(dinfo)
            
print(devices)

Adding an onclicklistener to listview (android)

listView.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = prestListView.getItemAtPosition(position);
        prestationEco str = (prestationEco)o; //As you are using Default String Adapter
        Toast.makeText(getBaseContext(),str.getTitle(),Toast.LENGTH_SHORT).show();
    }
});

How to use a WSDL

I would fire up Visual Studio, create a web project (or console app - doesn't matter).

For .Net Standard:

  1. I would right-click on the project and pick "Add Service Reference" from the Add context menu.
  2. I would click on Advanced, then click on Add Service Reference.
  3. I would get the complete file path of the wsdl and paste into the address bar. Then fire the Arrow (go button).
  4. If there is an error trying to load the file, then there must be a broken and unresolved url the file needs to resolve as shown below: enter image description here Refer to this answer for information on how to fix: Stackoverflow answer to: Unable to create service reference for wsdl file

If there is no error, you should simply set the NameSpace you want to use to access the service and it'll be generated for you.

For .Net Core

  1. I would right click on the project and pick Connected Service from the Add context menu.
  2. I would select Microsoft WCF Web Service Reference Provider from the list.
  3. I would press browse and select the wsdl file straight away, Set the namespace and I am good to go. Refer to the error fix url above if you encounter any error.

Any of the methods above will generate a simple, very basic WCF client for you to use. You should find a "YourservicenameClient" class in the generated code.

For reference purpose, the generated cs file can be found in your Obj/debug(or release)/XsdGeneratedCode and you can still find the dlls in the TempPE folder.

The created Service(s) should have methods for each of the defined methods on the WSDL contract.

Instantiate the client and call the methods you want to call - that's all there is!

YourServiceClient client = new YourServiceClient();
client.SayHello("World!");

If you need to specify the remote URL (not using the one created by default), you can easily do this in the constructor of the proxy client:

YourServiceClient client = new YourServiceClient("configName", "remoteURL");

where configName is the name of the endpoint to use (you will use all the settings except the URL), and the remoteURL is a string representing the URL to connect to (instead of the one contained in the config).

Why split the <script> tag when writing it with document.write()?

</script> has to be broken up because otherwise it would end the enclosing <script></script> block too early. Really it should be split between the < and the /, because a script block is supposed (according to SGML) to be terminated by any end-tag open (ETAGO) sequence (i.e. </):

Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "</" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.

However in practice browsers only end parsing a CDATA script block on an actual </script> close-tag.

In XHTML there is no such special handling for script blocks, so any < (or &) character inside them must be &escaped; like in any other element. However then browsers that are parsing XHTML as old-school HTML will get confused. There are workarounds involving CDATA blocks, but it's easiest simply to avoid using these characters unescaped. A better way of writing a script element from script that works on either type of parser would be:

<script type="text/javascript">
    document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>');
</script>

Difference between TCP and UDP?

Short and simple differences between Tcp and Udp protocol:

1) Tcp - Transmission control protocol and Udp - User datagram protocol.

2) Tcp is reliable protocol, Where as Udp is a unreliable protocol.

3) Tcp is a stream oriented, where as Udp is a message oriented protocol.

4) Tcp is a slower than Udp.

JQuery html() vs. innerHTML

If you're wondering about functionality, then jQuery's .html() performs the same intended functionality as .innerHTML, but it also performs checks for cross-browser compatibility.

For this reason, you can always use jQuery's .html() instead of .innerHTML where possible.

Reading the selected value from asp:RadioButtonList using jQuery

For my scenario, my JS was in a separate file, so using a ClientID response output wasn't conducive. Surprisingly, the solution was as simple as adding a CssClass to the RadioButtonList, which I found out on DevCurry

Just incase that solution disappears, add a class to your radio button list

<asp:RadioButtonList id="rbl" runat="server" class="tbl">...

As the article points out, when the radio button list is rendered, the class "tbl" is appended to the surrounding table

<table id="rbl" class="tbl" border="0">
<tr>...

Now because of the CSS class that has been appended, you can just refer to input:radio items within your table, based on the css class selector

$(function () {
            var $radBtn = $("table.tbl input:radio");
            $radBtn.click(function () {
                var $radChecked = $(':radio:checked');
                alert($radChecked.val());
            });
        });

Again, this avoids using the "ClientID" mentioned above which I found messy for my scenario. Hope this helps!

Passing a URL with brackets to curl

Never mind, I found it in the docs:

-g/--globoff
              This  option  switches  off  the "URL globbing parser". When you set this option, you can
              specify URLs that contain the letters {}[] without having them being interpreted by  curl
              itself.  Note  that  these  letters  are not normal legal URL contents but they should be
              encoded according to the URI standard.

Math functions in AngularJS bindings

Better option is to use :

{{(100*score/questionCounter) || 0 | number:0}}

It sets default value of equation to 0 in the case when values are not initialized.

.includes() not working in Internet Explorer

String.prototype.includes is, as you write, not supported in Internet Explorer (or Opera).

Instead you can use String.prototype.indexOf. #indexOf returns the index of the first character of the substring if it is in the string, otherwise it returns -1. (Much like the Array equivalent)

var myString = 'this is my string';
myString.indexOf('string');
// -> 11

myString.indexOf('hello');
// -> -1

MDN has a polyfill for includes using indexOf: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill

EDIT: Opera supports includes as of version 28.

EDIT 2: Current versions of Edge supports the method. (as of 2019)

Conveniently map between enum and int / String

You could perhaps use something like

interface EnumWithId {
    public int getId();

}


enum Foo implements EnumWithId {

   ...
}

That would reduce the need for reflection in your utility class.

Doctrine and LIKE query

This is not possible with the magic methods, however you can achieve this using DQL (Doctrine Query Language). In your example, assuming you have entity named Orders with Product property, just go ahead and do the following:

$dql_query = $em->createQuery("
    SELECT o FROM AcmeCodeBundle:Orders o
    WHERE 
      o.OrderEmail = '[email protected]' AND
      o.Product LIKE 'My Products%'
");
$orders = $dql_query->getResult();

Should do exactly what you need.

JAXB :Need Namespace Prefix to all the elements

Another way is to tell the marshaller to always use a certain prefix

marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
             @Override
            public String getPreferredPrefix(String arg0, String arg1, boolean arg2) {
                return "ns1";
            }
        });'

Install pdo for postgres Ubuntu

Try the packaged pecl version instead (the advantage of the packaged installs is that they're easier to upgrade):

apt-get install php5-dev
pecl install pdo
pecl install pdo_pgsql

or, if you just need a driver for PHP, but that it doesn't have to be the PDO one:

apt-get install php5-pgsql

Otherwise, that message most likely means you need to install a more recent libpq package. You can check which version you have by running:

dpkg -s libpq-dev

OSError [Errno 22] invalid argument when use open() in Python

I had the same problem It happens because files can't contain special characters like ":", "?", ">" and etc. You should replace these files by using replace() function:

filename = filename.replace("special character to replace", "-")

The apk must be signed with the same certificates as the previous version

I had faced this issue recently, after trying different ways to sign in like enable V1 Or V2, signed in by changing alias name and last come to know that I am using wrong key store file

Reload activity in Android

for me it's working it's not creating another Intents and on same the Intents new data loaded.

    overridePendingTransition(0, 0);
    finish();
    overridePendingTransition(0, 0);
    startActivity(getIntent());
    overridePendingTransition(0, 0);

How to search if dictionary value contains certain string with Python

def search(myDict, lookup):
    a=[]
    for key, value in myDict.items():
        for v in value:
            if lookup in v:
                 a.append(key)
    a=list(set(a))
    return a

if the research involves more keys maybe you should create a list with all the keys

Java Array, Finding Duplicates

Let's see how your algorithm works:

an array of unique values:

[1, 2, 3]

check 1 == 1. yes, there is duplicate, assigning duplicate to true.
check 1 == 2. no, doing nothing.
check 1 == 3. no, doing nothing.
check 2 == 1. no, doing nothing.
check 2 == 2. yes, there is duplicate, assigning duplicate to true.
check 2 == 3. no, doing nothing.
check 3 == 1. no, doing nothing.
check 3 == 2. no, doing nothing.
check 3 == 3. yes, there is duplicate, assigning duplicate to true.

a better algorithm:

for (j=0;j<zipcodeList.length;j++) {
    for (k=j+1;k<zipcodeList.length;k++) {
        if (zipcodeList[k]==zipcodeList[j]){ // or use .equals()
            return true;
        }
    }
}
return false;

Postgres Error: More than one row returned by a subquery used as an expression

This error means that the SELECT store_key FROM store query has returned two or more rows in the SERVER1 database. If you would like to update all customers, use a join instead of a scalar = operator. You need a condition to "connect" customers to store items in order to do that.

If you wish to update all customer_ids to the same store_key, you need to supply a WHERE clause to the remotely executed SELECT so that the query returns a single row.

How to display and hide a div with CSS?

To hide an element, use:

display: none;
visibility: hidden;

To show an element, use:

display: block;
visibility: visible;

The difference is:

Visibility handles the visibility of the tag, the display handles space it occupies on the page.

If you set the visibility and do not change the display, even if the tags are not seen, it still occupies space.

Java OCR implementation

Just found this one (don't know it, not tested, check yourself)

Ron Cemer Java OCR


As you only need this for curiosity you could look into the source of this applet.

It does OCR of handwritten characters with a neural network

Java OCR: Handwriting Recognition

How do you remove an invalid remote branch reference from Git?

You might be needing a cleanup:

git gc --prune=now

or you might be needing a prune:

git remote prune public

prune

Deletes all stale tracking branches under <name>. These stale branches have already been removed from the remote repository referenced by <name>, but are still locally available in "remotes/<name>".

With --dry-run option, report what branches will be pruned, but do no actually prune them.

However, it appears these should have been cleaned up earlier with

git remote rm public 

rm

Remove the remote named <name>. All remote tracking branches and configuration settings for the remote are removed.

So it might be you hand-edited your config file and this did not occur, or you have privilege problems.

Maybe run that again and see what happens.


Advice Context

If you take a look in the revision logs, you'll note I suggested more "correct" techniques, which for whatever reason didn't want to work on their repository.

I suspected the OP had done something that left their tree in an inconsistent state that caused it to behave a bit strangely, and git gc was required to fix up the left behind cruft.

Usually git branch -rd origin/badbranch is sufficient for nuking a local tracking branch , or git push origin :badbranch for nuking a remote branch, and usually you will never need to call git gc

Regex to test if string begins with http:// or https://

^https?://

You might have to escape the forward slashes though, depending on context.

Media query to detect if device is touchscreen

I would suggest using modernizr and using its media query features.

if (Modernizr.touch){
   // bind to touchstart, touchmove, etc and watch `event.streamId`
} else {
   // bind to normal click, mousemove, etc
}

However, using CSS, there are pseudo class like, for example in Firefox. You can use :-moz-system-metric(touch-enabled). But these features are not available for every browser.

For Apple devices, you can simple use:

if(window.TouchEvent) {
   //.....
}

Especially for Ipad:

if(window.Touch) {
    //....
}

But, these do not work on Android.

Modernizr gives feature detection abilities, and detecting features is a good way to code, rather than coding on basis of browsers.

Styling Touch Elements

Modernizer adds classes to the HTML tag for this exact purpose. In this case, touch and no-touch so you can style your touch related aspects by prefixing your selectors with .touch. e.g. .touch .your-container. Credits: Ben Swinburne

How to add item to the beginning of List<T>?

Update: a better idea, set the "AppendDataBoundItems" property to true, then declare the "Choose item" declaratively. The databinding operation will add to the statically declared item.

<asp:DropDownList ID="ddl" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="0" Text="Please choose..."></asp:ListItem>
</asp:DropDownList>

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx

-Oisin

How do I view / replay a chrome network debugger har file saved with content?

The Most Reliable way to replay har file is using a free tool like Fiddler, the tool is always free and can be downloaded quickly. The sites for the opening har file are all buggy and cannot open large files. Fiddler is available for all platforms.

https://www.telerik.com/download/fiddler

Go to File Menu -> Import Sessions...

Open Fiddler

Select the "HTTPArchive" Option

Select the Http Archieve option

Browse to your HAR file

enter image description here

The HAR file will open and replay on the fiddler window.

Pinging servers in Python

Programmatic ICMP ping is complicated due to the elevated privileges required to send raw ICMP packets, and calling ping binary is ugly. For server monitoring, you can achieve the same result using a technique called TCP ping:

# pip3 install tcping
>>> from tcping import Ping
# Ping(host, port, timeout)
>>> ping = Ping('212.69.63.54', 22, 60)
>>> ping.ping(3)
Connected to 212.69.63.54[:22]: seq=1 time=23.71 ms
Connected to 212.69.63.54[:22]: seq=2 time=24.38 ms
Connected to 212.69.63.54[:22]: seq=3 time=24.00 ms

Internally, this simply establishes a TCP connection to the target server and drops it immediately, measuring time elapsed. This particular implementation is a bit limited in that it doesn't handle closed ports but for your own servers it works pretty well.

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

THE FINAL ANSWER FOR THOSE WHO USES ANGULAR 6:

Add the below command in your *.service.ts file"

import { map } from "rxjs/operators";

**********************************************Example**Below**************************************
getPosts(){
this.http.get('http://jsonplaceholder.typicode.com/posts')
.pipe(map(res => res.json()));
}
}

I am using windows 10;

angular6 with typescript V 2.3.4.0

Formatting doubles for output in C#

Though this question is meanwhile closed, I believe it is worth mentioning how this atrocity came into existence. In a way, you may blame the C# spec, which states that a double must have a precision of 15 or 16 digits (the result of IEEE-754). A bit further on (section 4.1.6) it's stated that implementations are allowed to use higher precision. Mind you: higher, not lower. They are even allowed to deviate from IEEE-754: expressions of the type x * y / z where x * y would yield +/-INF but would be in a valid range after dividing, do not have to result in an error. This feature makes it easier for compilers to use higher precision in architectures where that'd yield better performance.

But I promised a "reason". Here's a quote (you requested a resource in one of your recent comments) from the Shared Source CLI, in clr/src/vm/comnumber.cpp:

"In order to give numbers that are both friendly to display and round-trippable, we parse the number using 15 digits and then determine if it round trips to the same value. If it does, we convert that NUMBER to a string, otherwise we reparse using 17 digits and display that."

In other words: MS's CLI Development Team decided to be both round-trippable and show pretty values that aren't such a pain to read. Good or bad? I'd wish for an opt-in or opt-out.

The trick it does to find out this round-trippability of any given number? Conversion to a generic NUMBER structure (which has separate fields for the properties of a double) and back, and then compare whether the result is different. If it is different, the exact value is used (as in your middle value with 6.9 - i) if it is the same, the "pretty value" is used.

As you already remarked in a comment to Andyp, 6.90...00 is bitwise equal to 6.89...9467. And now you know why 0.0...8818 is used: it is bitwise different from 0.0.

This 15 digits barrier is hard-coded and can only be changed by recompiling the CLI, by using Mono or by calling Microsoft and convincing them to add an option to print full "precision" (it is not really precision, but by the lack of a better word). It's probably easier to just calculate the 52 bits precision yourself or use the library mentioned earlier.

EDIT: if you like to experiment yourself with IEE-754 floating points, consider this online tool, which shows you all relevant parts of a floating point.

How to add a TextView to a LinearLayout dynamically in Android?

TextView rowTextView = (TextView)getLayoutInflater().inflate(R.layout.yourTextView, null);
        rowTextView.setText(text);
        layout.addView(rowTextView);

This is how I'm using this:

 private List<Tag> tags = new ArrayList<>();


if(tags.isEmpty()){
        Gson gson = new Gson();
        Type listType = new TypeToken<List<Tag>>() {
        }.getType();
        tags = gson.fromJson(tour.getTagsJSONArray(), listType);
    }



if (flowLayout != null) {
        if(!tags.isEmpty()) {
            Log.e(TAG, "setTags: "+ flowLayout.getChildCount() );
            flowLayout.removeAllViews();
            for (Tag tag : tags) {
                FlowLayout.LayoutParams lparams = new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.WRAP_CONTENT);
                lparams.setMargins(PixelUtil.dpToPx(this, 0), PixelUtil.dpToPx(this, 5), PixelUtil.dpToPx(this, 10), PixelUtil.dpToPx(this, 5));// llp.setMargins(left, top, right, bottom);
                TextView rowTextView = (TextView) getLayoutInflater().inflate(R.layout.tag, null);
                rowTextView.setText(tag.getLabel());
                rowTextView.setLayoutParams(lparams);
                flowLayout.addView(rowTextView);
            }
        }
        Log.e(TAG, "setTags: after "+ flowLayout.getChildCount() );
    }

And this is my custom TextView named tag:

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"    
android:textSize="10dp"
android:textAllCaps="true"
fontPath="@string/font_light"
android:background="@drawable/tag_shape"
android:paddingLeft="11dp"
android:paddingTop="6dp"
android:paddingRight="11dp"
android:paddingBottom="6dp">

this is my tag_shape:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f2f2f2" />
<corners android:radius="15dp" />
</shape>

efect:

enter image description here

In other place I'm adding textviews with language names from dialog with listview:

enter image description here

enter image description here

What is the difference between g++ and gcc?

One notable difference is that if you pass a .c file to gcc it will compile as C.

The default behavior of g++ is to treat .c files as C++ (unless -x c is specified).

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

I had the same problem cause i had no public keys, so i did:

heroku keys:clear
heroku keys:add

That will generate a public key and then it works well

Batch not-equal (inequality) operator

Try:

if not "asdf" == "fdas" echo asdf

That works for me on Windows XP (I get the same error as you for the code you posted).

Is there a way to specify which pytest tests to run from a file?

According to the doc about Run tests by node ids

since you have all node ids in foo.txt, just run

pytest `cat foo.txt | tr '\n' ' '`

this is same with below command (with file content in the question)

pytest tests_directory/foo.py::test_001 tests_directory/bar.py::test_some_other_test

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

All of the current answers are addressing the symptom (shared memory pool exhaustion), and not the problem, which is likely not using bind variables in your sql \ JDBC queries, even when it does not seem necessary to do so. Passing queries without bind variables causes Oracle to "hard parse" the query each time, determining its plan of execution, etc.

https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:528893984337

Some snippets from the above link:

"Java supports bind variables, your developers must start using prepared statements and bind inputs into it. If you want your system to ultimately scale beyond say about 3 or 4 users -- you will do this right now (fix the code). It is not something to think about, it is something you MUST do. A side effect of this - your shared pool problems will pretty much disappear. That is the root cause. "

"The way the Oracle shared pool (a very important shared memory data structure) operates is predicated on developers using bind variables."

" Bind variables are SO MASSIVELY important -- I cannot in any way shape or form OVERSTATE their importance. "

How do you follow an HTTP Redirect in Node.js?

In case of PUT or POST Request. if you receive statusCode 405 or method not allowed. Try this implementation with "request" library, and add mentioned properties.
followAllRedirects: true,
followOriginalHttpMethod: true

       const options = {
           headers: {
               Authorization: TOKEN,
               'Content-Type': 'application/json',
               'Accept': 'application/json'
           },
           url: `https://${url}`,
           json: true,
           body: payload,
           followAllRedirects: true,
           followOriginalHttpMethod: true
       }

       console.log('DEBUG: API call', JSON.stringify(options));
       request(options, function (error, response, body) {
       if (!error) {
        console.log(response);
        }
     });
}

Insertion Sort vs. Selection Sort

I want to add a little bit of improvement from an almost excellent answer from user @thyago stall above. In Python, we can do one line swapping. The selection_sort below also has been fixed by just swapping the current element with the minimum element at the right side.

In insertion sort we will run the outer loop from the second element and do an inner loop on the left side of the current element, shifting the smaller elements to the left.

def insertion_sort(arr):
    i = 1
    while i < len(arr):
        for j in range(i):
            if arr[i] < arr[j]:
                arr[i], arr[j] = arr[j], arr[i]
    i += 1

In selection sort, we also run the outer loop but instead of starting from the second element, we start from the first element. Then inner loop will loop the current + i element to the end of array to find the minimum element and we will swapped with the current index.

def selection_sort(arr):
    i = 0
    while i < len(arr):
        min_idx = i
        for j in range(i + 1, len(arr)):
            if arr[min_idx] > arr[j]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    i += 1

How do I check if an object's type is a particular subclass in C++?

You can do it with dynamic_cast (at least for polymorphic types).

Actually, on second thought--you can't tell if it is SPECIFICALLY a particular type with dynamic_cast--but you can tell if it is that type or any subclass thereof.

template <class DstType, class SrcType>
bool IsType(const SrcType* src)
{
  return dynamic_cast<const DstType*>(src) != nullptr;
}

No Exception while type casting with a null in java

This language feature is convenient in this situation.

public String getName() {
  return (String) memberHashMap.get("Name");
}

If memberHashMap.get("Name") returns null, you'd still want the method above to return null without throwing an exception. No matter what the class is, null is null.

How to force a list to be vertical using html css

Try putting display: block in the <li> tags instead of the <ul>

Paste MS Excel data to SQL Server

I have developed an Excel VBA Macro for cutting and pasting any selection from Excel into SQL Server, creating a new table. The macro is great for quick and dirty table creations up to a few thousand rows and multiple columns (It can theoretically manage up to 200 columns). The macro attempts to automatically detect header names and assign the most appropriate datatype to each column (it handles varchar columns upto 1000 chars).

Recommended Setup procedure:

  1. Make sure Excel is enabled to run macros. (File->Options->Trust Center->Trust Center Settings->Macro Settings->Enable all macros..)
  2. Copy the VBA code below to the module associated with your personal workbook (So that the Macro will be available for all worksheets)
  3. Assign an appropriate keystroke to the macro ( I have assigned Ctrl Shift X)
  4. Save your personal workbook

Use of Macro

  1. Select the cells in Excel (including column headers if they exist) to be transferred to SQL
  2. Press the assigned keyword combination that you have assigned to run the macro
  3. Follow the prompts. (Default table name is ##Table)
  4. Paste the clipboard contents into a SSMS window and run the generated SQL code. BriFri 238

VBA Code:

Sub TransferToSQL()
'
' TransferToSQL Macro
' This macro prepares data for pasting into SQL Server and posts it to the clipboard for inserting into SSMS
' It attempts to automatically detect header rows and does a basic analysis of the first 15 rows to determine the most appropriate datatype to use handling text entries upto 1000 chars.
'
' Max Number of Columns: 200
'
' Keyboard Shortcut: Ctrl+Shift+X
'
' ver   Date    Reason
' ===   ====    ======

' 1.6   06/2012 Fixed bug that prevented auto exit if no selection made / auto exit if blank Tablename entered or 'cancel' button pressed
' 1.5   02/2012 made use of function fn_ColLetter to retrieve the Column Letter for a specified column
' 1.4   02/2012 Replaces any Tabs in text data to spaces to prevent Double quotes being output in final results
' 1.3   02/2012 Place the 'drop table if already exists' code into a separate batch to prevent errors when inserting new table with same name but different shape and > 100 rows
' 1.2   01/2012 If null dates encountered code to cast it as Null rather than '00-Jan-1900'
' 1.1   10/2011 Code to drop the table if already exists
' 1.0   03/2011 Created

Dim intLastRow As Long
Dim intlastColumn As Integer
Dim intRow As Long
Dim intDataStartRow As Long
Dim intColumn As Integer
Dim strKeyWord As String
Dim intPos As Integer
Dim strDataTypeLevel(4) As String
Dim strColumnHeader(200) As String
Dim strDataType(200) As String
Dim intRowCheck As Integer
Dim strFormula(20) As String
Dim intHasHeaderRow As Integer
Dim strCellRef As String
Dim intFormulaCount As Integer
Dim strSQLTableName As String
Dim strSQLTableName_Encap As String
Dim intdataTypelevel As Integer
Const strConstHeaderKeyword As String = "ID,URN,name,Title,Job,Company,Contact,Address,Post,Town,Email,Tele,phone,Area,Region,Business,Total,Month,Week,Year,"
Const intConstMaxBatchSize As Integer = 100
    Const intConstNumberRowsToAnalyse As Integer = 100
intHasHeaderRow = 0

strDataTypeLevel(1) = "VARCHAR(1000)"
strDataTypeLevel(2) = "FLOAT"
strDataTypeLevel(3) = "INTEGER"
strDataTypeLevel(4) = "DATETIME"



' Use current selection and paste to new temp worksheet

    Selection.Copy
    Workbooks.Add       ' add temp 'Working' Workbook
    ' Paste "Values Only" back into new temp workbook
    Range("A3").Select  ' Goto 3rd Row
    Selection.PasteSpecial Paste:=xlFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False ' Copy Format of Selection
    Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False  ' Copy Values of Selection
    ActiveCell.SpecialCells(xlLastCell).Select  ' Goto last cell
    intLastRow = ActiveCell.Row
    intlastColumn = ActiveCell.Column


' Check to make sure that there are cells which are selected
If intLastRow = 3 And intlastColumn = 1 Then
    Application.DisplayAlerts = False       ' Temporarily switch off Display Alerts
    ActiveWindow.Close                      ' Delete newly created worksheet
    Application.DisplayAlerts = True        ' Switch display alerts back on
    MsgBox "*** Please Make selection before running macro - Terminating ***", vbOKOnly, "Transfer Data to SQL Server"
    Exit Sub
End If

' Prompt user for Name of SQL Server table
strSQLTableName = InputBox("SQL Server Table Name?", "Transfer Excel Data To SQL", "##Table")

' if blank table name entered or 'Cancel' selected then exit
If strSQLTableName = "" Then
    Application.DisplayAlerts = False       ' Temporarily switch off Display Alerts
    ActiveWindow.Close                      ' Delete newly created worksheet
    Application.DisplayAlerts = True        ' Switch display alerts back on
    Exit Sub
End If



' encapsulate tablename with square brackets if user has not already done so
strSQLTableName_Encap = Replace(Replace(Replace("[" & Replace(strSQLTableName, ".", "].[") & "]", "[]", ""), "[[", "["), "]]", "]")

' Try to determine if the First Row is a header row or contains data and if a header load names of Columns
Range("A3").Select
For intColumn = 1 To intlastColumn
    ' first check to see if the first row contains any pure numbers or pure dates
    If IsNumeric(ActiveCell.Value) Or IsDate(ActiveCell.Value) Then
    intHasHeaderRow = vbNo
    intDataStartRow = 3
    Exit For
    Else
    strColumnHeader(intColumn) = ActiveCell.Value
    ActiveCell.Offset(1, 0).Range("A1").Select  ' go to the row below
    If IsNumeric(ActiveCell.Value) Or IsDate(ActiveCell.Value) Then
        intHasHeaderRow = vbYes
        intDataStartRow = 4
    End If
    ActiveCell.Offset(-1, 0).Range("A1").Select  ' go back up to the first row
    If intHasHeaderRow = 0 Then     ' if still not determined if header exists: Look for header using keywords
        intPos = 1
        While intPos < Len(strConstHeaderKeyword) And intHasHeaderRow = 0
        strKeyWord = Mid$(strConstHeaderKeyword, intPos, InStr(intPos, strConstHeaderKeyword, ",") - intPos)
        If InStr(1, ActiveCell.Value, strKeyWord) > 0 Then
            intHasHeaderRow = vbYes
            intDataStartRow = 4
        End If
        intPos = InStr(intPos, strConstHeaderKeyword, ",") + 1
        Wend
    End If
    End If
    ActiveCell.Offset(0, 1).Range("A1").Select  ' Goto next column
Next intColumn

' If auto header row detection has failed ask the user to manually select
If intHasHeaderRow = 0 Then
    intHasHeaderRow = MsgBox("Does current selection have a header row?", vbYesNo, "Auto header row detection failure")
    If intHasHeaderRow = vbYes Then
    intDataStartRow = 4
    Else
    intDataStartRow = 3
    End If

End If




' *** Determine the Data Type of each Column ***

' Go thru each Column to find Data types
If intLastRow < intConstNumberRowsToAnalyse  Then             ' Check the first intConstNumberRowsToAnalyse  rows or to end of selection whichever is less
    intRowCheck = intLastRow
Else
    intRowCheck = intConstNumberRowsToAnalyse 
End If

For intColumn = 1 To intlastColumn
    intdataTypelevel = 5

    For intRow = intDataStartRow To intRowCheck
    Application.Goto Reference:="R" & CStr(intRow) & "C" & CStr(intColumn)
    If ActiveCell.Value = "" Then   ' ignore blank (null) values
    ElseIf IsDate(ActiveCell.Value) = True And Len(ActiveCell.Value) >= 8 Then
        If intdataTypelevel > 4 Then intdataTypelevel = 4
    ElseIf IsNumeric(ActiveCell.Value) = True And InStr(1, CStr(ActiveCell.Value), ".") = 0 And (Left(CStr(ActiveCell.Value), 1) <> "0" Or ActiveCell.Value = "0") And Len(ActiveCell.Value) < 10 Then
        If intdataTypelevel > 3 Then intdataTypelevel = 3
    ElseIf IsNumeric(ActiveCell.Value) = True And InStr(1, CStr(ActiveCell.Value), ".") >= 1 Then
        If intdataTypelevel > 2 Then intdataTypelevel = 2
    Else
        intdataTypelevel = 1
        Exit For
    End If
    Next intRow
    If intdataTypelevel = 5 Then intdataTypelevel = 1
    strDataType(intColumn) = strDataTypeLevel(intdataTypelevel)
Next intColumn


' *** Build up the SQL
intFormulaCount = 1
If intHasHeaderRow = vbYes Then     ' *** Header Row ***
    Application.Goto Reference:="R4" & "C" & CStr(intlastColumn + 1)    ' Goto next column in first data row of selection
    strFormula(intFormulaCount) = "= ""SELECT "
    For intColumn = 1 To intlastColumn
    If strDataType(intColumn) = "DATETIME" Then         ' Code to take Excel Dates back to text
        strCellRef = "Text(" & fn_ColLetter(intColumn) & "4,""dd-mmm-yyyy hh:mm:ss"")"
    ElseIf strDataType(intColumn) = "VARCHAR(1000)" Then
        strCellRef = "SUBSTITUTE(" & fn_ColLetter(intColumn) & "4,""'"",""''"")" ' Convert any single ' to double ''
    Else
        strCellRef = fn_ColLetter(intColumn) & "4"
    End If


    strFormula(intFormulaCount) = strFormula(intFormulaCount) & "CAST('""& " & strCellRef & " & ""' AS " & strDataType(intColumn) & ") AS [" & strColumnHeader(intColumn) & "]"
    If intColumn < intlastColumn Then
        strFormula(intFormulaCount) = strFormula(intFormulaCount) + ", "
    Else
        strFormula(intFormulaCount) = strFormula(intFormulaCount) + " UNION ALL """
    End If
    ' since each cell can only hold a maximum no. of chars if Formula string gets too big continue formula in adjacent cell
    If Len(strFormula(intFormulaCount)) > 700 And intColumn < intlastColumn Then
        strFormula(intFormulaCount) = strFormula(intFormulaCount) + """"
        intFormulaCount = intFormulaCount + 1
        strFormula(intFormulaCount) = "= """
    End If
    Next intColumn

 ' Assign the formula to the cell(s) just right of the selection
    For intColumn = 1 To intFormulaCount
    ActiveCell.Value = strFormula(intColumn)
    If intColumn < intFormulaCount Then ActiveCell.Offset(0, 1).Range("A1").Select  ' Goto next column
    Next intColumn


 ' Auto Fill the formula for the full length of the selection
    ActiveCell.Offset(0, -intFormulaCount + 1).Range("A1:" & fn_ColLetter(intFormulaCount) & "1").Select
    If intLastRow > 4 Then Selection.AutoFill Destination:=Range(fn_ColLetter(intlastColumn + 1) & "4:" & fn_ColLetter(intlastColumn + intFormulaCount) & CStr(intLastRow)), Type:=xlFillDefault

 ' Go to start row of data selection to add 'Select into' code
   ActiveCell.Value = "SELECT * INTO " & strSQLTableName_Encap & " FROM (" & ActiveCell.Value

 ' Go to cells above data to insert code for deleting old table with the same name in separate SQL batch
   ActiveCell.Offset(-1, 0).Range("A1").Select  ' go to the row above
   ActiveCell.Value = "GO"
   ActiveCell.Offset(-1, 0).Range("A1").Select  ' go to the row above
   If Left(strSQLTableName, 1) = "#" Then      ' temp table
       ActiveCell.Value = "IF OBJECT_ID('tempdb.." & strSQLTableName & "') IS NOT NULL DROP TABLE " & strSQLTableName_Encap
   Else
       ActiveCell.Value = "IF OBJECT_ID('" & strSQLTableName & "') IS NOT NULL DROP TABLE " & strSQLTableName_Encap
   End If



' For Big selections (i.e. several 100 or 1000 rows) SQL Server takes a very long time to do a multiple union - Split up the table creation into many inserts
    intRow = intConstMaxBatchSize + 4   ' add 4 to make sure 1st batch = Max Batch Size
    While intRow < intLastRow
    Application.Goto Reference:="R" & CStr(intRow - 1) & "C" & CStr(intlastColumn + intFormulaCount)  ' Goto Row before intRow and the last column in formula selection
    ActiveCell.Value = Replace(ActiveCell.Value, " UNION ALL ", " ) a") ' Remove last 'UNION ALL'

    Application.Goto Reference:="R" & CStr(intRow) & "C" & CStr(intlastColumn + 1)    ' Goto intRow and the first column in formula selection
    ActiveCell.Value = "INSERT " & strSQLTableName_Encap & " SELECT * FROM (" & ActiveCell.Value
    intRow = intRow + intConstMaxBatchSize   ' increment intRow by intConstMaxBatchSize
    Wend


    ' Delete the last 'UNION AlL' replacing it with brackets to mark the end of the last insert
    Application.Goto Reference:="R" & CStr(intLastRow) & "C" & CStr(intlastColumn + intFormulaCount)
    ActiveCell.Value = Replace(ActiveCell.Value, " UNION ALL ", " ) a")

    ' Select all the formula cells
    ActiveCell.Offset(-intLastRow + 2, 1 - intFormulaCount).Range("A1:" & fn_ColLetter(intFormulaCount + 1) & CStr(intLastRow - 1)).Select
Else    ' *** No Header Row ***
    Application.Goto Reference:="R3" & "C" & CStr(intlastColumn + 1)    ' Goto next column in first data row of selection
    strFormula(intFormulaCount) = "= ""SELECT "

    For intColumn = 1 To intlastColumn
    If strDataType(intColumn) = "DATETIME" Then
        strCellRef = "Text(" & fn_ColLetter(intColumn) & "3,""dd-mmm-yyyy hh:mm:ss"")"   ' Format Excel dates into a text Date format that SQL will pick up
    ElseIf strDataType(intColumn) = "VARCHAR(1000)" Then
        strCellRef = "SUBSTITUTE(" & fn_ColLetter(intColumn) & "3,""'"",""''"")"         ' Change all single ' to double ''
    Else
        strCellRef = fn_ColLetter(intColumn) & "3"
    End If

    ' Since no column headers: Name each column "Column001",Column002"..
    strFormula(intFormulaCount) = strFormula(intFormulaCount) & "CAST('""& " & strCellRef & " & ""' AS " & strDataType(intColumn) & ") AS [Column" & CStr(intColumn) & "]"
    If intColumn < intlastColumn Then
        strFormula(intFormulaCount) = strFormula(intFormulaCount) + ", "
    Else
        strFormula(intFormulaCount) = strFormula(intFormulaCount) + " UNION ALL """
    End If

    ' since each cell can only hold a maximum no. of chars if Formula string gets too big continue formula in adjacent cell
    If Len(strFormula(intFormulaCount)) > 700 And intColumn < intlastColumn Then
        strFormula(intFormulaCount) = strFormula(intFormulaCount) + """"
        intFormulaCount = intFormulaCount + 1
        strFormula(intFormulaCount) = "= """
    End If
    Next intColumn

    ' Assign the formula to the cell(s) just right of the selection
    For intColumn = 1 To intFormulaCount
    ActiveCell.Value = strFormula(intColumn)
    If intColumn < intFormulaCount Then ActiveCell.Offset(0, 1).Range("A1").Select  ' Goto next column
    Next intColumn

 ' Auto Fill the formula for the full length of the selection
    ActiveCell.Offset(0, -intFormulaCount + 1).Range("A1:" & fn_ColLetter(intFormulaCount) & "1").Select
    If intLastRow > 4 Then Selection.AutoFill Destination:=Range(fn_ColLetter(intlastColumn + 1) & "3:" & fn_ColLetter(intlastColumn + intFormulaCount) & CStr(intLastRow)), Type:=xlFillDefault

 ' Go to start row of data selection to add 'Select into' code
   ActiveCell.Value = "SELECT * INTO " & strSQLTableName_Encap & " FROM (" & ActiveCell.Value

 ' Go to cells above data to insert code for deleting old table with the same name in separate SQL batch
   ActiveCell.Offset(-1, 0).Range("A1").Select  ' go to the row above
   ActiveCell.Value = "GO"
   ActiveCell.Offset(-1, 0).Range("A1").Select  ' go to the row above
   If Left(strSQLTableName, 1) = "#" Then      ' temp table
       ActiveCell.Value = "IF OBJECT_ID('tempdb.." & strSQLTableName & "') IS NOT NULL DROP TABLE " & strSQLTableName_Encap
   Else
       ActiveCell.Value = "IF OBJECT_ID('" & strSQLTableName & "') IS NOT NULL DROP TABLE " & strSQLTableName_Encap
   End If

  ' For Big selections (i.e. serveral 100 or 1000 rows) SQL Server takes a very long time to do a multiple union - Split up the table creation into many inserts
   intRow = intConstMaxBatchSize + 3        ' add 3 to make sure 1st batch = Max Batch Size
    While intRow < intLastRow
    Application.Goto Reference:="R" & CStr(intRow - 1) & "C" & CStr(intlastColumn + intFormulaCount)  ' Goto Row before intRow and the last column in formula selection
    ActiveCell.Value = Replace(ActiveCell.Value, " UNION ALL ", " ) a") ' Remove last 'UNION ALL'

    Application.Goto Reference:="R" & CStr(intRow) & "C" & CStr(intlastColumn + 1)    ' Goto intRow and the first column in formula selection
    ActiveCell.Value = "INSERT " & strSQLTableName_Encap & " SELECT * FROM (" & ActiveCell.Value
    intRow = intRow + intConstMaxBatchSize   ' increment intRow by intConstMaxBatchSize
    Wend

    ' Delete the last 'UNION AlL'
    Application.Goto Reference:="R" & CStr(intLastRow) & "C" & CStr(intlastColumn + intFormulaCount)
    ActiveCell.Value = Replace(ActiveCell.Value, " UNION ALL ", " ) a")

    ' Select all the formula cells
    ActiveCell.Offset(-intLastRow + 1, 1 - intFormulaCount).Range("A1:" & fn_ColLetter(intFormulaCount + 1) & CStr(intLastRow)).Select
End If


' Final Selection to clipboard and Cleaning of data
Selection.Copy
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False              ' Repaste "Values Only" back into cells
Selection.Replace What:="CAST('' AS", Replacement:="CAST(NULL AS", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False  ' convert all blank cells to NULL
Selection.Replace What:="'00-Jan-1900 00:00:00'", Replacement:="NULL", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False  ' convert all blank Date cells to NULL
Selection.Replace What:="'NULL'", Replacement:="NULL", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False  ' convert all 'NULL' cells to NULL
Selection.Replace What:=vbTab, Replacement:=" ", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False        ' Replace all Tabs in cells to Space to prevent Double Quotes occuring in the final paste text
Selection.Copy


MsgBox "SQL Code has been added to clipboard - Please Paste into SSMS window", vbOKOnly, "Transfer to SQL"

Application.DisplayAlerts = False       ' Temporarily switch off Display Alerts
ActiveWindow.Close                      ' Delete newly created worksheet
Application.DisplayAlerts = True        ' Switch display alerts back on



End Sub




Function fn_ColLetter(Col As Integer) As String

Dim strColLetter As String

If Col > 26 Then
    ' double letter columns
    strColLetter = Chr(Int((Col - 1) / 26) + 64) & _
        Chr(((Col - 1) Mod 26) + 65)
Else
    ' single letter columns
    strColLetter = Chr(Col + 64)
End If
fn_ColLetter = strColLetter
End Function

How to serialize an Object into a list of URL query parameters?

One line with no dependencies:

new URLSearchParams(obj).toString();
// OUT: param1=something&param2=somethingelse&param3=another&param4=yetanother

Use it with the URL builtin like so:

let obj = { param1: 'something', param2: 'somethingelse', param3: 'another' }
obj['param4'] = 'yetanother';
const url = new URL(`your_url.com`);
url.search = new URLSearchParams(obj);
const response = await fetch(url);

[Edit April 4, 2020]: null values will be interpreted as the string 'null'.

How to get status code from webclient?

You can try this code to get HTTP status code from WebException or from OpenReadCompletedEventArgs.Error. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.

HttpStatusCode GetHttpStatusCode(System.Exception err)
{
    if (err is WebException)
    {
        WebException we = (WebException)err;
        if (we.Response is HttpWebResponse)
        {
            HttpWebResponse response = (HttpWebResponse)we.Response;
            return response.StatusCode;
        }
    }
    return 0;
}

echo that outputs to stderr

Don't use cat as some have mentioned here. cat is a program while echo and printf are bash (shell) builtins. Launching a program or another script (also mentioned above) means to create a new process with all its costs. Using builtins, writing functions is quite cheap, because there is no need to create (execute) a process (-environment).

The opener asks "is there any standard tool to output (pipe) to stderr", the short answer is : NO ... why? ... redirecting pipes is an elementary concept in systems like unix (Linux...) and bash (sh) builds up on these concepts.

I agree with the opener that redirecting with notations like this: &2>1 is not very pleasant for modern programmers, but that's bash. Bash was not intended to write huge and robust programs, it is intended to help the admins to get there work with less keypresses ;-)

And at least, you can place the redirection anywhere in the line:

$ echo This message >&2 goes to stderr 
This message goes to stderr

How to make fixed header table inside scrollable div?

Using position: sticky on th will do the trick.

Note: if you use position: sticky on thead or tr, it won't work.

https://jsfiddle.net/hrg3tmxj/

syntax error when using command line in python

Running from the command line means running from the terminal or DOS shell. You are running it from Python itself.

Spring get current ApplicationContext

If you're implementing a class that's not instantiated by Spring, like a JsonDeserializer you can use:

WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
MyClass myBean = context.getBean(MyClass.class);

Django values_list vs values

The best place to understand the difference is at the official documentation on values / values_list. It has many useful examples and explains it very clearly. The django docs are very user freindly.

Here's a short snippet to keep SO reviewers happy:

values

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

And read the section which follows it:

value_list

This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over.

Is there a good jQuery Drag-and-drop file upload plugin?

I created a plugin which allows you to drop some files onto a given area. This plugin currently works in Firefox, Safari and Chrome.

http://code.google.com/p/dnd-file-upload/

What's the difference between a word and byte?

The terms of BYTE and WORD are relative to the size of the processor that is being referred to. The most common processors are/were 8 bit, 16 bit, 32 bit or 64 bit. These are the WORD lengths of the processor. Actually half of a WORD is a BYTE, whatever the numerical length is. Ready for this, half of a BYTE is a NIBBLE.

Check if null Boolean is true results in exception

Or with the power of Java 8 Optional, you also can do such trick:

Optional.ofNullable(boolValue).orElse(false)

:)

Set Background cell color in PHPExcel

function cellColor($cells,$color){
    global $objPHPExcel;

    $objPHPExcel->getActiveSheet()->getStyle($cells)->getFill()->applyFromArray(array(
        'type' => PHPExcel_Style_Fill::FILL_SOLID,
        'startcolor' => array(
             'rgb' => $color
        )
    ));
}

cellColor('B5', 'F28A8C');
cellColor('G5', 'F28A8C');
cellColor('A7:I7', 'F28A8C');
cellColor('A17:I17', 'F28A8C');
cellColor('A30:Z30', 'F28A8C');

enter image description here

Is there a way to catch the back button event in javascript?

I did a fun hack to solve this issue to my satisfaction. I've got an AJAX site that loads content dynamically, then modifies the window.location.hash, and I had code to run upon $(document).ready() to parse the hash and load the appropriate section. The thing is that I was perfectly happy with my section loading code for navigation, but wanted to add a way to intercept the browser back and forward buttons, which change the window location, but not interfere with my current page loading routines where I manipulate the window.location, and polling the window.location at constant intervals was out of the question.

What I ended up doing was creating an object as such:

var pageload = {
    ignorehashchange: false,
    loadUrl: function(){
        if (pageload.ignorehashchange == false){
            //code to parse window.location.hash and load content
        };
    }
};

Then, I added a line to my site script to run the pageload.loadUrl function upon the hashchange event, as such:

window.addEventListener("hashchange", pageload.loadUrl, false);

Then, any time I want to modify the window.location.hash without triggering this page loading routine, I simply add the following line before each window.location.hash = line:

pageload.ignorehashchange = true;

and then the following line after each hash modification line:

setTimeout(function(){pageload.ignorehashchange = false;}, 100);

So now my section loading routines are usually running, but if the user hits the 'back' or 'forward' buttons, the new location is parsed and the appropriate section loaded.

What data type to use for money in Java?

An integral type representing the smallest value possible. In other words your program should think in cents not in dollars/euros.

This should not stop you from having the gui translate it back to dollars/euros.

How to set the Default Page in ASP.NET?

if you are using login page in your website go to web.config file

<authentication mode="Forms">
  <forms loginUrl="login.aspx" defaultUrl="index.aspx"  >
    </forms>
</authentication>

replace your authentication tag to above (where index.aspx will be your startup page)

and one more thing write this in your web.config file inside

<configuration>
   <system.webServer>
   <defaultDocument>
    <files>
     <clear />
     <add value="index.aspx" />
    </files>
  </defaultDocument>
  </system.webServer>

  <location path="index.aspx">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
   </system.web>
  </location>
</configuration>

Differences between "java -cp" and "java -jar"?

java -cp CLASSPATH is necesssary if you wish to specify all code in the classpath. This is useful for debugging code.

The jarred executable format: java -jar JarFile can be used if you wish to start the app with a single short command. You can specify additional dependent jar files in your MANIFEST using space separated jars in a Class-Path entry, e.g.:

Class-Path: mysql.jar infobus.jar acme/beans.jar

Both are comparable in terms of performance.

Swift how to sort array of custom objects by property value

With Swift 5, Array has two methods called sorted() and sorted(by:). The first method, sorted(), has the following declaration:

Returns the elements of the collection, sorted.

func sorted() -> [Element]

The second method, sorted(by:), has the following declaration:

Returns the elements of the collection, sorted using the given predicate as the comparison between elements.

func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]

#1. Sort with ascending order for comparable objects

If the element type inside your collection conforms to Comparable protocol, you will be able to use sorted() in order to sort your elements with ascending order. The following Playground code shows how to use sorted():

class ImageFile: CustomStringConvertible, Comparable {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

    static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID == rhs.fileID
    }

    static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID < rhs.fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted()
print(sortedImages)

/*
 prints: [ImageFile with ID: 100, ImageFile with ID: 200, ImageFile with ID: 300]
 */

#2. Sort with descending order for comparable objects

If the element type inside your collection conforms to Comparable protocol, you will have to use sorted(by:) in order to sort your elements with a descending order.

class ImageFile: CustomStringConvertible, Comparable {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

    static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID == rhs.fileID
    }

    static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID < rhs.fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
    return img0 > img1
})
//let sortedImages = images.sorted(by: >) // also works
//let sortedImages = images.sorted { $0 > $1 } // also works
print(sortedImages)

/*
 prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
 */

#3. Sort with ascending or descending order for non-comparable objects

If the element type inside your collection DOES NOT conform to Comparable protocol, you will have to use sorted(by:) in order to sort your elements with ascending or descending order.

class ImageFile: CustomStringConvertible {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
    return img0.fileID < img1.fileID
})
//let sortedImages = images.sorted { $0.fileID < $1.fileID } // also works
print(sortedImages)

/*
 prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
 */

Note that Swift also provides two methods called sort() and sort(by:) as counterparts of sorted() and sorted(by:) if you need to sort your collection in-place.

How can I simulate a click to an anchor tag?

Quoted from https://developer.mozilla.org/en/DOM/element.click

The click method is intended to be used with INPUT elements of type button, checkbox, radio, reset or submit. Gecko does not implement the click method on other elements that might be expected to respond to mouse–clicks such as links (A elements), nor will it necessarily fire the click event of other elements.

Non–Gecko DOMs may behave differently.

Unfortunately it sounds like you have already discovered the best solution to your problem.

As a side note, I agree that your solution seems less than ideal, but if you encapsulate the functionality inside a method (much like JQuery would do) it is not so bad.

Encoding Javascript Object to Json string

You can use JSON.stringify like:

JSON.stringify(new_tweets);

Implementing INotifyPropertyChanged - does a better way exist?

I resolved in This Way (it's a little bit laboriouse, but it's surely the faster in runtime).

In VB (sorry, but I think it's not hard translate it in C#), I make this substitution with RE:

(?<Attr><(.*ComponentModel\.)Bindable\(True\)>)( |\r\n)*(?<Def>(Public|Private|Friend|Protected) .*Property )(?<Name>[^ ]*) As (?<Type>.*?)[ |\r\n](?![ |\r\n]*Get)

with:

Private _${Name} As ${Type}\r\n${Attr}\r\n${Def}${Name} As ${Type}\r\nGet\r\nReturn _${Name}\r\nEnd Get\r\nSet (Value As ${Type})\r\nIf _${Name} <> Value Then \r\n_${Name} = Value\r\nRaiseEvent PropertyChanged(Me, New ComponentModel.PropertyChangedEventArgs("${Name}"))\r\nEnd If\r\nEnd Set\r\nEnd Property\r\n

This transofrm all code like this:

<Bindable(True)>
Protected Friend Property StartDate As DateTime?

In

Private _StartDate As DateTime?
<Bindable(True)>
Protected Friend Property StartDate As DateTime?
    Get
        Return _StartDate
    End Get
    Set(Value As DateTime?)
        If _StartDate <> Value Then
            _StartDate = Value
            RaiseEvent PropertyChange(Me, New ComponentModel.PropertyChangedEventArgs("StartDate"))
        End If
    End Set
End Property

And If I want to have a more readable code, I can be the opposite just making the following substitution:

Private _(?<Name>.*) As (?<Type>.*)[\r\n ]*(?<Attr><(.*ComponentModel\.)Bindable\(True\)>)[\r\n ]*(?<Def>(Public|Private|Friend|Protected) .*Property )\k<Name> As \k<Type>[\r\n ]*Get[\r\n ]*Return _\k<Name>[\r\n ]*End Get[\r\n ]*Set\(Value As \k<Type>\)[\r\n ]*If _\k<Name> <> Value Then[\r\n ]*_\k<Name> = Value[\r\n ]*RaiseEvent PropertyChanged\(Me, New (.*ComponentModel\.)PropertyChangedEventArgs\("\k<Name>"\)\)[\r\n ]*End If[\r\n ]*End Set[\r\n ]*End Property

With

${Attr} ${Def} ${Name} As ${Type}

I throw to replace the IL code of the set method, but I can't write a lot of compiled code in IL... If a day I write it, I'll say you!

Call PHP function from Twig template

Its not possible to access any PHP function inside Twig directly.

What you can do is write a Twig extension. A common structure is, writing a service with some utility functions, write a Twig extension as bridge to access the service from twig. The Twig extension will use the service and your controller can use the service too.

Take a look: http://symfony.com/doc/current/cookbook/templating/twig_extension.html

Cheers.

How to pause for specific amount of time? (Excel/VBA)

Wait and Sleep functions lock Excel and you can't do anything else until the delay finishes. On the other hand Loop delays doesn't give you an exact time to wait.

So, I've made this workaround joining a little bit of both concepts. It loops until the time is the time you want.

Private Sub Waste10Sec()
   target = (Now + TimeValue("0:00:10"))
   Do
       DoEvents 'keeps excel running other stuff
   Loop Until Now >= target
End Sub

You just need to call Waste10Sec where you need the delay

taking input of a string word by word

Put the line in a stringstream and extract word by word back:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string t;
    getline(cin,t);

    istringstream iss(t);
    string word;
    while(iss >> word) {
        /* do stuff with word */
    }
}

Of course, you can just skip the getline part and read word by word from cin directly.

And here you can read why is using namespace std considered bad practice.

Subset and ggplot2

Here 2 options for subsetting:

Using subset from base R:

library(ggplot2)
ggplot(subset(dat,ID %in% c("P1" , "P3"))) + 
         geom_line(aes(Value1, Value2, group=ID, colour=ID))

Using subset the argument of geom_line(Note I am using plyr package to use the special . function).

library(plyr)
ggplot(data=dat)+ 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
                ,subset = .(ID %in% c("P1" , "P3")))

You can also use the complementary subsetting:

subset(dat,ID != "P2")

Stop handler.postDelayed()

  Boolean condition=false;  //Instance variable declaration.

 //-----------------Inside oncreate--------------------------------------------------- 
  start =(Button)findViewById(R.id.id_start);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                starthandler();

                if(condition=true)
                {
                    condition=false;
                }


            }
        });

        stop=(Button) findViewById(R.id.id_stoplocatingsmartplug);

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stophandler();

            }
        });


    }

//-----------------Inside oncreate---------------------------------------------------

 public void starthandler()
    {

        handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {


                if(!condition)
                {
                    //Do something after 100ms 


                }

            }
        }, 5000);

    }


    public void stophandler()
    {
        condition=true;
    }

How can I decrease the size of Ratingbar?

Working Example

             <RatingBar
                style="@style/RatingBar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:numStars="5"
                android:rating="3.5"
                android:stepSize="0.5" />

and add this in your styles xml file

<style name="RatingBar"   
parent="android:style/Widget.Material.RatingBar.Small">
<item name="colorControlNormal">@color/primary_light</item>
<item name="colorControlActivated">@color/primary_dark</item>
</style>

This way you dont need to customise ratingBar.

How to use 'cp' command to exclude a specific directory?

This is a modification of Linus Kleen's answer. His answer didn't work for me because there would be a . added in front of the file path which cp doesn't like (the path would look like source/.destination/file).

This command worked for me:

find . -type f -not -path '*/exlude-path/*' -exec cp --parents '{}' '/destination/' \;

the --parents command preserves the directory structure.

How can I get name of element with jQuery?

Play around with this jsFiddle example:

HTML:

<p id="foo" name="bar">Hello, world!</p>

jQuery:

$(function() {
    var name = $('#foo').attr('name');

    alert(name);
    console.log(name);
});

This uses jQuery's .attr() method to get value for the first element in the matched set.

While not specifically jQuery, the result is shown as an alert prompt and written to the browser's console.

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Place your script inside the body tag

<body>
  // Rest of html
  <script>
  function hideButton() {
    $(".loading").hide();
  }
function showButton() {
  $(".loading").show();
}
</script> 
< /body>

If you check this JSFIDDLE and click on javascript, you will see the load Type body is selected

Unit testing with Spring Security

You are quite right to be concerned - static method calls are particularly problematic for unit testing as you cannot easily mock your dependencies. What I am going to show you is how to let the Spring IoC container do the dirty work for you, leaving you with neat, testable code. SecurityContextHolder is a framework class and while it may be ok for your low-level security code to be tied to it, you probably want to expose a neater interface to your UI components (i.e. controllers).

cliff.meyers mentioned one way around it - create your own "principal" type and inject an instance into consumers. The Spring <aop:scoped-proxy/> tag introduced in 2.x combined with a request scope bean definition, and the factory-method support may be the ticket to the most readable code.

It could work like following:

public class MyUserDetails implements UserDetails {
    // this is your custom UserDetails implementation to serve as a principal
    // implement the Spring methods and add your own methods as appropriate
}

public class MyUserHolder {
    public static MyUserDetails getUserDetails() {
        Authentication a = SecurityContextHolder.getContext().getAuthentication();
        if (a == null) {
            return null;
        } else {
            return (MyUserDetails) a.getPrincipal();
        }
    }
}

public class MyUserAwareController {        
    MyUserDetails currentUser;

    public void setCurrentUser(MyUserDetails currentUser) { 
        this.currentUser = currentUser;
    }

    // controller code
}

Nothing complicated so far, right? In fact you probably had to do most of this already. Next, in your bean context define a request-scoped bean to hold the principal:

<bean id="userDetails" class="MyUserHolder" factory-method="getUserDetails" scope="request">
    <aop:scoped-proxy/>
</bean>

<bean id="controller" class="MyUserAwareController">
    <property name="currentUser" ref="userDetails"/>
    <!-- other props -->
</bean>

Thanks to the magic of the aop:scoped-proxy tag, the static method getUserDetails will be called every time a new HTTP request comes in and any references to the currentUser property will be resolved correctly. Now unit testing becomes trivial:

protected void setUp() {
    // existing init code

    MyUserDetails user = new MyUserDetails();
    // set up user as you wish
    controller.setCurrentUser(user);
}

Hope this helps!

fork() and wait() with two child processes

brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)

#include <sys/types.h>

How to check if a textbox is empty using javascript

Canonical without using frameworks with added trim prototype for older browsers

<html>
<head>
<script type="text/javascript">
// add trim to older IEs
if (!String.trim) {
  String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g, "");};
}

window.onload=function() { // onobtrusively adding the submit handler
  document.getElementById("form1").onsubmit=function() { // needs an ID
    var val = this.textField1.value; // 'this' is the form 
    if (val==null || val.trim()=="") { 
      alert('Please enter something');
      this.textField1.focus();
      return false; // cancel submission
    }
    return true; // allow submit
  }
}
</script>
</head>
<body>
<form id="form1">
  <input type="text" name="textField1" value="" /><br/>
  <input type="submit" />
</form>
</body>
</html>

Here is the inline version, although not recommended I show it here in case you need to add validation without being able to refactor the code

function validate(theForm) { // passing the form object
  var val = theForm.textField1.value;
  if (val==null || val.trim()=="") { 
    alert('Please enter something');
    theForm.textField1.focus();
    return false; // cancel submission
  }
  return true; // allow submit
}

passing the form object in (this)

<form onsubmit="return validate(this)">
  <input type="text" name="textField1" value="" /><br/>
  <input type="submit" />
</form>

psql: FATAL: database "<user>" does not exist

Login using default template1 database:

#psql -d template1
#template1=# \l

  List of databases
   Name    |  Owner  | Encoding |   Collate   |    Ctype    |  Access privileges  
-----------+---------+----------+-------------+-------------+---------------------
 postgres  | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0 | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/gogasca         +
           |         |          |             |             | gogasca=CTc/gogasca
 template1 | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/gogasca         +
           |         |          |             |             | gogasca=CTc/gogasca
(3 rows)

Create a database with your userId:

template1=# CREATE DATABASE gogasca WITH OWNER gogasca ENCODING 'UTF8';
CREATE DATABASE

Quit and then login again

template1=# \q
gonzo:~ gogasca$ psql -h localhost
psql (9.4.0)
Type "help" for help.

gogasca=# \l
                                List of databases
   Name    |  Owner  | Encoding |   Collate   |    Ctype    |  Access privileges  
-----------+---------+----------+-------------+-------------+---------------------
 gogasca   | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 postgres  | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0 | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/gogasca         +
           |         |          |             |             | gogasca=CTc/gogasca
 template1 | gogasca | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/gogasca         +
           |         |          |             |             | gogasca=CTc/gogasca
(4 rows)

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

_x000D_
_x000D_
<script type="text/javascript">_x000D_
      jQuery(function($){_x000D_
        $('#map-country').cssMap({'size' : 810});_x000D_
       });_x000D_
    </script>
_x000D_
_x000D_
_x000D_

strong text

How do I check if a C++ string is an int?

Ok, the way I see it you have 3 options.

1: If you simply wish to check whether the number is an integer, and don't care about converting it, but simply wish to keep it as a string and don't care about potential overflows, checking whether it matches a regex for an integer would be ideal here.

2: You can use boost::lexical_cast and then catch a potential boost::bad_lexical_cast exception to see if the conversion failed. This would work well if you can use boost and if failing the conversion is an exceptional condition.

3: Roll your own function similar to lexical_cast that checks the conversion and returns true/false depending on whether it's successful or not. This would work in case 1 & 2 doesn't fit your requirements.

Iterating through map in template

Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:

{{ range $key, $value := . }}
   <li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}

Execution sequence of Group By, Having and Where clause in SQL Server?

Here is the complete sequence for sql server :

1.  FROM
2.  ON
3.  JOIN
4.  WHERE
5.  GROUP BY
6.  WITH CUBE or WITH ROLLUP
7.  HAVING
8.  SELECT
9.  DISTINCT
10. ORDER BY
11. TOP

So from the above list, you can easily understand the execution sequence of GROUP BY, HAVING and WHERE which is :

1.  WHERE
2.  GROUP BY
3.  HAVING

Get more information about it from Microsoft

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

For any array of length n, elements of the array will have an index from 0 to n-1.

If your program is trying to access any element (or memory) having array index greater than n-1, then Java will throw ArrayIndexOutOfBoundsException

So here are two solutions that we can use in a program

  1. Maintaining count:

    for(int count = 0; count < array.length; count++) {
        System.out.println(array[count]);
    }
    

    Or some other looping statement like

    int count = 0;
    while(count < array.length) {
        System.out.println(array[count]);
        count++;
    }
    
  2. A better way go with a for each loop, in this method a programmer has no need to bother about the number of elements in the array.

    for(String str : array) {
        System.out.println(str);
    }
    

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

you can use the keyword 'In' and pass the List argument. e.g : findByInventoryIdIn

 List<AttributeHistory> findByValueIn(List<String> values);

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

Use

export LD_LIBRARY_PATH="/path/to/library/"

in your .bashrc otherwise, it'll only be available to bash and not any programs you start.

Try -R/path/to/library/ flag when you're linking, it'll make the program look in that directory and you won't need to set any environment variables.

EDIT: Looks like -R is Solaris only, and you're on Linux.

An alternate way would be to add the path to /etc/ld.so.conf and run ldconfig. Note that this is a global change that will apply to all dynamically linked binaries.

How to get a substring of text?

If you want a string, then the other answers are fine, but if what you're looking for is the first few letters as characters you can access them as a list:

your_text.chars.take(30)

Crontab Day of the Week syntax

You can also use day names like Mon for Monday, Tue for Tuesday, etc. It's more human friendly.

Converting from signed char to unsigned char and back again?

There are two ways to interpret the input data; either -128 is the lowest value, and 127 is the highest (i.e. true signed data), or 0 is the lowest value, 127 is somewhere in the middle, and the next "higher" number is -128, with -1 being the "highest" value (that is, the most significant bit already got misinterpreted as a sign bit in a two's complement notation.

Assuming you mean the latter, the formally correct way is

signed char in = ...
unsigned char out = (in < 0)?(in + 256):in;

which at least gcc properly recognizes as a no-op.

Basic authentication with fetch?

If you have a backend server asking for the Basic Auth credentials before the app then this is sufficient, it will re-use that then:

fetch(url, {
  credentials: 'include',
}).then(...);

Java List.add() UnsupportedOperationException

You must initialize your List seeAlso :

List<String> seeAlso = new Vector<String>();

or

List<String> seeAlso = new ArrayList<String>();

Inserting the same value multiple times when formatting a string

>>> s1 ='arbit'
>>> s2 = 'hello world '.join( [s]*3 )
>>> print s2
arbit hello world arbit hello world arbit

How to import module when module name has a '-' dash or hyphen in it?

Starting from Python 3.1, you can use importlib :

import importlib  
foobar = importlib.import_module("foo-bar")

( https://docs.python.org/3/library/importlib.html )

ORA-12560: TNS:protocol adaptor error

from command console, if you get this error you can avoid it by typing

c:\> sqlplus /nolog

then you can connect

SQL> conn user/pass @host:port/service

Force a screen update in Excel VBA

This worked for me:

ActiveWindow.SmallScroll down:=0

or more simply:

ActiveWindow.SmallScroll 0

What size do you use for varchar(MAX) in your parameter declaration?

For those of us who did not see -1 by Michal Chaniewski, the complete line of code:

cmd.Parameters.Add("@blah",SqlDbType.VarChar,-1).Value = "some large text";

How to update npm

Tried the options above on Ubuntu 14.04, but they would constantly produce this error:

npm ERR! tar pack Error reading /root/tmp/npm-15864/1465947804069-0.4854120113886893/package

Then found this solution online:

1) Clean the cache of npm first:

sudo npm cache clean -f

2) Install n module of npm:

sudo npm install -g n

3) Begin the installation by selecting the version of node to install: stable or latest, we will use stable here:

sudo n stable

4) Check the version of node:

node -v

5) Check the version of npm:

npm -v

Python unittest passing arguments

Unit testing is meant for testing the very basic functionality (the lowest level functions of the application) to be sure that your application building blocks work correctly. There is probably no formal definition of what does that exactly mean, but you should consider other kinds of testing for the bigger functionality -- see Integration testing. The unit testing framework may not be ideal for the purpose.

Linux c++ error: undefined reference to 'dlopen'

@Masci is correct, but in case you're using C (and the gcc compiler) take in account that this doesn't work:

gcc -ldl dlopentest.c

But this does:

gcc dlopentest.c -ldl

Took me a bit to figure out...

Align labels in form next to input

You can also try using flex-box

<head><style>
body {
    color:white;
    font-family:arial;
    font-size:1.2em;
}
form {
    margin:0 auto;
    padding:20px;
    background:#444;
}
.input-group {
    margin-top:10px;
    width:60%;
    display:flex;
    justify-content:space-between;
    flex-wrap:wrap;
}
label, input {
    flex-basis:100px;
}
</style></head>
<body>

<form>
    <div class="wrapper">
        <div class="input-group">
            <label for="user_name">name:</label>
            <input type="text" id="user_name">
        </div>
        <div class="input-group">
            <label for="user_pass">Password:</label>
            <input type="password" id="user_pass">
        </div>
    </div>
</form>

</body>
</html>

extract column value based on another column pandas dataframe

It's easier for me to think in these terms, but borrowing from other answers. The value you want is located in the series:

df[*column*][*row*]

where column and row point to the value you want returned. For your example, column is 'A' and for row you use a mask:

df['B'] == 3

To get the value from the series there are several options:

df['A'][df['B'] == 3].values[0]
df['A'][df['B'] == 3].iloc[0]
df['A'][df['B'] == 3].to_numpy()[0]

Add numpy array as column to Pandas data frame

You can add and retrieve a numpy array from dataframe using this:

import numpy as np
import pandas as pd

df = pd.DataFrame({'b':range(10)}) # target dataframe
a = np.random.normal(size=(10,2)) # numpy array
df['a']=a.tolist() # save array
np.array(df['a'].tolist()) # retrieve array

This builds on the previous answer that confused me because of the sparse part and this works well for a non-sparse numpy arrray.

Proper way to exit command line program?

Take a look at Job Control on UNIX systems

If you don't have control of your shell, simply hitting ctrl + C should stop the process. If that doesn't work, you can try ctrl + Z and using the jobs and kill -9 %<job #> to kill it. The '-9' is a type of signal. You can man kill to see a list of signals.

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

I had similar issue and the below line helped me solving the issue.Thanks to rene. I just pasted this line above the authentication code and it worked

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

How to find the array index with a value?

For objects array use map with indexOf:

_x000D_
_x000D_
var imageList = [_x000D_
   {value: 100},_x000D_
   {value: 200},_x000D_
   {value: 300},_x000D_
   {value: 400},_x000D_
   {value: 500}_x000D_
];_x000D_
_x000D_
var index = imageList.map(function (img) { return img.value; }).indexOf(200);_x000D_
_x000D_
console.log(index);
_x000D_
_x000D_
_x000D_


In modern browsers you can use findIndex:

_x000D_
_x000D_
var imageList = [_x000D_
   {value: 100},_x000D_
   {value: 200},_x000D_
   {value: 300},_x000D_
   {value: 400},_x000D_
   {value: 500}_x000D_
];_x000D_
_x000D_
var index = imageList.findIndex(img => img.value === 200);_x000D_
_x000D_
console.log(index);
_x000D_
_x000D_
_x000D_

Its part of ES6 and supported by Chrome, FF, Safari and Edge

Simple mediaplayer play mp3 from file path?

String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();   
mediaPlayer.start()

and this play from raw folder.

int resID = myContext.getResources().getIdentifier(playSoundName,"raw",myContext.getPackageName());

            MediaPlayer mediaPlayer = MediaPlayer.create(myContext,resID);
            mediaPlayer.prepare();
            mediaPlayer.start();

mycontext=application.this. use.

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

Custom alert and confirm box in jquery

jQuery UI has it's own elements, but jQuery alone hasn't.

http://jqueryui.com/dialog/

Working example:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Dialog - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script>
  $(function() {
    $( "#dialog" ).dialog();
  });
  </script>
</head>
<body>

<div id="dialog" title="Basic dialog">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>


</body>
</html>

How do you pass a function as a parameter in C?

This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.

typedef void (*functiontype)();

Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:

void dosomething() { }

functiontype func = &dosomething;
func();

For a function that returns an int and takes a char you would do

typedef int (*functiontype2)(char);

and to use it

int dosomethingwithchar(char a) { return 1; }

functiontype2 func2 = &dosomethingwithchar
int result = func2('a');

There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!

boost::function<int (char a)> functiontype2;

is so much nicer than the above.

Regular Expression for matching parentheses

Because ( is special in regex, you should escape it \( when matching. However, depending on what language you are using, you can easily match ( with string methods like index() or other methods that enable you to find at what position the ( is in. Sometimes, there's no need to use regex.

Xcode 7.2 no matching provisioning profiles found

I updated to Xcode v7.3.1 and it solved the issue.

Difference between onCreate() and onStart()?

onCreate() method gets called when activity gets created, and its called only once in whole Activity life cycle. where as onStart() is called when activity is stopped... I mean it has gone to background and its onStop() method is called by the os. onStart() may be called multiple times in Activity life cycle.More details here

How to prevent favicon.ico requests?

You can't. All you can do is to make that image as small as possible and set some cache invalidation headers (Expires, Cache-Control) far in the future. Here's what Yahoo! has to say about favicon.ico requests.

Why is vertical-align:text-top; not working in CSS

The all above not work for me, I have just checked this and its work :

vertical-align: super;

 <div id="lbk_mng_rdooption" style="float: left;">
     <span class="bold" style="vertical-align: super;">View:</span>
 </div>

I know by padding or margin will work, but that is last choise I prefer.

SQL: How to perform string does not equal

The strcomp function may be appropriate here (returns 0 when strings are identical):

 SELECT * from table WHERE Strcmp(user, testername) <> 0;

iOS: Multi-line UILabel in Auto Layout

I find you need the following:

  • A top constraint
  • A leading constraint (eg left side)
  • A trailing constraint (eg right side)
  • Set content hugging priority, horizontal to low, so it'll fill the given space if the text is short.
  • Set content compression resistance, horizontal to low, so it'll wrap instead of try to become wider.
  • Set the number of lines to 0.
  • Set the line break mode to word wrap.

Maven Run Project

1. Edit POM.xml

Add the following property in pom.xml. Make sure you use the fully qualified class name (i.e. with package name) which contains the main method:

<properties>
        <exec.mainClass>fully-qualified-class-name</exec.mainClass>
</properties>

2. Run Command

Now from the terminal, trigger the following command:

mvn clean compile exec:java

NOTE You can pass further arguments via -Dexec.args="xxx" flag.

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

I found that my version of Xcode was too outdated and installing command-line-tools wasn't helping. Here's what I did:

  • I completely uninstalled the outdated XCode
  • I reinstalled the most recent XCode from the app store
  • That was all. Git was restored.

Safe width in pixels for printing web pages?

A printer doesn't understand pixels, it understand dots (pt in CSS). The best solution is to write an extra CSS for printing, with all of its measures in dots.

Then, in your HTML code, in head section, put:

<link href="style.css" rel="stylesheet" type="text/css" media="screen">
<link href="style_print.css" rel="stylesheet" type="text/css" media="print">

Remove Array Value By index in jquery

Use the splice method.

ArrayName.splice(indexValueOfArray,1);

This removes 1 item from the array starting at indexValueOfArray.

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

I had a git conflict left in my workspace.xml i.e.

<<<<———————HEAD

which caused the unknown tag error. It is a bit annoying that it doesn’t name the file.

angularjs: ng-src equivalent for background-image:url(...)

ngSrc is a native directive, so it seems you want a similar directive that modifies your div's background-image style.

You could write your own directive that does exactly what you want. For example

app.directive('backImg', function(){
    return function(scope, element, attrs){
        var url = attrs.backImg;
        element.css({
            'background-image': 'url(' + url +')',
            'background-size' : 'cover'
        });
    };
});?

Which you would invoke like this

<div back-img="<some-image-url>" ></div>

JSFiddle with cute cats as a bonus: http://jsfiddle.net/jaimem/aSjwk/1/

SQL Server: SELECT only the rows with MAX(DATE)

This works for me. use MAX(CONVERT(date, ReportDate)) to make sure you have date value

select max( CONVERT(date, ReportDate)) FROM [TraxHistory]