Programs & Examples On #Seq

How do I generate a list with a specified increment step?

You can use scalar multiplication to modify each element in your vector.

> r <- 0:10 
> r <- r * 2
> r 
 [1]  0  2  4  6  8 10 12 14 16 18 20

or

> r <- 0:10 * 2 
> r 
 [1]  0  2  4  6  8 10 12 14 16 18 20

Difference between a Seq and a List in Scala

As @daniel-c-sobral said, List extends the trait Seq and is an abstract class implemented by scala.collection.immutable.$colon$colon (or :: for short), but technicalities aside, mind that most of lists and seqs we use are initialized in the form of Seq(1, 2, 3) or List(1, 2, 3) which both return scala.collection.immutable.$colon$colon, hence one can write:

var x: scala.collection.immutable.$colon$colon[Int] = null
x = Seq(1, 2, 3).asInstanceOf[scala.collection.immutable.$colon$colon[Int]]
x = List(1, 2, 3).asInstanceOf[scala.collection.immutable.$colon$colon[Int]]

As a result, I'd argue than the only thing that matters are the methods you want to expose, for instance to prepend you can use :: from List that I find redundant with +: from Seq and I personally stick to Seq by default.

Create sequence of repeated values, in sequence?

For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.

# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
         x .groups
     <dbl> <fct>  
 1  0.891  1      
 2 -1.13   1      
 3 -0.500  1      
 4 -1.12   1      
 5 -0.0187 1      
 6  0.420  2      
 7 -0.449  2      
 8  0.365  2      
 9  0.526  2      
10  0.466  2      
# … with 17 more rows

There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z") the grouping factor would be c(1,1,2,3,3).

How to select the rows with maximum values in each group with dplyr?

More generally, I think you might want to get "top" of the rows that are sorted within a given group.

For the case of where a single value is max'd out, you have essentially sorted by only one column. However, it's often useful to hierarchically sort by multiple columns (for example: a date column and a time-of-day column).

# Answering the question of getting row with max "value".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in descending order by "value" column.
  arrange( desc(value) ) %>% 
  # Pick the top 1 value
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

# Answering an extension of the question of 
# getting row with the max value of the lowest "C".
df %>% 
  # Within each grouping of A and B values.
  group_by( A, B) %>% 
  # Sort rows in ascending order by C, and then within that by 
  # descending order by "value" column.
  arrange( C, desc(value) ) %>% 
  # Pick the one top row based on the sort
  slice(1) %>% 
  # Remember to ungroup in case you want to do further work without grouping.
  ungroup()

Converting Numpy Array to OpenCV Array

The simplest solution would be to use Pillow lib:

from PIL import Image

image = Image.fromarray(<your_numpy_array>.astype(np.uint8))

And you can use it as an image.

jQuery.ajax handling continue responses: "success:" vs ".done"?

success has been the traditional name of the success callback in jQuery, defined as an option in the ajax call. However, since the implementation of $.Deferreds and more sophisticated callbacks, done is the preferred way to implement success callbacks, as it can be called on any deferred.

For example, success:

$.ajax({
  url: '/',
  success: function(data) {}
});

For example, done:

$.ajax({url: '/'}).done(function(data) {});

The nice thing about done is that the return value of $.ajax is now a deferred promise that can be bound to anywhere else in your application. So let's say you want to make this ajax call from a few different places. Rather than passing in your success function as an option to the function that makes this ajax call, you can just have the function return $.ajax itself and bind your callbacks with done, fail, then, or whatever. Note that always is a callback that will run whether the request succeeds or fails. done will only be triggered on success.

For example:

function xhr_get(url) {

  return $.ajax({
    url: url,
    type: 'get',
    dataType: 'json',
    beforeSend: showLoadingImgFn
  })
  .always(function() {
    // remove loading image maybe
  })
  .fail(function() {
    // handle request failures
  });

}

xhr_get('/index').done(function(data) {
  // do stuff with index data
});

xhr_get('/id').done(function(data) {
  // do stuff with id data
});

An important benefit of this in terms of maintainability is that you've wrapped your ajax mechanism in an application-specific function. If you decide you need your $.ajax call to operate differently in the future, or you use a different ajax method, or you move away from jQuery, you only have to change the xhr_get definition (being sure to return a promise or at least a done method, in the case of the example above). All the other references throughout the app can remain the same.

There are many more (much cooler) things you can do with $.Deferred, one of which is to use pipe to trigger a failure on an error reported by the server, even when the $.ajax request itself succeeds. For example:

function xhr_get(url) {

  return $.ajax({
    url: url,
    type: 'get',
    dataType: 'json'
  })
  .pipe(function(data) {
    return data.responseCode != 200 ?
      $.Deferred().reject( data ) :
      data;
  })
  .fail(function(data) {
    if ( data.responseCode )
      console.log( data.responseCode );
  });
}

xhr_get('/index').done(function(data) {
  // will not run if json returned from ajax has responseCode other than 200
});

Read more about $.Deferred here: http://api.jquery.com/category/deferred-object/

NOTE: As of jQuery 1.8, pipe has been deprecated in favor of using then in exactly the same way.

How to set environment variable for everyone under my linux system?

Some interesting excerpts from the bash manpage:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
...
When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of /etc/bash.bashrc and ~/.bashrc.

So have a look at /etc/profile or /etc/bash.bashrc, these files are the right places for global settings. Put something like this in them to set up an environement variable:

export MY_VAR=xxx

What's the simplest way to list conflicted files in Git?

Here is a fool-proof way:

grep -H -r "<<<<<<< HEAD" /path/to/project/dir

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

You can do the folllwoing: import the jar file inside you class:

import javax.servlet.http.HttpServletResponse

add the Apache Tomcat library as follow:

Project > Properties > Java Build Path > Libraries > Add library from library tab > Choose server runtime > Next > choose Apache Tomcat v 6.0 > Finish > Ok

Also First of all, make sure that Servlet jar is included in your class path in eclipse as PermGenError said.

I think this will solve your error

How to get rid of punctuation using NLTK tokenizer?

Remove punctuaion(It will remove . as well as part of punctuation handling using below code)

        tbl = dict.fromkeys(i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith('P'))
        text_string = text_string.translate(tbl) #text_string don't have punctuation
        w = word_tokenize(text_string)  #now tokenize the string 

Sample Input/Output:

direct flat in oberoi esquire. 3 bhk 2195 saleable 1330 carpet. rate of 14500 final plus 1% floor rise. tax approx 9% only. flat cost with parking 3.89 cr plus taxes plus possession charger. middle floor. north door. arey and oberoi woods facing. 53% paymemt due. 1% transfer charge with buyer. total cost around 4.20 cr approx plus possession charges. rahul soni

['direct', 'flat', 'oberoi', 'esquire', '3', 'bhk', '2195', 'saleable', '1330', 'carpet', 'rate', '14500', 'final', 'plus', '1', 'floor', 'rise', 'tax', 'approx', '9', 'flat', 'cost', 'parking', '389', 'cr', 'plus', 'taxes', 'plus', 'possession', 'charger', 'middle', 'floor', 'north', 'door', 'arey', 'oberoi', 'woods', 'facing', '53', 'paymemt', 'due', '1', 'transfer', 'charge', 'buyer', 'total', 'cost', 'around', '420', 'cr', 'approx', 'plus', 'possession', 'charges', 'rahul', 'soni']

php & mysql query not echoing in html with tags?

<td class="first"> <?php echo $proxy ?> </td> is inside a literal string that you are echoing. End the string, or concatenate it correctly:

<td class="first">' . $proxy . '</td>

Override intranet compatibility mode IE8

Try this metatag:

<meta http-equiv="X-UA-Compatible" content="IE=8" />

It should force IE8 to render as IE8 Standard Mode even if "Display intranet sites in compatibility view" is checked [either for intranet or all websites],I tried it my self on IE 8.0.6

What's the difference between ViewData and ViewBag?

ViewData
  1. ViewData is used to pass data from controller to view
  2. It is derived from ViewDataDictionary class
  3. It is available for the current request only
  4. Requires typecasting for complex data type and checks for null values to avoid error
  5. If redirection occurs, then its value becomes null
ViewBag
  1. ViewBag is also used to pass data from the controller to the respective view
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
  3. It is also available for the current request only
  4. If redirection occurs, then its value becomes null
  5. Doesn’t require typecasting for complex data type

What is Inversion of Control?

  1. Wikipedia Article. To me, inversion of control is turning your sequentially written code and turning it into an delegation structure. Instead of your program explicitly controlling everything, your program sets up a class or library with certain functions to be called when certain things happen.

  2. It solves code duplication. For example, in the old days you would manually write your own event loop, polling the system libraries for new events. Nowadays, most modern APIs you simply tell the system libraries what events you're interested in, and it will let you know when they happen.

  3. Inversion of control is a practical way to reduce code duplication, and if you find yourself copying an entire method and only changing a small piece of the code, you can consider tackling it with inversion of control. Inversion of control is made easy in many languages through the concept of delegates, interfaces, or even raw function pointers.

    It is not appropriate to use in all cases, because the flow of a program can be harder to follow when written this way. It's a useful way to design methods when writing a library that will be reused, but it should be used sparingly in the core of your own program unless it really solves a code duplication problem.

Excel VBA - Range.Copy transpose paste

WorksheetFunction Transpose()

Instead of copying, pasting via PasteSpecial, and using the Transpose option you can simply type a formula

    =TRANSPOSE(Sheet1!A1:A5)

or if you prefer VBA:

    Dim v
    v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
    Sheet2.Range("A1").Resize(1, UBound(v)) = v

Note: alternatively you could use late-bound Application.Transpose instead.

MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.

Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365

Listview Scroll to the end of the list after updating the list

You need to use these parameters in your list view:

  • Scroll lv.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);

  • Set the head of the list to it bottom lv.setStackFromBottom(true);

You can also set these parameters in XML, eg. like this:

<ListView
   ...
   android:transcriptMode="alwaysScroll"
   android:stackFromBottom="true" />

Get the first element of each tuple in a list in Python

Use a list comprehension:

res_list = [x[0] for x in rows]

Below is a demonstration:

>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> [x[0] for x in rows]
[1, 3, 5]
>>>

Alternately, you could use unpacking instead of x[0]:

res_list = [x for x,_ in rows]

Below is a demonstration:

>>> lst = [(1, 2), (3, 4), (5, 6)]
>>> [x for x,_ in lst]
[1, 3, 5]
>>>

Both methods practically do the same thing, so you can choose whichever you like.

How to make picturebox transparent?

Try using an ImageList

ImageList imgList = new ImageList;

imgList.TransparentColor = Color.White;

Load the image like this:

picturebox.Image = imgList.Images[img_index];

jQuery won't parse my JSON from AJAX query

If returning an array works and returning a single object doesn't, you might also try returning your single object as an array containing that single object:

[ { title: "One", key: "1" } ]

that way you are returning a consistent data structure, an array of objects, no matter the data payload.

i see that you've tried wrapping your single object in "parenthesis", and suggest this with example because of course JavaScript treats [ .. ] differently than ( .. )

Fitting polynomial model to data in R

Regarding the question 'can R help me find the best fitting model', there is probably a function to do this, assuming you can state the set of models to test, but this would be a good first approach for the set of n-1 degree polynomials:

polyfit <- function(i) x <- AIC(lm(y~poly(x,i)))
as.integer(optimize(polyfit,interval = c(1,length(x)-1))$minimum)

Notes

  • The validity of this approach will depend on your objectives, the assumptions of optimize() and AIC() and if AIC is the criterion that you want to use,

  • polyfit() may not have a single minimum. check this with something like:

    for (i in 2:length(x)-1) print(polyfit(i))
    
  • I used the as.integer() function because it is not clear to me how I would interpret a non-integer polynomial.

  • for testing an arbitrary set of mathematical equations, consider the 'Eureqa' program reviewed by Andrew Gelman here

Update

Also see the stepAIC function (in the MASS package) to automate model selection.

Eclipse error: 'Failed to create the Java Virtual Machine'

I remove -XX:+UseStringDeduplication from eclipse.ini . If you run eclipsec.exe you get better descryiption .

Eclipse C++: Symbol 'std' could not be resolved

What allowed me to fix the problem was going to: Project -> Properties -> C/C++ General -> Preprocessor Include Paths, Macros, etc. -> Providers -> CDT GCC built-in compiler settings, enabling that and disabling the CDT Cross GCC Built-in Compiler Settings

Fastest way to update 120 Million records

Sounds like an indexing problem, like Pabla Santa Cruz mentioned. Since your update is not conditional, you can DROP the column and RE-ADD it with a DEFAULT value.

Running a shell script through Cygwin on Windows

Sure. On my (pretty vanilla) Cygwin setup, bash is in c:\cygwin\bin so I can run a bash script (say testit.sh) from a Windows batch file using a command like:

C:\cygwin\bin\bash testit.sh

... which can be included in a .bat file as easily as it can be typed at the command line, and with the same effect.

How can I create a Java method that accepts a variable number of arguments?

You could write a convenience method:

public PrintStream print(String format, Object... arguments) {
    return System.out.format(format, arguments);
}

But as you can see, you've simply just renamed format (or printf).

Here's how you could use it:

private void printScores(Player... players) {
    for (int i = 0; i < players.length; ++i) {
        Player player = players[i];
        String name   = player.getName();
        int    score  = player.getScore();
        // Print name and score followed by a newline
        System.out.format("%s: %d%n", name, score);
    }
}

// Print a single player, 3 players, and all players
printScores(player1);
System.out.println();
printScores(player2, player3, player4);
System.out.println();
printScores(playersArray);

// Output
Abe: 11

Bob: 22
Cal: 33
Dan: 44

Abe: 11
Bob: 22
Cal: 33
Dan: 44

Note there's also the similar System.out.printf method that behaves the same way, but if you peek at the implementation, printf just calls format, so you might as well use format directly.

Better way to revert to a previous SVN revision of a file?

What you're looking for is called a "reverse merge". You should consult the docs regarding the merge function in the SVN book (as luapyad, or more precisely the first commenter on that post, points out). If you're using Tortoise, you can also just go into the log view and right-click and choose "revert changes from this revision" on the one where you made the mistake.

To show error message without alert box in Java Script

web masters or web programmers, please insert

<!DOCTYPE html>

at the start of your page. Second you should enclose your attributes with quotes like

type="text" id="fname"

input element should not contain end element, just close it like:

 />

input element dont have innerHTML, it has value sor your javascript line should be:

document.getElementById("fname").value = "this is invalid name";

Please write in organized way and make sure it is convenient to standards.

ORA-01652 Unable to extend temp segment by in tablespace

You don't need to create a new datafile; you can extend your existing tablespace data files.

Execute the following to determine the filename for the existing tablespace:

  SELECT * FROM DBA_DATA_FILES;

Then extend the size of the datafile as follows (replace the filename with the one from the previous query):

  ALTER DATABASE DATAFILE 'D:\ORACLEXE\ORADATA\XE\SYSTEM.DBF' RESIZE 2048M; 

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

This error can occur when an application makes a new connection for every database interaction or the connections are not closed properly. One of the free tools to monitor and confirm this is Oracle Sql developer (although this is not the only tool you can use to monitor DB sessions).

you can download the tool from oracle site Sql Developer

here is a screenshot of how to monitor you sessions. (if you see many sessions piling up for your application user during when you see the ORA-12514 error then it's a good indication that you may have connection pool problem).

enter image description here

how do I change text in a label with swift?

use a simple formula: WHO.WHAT = VALUE

where,

WHO is the element in the storyboard you want to make changes to for eg. label

WHAT is the property of that element you wish to change for eg. text

VALUE is the change that you wish to be displayed

for eg. if I want to change the text from story text to You see a fork in the road in the label as shown in screenshot 1

In this case, our WHO is the label (element in the storyboard), WHAT is the text (property of element) and VALUE will be You see a fork in the road

so our final code will be as follows: Final code

screenshot 1 changes to screenshot 2 once the above code is executed.

I hope this solution helps you solve your issue. Thank you!

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

Use latest version of Internet Explorer in the webbrowser control

just adding the following to your html does the trick no need for registry settigns

<meta http-equiv="X-UA-Compatible" content="IE=11" >

How can I bind to the change event of a textarea in jQuery?

.delegate is the only one that is working to me with jQuery JavaScript Library v2.1.1

 $(document).delegate('#textareaID','change', function() {
          console.log("change!");
    });

jQuery plugin returning "Cannot read property of undefined"

Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.

Sometimes a prototype in some place add an extra element.

How to get Domain name from URL using jquery..?

Try like this.

var hostname = window.location.origin

If the URL is "http://example.com/path" then you will get  "http://example.com" as the result.

This won't work for local domains

When you have URL like "https://localhost/MyProposal/MyDir/MyTestPage.aspx" 
and your virtual directory path is "https://localhost/MyProposal/" 
In such cases, you will get "https://localhost".

Axios get access to response header fields

In case of CORS requests, browsers can only access the following response headers by default:

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

If you would like your client app to be able to access other headers, you need to set the Access-Control-Expose-Headers header on the server:

Access-Control-Expose-Headers: Access-Token, Uid

I need to convert an int variable to double

I think you should casting variable or use Integer class by call out method doubleValue().

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

change your @csrf in welcome.blade.php to <input type="hidden" name="_token" value="{{ csrf_token() }}">

so your code like this:

<form method="POST" action="/foo" >
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="text" name="name"/><br/>
    <input type="submit" value="Add"/>

   <button type="submit">Submit</button>
</form>

How to remove specific object from ArrayList in Java?

You can use Collections.binarySearch to find the element, then call remove on the returned index.

See the documentation for Collections.binarySearch here: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#binarySearch%28java.util.List,%20java.lang.Object%29

This would require the ArrayTest object to have .equals implemented though. You would also need to call Collections.sort to sort the list. Finally, ArrayTest would have to implement the Comparable interface, so that binarySearch would run correctly.

This is the "proper" way to do it in Java. If you are just looking to solve the problem in a quick and dirty fashion, then you can just iterate over the elements and remove the one with the attribute you are looking for.

How to get last month/year in java?

java.time

Using java.time framework built into Java 8:

import java.time.LocalDate;

LocalDate now = LocalDate.now(); // 2015-11-24
LocalDate earlier = now.minusMonths(1); // 2015-10-24

earlier.getMonth(); // java.time.Month = OCTOBER
earlier.getMonth.getValue(); // 10
earlier.getYear(); // 2015

TypeError: unsupported operand type(s) for -: 'list' and 'list'

This question has been answered but I feel I should also mention another potential cause. This is a direct result of coming across the same error message but for different reasons. If your list/s are empty the operation will not be performed. check your code for indents and typos

How do I access my webcam in Python?

import cv2 as cv

capture = cv.VideoCapture(0)

while True:
    isTrue,frame = capture.read()
    cv.imshow('Video',frame)
    if cv.waitKey(20) & 0xFF==ord('d'):
        break

capture.release()
cv.destroyAllWindows()

0 <-- refers to the camera , replace it with file path to read a video file

cv.waitKey(20) & 0xFF==ord('d') <-- to destroy window when key is pressed

How to read and write excel file

You can not read & write same file in parallel(Read-write lock). But, we can do parallel operations on temporary data(i.e. Input/output stream). Write the data to file only after closing the input stream. Below steps should be followed.

  • Open the file to Input stream
  • Open the same file to an Output Stream
  • Read and do the processing
  • Write contents to output stream.
  • Close the read/input stream, close file
  • Close output stream, close file.

Apache POI - read/write same excel example

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class XLSXReaderWriter {

    public static void main(String[] args) {

        try {
            File excel = new File("D://raju.xlsx");
            FileInputStream fis = new FileInputStream(excel);
            XSSFWorkbook book = new XSSFWorkbook(fis);
            XSSFSheet sheet = book.getSheetAt(0);

            Iterator<Row> itr = sheet.iterator();

            // Iterating over Excel file in Java
            while (itr.hasNext()) {
                Row row = itr.next();

                // Iterating over each column of Excel file
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {

                    Cell cell = cellIterator.next();

                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        System.out.print(cell.getBooleanCellValue() + "\t");
                        break;
                    default:

                    }
                }
                System.out.println("");
            }

            // writing data into XLSX file
            Map<String, Object[]> newData = new HashMap<String, Object[]>();
            newData.put("1", new Object[] { 1d, "Raju", "75K", "dev",
                    "SGD" });
            newData.put("2", new Object[] { 2d, "Ramesh", "58K", "test",
                    "USD" });
            newData.put("3", new Object[] { 3d, "Ravi", "90K", "PMO",
                    "INR" });

            Set<String> newRows = newData.keySet();
            int rownum = sheet.getLastRowNum();

            for (String key : newRows) {
                Row row = sheet.createRow(rownum++);
                Object[] objArr = newData.get(key);
                int cellnum = 0;
                for (Object obj : objArr) {
                    Cell cell = row.createCell(cellnum++);
                    if (obj instanceof String) {
                        cell.setCellValue((String) obj);
                    } else if (obj instanceof Boolean) {
                        cell.setCellValue((Boolean) obj);
                    } else if (obj instanceof Date) {
                        cell.setCellValue((Date) obj);
                    } else if (obj instanceof Double) {
                        cell.setCellValue((Double) obj);
                    }
                }
            }

            // open an OutputStream to save written data into Excel file
            FileOutputStream os = new FileOutputStream(excel);
            book.write(os);
            System.out.println("Writing on Excel file Finished ...");

            // Close workbook, OutputStream and Excel file to prevent leak
            os.close();
            book.close();
            fis.close();

        } catch (FileNotFoundException fe) {
            fe.printStackTrace();
        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }
}

Public class is inaccessible due to its protection level

This error is a result of the protection level of ClassB's constructor, not ClassB itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal by default. Declaring the constructor public will fix this problem:

public ClassB() { } 

* One could also say that constructors have no name, only a type; this does not change the essence of the problem.

What does "Content-type: application/json; charset=utf-8" really mean?

The header just denotes what the content is encoded in. It is not necessarily possible to deduce the type of the content from the content itself, i.e. you can't necessarily just look at the content and know what to do with it. That's what HTTP headers are for, they tell the recipient what kind of content they're (supposedly) dealing with.

Content-type: application/json; charset=utf-8 designates the content to be in JSON format, encoded in the UTF-8 character encoding. Designating the encoding is somewhat redundant for JSON, since the default (only?) encoding for JSON is UTF-8. So in this case the receiving server apparently is happy knowing that it's dealing with JSON and assumes that the encoding is UTF-8 by default, that's why it works with or without the header.

Does this encoding limit the characters that can be in the message body?

No. You can send anything you want in the header and the body. But, if the two don't match, you may get wrong results. If you specify in the header that the content is UTF-8 encoded but you're actually sending Latin1 encoded content, the receiver may produce garbage data, trying to interpret Latin1 encoded data as UTF-8. If of course you specify that you're sending Latin1 encoded data and you're actually doing so, then yes, you're limited to the 256 characters you can encode in Latin1.

Regex that matches integers in between whitespace or start/end of string only

This solution matches integers:

  • Negative integers are matched (-1,-2,etc)
  • Single zeroes are matched (0)
  • Negative zeroes are not (-0, -01, -02)
  • Empty spaces are not matched ('')
/^(0|-*[1-9]+[0-9]*)$/

Generate .pem file used to set up Apple Push Notifications

Thanks! to all above answers. I hope you have a .p12 file. Now, open terminal write following command. Set terminal to the path where you have put .12 file.

$ openssl pkcs12 -in yourCertifcate.p12 -out pemAPNSCert.pem -nodes
Enter Import Password: <Just enter your certificate password>
MAC verified OK

Now your .pem file is generated.

Verify .pem file First, open the .pem in a text editor to view its content. The certificate content should be in format as shown below. Make sure the pem file contains both Certificate content(from BEGIN CERTIFICATE to END CERTIFICATE) as well as Certificate Private Key (from BEGIN PRIVATE KEY to END PRIVATE KEY) :

> Bag Attributes
>     friendlyName: Apple Push Services:<Bundle ID>
>     localKeyID: <> subject=<>
> -----BEGIN CERTIFICATE-----
> 
> <Certificate Content>
> 
> -----END CERTIFICATE----- Bag Attributes
>     friendlyName: <>
>     localKeyID: <> Key Attributes: <No Attributes>
> -----BEGIN PRIVATE KEY-----
> 
> <Certificate Private Key>
> 
> -----END PRIVATE KEY-----

Also, you check the validity of the certificate by going to SSLShopper Certificate Decoder and paste the Certificate Content (from BEGIN CERTIFICATE to END CERTIFICATE) to get all the info about the certificate as shown below:

enter image description here

How can I check if a View exists in a Database?

You can check the availability of the view in various ways

FOR SQL SERVER

use sys.objects

IF EXISTS(
   SELECT 1
   FROM   sys.objects
   WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
          AND Type_Desc = 'VIEW'
)
BEGIN
    PRINT 'View Exists'
END

use sysobjects

IF NOT EXISTS (
   SELECT 1
   FROM   sysobjects
   WHERE  NAME = '[schemaName].[ViewName]'
          AND xtype = 'V'
)
BEGIN
    PRINT 'View Exists'
END

use sys.views

IF EXISTS (
   SELECT 1
   FROM sys.views
   WHERE OBJECT_ID = OBJECT_ID(N'[schemaName].[ViewName]')
)
BEGIN
    PRINT 'View Exists'
END

use INFORMATION_SCHEMA.VIEWS

IF EXISTS (
   SELECT 1
   FROM   INFORMATION_SCHEMA.VIEWS
   WHERE  table_name = 'ViewName'
          AND table_schema = 'schemaName'
)
BEGIN
    PRINT 'View Exists'
END

use OBJECT_ID

IF EXISTS(
   SELECT OBJECT_ID('ViewName', 'V')
)
BEGIN
    PRINT 'View Exists'
END

use sys.sql_modules

IF EXISTS (
   SELECT 1
   FROM   sys.sql_modules
   WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
)
BEGIN
   PRINT 'View Exists'
END

Core dump file analysis

You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file to debug it.

When it starts up, you can use bt (for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number (replacing number with the corresponding number in the stack trace) to select a particular stack frame.

You can then use list to see code around that function, and info locals to see the local variables. You can also use print name_of_variable (replacing "name_of_variable" with a variable name) to see its value.

Typing help within GDB will give you a prompt that will let you see additional commands.

How does one output bold text in Bash?

This is an old post but regardless, you can also get boldface and italic characters by leveraging utf-32. There are even greek and math symbols that can be used as well as the roman alphabet.

The difference between sys.stdout.write and print?

My question is whether or not there are situations in which sys.stdout.write() is preferable to print

If you're writing a command line application that can write to both files and stdout then it is handy. You can do things like:

def myfunc(outfile=None):
    if outfile is None:
        out = sys.stdout
    else:
        out = open(outfile, 'w')
    try:
        # do some stuff
        out.write(mytext + '\n')
        # ...
    finally:
        if outfile is not None:
            out.close()

It does mean you can't use the with open(outfile, 'w') as out: pattern, but sometimes it is worth it.

How can I lock a file using java (if possible)

Use a RandomAccessFile, get it's channel, then call lock(). The channel provided by input or output streams does not have sufficient privileges to lock properly. Be sure to call unlock() in the finally block (closing the file doesn't necessarily release the lock).

What is the maximum float in Python?

sys.maxint is not the largest integer supported by python. It's the largest integer supported by python's regular integer type.

How to allow users to check for the latest app version from inside the app?

You can use this Android Library: https://github.com/danielemaddaluno/Android-Update-Checker. It aims to provide a reusable instrument to check asynchronously if exists any newer released update of your app on the Store. It is based on the use of Jsoup (http://jsoup.org/) to test if a new update really exists parsing the app page on the Google Play Store:

private boolean web_update(){
    try {       
        String curVersion = applicationContext.getPackageManager().getPackageInfo(package_name, 0).versionName; 
        String newVersion = curVersion;
        newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + package_name + "&hl=en")
                .timeout(30000)
                .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                .referrer("http://www.google.com")
                .get()
                .select("div[itemprop=softwareVersion]")
                .first()
                .ownText();
        return (value(curVersion) < value(newVersion)) ? true : false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

And as "value" function the following (works if values are beetween 0-99):

private long value(String string) {
    string = string.trim();
    if( string.contains( "." )){ 
        final int index = string.lastIndexOf( "." );
        return value( string.substring( 0, index ))* 100 + value( string.substring( index + 1 )); 
    }
    else {
        return Long.valueOf( string ); 
    }
}

If you want only to verify a mismatch beetween versions, you can change:

value(curVersion) < value(newVersion) with value(curVersion) != value(newVersion)

How do I register a .NET DLL file in the GAC?

Try GACView if you have a fear of command prompts.

You have not set the PATH properly in DOS.You need to point the path to where the gacutil resides to use it in DOS.

JComboBox Selection Change Listener?

It should respond to ActionListeners, like this:

combo.addActionListener (new ActionListener () {
    public void actionPerformed(ActionEvent e) {
        doSomething();
    }
});

@John Calsbeek rightly points out that addItemListener() will work, too. You may get 2 ItemEvents, though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types!

What is the difference between the HashMap and Map objects in Java?

Map is the Interface and Hashmap is the class that implements that.

So in this implementation you create the same objects

How to merge two files line by line in Bash

Try following.

pr -tmJ a.txt b.txt > c.txt

Why doesn't java.io.File have a close method?

Essentially random access file wraps input and output streams in order to manage the random access. You don't open and close a file, you open and close streams to a file.

Similarity String Comparison in Java

You can achieve this using the apache commons java library. Take a look at these two functions within it:
- getLevenshteinDistance
- getFuzzyDistance

Jquery If radio button is checked

$('input:radio[name="postage"]').change(function(){
    if($(this).val() === 'Yes'){
       // append stuff
    }
});

This will listen for a change event on the radio buttons. At the time the user clicks Yes, the event will fire and you will be able to append anything you like to the DOM.

How to view table contents in Mysql Workbench GUI?

Select Database , select table and click icon as shown in picture.enter image description here

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Installing mysql-server solved the issue

sudo apt-get install mysql-server

Creating a file name as a timestamp in a batch job

I know this thread is old but I just want to add this here because it helped me alot trying to figure this all out and its clean. The nice thing about this is you could put it in a loop for a batch file that's always running. Server up-time log or something. That's what I use it for anyways. I hope this helps someone someday.

@setlocal enableextensions enabledelayedexpansion
@echo off

call :timestamp freshtime freshdate
echo %freshdate% - %freshtime% - Some data >> "%freshdate - Somelog.log"

:timestamp
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
set FreshTime=%hour%:%min%:%secs%

set year=%date:~-4%
set month=%date:~4,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
set day=%date:~7,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
set FreshDate=%month%.%day%.%year%

How to print a two dimensional array?

Something like this that i answer in another question

public class Snippet {
    public static void main(String[] args) {
        int [][]lst = new int[10][10];

        for (int[] arr : lst) {
            System.out.println(Arrays.toString(arr));
        }
    }

}

presenting ViewController with NavigationViewController swift

Calling presentViewController presents the view controller modally, outside the existing navigation stack; it is not contained by your UINavigationController or any other. If you want your new view controller to have a navigation bar, you have two main options:

Option 1. Push the new view controller onto your existing navigation stack, rather than presenting it modally:

let VC1 = self.storyboard!.instantiateViewControllerWithIdentifier("MyViewController") as! ViewController
self.navigationController!.pushViewController(VC1, animated: true)

Option 2. Embed your new view controller into a new navigation controller and present the new navigation controller modally:

let VC1 = self.storyboard!.instantiateViewControllerWithIdentifier("MyViewController") as! ViewController
let navController = UINavigationController(rootViewController: VC1) // Creating a navigation controller with VC1 at the root of the navigation stack.
self.present(navController, animated:true, completion: nil)

Bear in mind that this option won't automatically include a "back" button. You'll have to build in a close mechanism yourself.

Which one is best for you is a human interface design question, but it's normally clear what makes the most sense.

How can I measure the actual memory usage of an application or process?

#!/bin/ksh
#
# Returns total memory used by process $1 in kb.
#
# See /proc/NNNN/smaps if you want to do something
# more interesting.
#

IFS=$'\n'

for line in $(</proc/$1/smaps)
do
   [[ $line =~ ^Size:\s+(\S+) ]] && ((kb += ${.sh.match[1]}))
done

print $kb

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

I installed MySQL as root user($SUDO) and got this same issue
Here is how I fixed it-

  1. $ sudo cat /etc/mysql/debian.cnf

This will show details as-

# Automatically generated for Debian scripts. DO NOT TOUCH! [client] host = localhost user = debian-sys-maint password = GUx0RblkD3sPhHL5 socket = /var/run/mysqld/mysqld.sock [mysql_upgrade] host = localhost user = debian-sys-maint password = GUx0RblkD3sPhHL5 socket = /var/run/mysqld/mysqld.sock

Above we can see password just we are going to use(GUx0RblkD3sPhHL5) that in the prompt-

  1. mysql -u debian-sys-maint -p Enter password:
    now provide password(GUx0RblkD3sPhHL5).

  2. Now exit from MySQL and login again as-

    mysql -u root -p Enter password:
    Now provide new password. That's all, we have new password for further uses.

It worked for me, hope help you too!

Left Join With Where Clause

For this problem, as for many others involving non-trivial left joins such as left-joining on inner-joined tables, I find it convenient and somewhat more readable to split the query with a with clause. In your example,

with settings_for_char as (
  select setting_id, value from character_settings where character_id = 1
)
select
  settings.*,
  settings_for_char.value
from
  settings
  left join settings_for_char on settings_for_char.setting_id = settings.id;

Unnamed/anonymous namespaces vs. static functions

From experience I'll just note that while it is the C++ way to put formerly-static functions into the anonymous namespace, older compilers can sometimes have problems with this. I currently work with a few compilers for our target platforms, and the more modern Linux compiler is fine with placing functions into the anonymous namespace.

But an older compiler running on Solaris, which we are wed to until an unspecified future release, will sometimes accept it, and other times flag it as an error. The error is not what worries me, it's what it might be doing when it accepts it. So until we go modern across the board, we are still using static (usually class-scoped) functions where we'd prefer the anonymous namespace.

How to check for a valid Base64 encoded string

I would suggest creating a regex to do the job. You'll have to check for something like this: [a-zA-Z0-9+/=] You'll also have to check the length of the string. I'm not sure on this one, but i'm pretty sure if something gets trimmed (other than the padding "=") it would blow up.

Or better yet check out this stackoverflow question

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Use these commands on a windows command prompt(cmd) with administrator privilege (run as administrator):

netsh wlan set hostednetwork mode=allow ssid=tests key=tests123

netsh wlan start hostednetwork

Then you go to Network and sharing center and click on "change adapter settings" (I'm using windows 7, it can be a little different on windows 8)

Then right click on the lan connection (internet connection that you are using), properties.

Click on sharing tab, select the wireless connection tests (the name tests you can change on the command line) and check "Allow other network users to connect through this network connection"

This done, your connection is ready to use!

What are some good Python ORM solutions?

If you're looking for lightweight and are already familiar with django-style declarative models, check out peewee: https://github.com/coleifer/peewee

Example:

import datetime
from peewee import *

class Blog(Model):
    name = CharField()

class Entry(Model):
    blog = ForeignKeyField(Blog)
    title = CharField()
    body = TextField()
    pub_date = DateTimeField(default=datetime.datetime.now)

# query it like django
Entry.filter(blog__name='Some great blog')

# or programmatically for finer-grained control
Entry.select().join(Blog).where(Blog.name == 'Some awesome blog')

Check the docs for more examples.

document.getElementByID is not a function

It worked like this for me:

document.getElementById("theElementID").setAttribute("src", source);
document.getElementById("task-text").innerHTML = "";

Change the

getElementById("theElementID")

for your element locator (name, css, xpath...)

How to cancel/abort jQuery AJAX request?

The jquery ajax method returns a XMLHttpRequest object. You can use this object to cancel the request.

The XMLHttpRequest has a abort method, which cancels the request, but if the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for/handle the response.

The xhr object also contains a readyState which contains the state of the request(UNSENT-0, OPENED-1, HEADERS_RECEIVED-2, LOADING-3 and DONE-4). we can use this to check whether the previous request was completed.

$(document).ready(
    var xhr;

    var fn = function(){
        if(xhr && xhr.readyState != 4){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
);

How do I test axios in Jest?

For those looking to use axios-mock-adapter in place of the mockfetch example in the Redux documentation for async testing, I successfully used the following:

File actions.test.js:

describe('SignInUser', () => {
  var history = {
    push: function(str) {
        expect(str).toEqual('/feed');
    }
  }

  it('Dispatches authorization', () => {
    let mock = new MockAdapter(axios);
    mock.onPost(`${ROOT_URL}/auth/signin`, {
        email: '[email protected]',
        password: 'test'
    }).reply(200, {token: 'testToken' });

    const expectedActions = [ { type: types.AUTH_USER } ];
    const store = mockStore({ auth: [] });

    return store.dispatch(actions.signInUser({
        email: '[email protected]',
        password: 'test',
      }, history)).then(() => {
        expect(store.getActions()).toEqual(expectedActions);
  });

});

In order to test a successful case for signInUser in file actions/index.js:

export const signInUser = ({ email, password }, history) => async dispatch => {
  const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
    .catch(({ response: { data } }) => {
        ...
  });

  if (res) {
    dispatch({ type: AUTH_USER });                 // Test verified this
    localStorage.setItem('token', res.data.token); // Test mocked this
    history.push('/feed');                         // Test mocked this
  }
}

Given that this is being done with jest, the localstorage call had to be mocked. This was in file src/setupTests.js:

const localStorageMock = {
  removeItem: jest.fn(),
  getItem: jest.fn(),
  setItem: jest.fn(),
  clear: jest.fn()
};
global.localStorage = localStorageMock;

How to run python script with elevated privilege on windows

I wanted a more enhanced version so I ended up with a module which allows: UAC request if needed, printing and logging from nonprivileged instance (uses ipc and a network port) and some other candies. usage is just insert elevateme() in your script: in nonprivileged it listen for privileged print/logs and then exits returning false, in privileged instance it returns true immediately. Supports pyinstaller.

prototype:

# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):

winadmin.py

#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4

# (C) COPYRIGHT © Preston Landers 2010
# (C) COPYRIGHT © Matteo Azzali 2020
# Released under the same license as Python 2.6.5/3.7


import sys, os
from traceback import print_exc
from multiprocessing.connection import Listener, Client
import win32event #win32com.shell.shell, win32process
import builtins as __builtin__ # python3

# debug suffixes for remote printing
dbz=["","","",""] #["J:","K:", "G:", "D:"]
LOGTAG="LOGME:"

wrconn = None


#fake logger for message sending
class fakelogger:
    def __init__(self, xlogger=None):
        self.lg = xlogger
    def write(self, a):
        global wrconn
        if wrconn is not None:
            wrconn.send(LOGTAG+a)
        elif self.lg is not None:
            self.lg.write(a)
        else:
            print(LOGTAG+a)
        

class Writer():
    wzconn=None
    counter = 0
    def __init__(self, tport=6000,authkey=b'secret password'):
        global wrconn
        if wrconn is None:
            address = ('localhost', tport)
            try:
                wrconn = Client(address, authkey=authkey)
            except:
                wrconn = None
            wzconn = wrconn
            self.wrconn = wrconn
        self.__class__.counter+=1
        
    def __del__(self):
        self.__class__.counter-=1
        if self.__class__.counter == 0 and wrconn is not None:
            import time
            time.sleep(0.1) # slows deletion but is enough to print stderr
            wrconn.send('close')
            wrconn.close()
    
    def sendx(cls, mesg):
        cls.wzconn.send(msg)
        
    def sendw(self, mesg):
        self.wrconn.send(msg)
        

#fake file to be passed as stdout and stderr
class connFile():
    def __init__(self, thekind="out", tport=6000):
        self.cnt = 0
        self.old=""
        self.vg=Writer(tport)
        if thekind == "out":
            self.kind=sys.__stdout__
        else:
            self.kind=sys.__stderr__
        
    def write(self, *args, **kwargs):
        global wrconn
        global dbz
        from io import StringIO # # Python2 use: from cStringIO import StringIO
        mystdout = StringIO()
        self.cnt+=1
        __builtin__.print(*args, **kwargs, file=mystdout, end = '')
        
        #handles "\n" wherever it is, however usually is or string or \n
        if "\n" not in mystdout.getvalue():
            if mystdout.getvalue() != "\n":
                #__builtin__.print("A:",mystdout.getvalue(), file=self.kind, end='')
                self.old += mystdout.getvalue()
            else:
                #__builtin__.print("B:",mystdout.getvalue(), file=self.kind, end='')
                if wrconn is not None:
                    wrconn.send(dbz[1]+self.old)
                else:
                    __builtin__.print(dbz[2]+self.old+ mystdout.getvalue(), file=self.kind, end='')
                    self.kind.flush()
                self.old=""
        else:
                vv = mystdout.getvalue().split("\n")
                #__builtin__.print("V:",vv, file=self.kind, end='')
                for el in vv[:-1]:
                    if wrconn is not None:
                        wrconn.send(dbz[0]+self.old+el)
                        self.old = ""
                    else:
                        __builtin__.print(dbz[3]+self.old+ el+"\n", file=self.kind, end='')
                        self.kind.flush()
                        self.old=""
                self.old=vv[-1]

    def open(self):
        pass
    def close(self):
        pass
    def flush(self):
        pass
        
        
def isUserAdmin():
    if os.name == 'nt':
        import ctypes
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            traceback.print_exc()
            print ("Admin check failed, assuming not an admin.")
            return False
    elif os.name == 'posix':
        # Check for root on Posix
        return os.getuid() == 0
    else:
        print("Unsupported operating system for this module: %s" % (os.name,))
        exit()
        #raise (RuntimeError, "Unsupported operating system for this module: %s" % (os.name,))

def runAsAdmin(cmdLine=None, wait=True, hidden=False):

    if os.name != 'nt':
        raise (RuntimeError, "This function is only implemented on Windows.")

    import win32api, win32con, win32process
    from win32com.shell.shell import ShellExecuteEx

    python_exe = sys.executable
    arb=""
    if cmdLine is None:
        cmdLine = [python_exe] + sys.argv
    elif not isinstance(cmdLine, (tuple, list)):
        if isinstance(cmdLine, (str)):
            arb=cmdLine
            cmdLine = [python_exe] + sys.argv
            print("original user", arb)
        else:
            raise( ValueError, "cmdLine is not a sequence.")
    cmd = '"%s"' % (cmdLine[0],)

    params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
    if len(arb) > 0:
        params += " "+arb
    cmdDir = ''
    if hidden:
        showCmd = win32con.SW_HIDE
    else:
        showCmd = win32con.SW_SHOWNORMAL
    lpVerb = 'runas'  # causes UAC elevation prompt.

    # print "Running", cmd, params

    # ShellExecute() doesn't seem to allow us to fetch the PID or handle
    # of the process, so we can't get anything useful from it. Therefore
    # the more complex ShellExecuteEx() must be used.

    # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)

    procInfo = ShellExecuteEx(nShow=showCmd,
                              fMask=64,
                              lpVerb=lpVerb,
                              lpFile=cmd,
                              lpParameters=params)

    if wait:
        procHandle = procInfo['hProcess']    
        obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
        rc = win32process.GetExitCodeProcess(procHandle)
        #print "Process handle %s returned code %s" % (procHandle, rc)
    else:
        rc = procInfo['hProcess']

    return rc


# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):
    global dbz
    if not isUserAdmin():
        print ("You're not an admin.", os.getpid(), "params: ", sys.argv)

        import getpass
        uname = getpass.getuser()
        
        if (tport> 0):
            address = ('localhost', tport)     # family is deduced to be 'AF_INET'
            listener = Listener(address, authkey=b'secret password')
        rc = runAsAdmin(uname, wait=False, hidden=True)
        if (tport> 0):
            hr = win32event.WaitForSingleObject(rc, 40)
            conn = listener.accept()
            print ('connection accepted from', listener.last_accepted)
            sys.stdout.flush()
            while True:
                msg = conn.recv()
                # do something with msg
                if msg == 'close':
                    conn.close()
                    break
                else:
                    if msg.startswith(dbz[0]+LOGTAG):
                        if xlogger != None:
                            xlogger.write(msg[len(LOGTAG):])
                        else:
                            print("Missing a logger")
                    else:
                        print(msg)
                    sys.stdout.flush()
            listener.close()
        else: #no port connection, its silent
            WaitForSingleObject(rc, INFINITE);
        return False
    else:
        #redirect prints stdout on  master, errors in error.txt
        print("HIADM")
        sys.stdout.flush()
        if (tport > 0) and (redir):
            vox= connFile(tport=tport)
            sys.stdout=vox
            if not errFile:
                sys.stderr=vox
            else:
                vfrs=open("errFile.txt","w")
                sys.stderr=vfrs
            
            #print("HI ADMIN")
        return True


def test():
    rc = 0
    if not isUserAdmin():
        print ("You're not an admin.", os.getpid(), "params: ", sys.argv)
        sys.stdout.flush()
        #rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
        rc = runAsAdmin()
    else:
        print ("You are an admin!", os.getpid(), "params: ", sys.argv)
        rc = 0
    x = raw_input('Press Enter to exit.')
    return rc
    
if __name__ == "__main__":
    sys.exit(test())

Define the selected option with the old input in Laravel / Blade

      <select class="form-control" name="kategori_id">
        <option value="">-- PILIH --</option>
        @foreach($kategori as $id => $nama)
            @if(old('kategori_id', $produk->kategori_id) == $id )
            <option value="{{ $id }}" selected>{{ $nama }}</option>
            @else
            <option value="{{ $id }}">{{ $nama }}</option>
            @endif
        @endforeach
        </select>

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

One way I found after some struggling is creating a function which gets data_plot matrix, file name and order as parameter to create boxplots from the given data in the ordered figure (different orders = different figures) and save it under the given file_name.

def plotFigure(data_plot,file_name,order):
    fig = plt.figure(order, figsize=(9, 6))
    ax = fig.add_subplot(111)
    bp = ax.boxplot(data_plot)
    fig.savefig(file_name, bbox_inches='tight')
    plt.close()

Pods stuck in Terminating status

You can use following command to delete the POD forcefully.

kubectl delete pod <PODNAME> --grace-period=0 --force --namespace <NAMESPACE>

Copy and paste content from one file to another file in vi

Since you already know how to cut/yank text, here are a few ideas for pasting it back into another file:

  • Edit the first file, yanking the text you want. Then open your second file from within vi (:e /path/to/other/file) and paste it
  • Open both files together in a split window and navigate between them using Ctrl + w, Up/Down either by:

    • vi -o /path/to/file1 /path/to/file2
    • From within the first file, Ctrl + w, s

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

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

It happens when you are trying to access secure Website like Https.

I hope you missed 's'

Try Changing URL to curl -sS -u "username:password" https://www.example.com/backup.php

Import error: No module name urllib2

The above didn't work for me in 3.3. Try this instead (YMMV, etc)

import urllib.request
url = "http://www.google.com/"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
print (response.read().decode('utf-8'))

Convert Existing Eclipse Project to Maven Project

It's necessary because, more or less, when we import a project from git, it's not a maven project, so the maven dependencies are not in the build path.

Here's what I have done to turn a general project to a maven project.

general project-->java project right click the project, properties->project facets, click "java". This step will turn a general project into java project.

java project --> maven project right click project, configure-->convert to maven project At this moment, maven dependencies lib are still not in the build path. project properties, build path, add library, add maven dependencies lib

And wait a few seconds, when the dependencies are loaded, the project is ready!

Can we import XML file into another XML file?

You could use an external (parsed) general entity.

You declare the entity like this:

<!ENTITY otherFile SYSTEM "otherFile.xml">

Then you reference it like this:

&otherFile;

A complete example:

<?xml version="1.0" standalone="no" ?>
<!DOCTYPE doc [
<!ENTITY otherFile SYSTEM "otherFile.xml">
]>
<doc>
  <foo>
    <bar>&otherFile;</bar>
  </foo>
</doc>

When the XML parser reads the file, it will expand the entity reference and include the referenced XML file as part of the content.

If the "otherFile.xml" contained: <baz>this is my content</baz>

Then the XML would be evaluated and "seen" by an XML parser as:

<?xml version="1.0" standalone="no" ?>
<doc>
  <foo>
    <bar><baz>this is my content</baz></bar>
  </foo>
</doc>

A few references that might be helpful:

How can I install pip on Windows?

When I have to use Windows, I use ActivePython, which automatically adds everything to your PATH and includes a package manager called PyPM which provides binary package management making it faster and simpler to install packages.

pip and easy_install aren't exactly the same thing, so there are some things you can get through pip but not easy_install and vice versa.

My recommendation is that you get ActivePython Community Edition and don't worry about the huge hassle of getting everything set up for Python on Windows. Then, you can just use pypm.

In case you want to use pip you have to check the PyPM option in the ActiveState installer. After installation you only need to logoff and log on again, and pip will be available on the commandline, because it is contained in the ActiveState installer PyPM option and the paths have been set by the installer for you already. PyPM will also be available, but you do not have to use it.

Select All distinct values in a column using LINQ

Interestingly enough I tried both of these in LinqPad and the variant using group from Dmitry Gribkov by appears to be quicker. (also the final distinct is not required as the result is already distinct.

My (somewhat simple) code was:

public class Pair 
{ 
    public int id {get;set;}
    public string Arb {get;set;}
}

void Main()
{

    var theList = new List<Pair>();
    var randomiser = new Random();
    for (int count = 1; count < 10000; count++)
    {
        theList.Add(new Pair 
        {
            id = randomiser.Next(1, 50),
            Arb = "not used"
        });
    }

    var timer = new Stopwatch();
    timer.Start();
    var distinct = theList.GroupBy(c => c.id).Select(p => p.First().id);
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);

    timer.Start();
    var otherDistinct = theList.Select(p => p.id).Distinct();
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);
}

How to pass multiple arguments in processStartInfo?

Remember to include System.Diagnostics

ProcessStartInfo startInfo = new ProcessStartInfo("myfile.exe");        // exe file
startInfo.WorkingDirectory = @"C:\..\MyFile\bin\Debug\netcoreapp3.1\"; // exe folder

//here you add your arguments
startInfo.ArgumentList.Add("arg0");       // First argument          
startInfo.ArgumentList.Add("arg2");       // second argument
startInfo.ArgumentList.Add("arg3");       // third argument
Process.Start(startInfo);                 

Get Memory Usage in Android

I use this function to calculate cpu usage. Hope it can help you.

private float readUsage() {
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();

        String[] toks = load.split(" +");  // Split on one or more spaces

        long idle1 = Long.parseLong(toks[4]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
              + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        try {
            Thread.sleep(360);
        } catch (Exception e) {}

        reader.seek(0);
        load = reader.readLine();
        reader.close();

        toks = load.split(" +");

        long idle2 = Long.parseLong(toks[4]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
            + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return 0;
} 

What is the command to truncate a SQL Server log file?

if I remember well... in query analyzer or equivalent:

BACKUP LOG  databasename  WITH TRUNCATE_ONLY

DBCC SHRINKFILE (  databasename_Log, 1)

Comparing Class Types in Java

Hmmm... Keep in mind that Class may or may not implement equals() -- that is not required by the spec. For instance, HP Fortify will flag myClass.equals(myOtherClass).

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

It is really simple.

googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {

            // Use default InfoWindow frame
            @Override
            public View getInfoWindow(Marker marker) {              
                return null;
            }           

            // Defines the contents of the InfoWindow
            @Override
            public View getInfoContents(Marker marker) {

                // Getting view from the layout file info_window_layout
                View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);

                // Getting reference to the TextView to set title
                TextView note = (TextView) v.findViewById(R.id.note);

                note.setText(marker.getTitle() );

                // Returning the view containing InfoWindow contents
                return v;

            }

        });

Just add above code in your class where you are using GoogleMap. R.layout.info_window_layout is our custom layout that is showing the view that will come in place of infowindow. I just added the textview here. You can add additonal view here to make it like the sample snap. My info_window_layout was

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:orientation="vertical" 
    >

        <TextView 
        android:id="@+id/note"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

I hope it will help. We can find a working example of custom infowindow at http://wptrafficanalyzer.in/blog/customizing-infowindow-contents-in-google-map-android-api-v2-using-infowindowadapter/#comment-39731

EDITED : This code is shows how we can add custom view on infoWindow. This code did not handle the clicks on Custom View items. So it is close to answer but not exactly the answer that's why It is not accepted as answer.

HTTP Ajax Request via HTTPS Page

From the javascript I tried from several ways and I could not.

You need an server side solution, for example on c# I did create an controller that call to the http, en deserialize the object, and the result is that when I call from javascript, I'm doing an request from my https://domain to my htpps://domain. Please see my c# code:

[Authorize]
public class CurrencyServicesController : Controller
{
    HttpClient client;
    //GET: CurrencyServices/Consultar?url=valores?moedas=USD&alt=json
    public async Task<dynamic> Consultar(string url)
    {
        client = new HttpClient();
        client.BaseAddress = new Uri("http://api.promasters.net.br/cotacao/v1/");
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        System.Net.Http.HttpResponseMessage response = client.GetAsync(url).Result;

        var FromURL = response.Content.ReadAsStringAsync().Result;

        return JsonConvert.DeserializeObject(FromURL);
    }

And let me show to you my client side (Javascript)

<script async>
$(document).ready(function (data) {

    var TheUrl = '@Url.Action("Consultar", "CurrencyServices")?url=valores';
    $.getJSON(TheUrl)
        .done(function (data) {
            $('#DolarQuotation').html(
                '$ ' + data.valores.USD.valor.toFixed(2) + ','
            );
            $('#EuroQuotation').html(
                '€ ' + data.valores.EUR.valor.toFixed(2) + ','
            );

            $('#ARGPesoQuotation').html(
                'Ar$ ' + data.valores.ARS.valor.toFixed(2) + ''
            );

        });       

});

I wish that this help you! Greetings

How to detect a USB drive has been plugged in?

Microsoft API Code Pack. ShellObjectWatcher class.

jQuery load more data on scroll

The accepted answer of this question has some issue with chrome when the window is zoomed in to a value >100%. Here is the code recommended by chrome developers as part of a bug i had raised on the same.

$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() >= $(document).height()){
     //Your code here
  }
});

For reference:

Related SO question

Chrome Bug

How to show a confirm message before delete?

Its very simple

function archiveRemove(any) {
    var click = $(any);
    var id = click.attr("id");
    swal.fire({
        title: 'Are you sure !',
           text: "?????",
           type: 'warning',
           showCancelButton: true,
           confirmButtonColor: '#3085d6',
           cancelButtonColor: '#d33',
           confirmButtonText: 'yes!',
           cancelButtonText: 'no'
    }).then(function (success) {
        if (success) {
            $('a[id="' + id + '"]').parents(".archiveItem").submit();
        }
    })
}

How do I drag and drop files into an application?

Some sample code:

  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      this.AllowDrop = true;
      this.DragEnter += new DragEventHandler(Form1_DragEnter);
      this.DragDrop += new DragEventHandler(Form1_DragDrop);
    }

    void Form1_DragEnter(object sender, DragEventArgs e) {
      if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
    }

    void Form1_DragDrop(object sender, DragEventArgs e) {
      string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
      foreach (string file in files) Console.WriteLine(file);
    }
  }

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

Have you got the driver installed? If you go into Start > Settings > Control Panel > Administrative Tools and click the Data Sources, then select the Drivers tab your driver info should be registered there.

Failing that it may be easier to simply set up a DSN connection to test with.

You can define multiple connection strings of course and set-up a 'mode' for working on different machines.

Also there's ConnectionStrings.com.

-- EDIT --

Just to further this, I found this thread on another site.

numpy get index where value is true

To get the row numbers where at least one item is larger than 15:

>>> np.where(np.any(e>15, axis=1))
(array([1, 2], dtype=int64),)

Connect to Active Directory via LDAP

DC is your domain. If you want to connect to the domain example.com than your dc's are: DC=example,DC=com

You actually don't need any hostname or ip address of your domain controller (There could be plenty of them).

Just imagine that you're connecting to the domain itself. So for connecting to the domain example.com you can simply write

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");

And you're done.

You can also specify a user and a password used to connect:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");

Also be sure to always write LDAP in upper case. I had some trouble and strange exceptions until I read somewhere that I should try to write it in upper case and that solved my problems.

The directoryEntry.Path Property allows you to dive deeper into your domain. So if you want to search a user in a specific OU (Organizational Unit) you can set it there.

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";

This would match the following AD hierarchy:

  • com
    • example
      • Users
        • All Users
          • Specific Users

Simply write the hierarchy from deepest to highest.

Now you can do plenty of things

For example search a user by account name and get the user's surname:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
    PageSize = int.MaxValue,
    Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};

searcher.PropertiesToLoad.Add("sn");

var result = searcher.FindOne();

if (result == null) {
    return; // Or whatever you need to do in this case
}

string surname;

if (result.Properties.Contains("sn")) {
    surname = result.Properties["sn"][0].ToString();
}

Parsing json and searching through it

Functions to search through and print dicts, like JSON. *made in python 3

Search:

def pretty_search(dict_or_list, key_to_search, search_for_first_only=False):
    """
    Give it a dict or a list of dicts and a dict key (to get values of),
    it will search through it and all containing dicts and arrays
    for all values of dict key you gave, and will return you set of them
    unless you wont specify search_for_first_only=True

    :param dict_or_list: 
    :param key_to_search: 
    :param search_for_first_only: 
    :return: 
    """
    search_result = set()
    if isinstance(dict_or_list, dict):
        for key in dict_or_list:
            key_value = dict_or_list[key]
            if key == key_to_search:
                if search_for_first_only:
                    return key_value
                else:
                    search_result.add(key_value)
            if isinstance(key_value, dict) or isinstance(key_value, list) or isinstance(key_value, set):
                _search_result = pretty_search(key_value, key_to_search, search_for_first_only)
                if _search_result and search_for_first_only:
                    return _search_result
                elif _search_result:
                    for result in _search_result:
                        search_result.add(result)
    elif isinstance(dict_or_list, list) or isinstance(dict_or_list, set):
        for element in dict_or_list:
            if isinstance(element, list) or isinstance(element, set) or isinstance(element, dict):
                _search_result = pretty_search(element, key_to_search, search_result)
                if _search_result and search_for_first_only:
                    return _search_result
                elif _search_result:
                    for result in _search_result:
                        search_result.add(result)
    return search_result if search_result else None

Print:

def pretty_print(dict_or_list, print_spaces=0):
    """
    Give it a dict key (to get values of),
    it will return you a pretty for print version
    of a dict or a list of dicts you gave.

    :param dict_or_list: 
    :param print_spaces: 
    :return: 
    """
    pretty_text = ""
    if isinstance(dict_or_list, dict):
        for key in dict_or_list:
            key_value = dict_or_list[key]
            if isinstance(key_value, dict):
                key_value = pretty_print(key_value, print_spaces + 1)
                pretty_text += "\t" * print_spaces + "{}:\n{}\n".format(key, key_value)
            elif isinstance(key_value, list) or isinstance(key_value, set):
                pretty_text += "\t" * print_spaces + "{}:\n".format(key)
                for element in key_value:
                    if isinstance(element, dict) or isinstance(element, list) or isinstance(element, set):
                        pretty_text += pretty_print(element, print_spaces + 1)
                    else:
                        pretty_text += "\t" * (print_spaces + 1) + "{}\n".format(element)
            else:
                pretty_text += "\t" * print_spaces + "{}: {}\n".format(key, key_value)
    elif isinstance(dict_or_list, list) or isinstance(dict_or_list, set):
        for element in dict_or_list:
            if isinstance(element, dict) or isinstance(element, list) or isinstance(element, set):
                pretty_text += pretty_print(element, print_spaces + 1)
            else:
                pretty_text += "\t" * print_spaces + "{}\n".format(element)
    else:
        pretty_text += str(dict_or_list)
    if print_spaces == 0:
        print(pretty_text)
    return pretty_text

ORA-01843 not a valid month- Comparing Dates

If the source date contains minutes and seconds part, your date comparison will fail. you need to convert source date to the required format using to_char and the target date also.

What is the difference between supervised learning and unsupervised learning?

For instance, very often training a neural network is supervised learning: you're telling the network to which class corresponds the feature vector you're feeding.

Clustering is unsupervised learning: you let the algorithm decide how to group samples into classes that share common properties.

Another example of unsupervised learning is Kohonen's self organizing maps.

How to refresh token with Google API client?

Here is the code which I am using in my project and it is working fine:

public function getClient(){
    $client = new Google_Client();
    $client->setApplicationName(APPNAME);       // app name
    $client->setClientId(CLIENTID);             // client id
    $client->setClientSecret(CLIENTSECRET);     // client secret 
    $client->setRedirectUri(REDIRECT_URI);      // redirect uri
    $client->setApprovalPrompt('auto');

    $client->setAccessType('offline');         // generates refresh token

    $token = $_COOKIE['ACCESSTOKEN'];          // fetch from cookie

    // if token is present in cookie
    if($token){
        // use the same token
        $client->setAccessToken($token);
    }

    // this line gets the new token if the cookie token was not present
    // otherwise, the same cookie token
    $token = $client->getAccessToken();

    if($client->isAccessTokenExpired()){  // if token expired
        $refreshToken = json_decode($token)->refresh_token;

        // refresh the token
        $client->refreshToken($refreshToken);
    }

    return $client;
}

When should I use h:outputLink instead of h:commandLink?

The <h:outputLink> renders a fullworthy HTML <a> element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>

The <h:commandLink> renders a HTML <a> element with an onclick script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>.

<h:form>
    <h:commandLink value="link text" action="destination" />
</h:form>

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the <a> element to be a fullworthy URL. It still remains #.

<h:form>
    <h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>

Since JSF 2.0, there's also the <h:link> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a> element as well with the proper URL in href.

<h:link value="link text" outcome="destination" />

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

How to convert datatype:object to float64 in python?

Or you can use regular expression to handle multiple items as the general case of this issue,

df['2nd'] = pd.to_numeric(df['2nd'].str.replace(r'[,.%]','')) 
df['CTR'] = pd.to_numeric(df['CTR'].str.replace(r'[^\d%]',''))

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

This is the error that is returned when the Windows Firewall blocks the port (out-going). We have a strict web server so the outgoing ports are blocked by default. All I had to do was to create a rule to allow the TCP port number in wf.msc.

Serialize JavaScript object into JSON string

I was having some issues using the above solutions with an "associative array" type object. These solutions seem to preserve the values, but they do not preserve the actual names of the objects that those values are associated with, which can cause some issues. So I put together the following functions which I am using instead:

function flattenAssocArr(object) {
  if(typeof object == "object") {
    var keys = [];
    keys[0] = "ASSOCARR";
    keys.push(...Object.keys(object));
    var outArr = [];
    outArr[0] = keys;
    for(var i = 1; i < keys.length; i++) {
        outArr[i] = flattenAssocArr(object[keys[i]])
    }
    return outArr;
  } else {
    return object;
  }
}

function expandAssocArr(object) {
    if(typeof object !== "object")
        return object;
    var keys = object[0];
    var newObj = new Object();
    if(keys[0] === "ASSOCARR") {
        for(var i = 1; i < keys.length; i++) {
            newObj[keys[i]] = expandAssocArr(object[i])
        }
    }
    return newObj;
}

Note that these can't be used with any arbitrary object -- basically it creates a new array, stores the keys as element 0, with the data following it. So if you try to load an array that isn't created with these functions having element 0 as a key list, the results might be...interesting :)

I'm using it like this:

var objAsString = JSON.stringify(flattenAssocArr(globalDataset));
var strAsObject = expandAssocArr(JSON.parse(objAsString));

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

I installed webapi with it via the helppages nuget package. That package replaced most of the asp.net mvc 4 binaries with beta versions which didn't work well together with the rest of the project. Fix was to restore the original mvc 4 dll's and all was good.

How can I comment a single line in XML?

No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.

XML has only one definition for a comment:

'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'

XML forbids -- in comments to maintain compatibility with SGML.

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

How to create a temporary directory and get the path / file name in Python

To expand on another answer, here is a fairly complete example which can cleanup the tmpdir even on exceptions:

import contextlib
import os
import shutil
import tempfile

@contextlib.contextmanager
def cd(newdir, cleanup=lambda: True):
    prevdir = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(prevdir)
        cleanup()

@contextlib.contextmanager
def tempdir():
    dirpath = tempfile.mkdtemp()
    def cleanup():
        shutil.rmtree(dirpath)
    with cd(dirpath, cleanup):
        yield dirpath

def main():
    with tempdir() as dirpath:
        pass # do something here

jQuery/JavaScript: accessing contents of an iframe

You need to attach an event to an iframe's onload handler, and execute the js in there, so that you make sure the iframe has finished loading before accessing it.

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

The above will solve the 'not-yet-loaded' problem, but as regards the permissions, if you are loading a page in the iframe that is from a different domain, you won't be able to access it due to security restrictions.

Complexities of binary tree traversals

Travesal is O(n) for any order - because you are hitting each node once. Lookup is where it can be less than O(n) IF the tree has some sort of organizing schema (ie binary search tree).

How to convert float number to Binary?

void transfer(double x) {
unsigned long long* p = (unsigned long long*)&x;
for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}

How to add an empty column to a dataframe?

I like:

df['new'] = pd.Series(dtype='your_required_dtype')

If you have an empty dataframe, this solution makes sure that no new row containing only NaN is added.

Specifying dtype is not strictly necessary, however newer Pandas versions produce a DeprecationWarning if not specified.

Storing query results into a variable and modifying it inside a Stored Procedure

Yup, this is possible of course. Here are several examples.

-- one way to do this
DECLARE @Cnt int

SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn

-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)

-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double

SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable

XAMPP - Error: MySQL shutdown unexpectedly

I am new to XAMPP, but I find that a combination of these suggestions works best (At least on Windows 8.1 with the latest version of XAMPP. Note that the computer I tested this on, also had skype).

First logon to skype and navigate to "Tools < Options < Advanced < Connection." Then check the box that says "Use port 80 and 443 for additional incoming connections." Save, close, and quit skype.

Next, on your XAMPP control panel, click "config < my.ini" and change lines 19 and 27 (should have port = 3306) from "3306" to "3307."

Also, you will need to navigate to xampp < phpMyAdmin < config.inc and change line 27, which should like something like this:

$cfg['Servers'][$i]['host'] = '127.0.0.1';

You will need to add "3307" as follows:

$cfg['Servers'][$i]['host'] = '127.0.0.1:3307';

Now, open your browser and you should see the xampp page when you type in "localhost." Additionally, if this is your first time using xampp, you may see a warning about your lack of password (highlighted in pink) on your localhost/phpmyadmin/ page. This is easily remedied by going to the "user accounts" tab in phpmyadmin, clicking on "edit privileges" and entering password. Remember to save the hashed version of any and all passwords you create as we will use this next! -I opened a notepad and saved (and numbered) them. Note that phpMyadmin will notify you of when you are changing the password for your current session (this will be displayed at the top of your phpMyadmin page and is very important, as you will need THAT specific hashed version of your password).

Next, you will need to navigate to the following location "xampp < phpMyAdmin < config.inc" on your computer and open and edit the file with a text editor. You will want to put in the hashed version of your password between the single quotes for password and change "AllowNoPassword" from true to false.

And, that ought to do it.

CALL command vs. START with /WAIT option

I think that they should perform generally the same, but there are some differences. START is generally used to start applications or to start the default application for a given file type. That way if you START http://mywebsite.com it doesn't do START iexplore.exe http://mywebsite.com.

START myworddoc.docx would start Microsoft Word and open myworddoc.docx.CALL myworddoc.docx does the same thing... however START provides more options for the window state and things of that nature. It also allows process priority and affinity to be set.

In short, given the additional options provided by start, it should be your tool of choice.

START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
  [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
  [/NODE <NUMA node>] [/AFFINITY <hex affinity mask>] [/WAIT] [/B]
  [command/program] [parameters]

"title"     Title to display in window title bar.
path        Starting directory.
B           Start application without creating a new window. The
            application has ^C handling ignored. Unless the application
            enables ^C processing, ^Break is the only way to interrupt
            the application.
I           The new environment will be the original environment passed
            to the cmd.exe and not the current environment.
MIN         Start window minimized.
MAX         Start window maximized.
SEPARATE    Start 16-bit Windows program in separate memory space.
SHARED      Start 16-bit Windows program in shared memory space.
LOW         Start application in the IDLE priority class.
NORMAL      Start application in the NORMAL priority class.
HIGH        Start application in the HIGH priority class.
REALTIME    Start application in the REALTIME priority class.
ABOVENORMAL Start application in the ABOVENORMAL priority class.
BELOWNORMAL Start application in the BELOWNORMAL priority class.
NODE        Specifies the preferred Non-Uniform Memory Architecture (NUMA)
            node as a decimal integer.
AFFINITY    Specifies the processor affinity mask as a hexadecimal number.
            The process is restricted to running on these processors.

            The affinity mask is interpreted differently when /AFFINITY and
            /NODE are combined.  Specify the affinity mask as if the NUMA
            node's processor mask is right shifted to begin at bit zero.
            The process is restricted to running on those processors in
            common between the specified affinity mask and the NUMA node.
            If no processors are in common, the process is restricted to
            running on the specified NUMA node.
WAIT        Start application and wait for it to terminate.

Free Online Team Foundation Server

You can use Visual Studio Team Services for free. Also you can import a TFS repo to this cloud space.

How to sum columns in a dataTable?

Try this:

            DataTable dt = new DataTable();
            int sum = 0;
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    sum += (int)dr[dc];
                }
            } 

What should a JSON service return on failure / error

Yes, you should use HTTP status codes. And also preferably return error descriptions in a somewhat standardized JSON format, like Nottingham’s proposal, see apigility Error Reporting:

The payload of an API Problem has the following structure:

  • type: a URL to a document describing the error condition (optional, and "about:blank" is assumed if none is provided; should resolve to a human-readable document; Apigility always provides this).
  • title: a brief title for the error condition (required; and should be the same for every problem of the same type; Apigility always provides this).
  • status: the HTTP status code for the current request (optional; Apigility always provides this).
  • detail: error details specific to this request (optional; Apigility requires it for each problem).
  • instance: URI identifying the specific instance of this problem (optional; Apigility currently does not provide this).

sql searching multiple words in a string

Oracle SQL:

There is the "IN" Operator in Oracle SQL which can be used for that:

select 
    namet.customerfirstname, addrt.city, addrt.postalcode
from schemax.nametable namet
join schemax.addresstable addrt on addrt.adtid = namet.natadtid
where namet.customerfirstname in ('David', 'Moses', 'Robi'); 

POST request with a simple string in body with Alamofire

Your example Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"]) already contains "foo=bar" string as its body. But if you really want string with custom format. You can do this:

Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: [:], encoding: .Custom({
            (convertible, params) in
            var mutableRequest = convertible.URLRequest.copy() as NSMutableURLRequest
            mutableRequest.HTTPBody = "myBodyString".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
            return (mutableRequest, nil)
        }))

Note: parameters should not be nil

UPDATE (Alamofire 4.0, Swift 3.0):

In Alamofire 4.0 API has changed. So for custom encoding we need value/object which conforms to ParameterEncoding protocol.

extension String: ParameterEncoding {

    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var request = try urlRequest.asURLRequest()
        request.httpBody = data(using: .utf8, allowLossyConversion: false)
        return request
    }

}

Alamofire.request("http://mywebsite.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])

using .join method to convert array to string without commas

The .join() method has a parameter for the separator string. If you want it to be empty instead of the default comma, use

arr.join("");

How to terminate a window in tmux?

ctrl + d kills a window in linux terminal, also works in tmux.

This is kind of a approach.

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Running a command through /usr/bin/env has the benefit of looking for whatever the default version of the program is in your current environment.

This way, you don't have to look for it in a specific place on the system, as those paths may be in different locations on different systems. As long as it's in your path, it will find it.

One downside is that you will be unable to pass more than one argument (e.g. you will be unable to write /usr/bin/env awk -f) if you wish to support Linux, as POSIX is vague on how the line is to be interpreted, and Linux interprets everything after the first space to denote a single argument. You can use /usr/bin/env -S on some versions of env to get around this, but then the script will become even less portable and break on fairly recent systems (e.g. even Ubuntu 16.04 if not later).

Another downside is that since you aren't calling an explicit executable, it's got the potential for mistakes, and on multiuser systems security problems (if someone managed to get their executable called bash in your path, for example).

#!/usr/bin/env bash #lends you some flexibility on different systems
#!/usr/bin/bash     #gives you explicit control on a given system of what executable is called

In some situations, the first may be preferred (like running python scripts with multiple versions of python, without having to rework the executable line). But in situations where security is the focus, the latter would be preferred, as it limits code injection possibilities.

VBScript -- Using error handling

I'm exceptionally new to VBScript, so this may not be considered best practice or there may be a reason it shouldn't be done this that way I'm not yet aware of, but this is the solution I came up with to trim down the amount of error logging code in my main code block.

Dim oConn, connStr
Set oConn = Server.CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;Server=XX;UID=XX;PWD=XX;Databse=XX"

ON ERROR RESUME NEXT

oConn.Open connStr
If err.Number <> 0 Then : showError() : End If


Sub ShowError()

    'You could write the error details to the console...
    errDetail = "<script>" & _
    "console.log('Description: " & err.Description & "');" & _
    "console.log('Error number: " & err.Number & "');" & _
    "console.log('Error source: " & err.Source & "');" & _
    "</script>"

    Response.Write(errDetail)       

    '...you could display the error info directly in the page...
    Response.Write("Error Description: " & err.Description)
    Response.Write("Error Source: " & err.Source)
    Response.Write("Error Number: " & err.Number)

    '...or you could execute additional code when an error is thrown...
    'Insert error handling code here

    err.clear
End Sub

How can I make my flexbox layout take 100% vertical space?

Let me show you another way that works 100%. I will also add some padding for the example.

<div class = "container">
  <div class = "flex-pad-x">
    <div class = "flex-pad-y">
      <div class = "flex-pad-y">
        <div class = "flex-grow-y">
         Content Centered
        </div>
      </div>
    </div>
  </div>
</div>

.container {
  position: fixed;
  top: 0px;
  left: 0px;
  bottom: 0px;
  right: 0px;
  width: 100%;
  height: 100%;
}

  .flex-pad-x {
    padding: 0px 20px;
    height: 100%;
    display: flex;
  }

  .flex-pad-y {
    padding: 20px 0px;
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  .flex-grow-y {
    flex-grow: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
   }

As you can see we can achieve this with a few wrappers for control while utilising the flex-grow & flex-direction attribute.

1: When the parent "flex-direction" is a "row", its child "flex-grow" works horizontally. 2: When the parent "flex-direction" is "columns", its child "flex-grow" works vertically.

Hope this helps

Daniel

Make just one slide different size in Powerpoint

Although you cannot use different sized slides in one PowerPoint file, for the actual presentation you can link several different files together to create a presentation that has different slide sizes.

The process to do so is as follows:

  1. Create the two Powerpoints (with your desired slide dimensions)
    • They need to be properly filled in to have linkable objects and selectable slides
  2. Select an object in the main PowerPoint to act as the hyperlink
  3. Go to "Insert -> Links -> Action"
  4. Select either the "Mouse Click" or the "Mouse Over" tab
  5. Select "Hyperlink to:" and in the drop down menu choose "other PowerPoint Presentation"
  6. Select the slide that you want to link to.
    • Any slide that isn't empty should appear in the "Hyperlink to Slide" dialog box
  7. Repeat the Process in the second Presentation to link back to your main presentation

Reference to Office Support Page where this solution was first posted. https://support.office.com/en-us/article/can-i-use-portrait-and-landscape-slide-orientation-in-the-same-presentation-d8c21781-1fb6-4406-bcd6-25cfac37b5d6?ocmsassetID=HA010099556&CorrelationId=1ac4e97f-bfe6-47b1-bab6-5783e78d126d&ui=en-US&rs=en-US&ad=US

Where are logs located?

  • Ensure debug mode is on - either add APP_DEBUG=true to .env file or set an environment variable

  • Log files are in storage/logs folder. laravel.log is the default filename. If there is a permission issue with the log folder, Laravel just halts. So if your endpoint generally works - permissions are not an issue.

  • In case your calls don't even reach Laravel or aren't caused by code issues - check web server's log files (check your Apache/nginx config files to see the paths).

  • If you use PHP-FPM, check its log files as well (you can see the path to log file in PHP-FPM pool config).

Fetching data from MySQL database using PHP, Displaying it in a form for editing

<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
Password
<input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>

You didnt closed your opening Form in the first place, plus your code is very very messy. I wont go into the "use pdo or mysqli statements, instead of mysql" thats for you to find out on yourself. Also you have a php tag open and close below it, not sure what is needed there. Something else is that your code refers to an external page, which you didnt post, so if something isnt working there, might be handy to post it too.

Please also note that you had spaces between your $row array variables in the form. You have to link those up together by removing the space (see edited section from me). PHP isn't forgiving when it comes to those mistakes.

Then your HTML. I took the liberty to correct that too

<html>
    <head>
        <title> Delegate edit form</title>
    </head>

    <body>
          <p>Delegate update form</p>
<?php
$usernm="root";
$passwd="";
$host="localhost";
$database="swift";

mysql_connect($host,$usernm,$passwd); 
mysql_select_db($database);

$sql = "SELECT * FROM usermaster WHERE User_name='".$Username."'"; // Please look at this too.
$result = mysql_query($sql) or die (mysql_error()); // dont put spaces in between it, else your code wont recognize it the query that needs to be executed
while ($row = mysql_fetch_array($result)){     // here too, you put a space between it
    $Name=$row['Name'];
    $Username=$row['User_name'];
    $Password=$row['User_password'];
    }
?>

Also, try to be specific. "It doesnt work" doesnt help us much, a specific error type is commonly helpful, plus any indication what the code should do (well, it was kinda obvious here, since its a login/register edit here, but for larger chunks of code it should always be explained)

Anyway, welcome to Stack Overflow

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

You could sort the array and then run through it and then see if the next (or previous) index is the same as the current. Assuming your sort algorithm is good, this should be less than O(n2):

_x000D_
_x000D_
const findDuplicates = (arr) => {_x000D_
  let sorted_arr = arr.slice().sort(); // You can define the comparing function here. _x000D_
  // JS by default uses a crappy string compare._x000D_
  // (we use slice to clone the array so the_x000D_
  // original array won't be modified)_x000D_
  let results = [];_x000D_
  for (let i = 0; i < sorted_arr.length - 1; i++) {_x000D_
    if (sorted_arr[i + 1] == sorted_arr[i]) {_x000D_
      results.push(sorted_arr[i]);_x000D_
    }_x000D_
  }_x000D_
  return results;_x000D_
}_x000D_
_x000D_
let duplicatedArray = [9, 9, 111, 2, 3, 4, 4, 5, 7];_x000D_
console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);
_x000D_
_x000D_
_x000D_

In case, if you are to return as a function for duplicates. This is for similar type of case.

Reference: https://stackoverflow.com/a/57532964/8119511

Git - Won't add files?

I have tried all the above but nothing was working. Later on, I ran my command prompt as an admin and retried all the stages i.e. staging-> committing-> remote add -> pushing. It worked like a magic. The changes were reflected in the desired remote repository.

Plotting categorical data with pandas and matplotlib

You could also use countplot from seaborn. This package builds on pandas to create a high level plotting interface. It gives you good styling and correct axis labels for free.

import pandas as pd
import seaborn as sns
sns.set()

df = pd.DataFrame({'colour': ['red', 'blue', 'green', 'red', 'red', 'yellow', 'blue'],
                   'direction': ['up', 'up', 'down', 'left', 'right', 'down', 'down']})
sns.countplot(df['colour'], color='gray')

enter image description here

It also supports coloring the bars in the right color with a little trick

sns.countplot(df['colour'],
              palette={color: color for color in df['colour'].unique()})

enter image description here

Ambiguous overload call to abs(double)

The header <math.h> is a C std lib header. It defines a lot of stuff in the global namespace. The header <cmath> is the C++ version of that header. It defines essentially the same stuff in namespace std. (There are some differences, like that the C++ version comes with overloads of some functions, but that doesn't matter.) The header <cmath.h> doesn't exist.

Since vendors don't want to maintain two versions of what is essentially the same header, they came up with different possibilities to have only one of them behind the scenes. Often, that's the C header (since a C++ compiler is able to parse that, while the opposite won't work), and the C++ header just includes that and pulls everything into namespace std. Or there's some macro magic for parsing the same header with or without namespace std wrapped around it or not. To this add that in some environments it's awkward if headers don't have a file extension (like editors failing to highlight the code etc.). So some vendors would have <cmath> be a one-liner including some other header with a .h extension. Or some would map all includes matching <cblah> to <blah.h> (which, through macro magic, becomes the C++ header when __cplusplus is defined, and otherwise becomes the C header) or <cblah.h> or whatever.

That's the reason why on some platforms including things like <cmath.h>, which ought not to exist, will initially succeed, although it might make the compiler fail spectacularly later on.

I have no idea which std lib implementation you use. I suppose it's the one that comes with GCC, but this I don't know, so I cannot explain exactly what happened in your case. But it's certainly a mix of one of the above vendor-specific hacks and you including a header you ought not to have included yourself. Maybe it's the one where <cmath> maps to <cmath.h> with a specific (set of) macro(s) which you hadn't defined, so that you ended up with both definitions.

Note, however, that this code still ought not to compile:

#include <cmath>

double f(double d)
{
  return abs(d);
}

There shouldn't be an abs() in the global namespace (it's std::abs()). However, as per the above described implementation tricks, there might well be. Porting such code later (or just trying to compile it with your vendor's next version which doesn't allow this) can be very tedious, so you should keep an eye on this.

Check if String contains only letters

private boolean isOnlyLetters(String s){
    char c=' ';
    boolean isGood=false, safe=isGood;
    int failCount=0;
    for(int i=0;i<s.length();i++){
        c = s.charAt(i);
        if(Character.isLetter(c))
            isGood=true;
        else{
            isGood=false;
            failCount+=1;
        }
    }
    if(failCount==0 && s.length()>0)
        safe=true;
    else
        safe=false;
    return safe;
}

I know it's a bit crowded. I was using it with my program and felt the desire to share it with people. It can tell if any character in a string is not a letter or not. Use it if you want something easy to clarify and look back on.

Java 8 Streams FlatMap method example

Extract unique words sorted ASC from a list of phrases:

List<String> phrases = Arrays.asList(
        "sporadic perjury",
        "confounded skimming",
        "incumbent jailer",
        "confounded jailer");

List<String> uniqueWords = phrases
        .stream()
        .flatMap(phrase -> Stream.of(phrase.split("\\s+")))
        .distinct()
        .sorted()
        .collect(Collectors.toList());
System.out.println("Unique words: " + uniqueWords);

... and the output:

Unique words: [confounded, incumbent, jailer, perjury, skimming, sporadic]

Foreign key referring to primary keys across multiple tables?

You can probably add two foreign key constraints (honestly: I've never tried it), but it'd then insist the parent row exist in both tables.

Instead you probably want to create a supertype for your two employee subtypes, and then point the foreign key there instead. (Assuming you have a good reason to split the two types of employees, of course).

                 employee       
employees_ce     ————————       employees_sn
————————————     type           ————————————
empid —————————> empid <——————— empid
name               /|\          name
                    |  
                    |  
      deductions    |  
      ——————————    |  
      empid ————————+  
      name

type in the employee table would be ce or sn.

Linking to an external URL in Javadoc?

This creates a "See Also" heading containing the link, i.e.:

/**
 * @see <a href="http://google.com">http://google.com</a>
 */

will render as:

See Also:
           http://google.com

whereas this:

/**
 * See <a href="http://google.com">http://google.com</a>
 */

will create an in-line link:

See http://google.com

Is it better practice to use String.format over string Concatenation in Java?

Which one is more readable depends on how your head works.

You got your answer right there.

It's a matter of personal taste.

String concatenation is marginally faster, I suppose, but that should be negligible.

Recyclerview and handling different type of row inflation

getItemViewType(int position) is the key

In my opinion,the starting point to create this kind of recyclerView is the knowledge of this method. Since this method is optional to override therefore it is not visible in RecylerView class by default which in turn makes many developers(including me) wonder where to begin. Once you know that this method exists, creating such RecyclerView would be a cakewalk.

enter image description here

How to do it ?

You can create a RecyclerView with any number of different Views(ViewHolders). But for better readability lets take an example of RecyclerView with two Viewholders.
Remember these 3 simple steps and you will be good to go.

  • Override public int getItemViewType(int position)
  • Return different ViewHolders based on the ViewType in onCreateViewHolder() method
  • Populate View based on the itemViewType in onBindViewHolder() method

    Here is a code snippet for you

    public class YourListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    
        private static final int LAYOUT_ONE= 0;
        private static final int LAYOUT_TWO= 1;
    
        @Override
        public int getItemViewType(int position)
        {
            if(position==0)
               return LAYOUT_ONE;
            else
               return LAYOUT_TWO;
        }
    
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    
            View view =null;
            RecyclerView.ViewHolder viewHolder = null;
    
            if(viewType==LAYOUT_ONE)
            {
               view = LayoutInflater.from(parent.getContext()).inflate(R.layout.one,parent,false);
               viewHolder = new ViewHolderOne(view);
            }
            else
            {
               view = LayoutInflater.from(parent.getContext()).inflate(R.layout.two,parent,false);
               viewHolder= new ViewHolderTwo(view);
            }
    
            return viewHolder;
        }
    
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    
           if(holder.getItemViewType()== LAYOUT_ONE)
           {
               // Typecast Viewholder 
               // Set Viewholder properties 
               // Add any click listener if any 
           }
           else {
    
               ViewHolderOne vaultItemHolder = (ViewHolderOne) holder;
               vaultItemHolder.name.setText(displayText);
               vaultItemHolder.name.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       .......
                   }
               });
    
           }
    
       }
    
       /****************  VIEW HOLDER 1 ******************//
    
       public class ViewHolderOne extends RecyclerView.ViewHolder {
    
           public TextView name;
    
           public ViewHolderOne(View itemView) {
           super(itemView);
           name = (TextView)itemView.findViewById(R.id.displayName);
           }
       }
    
    
      //****************  VIEW HOLDER 2 ******************//
    
      public class ViewHolderTwo extends RecyclerView.ViewHolder{
    
           public ViewHolderTwo(View itemView) {
           super(itemView);
    
               ..... Do something
           }
      }
    }
    

GitHub Code:

Here is a project where I have implemented a RecyclerView with multiple ViewHolders.

What is the correct way to declare a boolean variable in Java?

There is no reason to do that. In fact, I would choose to combine declaration and initialization as in

final Boolean isMatch = email1.equals (email2);

using the final keyword so you can't change it (accidentally) afterwards anymore either.

Convert DataTable to IEnumerable<T>

        PagedDataSource objPage = new PagedDataSource();

        DataView dataView = listData.DefaultView;
        objPage.AllowPaging = true;
        objPage.DataSource = dataView;
        objPage.PageSize = PageSize;

        TotalPages = objPage.PageCount;

        objPage.CurrentPageIndex = CurrentPage - 1;

        //Convert PagedDataSource to DataTable
        System.Collections.IEnumerator pagedData = objPage.GetEnumerator();

        DataTable filteredData = new DataTable();
        bool flagToCopyDTStruct = false;
        while (pagedData.MoveNext())
        {
            DataRowView rowView = (DataRowView)pagedData.Current;
            if (!flagToCopyDTStruct)
            {
                filteredData = rowView.Row.Table.Clone();
                flagToCopyDTStruct = true;
            }
            filteredData.LoadDataRow(rowView.Row.ItemArray, true);
        }

        //Here is your filtered DataTable
        return filterData; 

Hide strange unwanted Xcode logs

Please find the below steps.

  1. Select Product => Scheme => Edit Scheme or use shortcut : CMD + <
  2. Select the Run option from left side.
  3. On Environment Variables section, add the variable OS_ACTIVITY_MODE = disable

For more information please find the below GIF representation.

Edit Scheme

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

I am not sure if this helps but I had the same problem.

You are using springSecurityFilterChain with CSRF protection. That means you have to send a token when you send a form via POST request. Try to add the next input to your form:

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

What is the purpose of a plus symbol before a variable?

It is a unary "+" operator which yields a numeric expression. It would be the same as d*1, I believe.

Failed to serialize the response in Web API with Json

In my case I have had similar error message:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

But when I dig deeper in it, the issue was:

Type 'name.SomeSubRootType' with data contract name 'SomeSubRootType://schemas.datacontract.org/2004/07/WhatEverService' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.

The way I solved by adding KnownType.

[KnownType(typeof(SomeSubRootType))]
public partial class SomeRootStructureType

This was solved inspired from this answer.

Reference: https://msdn.microsoft.com/en-us/library/ms730167(v=vs.100).aspx

Display Two <div>s Side-by-Side

Try to Use Flex as that is the new standard of html5.

http://jsfiddle.net/maxspan/1b431hxm/

<div id="row1">
    <div id="column1">I am column one</div>
    <div id="column2">I am column two</div>
</div>

#row1{
    display:flex;
    flex-direction:row;
justify-content: space-around;
}

#column1{
    display:flex;
    flex-direction:column;

}


#column2{
    display:flex;
    flex-direction:column;
}

Escaping quotation marks in PHP

Save your text not in a PHP file, but in an ordinary text file called, say, "text.txt"

Then with one simple $text1 = file_get_contents('text.txt'); command have your text with not a single problem.

Parsing JSON objects for HTML table

This one is ugly, but just want to throw there some other options to the mix. This one has no loops. I use it for debugging purposes

var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}
var myStrObj = JSON.stringify(myObject)
var myHtmlTableObj = myStrObj.replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")

$('#myDiv').html(myHtmlTableObj)

Example:

_x000D_
_x000D_
    var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}_x000D_
    var myStrObj = JSON.stringify(myObject)_x000D_
    var myHtmlTableObj = myStrObj.replace(/\"/g,"").replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")_x000D_
_x000D_
    $('#myDiv').html(myHtmlTableObj)
_x000D_
#myDiv table td{background:whitesmoke;border:1px solid lightgray}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div id='myDiv'>table goes here</div>
_x000D_
_x000D_
_x000D_

Array formula on Excel for Mac

  1. Select the desired range of cells
  2. Press Fn + F2 or CONTROL + U
  3. Paste in your array value
  4. Press COMMAND (?) + SHIFT + RETURN

How do I decode a URL parameter using C#?

Server.UrlDecode(xxxxxxxx)

String array initialization in Java

It is just not a valid Java syntax. You can do

names = new String[] {"Ankit","Bohra","Xyz"};

Haskell: Converting Int to String

An example based on Chuck's answer:

myIntToStr :: Int -> String
myIntToStr x
    | x < 3     = show x ++ " is less than three"
    | otherwise = "normal"

Note that without the show the third line will not compile.

Table border left and bottom

Give a class .border-lb and give this CSS

.border-lb {border: 1px solid #ccc; border-width: 0 0 1px 1px;}

And the HTML

<table width="770">
  <tr>
    <td class="border-lb">picture (border only to the left and bottom ) </td>
    <td>text</td>
  </tr>
  <tr>
    <td>text</td>
    <td class="border-lb">picture (border only to the left and bottom) </td>
  </tr>
</table>

Screenshot

Fiddle: http://jsfiddle.net/FXMVL/

IsNull function in DB2 SQL?

COALESCE function same ISNULL function Note. you must use COALESCE function with same data type of column that you check is null.

Add my custom http header to Spring RestTemplate request / extend RestTemplate

If the goal is to have a reusable RestTemplate which is in general useful for attaching the same header to a series of similar request a org.springframework.boot.web.client.RestTemplateCustomizer parameter can be used with a RestTemplateBuilder:

 String accessToken= "<the oauth 2 token>";
 RestTemplate restTemplate = new RestTemplateBuilder(rt-> rt.getInterceptors().add((request, body, execution) -> {
        request.getHeaders().add("Authorization", "Bearer "+accessToken);
        return execution.execute(request, body);
    })).build();

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.

<table>
    <tbody>
        <tr> 
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td> 
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>  
    </tbody>    
</table>?

<script>
    $('tbody').sortable();
</script> 

_x000D_
_x000D_
$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
});
_x000D_
 _x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
}
_x000D_
 _x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>1</td>_x000D_
            <td>2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>3</td>_x000D_
            <td>4</td>_x000D_
        </tr>_x000D_
        <tr> _x000D_
            <td>5</td>_x000D_
            <td>6</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>7</td>_x000D_
            <td>8</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>9</td> _x000D_
            <td>10</td>_x000D_
        </tr>  _x000D_
    </tbody>    _x000D_
</table>
_x000D_
_x000D_
_x000D_

How do I scroll to an element within an overflowed Div?

The above answers will position the inner element at the top of the overflow element even if it's in view inside the overflow element. I didn't want that so I modified it to not change the scroll position if the element is in view.

jQuery.fn.scrollTo = function(elem, speed) {
    var $this = jQuery(this);
    var $this_top = $this.offset().top;
    var $this_bottom = $this_top + $this.height();
    var $elem = jQuery(elem);
    var $elem_top = $elem.offset().top;
    var $elem_bottom = $elem_top + $elem.height();

    if ($elem_top > $this_top && $elem_bottom < $this_bottom) {
        // in view so don't do anything
        return;
    }
    var new_scroll_top;
    if ($elem_top < $this_top) {
        new_scroll_top = {scrollTop: $this.scrollTop() - $this_top + $elem_top};
    } else {
        new_scroll_top = {scrollTop: $elem_bottom - $this_bottom + $this.scrollTop()};
    }
    $this.animate(new_scroll_top, speed === undefined ? 100 : speed);
    return this;
};

Differences between git pull origin master & git pull origin/master

git pull = git fetch + git merge origin/branch

git pull and git pull origin branch only differ in that the latter will only "update" origin/branch and not all origin/* as git pull does.

git pull origin/branch will just not work because it's trying to do a git fetch origin/branch which is invalid.

Question related: git fetch + git merge origin/master vs git pull origin/master

Ternary operator ?: vs if...else

I think that there are situations where the inline if can yield "faster" code because of the scope it works at. Object creation and destruction can be costly so consider the follow scenario :

class A{
    public:
    A() : value(0) {
        cout << "Default ctor" << endl;
    }
    A(int myInt) : value(myInt)
    {
        cout << "Overloaded ctor" << endl;
    }

    A& operator=(const A& other){
        cout << "= operator" << endl;
        value = other.value; 
    }

    ~A(){
        cout << "destroyed" << std::endl;
    }

    int value;

};


int main()
{
   {
       A a;
       if(true){
           a = A(5);
       }else{
           a = A(10);
       }
   }

   cout << "Next test" << endl;
   {
        A b = true? A(5) : A(10);
   }
   return 0;
}

With this code, the output will be :

Default ctor                                                                                                                                                                                                                      
Overloaded ctor                                                                                                                                                                                                                   
= operator                                                                                                                                                                                                                        
destroyed                                                                                                                                                                                                                         
destroyed                                                                                                                                                                                                                         
Next test                                                                                                                                                                                                                         
Overloaded ctor                                                                                                                                                                                                                   
destroyed  

So by inlining the if, we save a bunch of operation needed to keep a alive at the same scope as b. While it is highly probable that the condition evaluation speed is pretty equal in both scenarios, changing scope forces you to take other factors into consideration that the inline if allows you to avoid.

How do I run a simple bit of code in a new thread?

I'd recommend looking at Jeff Richter's Power Threading Library and specifically the IAsyncEnumerator. Take a look at the video on Charlie Calvert's blog where Richter goes over it for a good overview.

Don't be put off by the name because it makes asynchronous programming tasks easier to code.

Add space between two particular <td>s

None of the answers worked for me. The simplest way would be to add <td>s in between with width = 5px and background='white' or whatever the background color of the page is.

Again this will fail in case you have a list of <th>s representing table headers.

Get list of JSON objects with Spring RestTemplate

After multiple tests, this is the best way I found :)

Set<User> test = httpService.get(url).toResponseSet(User[].class);

All you need there

public <T> Set<T> toResponseSet(Class<T[]> setType) {
    HttpEntity<?> body = new HttpEntity<>(objectBody, headers);
    ResponseEntity<T[]> response = template.exchange(url, method, body, setType);
    return Sets.newHashSet(response.getBody());
}

Multiple INSERT statements vs. single INSERT with multiple VALUES

It is not too surprising: the execution plan for the tiny insert is computed once, and then reused 1000 times. Parsing and preparing the plan is quick, because it has only four values to del with. A 1000-row plan, on the other hand, needs to deal with 4000 values (or 4000 parameters if you parameterized your C# tests). This could easily eat up the time savings you gain by eliminating 999 roundtrips to SQL Server, especially if your network is not overly slow.

If statement for strings in python?

proceed = "y", "Y"
if answer in proceed:

Also, you don't want

answer = str(input("Is the information correct? Enter Y for yes or N for no"))

You want

answer = raw_input("Is the information correct? Enter Y for yes or N for no")

input() evaluates whatever is entered as a Python expression, raw_input() returns a string.

Edit: That is only true on Python 2. On Python 3, input is fine, although str() wrapping is still redundant.

When should we use mutex and when should we use semaphore

Trying not to sound zany, but can't help myself.

Your question should be what is the difference between mutex and semaphores ? And to be more precise question should be, 'what is the relationship between mutex and semaphores ?'

(I would have added that question but I'm hundred % sure some overzealous moderator would close it as duplicate without understanding difference between difference and relationship.)

In object terminology we can observe that :

observation.1 Semaphore contains mutex

observation.2 Mutex is not semaphore and semaphore is not mutex.

There are some semaphores that will act as if they are mutex, called binary semaphores, but they are freaking NOT mutex.

There is a special ingredient called Signalling (posix uses condition_variable for that name), required to make a Semaphore out of mutex. Think of it as a notification-source. If two or more threads are subscribed to same notification-source, then it is possible to send them message to either ONE or to ALL, to wakeup.

There could be one or more counters associated with semaphores, which are guarded by mutex. The simple most scenario for semaphore, there is a single counter which can be either 0 or 1.

This is where confusion pours in like monsoon rain.

A semaphore with a counter that can be 0 or 1 is NOT mutex.

Mutex has two states (0,1) and one ownership(task). Semaphore has a mutex, some counters and a condition variable.

Now, use your imagination, and every combination of usage of counter and when to signal can make one kind-of-Semaphore.

  1. Single counter with value 0 or 1 and signaling when value goes to 1 AND then unlocks one of the guy waiting on the signal == Binary semaphore

  2. Single counter with value 0 to N and signaling when value goes to less than N, and locks/waits when values is N == Counting semaphore

  3. Single counter with value 0 to N and signaling when value goes to N, and locks/waits when values is less than N == Barrier semaphore (well if they dont call it, then they should.)

Now to your question, when to use what. (OR rather correct question version.3 when to use mutex and when to use binary-semaphore, since there is no comparison to non-binary-semaphore.) Use mutex when 1. you want a customized behavior, that is not provided by binary semaphore, such are spin-lock or fast-lock or recursive-locks. You can usually customize mutexes with attributes, but customizing semaphore is nothing but writing new semaphore. 2. you want lightweight OR faster primitive

Use semaphores, when what you want is exactly provided by it.

If you dont understand what is being provided by your implementation of binary-semaphore, then IMHO, use mutex.

And lastly read a book rather than relying just on SO.

How to get value of Radio Buttons?

For Win Forms :

To get the value (assuming that you want the value, not the text) out of a radio button, you get the Checked property:

string value = "";
bool isChecked = radioButton1.Checked;
if(isChecked )
  value=radioButton1.Text;
else
  value=radioButton2.Text;

For Web Forms :

<asp:RadioButtonList ID="rdoPriceRange" runat="server" RepeatLayout="Flow">
    <asp:ListItem Value="Male">Male</asp:ListItem>
    <asp:ListItem Value="Female">Female</asp:ListItem>
</asp:RadioButtonList>

And CS-in some button click

string value=rdoPriceRange.SelectedItem.Value.ToString();

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

clear data inside text file in c++

As far as I am aware, simply opening the file in write mode without append mode will erase the contents of the file.

ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append

The first one will place the position bit at the beginning erasing all contents while the second version will place the position bit at the end-of-file bit and write from there.

how to refresh page in angular 2

Just in case someone else encounters this problem. You need to call

window.location.reload()

And you cannot call this from a expression. If you want to call this from a click event you need to put this on a function:

(click)="realodPage()"

And simply define the function:

reloadPage() {
   window.location.reload();
}

If you are changing the route, it might not work because the click event seems to happen before the route changes. A very dirty solution is just to add a small delay

reloadPage() {
    setTimeout(()=>{
      window.location.reload();
    }, 100);
}

How to use z-index in svg elements?

As discussed, svgs render in order and don't take z-index into account (for now). Maybe just send the specific element to the bottom of its parent so that it'll render last.

function bringToTop(targetElement){
  // put the element at the bottom of its parent
  let parent = targetElement.parentNode;
  parent.appendChild(targetElement);
}

// then just pass through the element you wish to bring to the top
bringToTop(document.getElementById("one"));

Worked for me.

Update

If you have a nested SVG, containing groups, you'll need to bring the item out of its parentNode.

function bringToTopofSVG(targetElement){
  let parent = targetElement.ownerSVGElement;
  parent.appendChild(targetElement);
}

A nice feature of SVG's is that each element contains it's location regardless of what group it's nested in :+1:

Html.ActionLink as a button or an image, not a link

Using bootstrap this is the shortest and cleanest approach to create a link to a controller action that appears as a dynamic button:

<a href='@Url.Action("Action", "Controller")' class="btn btn-primary">Click Me</a>

Or to use Html helpers:

@Html.ActionLink("Click Me", "Action", "Controller", new { @class = "btn btn-primary" })

Sending Arguments To Background Worker?

You need RunWorkerAsync(object) method and DoWorkEventArgs.Argument property.

worker.RunWorkerAsync(5);

private void worker_DoWork(object sender, DoWorkEventArgs e) {
    int argument = (int)e.Argument; //5
}

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

It worked to me only using a specific service.

For example instead of use:

compile 'com.google.android.gms:play-services:10.0.1'

I used:

com.google.android.gms:play-services-places:10.0.1

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

Within Spring Boot 2.4 it is

sec:authorize="hasAnyRole('ROLE_ADMIN')

Ensure that you have

thymeleaf-extras-springsecurity5

in your dependencies. Also make sure that you include the namespace

xmlns:sec="http://www.thymeleaf.org/extras/spring-security"

in your html...

How to add manifest permission to an application?

That may be also interesting in context of adding INTERNET permission to your application:

Google has also given each app Internet access, effectively removing the Internet access permission. Oh, sure, Android developers still have to declare they want Internet access when putting together the app. But users can no longer see the Internet access permission when installing an app and current apps that don’t have Internet access can now gain Internet access with an automatic update without prompting you.

Source: http://www.howtogeek.com/190863/androids-app-permissions-were-just-simplified-now-theyre-much-less-secure/

Bottom line is that you still have to add INTERNET permission in manifest file but application will be updated on user's devices without asking them for new permission.

How to remove a key from HashMap while iterating over it?

Try:

Iterator<Map.Entry<String,String>> iter = testMap.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<String,String> entry = iter.next();
    if("Sample".equalsIgnoreCase(entry.getValue())){
        iter.remove();
    }
}

With Java 1.8 and onwards you can do the above in just one line:

testMap.entrySet().removeIf(entry -> "Sample".equalsIgnoreCase(entry.getValue()));

Git pull after forced update

This won't fix branches that already have the code you don't want in them (see below for how to do that), but if they had pulled some-branch and now want it to be clean (and not "ahead" of origin/some-branch) then you simply:

git checkout some-branch   # where some-branch can be replaced by any other branch
git branch base-branch -D  # where base-branch is the one with the squashed commits
git checkout -b base-branch origin/base-branch  # recreating branch with correct commits

Note: You can combine these all by putting && between them

Note2: Florian mentioned this in a comment, but who reads comments when looking for answers?

Note3: If you have contaminated branches, you can create new ones based off the new "dumb branch" and just cherry-pick commits over.

Ex:

git checkout feature-old  # some branch with the extra commits
git log                   # gives commits (write down the id of the ones you want)
git checkout base-branch  # after you have already cleaned your local copy of it as above
git checkout -b feature-new # make a new branch for your feature
git cherry-pick asdfasd   # where asdfasd is one of the commit ids you want
# repeat previous step for each commit id
git branch feature-old -D # delete the old branch

Now feature-new is your branch without the extra (possibly bad) commits!

What's the use of session.flush() in Hibernate

Flushing the Session gets the data that is currently in the session synchronized with what is in the database.

More on the Hibernate website:

flush() is useful, because there are absolutely no guarantees about when the Session executes the JDBC calls, only the order in which they are executed - except you use flush().

What is the difference between varchar and varchar2 in Oracle?

Currently, they are the same. but previously

  1. Somewhere on the net, I read that,

VARCHAR is reserved by Oracle to support distinction between NULL and empty string in future, as ANSI standard prescribes.

VARCHAR2 does not distinguish between a NULL and empty string, and never will.

  1. Also,

Emp_name varchar(10) - if you enter value less than 10 digits then remaining space cannot be deleted. it used total of 10 spaces.

Emp_name varchar2(10) - if you enter value less than 10 digits then remaining space is automatically deleted

Python: Writing to and Reading from serial port

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()

How to sort with a lambda?

To much code, you can use it like this:

#include<array>
#include<functional>

int main()
{
    std::array<int, 10> vec = { 1,2,3,4,5,6,7,8,9 };

    std::sort(std::begin(vec), 
              std::end(vec), 
              [](int a, int b) {return a > b; });

    for (auto item : vec)
      std::cout << item << " ";

    return 0;
}

Replace "vec" with your class and that's it.

How do I convert NSInteger to NSString datatype?

You can also try:

NSInteger month = 1;
NSString *inStr = [NSString stringWithFormat: @"%ld", month];

Differences between Microsoft .NET 4.0 full Framework and Client Profile

Cameron MacFarland nailed it.

I'd like to add that the .NET 4.0 client profile will be included in Windows Update and future Windows releases. Expect most computers to have the client profile, not the full profile. Do not underestimate that fact if you're doing business-to-consumer (B2C) sales.

Fastest way to check if a file exist using standard C++/C++11/C?

For those who like boost:

 boost::filesystem::exists(fileName)

What is the 'instanceof' operator used for in Java?

class Test48{
public static void main (String args[]){
Object Obj=new Hello();
//Hello obj=new Hello;
System.out.println(Obj instanceof String);
System.out.println(Obj instanceof Hello);
System.out.println(Obj instanceof Object);
Hello h=null;
System.out.println(h instanceof Hello);
System.out.println(h instanceof Object);
}
}  

Compile c++14-code with g++

For gcc 4.8.4 you need to use -std=c++1y in later versions, looks like starting with 5.2 you can use -std=c++14.

If we look at the gcc online documents we can find the manuals for each version of gcc and we can see by going to Dialect options for 4.9.3 under the GCC 4.9.3 manual it says:

‘c++1y’

The next revision of the ISO C++ standard, tentatively planned for 2014. Support is highly experimental, and will almost certainly change in incompatible ways in future releases.

So up till 4.9.3 you had to use -std=c++1y while the gcc 5.2 options say:

‘c++14’ ‘c++1y’

The 2014 ISO C++ standard plus amendments. The name ‘c++1y’ is deprecated.

It is not clear to me why this is listed under Options Controlling C Dialect but that is how the documents are currently organized.

HTTP requests and JSON parsing in Python

Try this:

import requests
import json

# Goole Maps API.
link = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'

# Request data from link as 'str'
data = requests.get(link).text

# convert 'str' to Json
data = json.loads(data)

# Now you can access Json 
for i in data['routes'][0]['legs'][0]['steps']:
    lattitude = i['start_location']['lat']
    longitude = i['start_location']['lng']
    print('{}, {}'.format(lattitude, longitude))

Please initialize the log4j system properly. While running web service

If the below statment is present in your class then your log4j.properties should be in java source(src) folder , if it is jar executable it should be packed in jar not a seperate file.

static Logger log = Logger.getLogger(MyClass.class);

Thanks,

Alternative for PHP_excel

I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.

http://github.com/elidickinson/php-export-data

How to set ssh timeout?

You could also connect with flag

-o ServerAliveInterval=<secs>
so the SSH client will send a null packet to the server each <secs> seconds, just to keep the connection alive. In Linux this could be also set globally in /etc/ssh/ssh_config or per-user in ~/.ssh/config.

Android Fastboot devices not returning device

Are you rebooting the device into the bootloader and entering fastboot USB on the bootloader menu?

Try

adb reboot bootloader

then look for on screen instructions to enter fastboot mode.

nuget 'packages' element is not declared warning

The problem is, you need a xsd schema for packages.config.

This is how you can create a schema (I found it here):

Open your Config file -> XML -> Create Schema

enter image description here

This would create a packages.xsd for you, and opens it in Visual Studio:

enter image description here

In my case, packages.xsd was created under this path:

C:\Users\MyUserName\AppData\Local\Temp

Now I don't want to reference the packages.xsd from a Temp folder, but I want it to be added to my solution and added to source control, so other users can get it... so I copied packages.xsd and pasted it into my solution folder. Then I added the file to my solution:

1. Copy packages.xsd in the same folder as your solution

2. From VS, right click on solution -> Add -> Existing Item... and then add packages.xsd

enter image description here

So, now we have created packages.xsd and added it to the Solution. All we need to do is to tell the config file to use this schema.

Open the config file, then from the top menu select:

XML -> Schemas...

Add your packages.xsd, and select Use this schema (see below)

enter image description here

java.io.FileNotFoundException: (Access is denied)

Also, in some cases is important to check the target folder permissions. To give write permission for the user might be the solution. That worked for me.

ANTLR: Is there a simple example?

For Antlr 4 the java code generation process is below:-

java -cp antlr-4.5.3-complete.jar org.antlr.v4.Tool Exp.g

Update your jar name in classpath accordingly.

How to do a batch insert in MySQL

mysql allows you to insert multiple rows at once INSERT manual

Splitting a string into separate variables

Like this?

$string = 'FirstPart SecondPart'
$a,$b = $string.split(' ')
$a
$b