Programs & Examples On #Mdsd

How to get the latest file in a folder?

A much faster method on windows (0.05s), call a bat script that does this:

get_latest.bat

@echo off
for /f %%i in ('dir \\directory\in\question /b/a-d/od/t:c') do set LAST=%%i
%LAST%

where \\directory\in\question is the directory you want to investigate.

get_latest.py

from subprocess import Popen, PIPE
p = Popen("get_latest.bat", shell=True, stdout=PIPE,)
stdout, stderr = p.communicate()
print(stdout, stderr)

if it finds a file stdout is the path and stderr is None.

Use stdout.decode("utf-8").rstrip() to get the usable string representation of the file name.

Why do we need C Unions?

Use a union when you have some function where you return a value that can be different depending on what the function did.

How to install beautiful soup 4 with python 2.7 on windows

You don't need pip for installing Beautiful Soup - you can just download it and run python setup.py install from the directory that you have unzipped BeautifulSoup in (assuming that you have added Python to your system PATH - if you haven't and you don't want to you can run C:\Path\To\Python27\python "C:\Path\To\BeautifulSoup\setup.py" install)

However, you really should install pip - see How to install pip on Windows for how to do that best (via @MartijnPieters comment)

Adjust list style image position?

Or you can use

list-style-position: inside;

How to delete the contents of a folder?

This:

  • removes all symbolic links
    • dead links
    • links to directories
    • links to files
  • removes subdirectories
  • does not remove the parent directory

Code:

for filename in os.listdir(dirpath):
    filepath = os.path.join(dirpath, filename)
    try:
        shutil.rmtree(filepath)
    except OSError:
        os.remove(filepath)

As many other answers, this does not try to adjust permissions to enable removal of files/directories.

Oracle: how to add minutes to a timestamp?

To edit Date in oracle you can try

  select to_char(<columnName> + 5 / 24 + 30 / (24 * 60),
           'DD/MM/RRRR hh:mi AM') AS <logicalName> from <tableName>

How would you implement an LRU cache in Java?

LinkedHashMap is O(1), but requires synchronization. No need to reinvent the wheel there.

2 options for increasing concurrency:

1. Create multiple LinkedHashMap, and hash into them: example: LinkedHashMap[4], index 0, 1, 2, 3. On the key do key%4 (or binary OR on [key, 3]) to pick which map to do a put/get/remove.

2. You could do an 'almost' LRU by extending ConcurrentHashMap, and having a linked hash map like structure in each of the regions inside of it. Locking would occur more granularly than a LinkedHashMap that is synchronized. On a put or putIfAbsent only a lock on the head and tail of the list is needed (per region). On a remove or get the whole region needs to be locked. I'm curious if Atomic linked lists of some sort might help here -- probably so for the head of the list. Maybe for more.

The structure would not keep the total order, but only the order per region. As long as the number of entries is much larger than the number of regions, this is good enough for most caches. Each region will have to have its own entry count, this would be used rather than the global count for the eviction trigger. The default number of regions in a ConcurrentHashMap is 16, which is plenty for most servers today.

  1. would be easier to write and faster under moderate concurrency.

  2. would be more difficult to write but scale much better at very high concurrency. It would be slower for normal access (just as ConcurrentHashMap is slower than HashMap where there is no concurrency)

Excel tab sheet names vs. Visual Basic sheet names

I think I may have an alternative solution. It's a little ugly, but it seems to work.

Function GetAnyNameValue(NameofName) As String
    Dim nm, ws, rng As String
    nm = ActiveWorkbook.Names(NameofName).Value
    ws = CStr(Split(nm, "!")(0))
    ws = Replace(ws, "'", "")
    ws = Replace(ws, "=", "")
    rng = CStr(Split(nm, "!")(1))
    GetAnyNameValue = CStr(Worksheets(ws).Range(rng).Value)
End Function

Performing a query on a result from another query?

You just wrap your query in another one:

SELECT COUNT(*), SUM(Age)
FROM (
    SELECT availables.bookdate AS Count, DATEDIFF(now(),availables.updated_at) as Age
    FROM availables
    INNER JOIN rooms
    ON availables.room_id=rooms.id
    WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
    GROUP BY availables.bookdate
) AS tmp;

Can I get "&&" or "-and" to work in PowerShell?

I tried this sequence of commands in PowerShell:

First Test

PS C:\> $MyVar = "C:\MyTxt.txt"
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
True

($MyVar -ne $null) returned true and (Get-Content $MyVar) also returned true.

Second Test

PS C:\> $MyVar = $null
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
False

($MyVar -ne $null) returned false and so far I must assume the (Get-Content $MyVar) also returned false.

The third test proved the second condition was not even analyzed.

PS C:\> ($MyVar -ne $null) -and (Get-Content "C:\MyTxt.txt")
False

($MyVar -ne $null) returned false and proved the second condition (Get-Content "C:\MyTxt.txt") never ran, by returning false on the whole command.

How to Remove Array Element and Then Re-Index Array?

array_splice($array, array_search(array_value, $array), 1);

Resize a picture to fit a JLabel

Outline

Here are the steps to follow.

  • Read the picture as a BufferedImage.
  • Resize the BufferedImage to another BufferedImage that's the size of the JLabel.
  • Create an ImageIcon from the resized BufferedImage.

You do not have to set the preferred size of the JLabel. Once you've scaled the image to the size you want, the JLabel will take the size of the ImageIcon.

Read the picture as a BufferedImage

BufferedImage img = null;
try {
    img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}

Resize the BufferedImage

Image dimg = img.getScaledInstance(label.getWidth(), label.getHeight(),
        Image.SCALE_SMOOTH);

Make sure that the label width and height are the same proportions as the original image width and height. In other words, if the picture is 600 x 900 pixels, scale to 100 X 150. Otherwise, your picture will be distorted.

Create an ImageIcon

ImageIcon imageIcon = new ImageIcon(dimg);

How can I escape white space in a bash loop list?

Here is a simple solution which handles tabs and/or whitespaces in the filename. If you have to deal with other strange characters in the filename like newlines, pick another answer.

The test directory

ls -F test
Baltimore/  Cherry Hill/  Edison/  New York City/  Philadelphia/  cities.txt

The code to go into the directories

find test -type d | while read f ; do
  echo "$f"
done

The filename must be quoted ("$f") if used as argument. Without quotes, the spaces act as argument separator and multiple arguments are given to the invoked command.

And the output:

test/Baltimore
test/Cherry Hill
test/Edison
test/New York City
test/Philadelphia

Passing references to pointers in C++

The problem is that you're trying to bind a temporary to the reference, which C++ doesn't allow unless the reference is const.

So you can do one of either the following:

void myfunc(string*& val)
{
    // Do stuff to the string pointer
}


void myfunc2(string* const& val)
{
    // Do stuff to the string pointer
}

int main()
// sometime later 
{
    // ...
    string s;
    string* ps = &s;

    myfunc( ps);   // OK because ps is not a temporary
    myfunc2( &s);  // OK because the parameter is a const&
    // ...

    return 0;
}

Select and display only duplicate records in MySQL

SELECT id, payer_email
FROM paypal_ipn_orders
WHERE payer_email IN (
    SELECT payer_email
    FROM paypal_ipn_orders
    GROUP BY payer_email
    HAVING COUNT(id) > 1
)

sqlfiddle

Set Label Text with JQuery

You can try:

<label id ="label_id"></label>
 $("#label_id").html('value');

WCF error: The caller was not authenticated by the service

set anonymous access in your virtual directory

write following credentials to your service

ADTService.ServiceClient adtService = new ADTService.ServiceClient();
adtService.ClientCredentials.Windows.ClientCredential.UserName="windowsuseraccountname";
adtService.ClientCredentials.Windows.ClientCredential.Password="windowsuseraccountpassword";
adtService.ClientCredentials.Windows.ClientCredential.Domain="windowspcname";

after that you call your webservice methods.

LINQ to read XML

Try this.

using System.Xml.Linq;

void Main()
{
    StringBuilder result = new StringBuilder();

    //Load xml
    XDocument xdoc = XDocument.Load("data.xml");

    //Run query
    var lv1s = from lv1 in xdoc.Descendants("level1")
               select new { 
                   Header = lv1.Attribute("name").Value,
                   Children = lv1.Descendants("level2")
               };

    //Loop through results
    foreach (var lv1 in lv1s){
            result.AppendLine(lv1.Header);
            foreach(var lv2 in lv1.Children)
                 result.AppendLine("     " + lv2.Attribute("name").Value);
    }

    Console.WriteLine(result);
}

How can I change the thickness of my <hr> tag

Sub-pixel rendering in browsers

Sub-pixel rendering is tricky. You can't actually expect a monitor to render a less than a pixel thin line. But it's possible to provide sub-pixel dimensions. Depending on the browser they render these differently. Check this John Resig's blog post about it.

Basically if your monitor is an LCD and you're drawing vertical lines, you can easily draw a 1/3 pixel line. If your background is white, give your line colour of #f0f. To the eye this line will be 1/3 of pixel wide. Although it will be of some colour, if you'd magnify monitor, you'd see that only one segment of the whole pixel (consisting of RGB) will be dark. This is pretty much technique that's used for fine type hinting i.e. ClearType.

But horizontal lines can only be a full pixel high. That's technology limitation of LCD monitors. CRTs were even more complicated with their triangular phosphors (unless they were aperture grille type ie. Sony Trinitron) but that's a different story.

Basically providing a sub-pixel dimension and expecting it to render that way is same as expecting an integer variable to store a number of 1.2034759349. If you understand this is impossible, you should understand that monitors aren't able to render sub-pixel dimensions.

Cross browser safe style

But the way horizontal rules that blend in are usually done using colours. So if your background is for instance white (#fff) you can always make your HR very light. Like #eee.

The cross browser safe style for very light horizontal rule would be:

hr
{
    background-color: #eee;
    border: 0 none;
    color: #eee;
    height: 1px;
}

And use a CSS file instead of in-line styles. They provide a central definition for the whole site not just a particular element. It makes maintainability much better.

Load data from txt with pandas

you can use this

import pandas as pd
dataset=pd.read_csv("filepath.txt",delimiter="\t")

Numbering rows within groups in a data frame

Another base R solution would be to split the data frame per cat, after that using lapply: add a column with number 1:nrow(x). The last step is to have your final data frame back with do.call, that is:

        df_split <- split(df, df$cat)
        df_lapply <- lapply(df_split, function(x) {
          x$num <- seq_len(nrow(x))
          return(x)
        })
        df <- do.call(rbind, df_lapply)

HTML5 Local storage vs. Session storage

sessionStorage is the same as localStorage, except that it stores the data for only one session, and it will be removed when the user closes the browser window that created it.

Is there an equivalent of CSS max-width that works in HTML emails?

The short answer: no.

The long answer:

Fixed formats work better for HTML emails. In my experience you're best off pretending it's 1999 when it comes to HTML emails. Be explicit and use HTML attributes (width="650") where ever possible in your table definitions, not CSS (style="width:650px"). Use fixed widths, no percentages. A table width of 650 pixels wide is a safe bet. Use inline CSS to set text properties.

It's not a matter of what works in "HTML emails", but rather the plethora of email clients and their limited (and sometimes deliberately so in the case of Gmail, Hotmail etc) ability to render HTML.

MySql Query Replace NULL with Empty String in Select

Some of these built in functions should work:

Coalesce
Is Null
IfNull

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

works great!

using both ways seem to be unnecessary now:

execBtn.onclick = function() { runCommand() };

apparently works in every current browser.

tested in current Firefox, IE, Safari, Opera, Chrome on Windows; Firefox and Epiphany on Ubuntu; not tested on Mac or mobile systems.

  • Craig: I'd try "document.getElementById(ID).type='password';
  • Has anyone checked the "AddEventListener" approach with different engines?

Regex for parsing directory and filename

Try this:

^(.+)\/([^\/]+)$

EDIT: escaped the forward slash to prevent problems when copy/pasting the Regex

Add Foreign Key to existing table

 ALTER TABLE TABLENAME ADD FOREIGN KEY (Column Name) REFERENCES TableName(column name)

Example:-

ALTER TABLE Department ADD FOREIGN KEY (EmployeeId) REFERENCES Employee(EmployeeId)

Set HTML dropdown selected option using JSTL

Assuming that you have a collection ${roles} of the elements to put in the combo, and ${selected} the selected element, It would go like this:

<select name='role'>
    <option value="${selected}" selected>${selected}</option>
    <c:forEach items="${roles}" var="role">
        <c:if test="${role != selected}">
            <option value="${role}">${role}</option>
        </c:if>
    </c:forEach>
</select>

UPDATE (next question)

You are overwriting the attribute "productSubCategoryName". At the end of the for loop, the last productSubCategoryName.

Because of the limitations of the expression language, I think the best way to deal with this is to use a map:

Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    map.put(productSubCategoryName, true);
}
request.setAttribute("productSubCategoryMap", map);

And then in the JSP:

<select multiple="multiple" name="prodSKUs">
    <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
        <option value="${productSubCategoryList}" ${not empty productSubCategoryMap[productSubCategoryList] ? 'selected' : ''}>${productSubCategoryList}</option>
    </c:forEach>
</select>

HTML form readonly SELECT tag/input

In an option you can use disabled="disabled", instead of on the select itself

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

put a int infront of the all the voxelCoord's...Like this below :

patch = numpyImage [int(voxelCoord[0]),int(voxelCoord[1])- int(voxelWidth/2):int(voxelCoord[1])+int(voxelWidth/2),int(voxelCoord[2])-int(voxelWidth/2):int(voxelCoord[2])+int(voxelWidth/2)]

Is Fortran easier to optimize than C for heavy calculations?

Fortran has better I/O routines, e.g. the implied do facility gives flexibility that C's standard library can't match.

The Fortran compiler directly handles the more complex syntax involved, and as such syntax can't be easily reduced to argument passing form, C can't implement it efficiently.

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

AngularJS: How to clear query parameters in the URL?

I've tried the above answers but could not get them to work. The only code that worked for me was $window.location.search = ''

PHP Checking if the current date is before or after a set date

If you are looking for a generic way of doing this via MySQL, you could simply use a SELECT statement, and add the WHERE clause to it.

This will grab all fields for all rows, where the date stored in field "date" is before "now".

SELECT * FROM table WHERE UNIX_TIMESTAMP(`date`) < UNIX_TIMESTAMP()

Personally, I found this method to be more gentle on newbies in MySQL, since it uses the standard SELECT statement with WHERE to fetch the results. Obviously, you could grab only the fields relevant if you wanted to, by listing them instead of using a wildcard (*).

Does static constexpr variable inside a function make sense?

The short answer is that not only is static useful, it is pretty well always going to be desired.

First, note that static and constexpr are completely independent of each other. static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.

Every variable declared constexpr is implicitly const but const and static are almost orthogonal (except for the interaction with static const integers.)

The C++ object model (§1.9) requires that all objects other than bit-fields occupy at least one byte of memory and have addresses; furthermore all such objects observable in a program at a given moment must have distinct addresses (paragraph 6). This does not quite require the compiler to create a new array on the stack for every invocation of a function with a local non-static const array, because the compiler could take refuge in the as-if principle provided it can prove that no other such object can be observed.

That's not going to be easy to prove, unfortunately, unless the function is trivial (for example, it does not call any other function whose body is not visible within the translation unit) because arrays, more or less by definition, are addresses. So in most cases, the non-static const(expr) array will have to be recreated on the stack at every invocation, which defeats the point of being able to compute it at compile time.

On the other hand, a local static const object is shared by all observers, and furthermore may be initialized even if the function it is defined in is never called. So none of the above applies, and a compiler is free not only to generate only a single instance of it; it is free to generate a single instance of it in read-only storage.

So you should definitely use static constexpr in your example.

However, there is one case where you wouldn't want to use static constexpr. Unless a constexpr declared object is either ODR-used or declared static, the compiler is free to not include it at all. That's pretty useful, because it allows the use of compile-time temporary constexpr arrays without polluting the compiled program with unnecessary bytes. In that case, you would clearly not want to use static, since static is likely to force the object to exist at runtime.

Bootstrap select dropdown list placeholder

dropdown or select doesn't have a placeholder because HTML doesn't support it but it's possible to create same effect so it looks the same as other inputs placeholder

_x000D_
_x000D_
    $('select').change(function() {_x000D_
     if ($(this).children('option:first-child').is(':selected')) {_x000D_
       $(this).addClass('placeholder');_x000D_
     } else {_x000D_
      $(this).removeClass('placeholder');_x000D_
     }_x000D_
    });
_x000D_
.placeholder{color: grey;}_x000D_
select option:first-child{color: grey; display: none;}_x000D_
select option{color: #555;} // bootstrap default color
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select class="form-control placeholder">_x000D_
   <option value="">Your Placeholder Text</option>_x000D_
   <option value="1">Text 1</option>_x000D_
   <option value="2">Text 2</option>_x000D_
   <option value="3">Text 3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

if you want to see first option in list remove display property from css

How to get active user's UserDetails

While Ralphs Answer provides an elegant solution, with Spring Security 3.2 you no longer need to implement your own ArgumentResolver.

If you have a UserDetails implementation CustomUser, you can just do this:

@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@AuthenticationPrincipal CustomUser customUser) {

    // .. find messages for this User and return them...
}

See Spring Security Documentation: @AuthenticationPrincipal

Javascript - User input through HTML input tag to set a Javascript variable?

I tried to send/add input tag's values into JavaScript variable which worked well for me, here is the code:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function changef()
            {
            var ctext=document.getElementById("c").value;

            document.writeln(ctext);
            }

        </script>
    </head>
    <body>
        <input type="text" id="c" onchange="changef"();>

        <button type="button" onclick="changef()">click</button>
    </body> 
</html>

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

What's the canonical way to check for type in Python?

To Hugo:

You probably mean list rather than array, but that points to the whole problem with type checking - you don't want to know if the object in question is a list, you want to know if it's some kind of sequence or if it's a single object. So try to use it like a sequence.

Say you want to add the object to an existing sequence, or if it's a sequence of objects, add them all

try:
   my_sequence.extend(o)
except TypeError:
  my_sequence.append(o)

One trick with this is if you are working with strings and/or sequences of strings - that's tricky, as a string is often thought of as a single object, but it's also a sequence of characters. Worse than that, as it's really a sequence of single-length strings.

I usually choose to design my API so that it only accepts either a single value or a sequence - it makes things easier. It's not hard to put a [ ] around your single value when you pass it in if need be.

(Though this can cause errors with strings, as they do look like (are) sequences.)

What is Options +FollowSymLinks?

How does the server know that it should pull image.png from the /pictures folder when you visit the website and browse to the /system/files/images folder in your web browser? A so-called symbolic link is the guy that is responsible for this behavior. Somewhere in your system, there is a symlink that tells your server "If a visitor requests /system/files/images/image.png then show him /pictures/image.png."

And what is the role of the FollowSymLinks setting in this?

FollowSymLinks relates to server security. When dealing with web servers, you can't just leave things undefined. You have to tell who has access to what. The FollowSymLinks setting tells your server whether it should or should not follow symlinks. In other words, if FollowSymLinks was disabled in our case, browsing to the /system/files/images/image.png file would return depending on other settings either the 403 (access forbidden) or 404 (not found) error.

http://www.maxi-pedia.com/FollowSymLinks

How to secure database passwords in PHP?

Actually, the best practice is to store your database crendentials in environment variables because :

  • These credentials are dependant to environment, it means that you won't have the same credentials in dev/prod. Storing them in the same file for all environment is a mistake.
  • Credentials are not related to business logic which means login and password have nothing to do in your code.
  • You can set environment variables without creating any business code class file, which means you will never make the mistake of adding the credential files to a commit in Git.
  • Environments variables are superglobales : you can use them everywhere in your code without including any file.

How to use them ?

  • Using the $_ENV array :
    • Setting : $_ENV['MYVAR'] = $myvar
    • Getting : echo $_ENV["MYVAR"]
  • Using the php functions :
  • In vhosts files and .htaccess but it's not recommended since its in another file and its not resolving the problem by doing it this way.

You can easily drop a file such as envvars.php with all environment variables inside and execute it (php envvars.php) and delete it. It's a bit old school, but it still work and you don't have any file with your credentials in the server, and no credentials in your code. Since it's a bit laborious, frameworks do it better.

Example with Symfony (ok its not only PHP) The modern frameworks such as Symfony recommends using environment variables, and store them in a .env not commited file or directly in command lines which means you wether can do :

Documentation :

How to read if a checkbox is checked in PHP?

$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;

How to get the device's IMEI/ESN programmatically in android?

Use below code gives you IMEI number:

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
System.out.println("IMEI::" + telephonyManager.getDeviceId());

How can I Insert data into SQL Server using VBNet

It means that the number of values specified in your VALUES clause on the INSERT statement is not equal to the total number of columns in the table. You must specify the columnname if you only try to insert on selected columns.

Another one, since you are using ADO.Net , always parameterized your query to avoid SQL Injection. What you are doing right now is you are defeating the use of sqlCommand.

ex

Dim query as String = String.Empty
query &= "INSERT INTO student (colName, colID, colPhone, "
query &= "                     colBranch, colCourse, coldblFee)  "
query &= "VALUES (@colName,@colID, @colPhone, @colBranch,@colCourse, @coldblFee)"

Using conn as New SqlConnection("connectionStringHere")
    Using comm As New SqlCommand()
        With comm
            .Connection = conn
            .CommandType = CommandType.Text
            .CommandText = query
            .Parameters.AddWithValue("@colName", strName)
            .Parameters.AddWithValue("@colID", strId)
            .Parameters.AddWithValue("@colPhone", strPhone)
            .Parameters.AddWithValue("@colBranch", strBranch)
            .Parameters.AddWithValue("@colCourse", strCourse)
            .Parameters.AddWithValue("@coldblFee", dblFee)
        End With
        Try
            conn.open()
            comm.ExecuteNonQuery()
        Catch(ex as SqlException)
            MessageBox.Show(ex.Message.ToString(), "Error Message")
        End Try
    End Using
End USing 

PS: Please change the column names specified in the query to the original column found in your table.

Refused to apply inline style because it violates the following Content Security Policy directive

Well, I think it is too late and many others have the solution so far.

But I hope this can Help:

I'm using react for an identity server so 'unsafe-inline' is not an option at all. If you look at your console and actually read the CSP docs, you might find that there are three options for solving the issue:

  1. 'unsafe-inline' as it says is unsafe if your project is using CSPs is for one reason and it is like throwing out the complete policy, will be the same to no have CSP policy at all

    1. 'sha-XXXCODE' this is good, safe but not optimal because there is a lot of manual work and every compilation the SHA might change so it will become easily a nightmare, use only when the script or style is unlikely to change and there are few references

    2. Nonce. This is the winner!

Nonce works in the similar way as scripts

CSP HEADER ///csp stuff nonce-12331

<script nonce="12331">
   //script content
</script>

Because the nonce in the csp is the same that the tag, the script will be executed

In the case of inline styles, the nonce also came in the form of attribute so the same rules apply.

so generate the nonce and put it on your inline scritps

If you are using webpack maybe you are using the style-loader

the following code will do the trick


module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          {
            loader: 'style-loader',
            options: {
              attributes: {
                nonce: '12345678',
              },
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

How to make a select with array contains value clause in psql

Note that this may also work:

SELECT * FROM table WHERE s=ANY(array)

Unable to copy ~/.ssh/id_rsa.pub

Have read the documentation you've linked. That's totally silly! xclip is just a clipboard. You'll find other ways to copy paste the key... (I'm sure)


If you aren't working from inside a graphical X session you need to pass the $DISPLAY environment var to the command. Run it like this:

DISPLAY=:0 xclip -sel clip < ~/.ssh/id_rsa.pub

Of course :0 depends on the display you are using. If you have a typical desktop machine it is likely that it is :0

Pass row number as variable in excel sheet

Assuming your row number is in B1, you can use INDIRECT:

=INDIRECT("A" & B1)

This takes a cell reference as a string (in this case, the concatenation of A and the value of B1 - 5), and returns the value at that cell.

Output single character in C

yes, %c will print a single char:

printf("%c", 'h');

also, putchar/putc will work too. From "man putchar":

#include <stdio.h>

int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);

* fputc() writes the character c, cast to an unsigned char, to stream.
* putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.
* putchar(c); is equivalent to putc(c,stdout).

EDIT:

Also note, that if you have a string, to output a single char, you need get the character in the string that you want to output. For example:

const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */

Phone: numeric keyboard for text input

Using the type="email" or type="url" will give you a keyboard on some phones at least, such as iPhone. For phone numbers, you can use type="tel".

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

A little more robust version of what you're attempting:

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

How do you keep parents of floated elements from collapsing?

Another possible solution which I think is more semantically correct is to change the floated inner elements to be 'display: inline'. This example and what I was working on when I came across this page both use floated divs in much exactly the same way that a span would be used. Instead of using divs, switch to span, or if you are using another element which is by default 'display: block' instead of 'display: inline' then change it to be 'display: inline'. I believe this is the 100% semantically correct solution.

Solution 1, floating the parent, is essentially to change the entire document to be floated.

Solution 2, setting an explicit height, is like drawing a box and saying I want to put a picture here, i.e. use this if you are doing an img tag.

Solution 3, adding a spacer to clear float, is like adding an extra line below your content and will mess with surrounding elements too. If you use this approach you probably want to set the div to be height: 0px.

Solution 4, overflow: auto, is acknowledging that you don't know how to lay out the document and you are admitting that you don't know what to do.

Create list of object from another using Java 8 Streams

What you are possibly looking for is map(). You can "convert" the objects in a stream to another by mapping this way:

...
 .map(userMeal -> new UserMealExceed(...))
...

How do I determine whether an array contains a particular value in Java?

Arrays.asList(yourArray).contains(yourValue)

Warning: this doesn't work for arrays of primitives (see the comments).


Since you can now use Streams.

String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);

To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.

Example

int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);

How can you print a variable name in python?

You can't, as there are no variables in Python but only names.

For example:

> a = [1,2,3]
> b = a
> a is b
True

Which of those two is now the correct variable? There's no difference between a and b.

There's been a similar question before.

How to write to file in Ruby?

Zambri's answer found here is the best.

File.open("out.txt", '<OPTION>') {|f| f.write("write your stuff here") }

where your options for <OPTION> are:

r - Read only. The file must exist.

w - Create an empty file for writing.

a - Append to a file.The file is created if it does not exist.

r+ - Open a file for update both reading and writing. The file must exist.

w+ - Create an empty file for both reading and writing.

a+ - Open a file for reading and appending. The file is created if it does not exist.

In your case, w is preferable.

Same Navigation Drawer in different Activities

For anyone else looking to do what the original poster is asking, please consider to use fragments instead the way Kevin said. Here is an excellent tutorial on how to do that:

https://github.com/codepath/android_guides/wiki/Fragment-Navigation-Drawer

If you choose to instead use activities instead of fragments you are going to run into the problem of the nav drawer being re-created every time you navigate to a new activity. This results in an ugly/slow rendering of the nav drawer each time.

Input button target="_blank" isn't causing the link to load in a new window/tab

<form target="_blank">
    <button class="btn btn-primary" formaction="http://www.google.com">Google</button>
</form>

Convert text into number in MySQL query

Simply use CAST,

CAST(column_name AS UNSIGNED)

The type for the cast result can be one of the following values:

BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

Had the same issue on windows XP. Resolved. The error was caused due to the system log being full. Control Panel -> Administrative Tools -> Event viewer Right click on application log, clear all events, optionaly save the log. Same process for system log. Restart and it should work.

Git: How to commit a manually deleted file?

Use git add -A, this will include the deleted files.

Note: use git rm for certain files.

plot different color for different categorical levels using matplotlib

You can convert the categorical column into a numerical one by using the commands:

#we converting it into categorical data
cat_col = df['column_name'].astype('categorical') 

#we are getting codes for it 
cat_col = cat_col.cat.codes 

# we are using c parameter to change the color.
plt.scatter(df['column1'],df['column2'], c=cat_col) 

How can I check if character in a string is a letter? (Python)

You can use str.isalpha().

For example:

s = 'a123b'

for char in s:
    print(char, char.isalpha())

Output:

a True
1 False
2 False
3 False
b True

libclntsh.so.11.1: cannot open shared object file.

Possibly you want to specify PATH — and also ORACLE_HOME and LD_LIBRARY_PATH — so that cron(1) knows where to find binaries.
Read "5 Crontab environment" here.

Navigation Controller Push View Controller

Create the navigation controller first and provide it as rootViewController of your window object.

Build not visible in itunes connect

You can see all of your activities (recently uploaded builds here). It will also provide current status of your build.

ImportError: No module named 'encodings'

For Python-3 try removing virtual environment files. And resetting it up.

rm -rf venv
virtualenv -p /usr/bin/python3 venv/
source venv/bin/activate
pip install -r requirements.txt

https://wiki.ubuntu.com/XenialXerus/ReleaseNotes#Python_3 edit fo

Why does range(start, end) not include end?

Exclusive ranges do have some benefits:

For one thing each item in range(0,n) is a valid index for lists of length n.

Also range(0,n) has a length of n, not n+1 which an inclusive range would.

Separation of business logic and data access in django

I'm mostly agree with chosen answer (https://stackoverflow.com/a/12857584/871392), but want to add option in Making Queries section.

One can define QuerySet classes for models for make filter queries and so on. After that you can proxy this queryset class for model's manager, like build-in Manager and QuerySet classes do.

Although, if you had to query several data models to get one domain model, it seems more reasonable to me to put this in separate module like suggested before.

How to get the difference between two arrays in JavaScript?

//es6 approach

function diff(a, b) {
  var u = a.slice(); //dup the array
  b.map(e => {
    if (u.indexOf(e) > -1) delete u[u.indexOf(e)]
    else u.push(e)   //add non existing item to temp array
  })
  return u.filter((x) => {return (x != null)}) //flatten result
}

What is the best JavaScript code to create an img element

jQuery:

$('#container').append('<img src="/path/to/image.jpg"
       width="16" height="16" alt="Test Image" title="Test Image" />');

I've found that this works even better because you don't have to worry about HTML escaping anything (which should be done in the above code, if the values weren't hard coded). It's also easier to read (from a JS perspective):

$('#container').append($('<img>', { 
    src : "/path/to/image.jpg", 
    width : 16, 
    height : 16, 
    alt : "Test Image", 
    title : "Test Image"
}));

jQuery 'input' event

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

Incidentally:

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

Error :The remote server returned an error: (401) Unauthorized

Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?

Something like request.Credentials = new NetworkCredential("UserName", "PassWord");

Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;

How to define constants in ReactJS

You don't need to use anything but plain React and ES6 to achieve what you want. As per Jim's answer, just define the constant in the right place. I like the idea of keeping the constant local to the component if not needed externally. The below is an example of possible usage.

import React from "react";

const sizeToLetterMap = {
  small_square: 's',
  large_square: 'q',
  thumbnail: 't',
  small_240: 'm',
  small_320: 'n',
  medium_640: 'z',
  medium_800: 'c',
  large_1024: 'b',
  large_1600: 'h',
  large_2048: 'k',
  original: 'o'
};

class PhotoComponent extends React.Component {
  constructor(args) {
    super(args);
  }

  photoUrl(image, size_text) {
    return (<span>
      Image: {image}, Size Letter: {sizeToLetterMap[size_text]}
    </span>);
  }

  render() {
    return (
      <div className="photo-wrapper">
        The url is: {this.photoUrl(this.props.image, this.props.size_text)}
      </div>
    )
  }
}

export default PhotoComponent;

// Call this with <PhotoComponent image="abc.png" size_text="thumbnail" />
// Of course the component must first be imported where used, example:
// import PhotoComponent from "./photo_component.jsx";

Convert Variable Name to String?

I'd like to point out a use case for this that is not an anti-pattern, and there is no better way to do it.

This seems to be a missing feature in python.

There are a number of functions, like patch.object, that take the name of a method or property to be patched or accessed.

Consider this:

patch.object(obj, "method_name", new_reg)

This can potentially start "false succeeding" when you change the name of a method. IE: you can ship a bug, you thought you were testing.... simply because of a bad method name refactor.

Now consider: varname. This could be an efficient, built-in function. But for now it can work by iterating an object or the caller's frame:

Now your call can be:

patch.member(obj, obj.method_name, new_reg)

And the patch function can call:

varname(var, obj=obj)

This would: assert that the var is bound to the obj and return the name of the member. Or if the obj is not specified, use the callers stack frame to derive it, etc.

Could be made an efficient built in at some point, but here's a definition that works. I deliberately didn't support builtins, easy to add tho:

Feel free to stick this in a package called varname.py, and use it in your patch.object calls:

patch.object(obj, varname(obj, obj.method_name), new_reg)

Note: this was written for python 3.

import inspect

def _varname_dict(var, dct):
    key_name = None
    for key, val in dct.items():
        if val is var:
            if key_name is not None:
                raise NotImplementedError("Duplicate names not supported %s, %s" % (key_name, key))
            key_name = key
    return key_name

def _varname_obj(var, obj):
    key_name = None
    for key in dir(obj):
        val = getattr(obj, key)
        equal = val is var
        if equal:
            if key_name is not None:
                raise NotImplementedError("Duplicate names not supported %s, %s" % (key_name, key))
            key_name = key
    return key_name

def varname(var, obj=None):
    if obj is None:
        if hasattr(var, "__self__"):
            return var.__name__
        caller_frame = inspect.currentframe().f_back
        try:
            ret = _varname_dict(var, caller_frame.f_locals)
        except NameError:
            ret = _varname_dict(var, caller_frame.f_globals)
    else:
        ret = _varname_obj(var, obj)
    if ret is None:
        raise NameError("Name not found. (Note: builtins not supported)")
    return ret

Exact difference between CharSequence and String in java

other than the fact that String implements CharSequence and that String is a sequence of character.

Several things happen in your code:

CharSequence obj = "hello";

That creates a String literal, "hello", which is a String object. Being a String, which implements CharSequence, it is also a CharSequence. (you can read this post about coding to interface for example).

The next line:

String str = "hello";

is a little more complex. String literals in Java are held in a pool (interned) so the "hello" on this line is the same object (identity) as the "hello" on the first line. Therefore, this line only assigns the same String literal to str.

At this point, both obj and str are references to the String literal "hello" and are therefore equals, == and they are both a String and a CharSequence.

I suggest you test this code, showing in action what I just wrote:

public static void main(String[] args) {
    CharSequence obj = "hello";
    String str = "hello";
    System.out.println("Type of obj: " + obj.getClass().getSimpleName());
    System.out.println("Type of str: " + str.getClass().getSimpleName());
    System.out.println("Value of obj: " + obj);
    System.out.println("Value of str: " + str);
    System.out.println("Is obj a String? " + (obj instanceof String));
    System.out.println("Is obj a CharSequence? " + (obj instanceof CharSequence));
    System.out.println("Is str a String? " + (str instanceof String));
    System.out.println("Is str a CharSequence? " + (str instanceof CharSequence));
    System.out.println("Is \"hello\" a String? " + ("hello" instanceof String));
    System.out.println("Is \"hello\" a CharSequence? " + ("hello" instanceof CharSequence));
    System.out.println("str.equals(obj)? " + str.equals(obj));
    System.out.println("(str == obj)? " + (str == obj));
}

Get the index of a certain value in an array in PHP

If you're only doing a few of them (and/or the array size is large), then you were on the right track with array_search:

$list = array('string1', 'string2', 'string3');
$k = array_search('string2', $list); //$k = 1;

If you want all (or a lot of them), a loop will prob do you better:

foreach ($list as $key => $value) {
    echo $value . " in " . $key . ", ";
}
// Prints "string1 in 0, string2 in 1, string3 in 2, "

What is difference between Errors and Exceptions?

An Error "indicates serious problems that a reasonable application should not try to catch."

while

An Exception "indicates conditions that a reasonable application might want to catch."

Error along with RuntimeException & their subclasses are unchecked exceptions. All other Exception classes are checked exceptions.

Checked exceptions are generally those from which a program can recover & it might be a good idea to recover from such exceptions programmatically. Examples include FileNotFoundException, ParseException, etc. A programmer is expected to check for these exceptions by using the try-catch block or throw it back to the caller

On the other hand we have unchecked exceptions. These are those exceptions that might not happen if everything is in order, but they do occur. Examples include ArrayIndexOutOfBoundException, ClassCastException, etc. Many applications will use try-catch or throws clause for RuntimeExceptions & their subclasses but from the language perspective it is not required to do so. Do note that recovery from a RuntimeException is generally possible but the guys who designed the class/exception deemed it unnecessary for the end programmer to check for such exceptions.

Errors are also unchecked exception & the programmer is not required to do anything with these. In fact it is a bad idea to use a try-catch clause for Errors. Most often, recovery from an Error is not possible & the program should be allowed to terminate. Examples include OutOfMemoryError, StackOverflowError, etc.

Do note that although Errors are unchecked exceptions, we shouldn't try to deal with them, but it is ok to deal with RuntimeExceptions(also unchecked exceptions) in code. Checked exceptions should be handled by the code.

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

From milliseconds to hour, minutes, seconds and milliseconds

Just an other java example:

long dayLength = 1000 * 60 * 60 * 24;
long dayMs = System.currentTimeMillis() % dayLength;
double percentOfDay = (double) dayMs / dayLength;
int hour = (int) (percentOfDay * 24);
int minute = (int) (percentOfDay * 24 * 60) % 60;
int second = (int) (percentOfDay * 24 * 60 * 60) % 60;

an advantage is that you can simulate shorter days, if you adjust dayLength

python: how to check if a line is an empty line

I think is more robust to use regular expressions:

import re

for i, line in enumerate(content):
    print line if not (re.match('\r?\n', line)) else pass

This would match in Windows/unix. In addition if you are not sure about lines containing only space char you could use '\s*\r?\n' as expression

Cannot serve WCF services in IIS on Windows 8

you can add this code to web.config in asp mvc

   <system.webServer>
    <staticContent>
      <remove fileExtension=".srt" />
      <mimeMap fileExtension=".srt" mimeType="text/srt" />
      <remove fileExtension=".vtt" />
      <mimeMap fileExtension=".vtt" mimeType="text/vtt" />
    </staticContent>
  </system.webServer>

you can change file extension with your file extension

How to use radio buttons in ReactJS?

Just an idea here: when it comes to radio inputs in React, I usually render all of them in a different way that was mentionned in the previous answers.

If this could help anyone who needs to render plenty of radio buttons:

_x000D_
_x000D_
import React from "react"_x000D_
import ReactDOM from "react-dom"_x000D_
_x000D_
// This Component should obviously be a class if you want it to work ;)_x000D_
_x000D_
const RadioInputs = (props) => {_x000D_
  /*_x000D_
    [[Label, associated value], ...]_x000D_
  */_x000D_
  _x000D_
  const inputs = [["Male", "M"], ["Female", "F"], ["Other", "O"]]_x000D_
  _x000D_
  return (_x000D_
    <div>_x000D_
      {_x000D_
        inputs.map(([text, value], i) => (_x000D_
   <div key={ i }>_x000D_
     <input type="radio"_x000D_
              checked={ this.state.gender === value } _x000D_
       onChange={ /* You'll need an event function here */ } _x000D_
       value={ value } /> _x000D_
         { text }_x000D_
          </div>_x000D_
        ))_x000D_
      }_x000D_
    </div>_x000D_
  )_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <RadioInputs />,_x000D_
  document.getElementById("root")_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

What is C# equivalent of <map> in C++?

The equivalent would be class SortedDictionary<TKey, TValue> in the System.Collections.Generic namespace.

If you don't care about the order the class Dictionary<TKey, TValue> in the System.Collections.Generic namespace would probably be sufficient.

What is the relative performance difference of if/else versus switch statement in Java?

A good explanation at the link below:
https://www.geeksforgeeks.org/switch-vs-else/

Test(c++17)
1 - If grouped
2 - If sequential
3 - Goto Array
4 - Switch Case - Jump Table
https://onlinegdb.com/Su7HNEBeG

Could not load file or assembly 'Microsoft.Web.Infrastructure,

You need to download the ASP.NET MVC framework on the server hosting your application. It's a quick fix just download and install from here (This is the MVC 3 framework http://www.asp.net/mvc/mvc3), then boom you are good to go.

UTL_FILE.FOPEN() procedure not accepting path for directory?

Since Oracle 9i there are two ways or declaring a directory for use with UTL_FILE.

The older way is to set the INIT.ORA parameter UTL_FILE_DIR. We have to restart the database for a change to take affect. The value can like any other PATH variable; it accepts wildcards. Using this approach means passing the directory path...

UTL_FILE.FOPEN('c:\temp', 'vineet.txt', 'W');

The alternative approach is to declare a directory object.

create or replace directory temp_dir as 'C:\temp'
/

grant read, write on directory temp_dir to vineet
/

Directory objects require the exact file path, and don't accept wildcards. In this approach we pass the directory object name...

UTL_FILE.FOPEN('TEMP_DIR', 'vineet.txt', 'W');

The UTL_FILE_DIR is deprecated because it is inherently insecure - all users have access to all the OS directories specified in the path, whereas read and write privileges can de granted discretely to individual users. Also, with Directory objects we can be add, remove or change directories without bouncing the database.

In either case, the oracle OS user must have read and/or write privileges on the OS directory. In case it isn't obvious, this means the directory must be visible from the database server. So we cannot use either approach to expose a directory on our local PC to a process running on a remote database server. Files must be uploaded to the database server, or a shared network drive.


If the oracle OS user does not have the appropriate privileges on the OS directory, or if the path specified in the database does not match to an actual path, the program will hurl this exception:

ORA-29283: invalid file operation
ORA-06512: at "SYS.UTL_FILE", line 536
ORA-29283: invalid file operation
ORA-06512: at line 7

The OERR text for this error is pretty clear:

29283 -  "invalid file operation"
*Cause:    An attempt was made to read from a file or directory that does
           not exist, or file or directory access was denied by the
           operating system.
*Action:   Verify file and directory access privileges on the file system,
           and if reading, verify that the file exists.

Recommended date format for REST GET API

Always use UTC:

For example I have a schedule component that takes in one parameter DATETIME. When I call this using a GET verb I use the following format where my incoming parameter name is scheduleDate.

Example:
https://localhost/api/getScheduleForDate?scheduleDate=2003-11-21T01:11:11Z

Site does not exist error for a2ensite

Try like this..

NameVirtualHost *:80
<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName www.cmsplus.dev
    ServerAlias cmsplus.dev

    DocumentRoot /var/www/cmsplus.dev/public

    LogLevel warn
    ErrorLog /var/www/cmsplus.dev/log/error.log
    CustomLog /var/www/cmsplus.dev/log/access.log combined
</VirtualHost>

and add entry in /etc/hosts

127.0.0.1 www.cmsplus.dev

restart apache..

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

No restricted globals

/* eslint no-restricted-globals:0 */

is another alternate approach

Promise.all().then() resolve?

But that doesn't seem like the proper way to do it..

That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("First handler", data);_x000D_
    return data.map(entry => entry * 10);_x000D_
  })_x000D_
  .then(data => {_x000D_
    console.log("Second handler", data);_x000D_
  });
_x000D_
_x000D_
_x000D_

(catch handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)

The output we see from that is:

First handler [1,2]
Second handler [10,20]

...because the first handler gets the resolution of the two promises (1 and 2) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.

If the additional work you're doing is synchronous, you can also put it in the first handler:

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("Initial data", data);_x000D_
    data = data.map(entry => entry * 10);_x000D_
    console.log("Updated data", data);_x000D_
    return data;_x000D_
  });
_x000D_
_x000D_
_x000D_

...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.

How do I remove the passphrase for the SSH key without having to create a new key?

In windows for me it kept saying "id_ed25135: No such file or directory" upon entering above commands. So I went to the folder, copied the path within folder explorer and added "\id_ed25135" at the end.

This is what I ended up typing and worked:
ssh-keygen -p -f C:\Users\john\.ssh\id_ed25135

This worked. Because for some reason, in Cmder the default path was something like this C:\Users\capit/.ssh/id_ed25135 (some were backslashes: "\" and some were forward slashes: "/")

Removing an element from an Array (Java)

I hope you use the java collection / java commons collections!

With an java.util.ArrayList you can do things like the following:

yourArrayList.remove(someObject);

yourArrayList.add(someObject);

Reading an integer from user input

static void Main(string[] args)
    {
        Console.WriteLine("Please enter a number from 1 to 10");
        int counter = Convert.ToInt32(Console.ReadLine());
        //Here is your variable
        Console.WriteLine("The numbers start from");
        do
        {
            counter++;
            Console.Write(counter + ", ");

        } while (counter < 100);

        Console.ReadKey();

    }

Comparing strings in Java

You can compare the values using equals() of Java :

public void onClick(View v) {
    // TODO Auto-generated method stub

    s1=text1.getText().toString();
    s2=text2.getText().toString();

    if(s1.equals(s2))
        Show.setText("Are Equal");
    else
        Show.setText("Not Equal");
}

WAMP server, localhost is not working

Best try for windows: Open up cmd. run the following command: C:\wamp64\bin\apache\apache2.4.17\bin\httpd.exe -d C:/wamp64/bin/apache/apache2.4.17
C:\wamp64\bin\apache\apache2.4.17\bin\ Should be replaced with the path where your Apache is installed.
you use \ because \ is an escape character ;)
If the service could not start it will return the error.
For me it was the DocumentRoot was invalid :)

How do I retrieve the number of columns in a Pandas data frame?

#use a regular expression to parse the column count
#https://docs.python.org/3/library/re.html

buffer = io.StringIO()
df.info(buf=buffer)
s = buffer.getvalue()
pat=re.search(r"total\s{1}[0-9]\s{1}column",s)
print(s)
phrase=pat.group(0)
value=re.findall(r'[0-9]+',phrase)[0]
print(int(value))

Mutex example / tutorial?

While a mutex may be used to solve other problems, the primary reason they exist is to provide mutual exclusion and thereby solve what is known as a race condition. When two (or more) threads or processes are attempting to access the same variable concurrently, we have potential for a race condition. Consider the following code

//somewhere long ago, we have i declared as int
void my_concurrently_called_function()
{
  i++;
}

The internals of this function look so simple. It's only one statement. However, a typical pseudo-assembly language equivalent might be:

load i from memory into a register
add 1 to i
store i back into memory

Because the equivalent assembly-language instructions are all required to perform the increment operation on i, we say that incrementing i is a non-atmoic operation. An atomic operation is one that can be completed on the hardware with a gurantee of not being interrupted once the instruction execution has begun. Incrementing i consists of a chain of 3 atomic instructions. In a concurrent system where several threads are calling the function, problems arise when a thread reads or writes at the wrong time. Imagine we have two threads running simultaneoulsy and one calls the function immediately after the other. Let's also say that we have i initialized to 0. Also assume that we have plenty of registers and that the two threads are using completely different registers, so there will be no collisions. The actual timing of these events may be:

thread 1 load 0 into register from memory corresponding to i //register is currently 0
thread 1 add 1 to a register //register is now 1, but not memory is 0
thread 2 load 0 into register from memory corresponding to i
thread 2 add 1 to a register //register is now 1, but not memory is 0
thread 1 write register to memory //memory is now 1
thread 2 write register to memory //memory is now 1

What's happened is that we have two threads incrementing i concurrently, our function gets called twice, but the outcome is inconsistent with that fact. It looks like the function was only called once. This is because the atomicity is "broken" at the machine level, meaning threads can interrupt each other or work together at the wrong times.

We need a mechanism to solve this. We need to impose some ordering to the instructions above. One common mechanism is to block all threads except one. Pthread mutex uses this mechanism.

Any thread which has to execute some lines of code which may unsafely modify shared values by other threads at the same time (using the phone to talk to his wife), should first be made acquire a lock on a mutex. In this way, any thread that requires access to the shared data must pass through the mutex lock. Only then will a thread be able to execute the code. This section of code is called a critical section.

Once the thread has executed the critical section, it should release the lock on the mutex so that another thread can acquire a lock on the mutex.

The concept of having a mutex seems a bit odd when considering humans seeking exclusive access to real, physical objects but when programming, we must be intentional. Concurrent threads and processes don't have the social and cultural upbringing that we do, so we must force them to share data nicely.

So technically speaking, how does a mutex work? Doesn't it suffer from the same race conditions that we mentioned earlier? Isn't pthread_mutex_lock() a bit more complex that a simple increment of a variable?

Technically speaking, we need some hardware support to help us out. The hardware designers give us machine instructions that do more than one thing but are guranteed to be atomic. A classic example of such an instruction is the test-and-set (TAS). When trying to acquire a lock on a resource, we might use the TAS might check to see if a value in memory is 0. If it is, that would be our signal that the resource is in use and we do nothing (or more accurately, we wait by some mechanism. A pthreads mutex will put us into a special queue in the operating system and will notify us when the resource becomes available. Dumber systems may require us to do a tight spin loop, testing the condition over and over). If the value in memory is not 0, the TAS sets the location to something other than 0 without using any other instructions. It's like combining two assembly instructions into 1 to give us atomicity. Thus, testing and changing the value (if changing is appropriate) cannot be interrupted once it has begun. We can build mutexes on top of such an instruction.

Note: some sections may appear similar to an earlier answer. I accepted his invite to edit, he preferred the original way it was, so I'm keeping what I had which is infused with a little bit of his verbiage.

Failed to load resource: the server responded with a status of 404 (Not Found) css

you have defined the public dir in app root/public

app.use(express.static(__dirname + '/public')); 

so you have to use:

./css/main.css

Plotting time in Python with Matplotlib

7 years later and this code has helped me. However, my times still were not showing up correctly.

enter image description here

Using Matplotlib 2.0.0 and I had to add the following bit of code from Editing the date formatting of x-axis tick labels in matplotlib by Paul H.

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

I changed the format to (%H:%M) and the time displayed correctly. enter image description here

All thanks to the community.

How to do integer division in javascript (Getting division answer in int not float)?

var x = parseInt(455/10);

The parseInt() function parses a string and returns an integer.

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

If the radix parameter is omitted, JavaScript assumes the following:

If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)

How to declare Global Variables in Excel VBA to be visible across the Workbook

Your question is: are these not modules capable of declaring variables at global scope?

Answer: YES, they are "capable"

The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1, e.g.) References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).

For instance, place in Sheet1 code

Public glob_sh1 As String

Sub test_sh1()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

place in ThisWorkbook code

Public glob_this As String

Sub test_this()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

and in a Standard Module code

Public glob_mod As String

Sub test_mod()
    glob_mod = "glob_mod"
    ThisWorkbook.glob_this = "glob_this"
    Sheet1.glob_sh1 = "glob_sh1"
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

All three subs work fine.

PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).

PS2: Your line Debug.Print ("Hello") will give you the compile error Invalid outside procedure.

PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.

PS4: Check also Put Excel-VBA code in module or sheet?.

PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.

PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.

DateTime to javascript date

Try:

return DateTime.Now.Subtract(new DateTime(1970, 1,1)).TotalMilliseconds

Edit: true UTC is better, but then we need to be consistent

return DateTime.UtcNow
               .Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc))
               .TotalMilliseconds;

Although, on second thoughts it does not matter, as long as both dates are in the same time zone.

Git: See my last commit

$ git diff --name-only HEAD^..HEAD

or

$ git log --name-only HEAD^..HEAD

How do you connect localhost in the Android emulator?

Thanks to author of this blog: https://bigdata-etl.com/solved-how-to-connect-from-android-emulator-to-application-on-localhost/

Defining network security config in xml

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
       <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

And setting it on AndroidManifest.xml

 <application
    android:networkSecurityConfig="@xml/network_security_config"
</application>

Solved issue for me!

Please refer: https://developer.android.com/training/articles/security-config

ImportError: No module named 'django.core.urlresolvers'

You need replace all occurrences of:

from django.core.urlresolvers import reverse

to:

from django.urls import reverse

enter image description here

NOTE: The same apply to reverse_lazy

in Pycharm Cmd+Shift+R for starting replacment in Path.

DropDownList's SelectedIndexChanged event not firing

try setting AutoPostBack="True" on the DropDownList.

How do I center a window onscreen in C#?

A single line:

this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
                          (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);

Simple JavaScript login form validation

  1. The input tag doesn't have onsubmit handler. Instead, you should put your onsubmit handler on actual form tag, like this:

    <form name="loginform" onsubmit="validateForm()" method="post">

    Here are some useful links:

  2. For the form tag you can specify the request method, GET or POST. By default, the method is GET. One of the differences between them is that in case of GET method, the parameters are appended to the URL (just what you have shown), while in case of POST method there are not shown in URL.

    You can read more about the differences here.

UPDATE:

You should return the function call and also you can specify the URL in action attribute of form tag. So here is the updated code:

<form name="loginform" onSubmit="return validateForm();" action="main.html" method="post">
    <label>User name</label>
    <input type="text" name="usr" placeholder="username"> 
    <label>Password</label>
    <input type="password" name="pword" placeholder="password">
    <input type="submit" value="Login"/>
</form>

<script>
    function validateForm() {
        var un = document.loginform.usr.value;
        var pw = document.loginform.pword.value;
        var username = "username"; 
        var password = "password";
        if ((un == username) && (pw == password)) {
            return true;
        }
        else {
            alert ("Login was unsuccessful, please check your username and password");
            return false;
        }
  }
</script>

How to find the mysql data directory from command line in windows

Output on Windows:
you can just use this command,it is very easy!

1. no password of MySQL:

mysql ?

2. have password of MySQL:

mysql -uroot -ppassword mysql ?

enter image description here enter image description here

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

If you would like to ignore case you could use the following:

String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
    //-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
    // strings are equal.
}

How to get exit code when using Python subprocess communicate method?

exitcode = data.wait(). The child process will be blocked If it writes to standard output/error, and/or reads from standard input, and there are no peers.

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

grep a file, but show several surrounding lines?

Use grep

$ grep --help | grep -i context
Context control:
  -B, --before-context=NUM  print NUM lines of leading context
  -A, --after-context=NUM   print NUM lines of trailing context
  -C, --context=NUM         print NUM lines of output context
  -NUM                      same as --context=NUM

Default value in Go's method

No, the powers that be at Google chose not to support that.

https://groups.google.com/forum/#!topic/golang-nuts/-5MCaivW0qQ

Using gradle to find dependency tree

In Android Studio (at least since v2.3.3) you can run the command directly from the UI:

Click on the Gradle tab and then double click on :yourmodule -> Tasks -> android -> androidDependencies

The tree will be displayed in the Gradle Console tab

An image is worth a thousand words

Remove leading zeros from a number in Javascript

It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary + [docs]:

value = +value;

If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then

input.value = +input.value;

is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.

Multi column forms with fieldsets

I disagree that .form-group should be within .col-*-n elements. In my experience, all the appropriate padding happens automatically when you use .form-group like .row within a form.

<div class="form-group">
    <div class="col-sm-12">
        <label for="user_login">Username</label>
        <input class="form-control" id="user_login" name="user[login]" required="true" size="30" type="text" />
    </div>
</div>

Check out this demo.

Altering the demo slightly by adding .form-horizontal to the form tag changes some of that padding.

<form action="#" method="post" class="form-horizontal">

Check out this demo.

When in doubt, inspect in Chrome or use Firebug in Firefox to figure out things like padding and margins. Using .row within the form fails in edsioufi's fiddle because .row uses negative left and right margins thereby drawing the horizontal bounds of the divs classed .row beyond the bounds of the containing fieldsets.

Adding backslashes without escaping [Python]

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

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

How to find what code is run by a button or element in Chrome using Developer Tools

Alexander Pavlov's answer gets the closest to what you want.

Due to the extensiveness of jQuery's abstraction and functionality, a lot of hoops have to be jumped in order to get to the meat of the event. I have set up this jsFiddle to demonstrate the work.


1. Setting up the Event Listener Breakpoint

You were close on this one.

  1. Open the Chrome Dev Tools (F12), and go to the Sources tab.
  2. Drill down to Mouse -> Click
    Chrome Dev Tools -> Sources tab -> Mouse -> Click
    (click to zoom)

2. Click the button!

Chrome Dev Tools will pause script execution, and present you with this beautiful entanglement of minified code:

Chrome Dev Tools paused script execution (click to zoom)


3. Find the glorious code!

Now, the trick here is to not get carried away pressing the key, and keep an eye out on the screen.

  1. Press the F11 key (Step In) until desired source code appears
  2. Source code finally reached
    • In the jsFiddle sample provided above, I had to press F11 108 times before reaching the desired event handler/function
    • Your mileage may vary, depending on the version of jQuery (or framework library) used to bind the events
    • With enough dedication and time, you can find any event handler/function

Desired event handler/function


4. Explanation

I don't have the exact answer, or explanation as to why jQuery goes through the many layers of abstractions it does - all I can suggest is that it is because of the job it does to abstract away its usage from the browser executing the code.

Here is a jsFiddle with a debug version of jQuery (i.e., not minified). When you look at the code on the first (non-minified) breakpoint, you can see that the code is handling many things:

    // ...snip...

    if ( !(eventHandle = elemData.handle) ) {
        eventHandle = elemData.handle = function( e ) {
            // Discard the second event of a jQuery.event.trigger() and
            // when an event is called after a page has unloaded
            return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
                jQuery.event.dispatch.apply( elem, arguments ) : undefined;
        };
    }

    // ...snip...

The reason I think you missed it on your attempt when the "execution pauses and I jump line by line", is because you may have used the "Step Over" function, instead of Step In. Here is a StackOverflow answer explaining the differences.

Finally, the reason why your function is not directly bound to the click event handler is because jQuery returns a function that gets bound. jQuery's function in turn goes through some abstraction layers and checks, and somewhere in there, it executes your function.

Playing a video in VideoView in Android

VideoView videoView =(VideoView) findViewById(R.id.videoViewId);

Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo");

 videoView.setVideoURI(uri);
videoView.start();

Instead of using setVideoPath use setVideoUri. you can get path of your video stored in external storage by using (Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo")and parse it into Uri. If your video is stored in sdcard/MyVideo/video.mp4 replace "/yourvideo" in code by "/MyVideo/video.mp4"

This works fine for me :) `

What is the difference between char array and char pointer in C?

As far as I can remember, an array is actually a group of pointers. For example

p[1]== *(&p+1)

is a true statement

How to get the type of T from a member of a generic class or method?

You can use this one for return type of generic list:

public string ListType<T>(T value)
{
    var valueType = value.GetType().GenericTypeArguments[0].FullName;
    return valueType;
}

How are ssl certificates verified?

if you're more technically minded, this site is probably what you want: http://www.zytrax.com/tech/survival/ssl.html

warning: the rabbit hole goes deep :).

How to force ViewPager to re-instantiate its items

public class DayFlipper extends ViewPager {

private Flipperadapter adapter;
public class FlipperAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        return DayFlipper.DAY_HISTORY;
    }

    @Override
    public void startUpdate(View container) {
    }

    @Override
    public Object instantiateItem(View container, int position) {
        Log.d(TAG, "instantiateItem(): " + position);

        Date d = DateHelper.getBot();
        for (int i = 0; i < position; i++) {
            d = DateHelper.getTomorrow(d);
        }

        d = DateHelper.normalize(d);

        CubbiesView cv = new CubbiesView(mContext);
        cv.setLifeDate(d);
        ((ViewPager) container).addView(cv, 0);
        // add map
        cv.setCubbieMap(mMap);
        cv.initEntries(d);
adpter = FlipperAdapter.this;
        return cv;
    }

    @Override
    public void destroyItem(View container, int position, Object object) {
        ((ViewPager) container).removeView((CubbiesView) object);
    }

    @Override
    public void finishUpdate(View container) {

    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((CubbiesView) object);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {

    }

}

    ...

    public void refresh() {
    adapter().notifyDataSetChanged();
}
}

try this.

Install Application programmatically on Android

First add the following line to AndroidManifest.xml :

<uses-permission android:name="android.permission.INSTALL_PACKAGES"
    tools:ignore="ProtectedPermissions" />

Then use the following code to install apk:

File sdCard = Environment.getExternalStorageDirectory();
            String fileStr = sdCard.getAbsolutePath() + "/MyApp";// + "app-release.apk";
            File file = new File(fileStr, "TaghvimShamsi.apk");
            Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
            startActivity(promptInstall);

Pretty printing XML in Python

For converting an entire xml document to a pretty xml document
(ex: assuming you've extracted [unzipped] a LibreOffice Writer .odt or .ods file, and you want to convert the ugly "content.xml" file to a pretty one for automated git version control and git difftooling of .odt/.ods files, such as I'm implementing here)

import xml.dom.minidom

file = open("./content.xml", 'r')
xml_string = file.read()
file.close()

parsed_xml = xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = parsed_xml.toprettyxml()

file = open("./content_new.xml", 'w')
file.write(pretty_xml_as_string)
file.close()

References:
- Thanks to Ben Noland's answer on this page which got me most of the way there.

Javascript extends class

Take a look at Simple JavaScript Inheritance and Inheritance Patterns in JavaScript.

The simplest method is probably functional inheritance but there are pros and cons.

How to sum data.frame column values?

When you have 'NA' values in the column, then

sum(as.numeric(JuneData1$Account.Balance), na.rm = TRUE)

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

This issue occurs when someone has commited the code to develop/master and latest code has not been rebased from develop/master and you're trying to overwrite new changes to develop/master branch

Solution:

  • Take a backup if you're working on feature branch and switch to master/develop branch by doing git checkout develop/master
  • Do git pull
  • You will get changes and merge conflicts occur when you have made changes in the same file which has not been rebased from develop/master
  • Resolve the conflicts if it occurs and do git push,this should work

How to debug when Kubernetes nodes are in 'Not Ready' state

I found applying the network and rebooting both the nodes did the trick for me.

kubectl apply -f [podnetwork].yaml

How do I edit an incorrect commit message in git ( that I've pushed )?

(From http://git.or.cz/gitwiki/GitTips#head-9f87cd21bcdf081a61c29985604ff4be35a5e6c0)

How to change commits deeper in history

Since history in Git is immutable, fixing anything but the most recent commit (commit which is not branch head) requires that the history is rewritten from the changed commit and forward.

You can use StGIT for that, initialize branch if necessary, uncommitting up to the commit you want to change, pop to it if necessary, make a change then refresh patch (with -e option if you want to correct commit message), then push everything and stg commit.

Or you can use rebase to do that. Create new temporary branch, rewind it to the commit you want to change using git reset --hard, change that commit (it would be top of current head), then rebase branch on top of changed commit, using git rebase --onto .

Or you can use git rebase --interactive, which allows various modifications like patch re-ordering, collapsing, ...

I think that should answer your question. However, note that if you have pushed code to a remote repository and people have pulled from it, then this is going to mess up their code histories, as well as the work they've done. So do it carefully.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

Inside of VBS you can access parameters with

Wscript.Arguments(0)
Wscript.Arguments(1)

and so on. The number of parameter:

Wscript.Arguments.Count

Using only CSS, show div on hover over <a>

For me, if I want to interact with the hidden div without seeing it disappear each time I leave the triggering element (a in that case) I must add:

div:hover {
    display: block;
}

Calling the base constructor in C#

Modify your constructor to the following so that it calls the base class constructor properly:

public class MyExceptionClass : Exception
{
    public MyExceptionClass(string message, string extrainfo) : base(message)
    {
        //other stuff here
    }
}

Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body.

Unzip a file with php

Use below PHP code, with file name in the URL param "name"

<?php

$fileName = $_GET['name'];

if (isset($fileName)) {


    $zip = new ZipArchive;
    $res = $zip->open($fileName);
    if ($res === TRUE) {
      $zip->extractTo('./');
      $zip->close();
      echo 'Extracted file "'.$fileName.'"';
    } else {
      echo 'Cannot find the file name "'.$fileName.'" (the file name should include extension (.zip, ...))';
    }
}
else {
    echo 'Please set file name in the "name" param';
}

?>

How to filter rows in pandas by regex

Using str slice

foo[foo.b.str[0]=='f']
Out[18]: 
   a    b
1  2  foo
2  3  fat

Can git undo a checkout of unstaged files

In VSCODE ctrl+z (undo) worked for me

I did git checkout .instead of git add . and all my file changes were lost.

But Now using command + z in my mac , recovered the changes and saved a tone of work for me.

How can I set the default value for an HTML <select> element?

Set selected="selected" for the option you want to be the default.

<option selected="selected">
3
</option>

How to find files that match a wildcard string in Java?

The Apache filter is built for iterating files in a known directory. To allow wildcards in the directory also, you would have to split the path on '\' or '/' and do a filter on each part separately.

connecting to MySQL from the command line

This worked for me ::-

mysql --host=hostNameorIp --user=username --password=password  

or

mysql --host=hostNameorIp --user=username --password=password database_name

How to convert an Image to base64 string in java?

this did it for me. you can vary the options for the output format to Base64.Default whatsoever.

// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

Fix the permissions of /data/db (or /var/lib/mongodb):

sudo chown -R mongodb: /data/db

then restart MongoDB e.g. using

sudo systemctl restart mongod

In case that does not help, check your error message if you are using a data directory different to /var/lib/mongodb. In that case run

sudo chown -R mongodb: <insert your data directory here>

source

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

#include <string.h>
#include <stdio.h>
#include <jni.h>

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

You can use:

window.location.href = '/Branch/Details/' + id;

But your Ajax code is incomplete without success or error functions.

Access parent DataContext from DataTemplate

I was searching how to do something similar in WPF and I got this solution:

<ItemsControl ItemsSource="{Binding MyItems,Mode=OneWay}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical" />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <RadioButton 
            Content="{Binding}" 
            Command="{Binding Path=DataContext.CustomCommand, 
                        RelativeSource={RelativeSource Mode=FindAncestor,      
                        AncestorType={x:Type ItemsControl}} }"
            CommandParameter="{Binding}" />
    </DataTemplate>
</ItemsControl.ItemTemplate>

I hope this works for somebody else. I have a data context which is set automatically to the ItemsControls, and this data context has two properties: MyItems -which is a collection-, and one command 'CustomCommand'. Because of the ItemTemplate is using a DataTemplate, the DataContext of upper levels is not directly accessible. Then the workaround to get the DC of the parent is use a relative path and filter by ItemsControl type.

Check if one date is between two dates

The answer that has 50 votes doesn't check for date in only checks for months. That answer is not correct. The code below works.

var dateFrom = "01/08/2017";
var dateTo = "01/10/2017";
var dateCheck = "05/09/2017";

var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");

var from = new Date(d1);  // -1 because months are from 0 to 11
var to   = new Date(d2);
var check = new Date(c);

alert(check > from && check < to);

This is the code posted in another answer and I have changed the dates and that's how I noticed it doesn't work

var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "07/07/2013";

var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");

var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]);  // -1 because months are from 0 to 11
var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);


alert(check > from && check < to);

SharePoint 2013 get current user using JavaScript

try this code..

function GetCurrentUsers() {

    var context = new SP.ClientContext.get_current();
    this.website = context.get_web();
    var currentUser = website.get_currentUser();
    context.load(currentUser);
    context.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
   function onQuerySucceeded() {

       var currentUsers = currentUser.get_title();
       document.getElementById("txtIssued").innerHTML = currentUsers;

    }

    function onQueryFailed(sender, args) {
        alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
    }   

}

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

Add labels to each argument in your plot call corresponding to the series it is graphing, i.e. label = "series 1"

Then simply add Pyplot.legend() to the bottom of your script and the legend will display these labels.

Scroll part of content in fixed position container

Set the scrollable div to have a max-size and add overflow-y: scroll; to it's properties.

Edit: trying to get the jsfiddle to work, but it's not scrolling properly. This will take some time to figure out.

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

I have solved it by importing FormModule in a shared.module and importing the shared.module in all other modules. My case is the FormModule is used in multiple modules.

LINQ Joining in C# with multiple conditions

Your and should be a && in the where clause.

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
and epl.ArriveAirportBy > sd.UTCArrivalTime

should be

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
&& epl.ArriveAirportBy > sd.UTCArrivalTime

Forward X11 failed: Network error: Connection refused

PuTTY can't find where your X server is, because you didn't tell it. (ssh on Linux doesn't have this problem because it runs under X so it just uses that one.) Fill in the blank box after "X display location" with your Xming server's address.

Alternatively, try MobaXterm. It has an X server builtin.

using favicon with css

If (1) you need a favicon that is different for some parts of the domain, or (2) you want this to work with IE 8 or older (haven't tested any newer version), then you have to edit the html to specify the favicon

How to convert currentTimeMillis to a date in Java?

Easiest way:

private String millisToDate(long millis){

    return DateFormat.getDateInstance(DateFormat.SHORT).format(millis);
    //You can use DateFormat.LONG instead of SHORT

}

how to modify an existing check constraint?

You have to drop it and recreate it, but you don't have to incur the cost of revalidating the data if you don't want to.

alter table t drop constraint ck ;
alter table t add constraint ck check (n < 0) enable novalidate;

The enable novalidate clause will force inserts or updates to have the constraint enforced, but won't force a full table scan against the table to verify all rows comply.

what's data-reactid attribute in html?

It's a custom html attribute but probably in this case is used by the Facebook React JS Library.

Take a look: http://facebook.github.io/react/

How to create an array from a CSV file using PHP and the fgetcsv function

Old question, but still relevant for PHP 5.2 users. str_getcsv is available from PHP 5.3. I've written a small function that works with fgetcsv itself.

Below is my function from https://gist.github.com/4152628:

function parse_csv_file($csvfile) {
    $csv = Array();
    $rowcount = 0;
    if (($handle = fopen($csvfile, "r")) !== FALSE) {
        $max_line_length = defined('MAX_LINE_LENGTH') ? MAX_LINE_LENGTH : 10000;
        $header = fgetcsv($handle, $max_line_length);
        $header_colcount = count($header);
        while (($row = fgetcsv($handle, $max_line_length)) !== FALSE) {
            $row_colcount = count($row);
            if ($row_colcount == $header_colcount) {
                $entry = array_combine($header, $row);
                $csv[] = $entry;
            }
            else {
                error_log("csvreader: Invalid number of columns at line " . ($rowcount + 2) . " (row " . ($rowcount + 1) . "). Expected=$header_colcount Got=$row_colcount");
                return null;
            }
            $rowcount++;
        }
        //echo "Totally $rowcount rows found\n";
        fclose($handle);
    }
    else {
        error_log("csvreader: Could not read CSV \"$csvfile\"");
        return null;
    }
    return $csv;
}

Returns

Begin Reading CSV

Array
(
    [0] => Array
        (
            [vid] => 
            [agency] => 
            [division] => Division
            [country] => 
            [station] => Duty Station
            [unit] => Unit / Department
            [grade] => 
            [funding] => Fund Code
            [number] => Country Office Position Number
            [wnumber] => Wings Position Number
            [title] => Position Title
            [tor] => Tor Text
            [tor_file] => 
            [status] => 
            [datetime] => Entry on Wings
            [laction] => 
            [supervisor] => Supervisor Index Number
            [asupervisor] => Alternative Supervisor Index
            [author] => 
            [category] => 
            [parent] => Reporting to Which Position Number
            [vacant] => Status (Vacant / Filled)
            [index] => Index Number
        )

    [1] => Array
        (
            [vid] => 
            [agency] => WFP
            [division] => KEN Kenya, The Republic Of
            [country] => 
            [station] => Nairobi
            [unit] => Human Resources Officer P4
            [grade] => P-4
            [funding] => 5000001
            [number] => 22018154
            [wnumber] => 
            [title] => Human Resources Officer P4
            [tor] => 
            [tor_file] => 
            [status] => 
            [datetime] => 
            [laction] => 
            [supervisor] => 
            [asupervisor] => 
            [author] => 
            [category] => Professional
            [parent] => 
            [vacant] => 
            [index] => xxxxx
        )
) 

How to compare only date in moment.js

You could use startOf('day') method to compare just the date

Example :

var dateToCompare = moment("06/04/2015 18:30:00");
var today = moment(new Date());

dateToCompare.startOf('day').isSame(today.startOf('day'));

Best way to retrieve variable values from a text file?

How reliable is your format? If the seperator is always exactly ': ', the following works. If not, a comparatively simple regex should do the job.

As long as you're working with fairly simple variable types, Python's eval function makes persisting variables to files surprisingly easy.

(The below gives you a dictionary, btw, which you mentioned was one of your prefered solutions).

def read_config(filename):
    f = open(filename)
    config_dict = {}
    for lines in f:
        items = lines.split(': ', 1)
        config_dict[items[0]] = eval(items[1])
    return config_dict

Creating an empty list in Python

I use [].

  1. It's faster because the list notation is a short circuit.
  2. Creating a list with items should look about the same as creating a list without, why should there be a difference?

What is dynamic programming?

Memoization is the when you store previous results of a function call (a real function always returns the same thing, given the same inputs). It doesn't make a difference for algorithmic complexity before the results are stored.

Recursion is the method of a function calling itself, usually with a smaller dataset. Since most recursive functions can be converted to similar iterative functions, this doesn't make a difference for algorithmic complexity either.

Dynamic programming is the process of solving easier-to-solve sub-problems and building up the answer from that. Most DP algorithms will be in the running times between a Greedy algorithm (if one exists) and an exponential (enumerate all possibilities and find the best one) algorithm.

  • DP algorithms could be implemented with recursion, but they don't have to be.
  • DP algorithms can't be sped up by memoization, since each sub-problem is only ever solved (or the "solve" function called) once.

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

URL Encoding the data works as well for me

For example

var data = '<b>Hello</b>'

In Browser call encodeURIComponent(data) before posting

On Server call HttpUtility.UrlDecode(received_data) to decode

That way you can control exactly which fields area allowed to have html

How can I subset rows in a data frame in R based on a vector of values?

This will give you what you want:

eg2011cleaned <- eg2011[!eg2011$ID %in% bg2011missingFromBeg, ]

The error in your second attempt is because you forgot the ,

In general, for convenience, the specification object[index] subsets columns for a 2d object. If you want to subset rows and keep all columns you have to use the specification object[index_rows, index_columns], while index_cols can be left blank, which will use all columns by default.

However, you still need to include the , to indicate that you want to get a subset of rows instead of a subset of columns.

Variable not accessible when initialized outside function

It really depends on where your JavaScript code is located.

The problem is probably caused by the DOM not being loaded when the line

var systemStatus = document.getElementById("system-status");

is executed. You could try calling this in an onload event, or ideally use a DOM ready type event from a JavaScript framework.

check if command was successful in a batch file

I don't know if javaw will write to the %errorlevel% variable, but it might.

echo %errorlevel% after you run it directly to see.

Other than that, you can pipe the output of javaw to a file, then use find to see what the results were. Without knowing the output of it, I can't really help you with that.

How do I compare a value to a backslash?

Escape the backslash:

if message.value[0] == "/" or message.value[0] == "\\":

From the documentation:

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

Rails 4 - passing variable to partial

Syntactically a little different but it looks cleaner in my opinion:

render 'my_partial', locals: { title: "My awesome title" }

# not a big fan of the arrow key syntax
render 'my_partial', :locals => { :title => "My awesome title" }

How to delete multiple files at once in Bash on Linux?

I am not a linux guru, but I believe you want to pipe your list of output files to xargs rm -rf. I have used something like this in the past with good results. Test on a sample directory first!

EDIT - I might have misunderstood, based on the other answers that are appearing. If you can use wildcards, great. I assumed that your original list that you displayed was generated by a program to give you your "selection", so I thought piping to xargs would be the way to go.

JQuery select2 set default value from an option in list?

For ajax select2 multiple select dropdown i did like this;

  //preset element values
  //topics is an array of format [{"id":"","text":""}, .....]
        $(id).val(topics);
          setTimeout(function(){
           ajaxTopicDropdown(id,
                2,location.origin+"/api for gettings topics/",
                "Pick a topic", true, 5);                      
            },1);
        // ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url

Losing scope when using ng-include

As @Renan mentioned, ng-include creates a new child scope. This scope prototypically inherits (see dashed lines below) from the HomeCtrl scope. ng-model="lineText" actually creates a primitive scope property on the child scope, not HomeCtrl's scope. This child scope is not accessible to the parent/HomeCtrl scope:

ng-include scope

To store what the user typed into HomeCtrl's $scope.lines array, I suggest you pass the value to the addLine function:

 <form ng-submit="addLine(lineText)">

In addition, since lineText is owned by the ngInclude scope/partial, I feel it should be responsible for clearing it:

 <form ng-submit="addLine(lineText); lineText=''">

Function addLine() would thus become:

$scope.addLine = function(lineText) {
    $scope.chat.addLine(lineText);
    $scope.lines.push({
        text: lineText
    });
};

Fiddle.

Alternatives:

  • define an object property on HomeCtrl's $scope, and use that in the partial: ng-model="someObj.lineText; fiddle
  • not recommended, this is more of a hack: use $parent in the partial to create/access a lineText property on the HomeCtrl $scope:  ng-model="$parent.lineText"; fiddle

It is a bit involved to explain why the above two alternatives work, but it is fully explained here: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I don't recommend using this in the addLine() function. It becomes much less clear which scope is being accessed/manipulated.

How do you reindex an array in PHP but with indexes starting from 1?

It feels like all of the array_combine() answers are all copying the same "mistake" (the unnecessary call of array_values()).

array_combine() ignores the keys of both parameters that it receives.

Code: (Demo)

$array = [
    2 => (object)['title' => 'Section', 'linked' => 1],
    1 => (object)['title' => 'Sub-Section', 'linked' => 1],
    0 => (object)['title' => 'Sub-Sub-Section', 'linked' => null]
];

var_export(array_combine(range(1, count($array)), $array));

Output:

array (
  1 => 
  (object) array(
     'title' => 'Section',
     'linked' => 1,
  ),
  2 => 
  (object) array(
     'title' => 'Sub-Section',
     'linked' => 1,
  ),
  3 => 
  (object) array(
     'title' => 'Sub-Sub-Section',
     'linked' => NULL,
  ),
)

Browse for a directory in C#

or even more better, you can put this code in a class file

using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;

internal class OpenFolderDialog : IDisposable {

    /// <summary>
    /// Gets/sets folder in which dialog will be open.
    /// </summary>
    public string InitialFolder { get; set; }

    /// <summary>
    /// Gets/sets directory in which dialog will be open if there is no recent directory available.
    /// </summary>
    public string DefaultFolder { get; set; }

    /// <summary>
    /// Gets selected folder.
    /// </summary>
    public string Folder { get; private set; }


    internal DialogResult ShowDialog(IWin32Window owner) {
        if (Environment.OSVersion.Version.Major >= 6) {
            return ShowVistaDialog(owner);
        } else {
            return ShowLegacyDialog(owner);
        }
    }

    private DialogResult ShowVistaDialog(IWin32Window owner) {
        var frm = (NativeMethods.IFileDialog)(new NativeMethods.FileOpenDialogRCW());
        uint options;
        frm.GetOptions(out options);
        options |= NativeMethods.FOS_PICKFOLDERS | NativeMethods.FOS_FORCEFILESYSTEM | NativeMethods.FOS_NOVALIDATE | NativeMethods.FOS_NOTESTFILECREATE | NativeMethods.FOS_DONTADDTORECENT;
        frm.SetOptions(options);
        if (this.InitialFolder != null) {
            NativeMethods.IShellItem directoryShellItem;
            var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
            if (NativeMethods.SHCreateItemFromParsingName(this.InitialFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
                frm.SetFolder(directoryShellItem);
            }
        }
        if (this.DefaultFolder != null) {
            NativeMethods.IShellItem directoryShellItem;
            var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
            if (NativeMethods.SHCreateItemFromParsingName(this.DefaultFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
                frm.SetDefaultFolder(directoryShellItem);
            }
        }

        if (frm.Show(owner.Handle) == NativeMethods.S_OK) {
            NativeMethods.IShellItem shellItem;
            if (frm.GetResult(out shellItem) == NativeMethods.S_OK) {
                IntPtr pszString;
                if (shellItem.GetDisplayName(NativeMethods.SIGDN_FILESYSPATH, out pszString) == NativeMethods.S_OK) {
                    if (pszString != IntPtr.Zero) {
                        try {
                            this.Folder = Marshal.PtrToStringAuto(pszString);
                            return DialogResult.OK;
                        } finally {
                            Marshal.FreeCoTaskMem(pszString);
                        }
                    }
                }
            }
        }
        return DialogResult.Cancel;
    }

    private DialogResult ShowLegacyDialog(IWin32Window owner) {
        using (var frm = new SaveFileDialog()) {
            frm.CheckFileExists = false;
            frm.CheckPathExists = true;
            frm.CreatePrompt = false;
            frm.Filter = "|" + Guid.Empty.ToString();
            frm.FileName = "any";
            if (this.InitialFolder != null) { frm.InitialDirectory = this.InitialFolder; }
            frm.OverwritePrompt = false;
            frm.Title = "Select Folder";
            frm.ValidateNames = false;
            if (frm.ShowDialog(owner) == DialogResult.OK) {
                this.Folder = Path.GetDirectoryName(frm.FileName);
                return DialogResult.OK;
            } else {
                return DialogResult.Cancel;
            }
        }
    }


    public void Dispose() { } //just to have possibility of Using statement.

}

internal static class NativeMethods {

    #region Constants

    public const uint FOS_PICKFOLDERS = 0x00000020;
    public const uint FOS_FORCEFILESYSTEM = 0x00000040;
    public const uint FOS_NOVALIDATE = 0x00000100;
    public const uint FOS_NOTESTFILECREATE = 0x00010000;
    public const uint FOS_DONTADDTORECENT = 0x02000000;

    public const uint S_OK = 0x0000;

    public const uint SIGDN_FILESYSPATH = 0x80058000;

    #endregion


    #region COM

    [ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
    internal class FileOpenDialogRCW { }


    [ComImport(), Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IFileDialog {
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        [PreserveSig()]
        uint Show([In, Optional] IntPtr hwndOwner); //IModalWindow 


        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr rgFilterSpec);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileTypeIndex([In] uint iFileType);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFileTypeIndex(out uint piFileType);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Unadvise([In] uint dwCookie);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetOptions([In] uint fos);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetOptions(out uint fos);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, uint fdap);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Close([MarshalAs(UnmanagedType.Error)] uint hr);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetClientGuid([In] ref Guid guid);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint ClearClientData();

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
    }


    [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IShellItem {
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint BindToHandler([In] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IntPtr ppvOut);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetDisplayName([In] uint sigdnName, out IntPtr ppszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder);
    }

    #endregion


    [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);

}

And use it like this

using (var frm = new OpenFolderDialog()) {
                if (frm.ShowDialog(this)== DialogResult.OK) {
                    MessageBox.Show(this, frm.Folder);
                }
            }

_csv.Error: field larger than field limit (131072)

.csv field sizes are controlled via [Python 3.Docs]: csv.field_size_limit([new_limit]) (emphasis is mine):

Returns the current maximum field size allowed by the parser. If new_limit is given, this becomes the new limit.

It is set by default to 131072 or 0x20000 (128k), which should be enough for any decent .csv:

>>> import csv
>>>
>>>
>>> limit0 = csv.field_size_limit()
>>> limit0
131072
>>> "0x{0:016X}".format(limit0)
'0x0000000000020000'

However, when dealing with a .csv file (with the correct quoting and delimiter) having (at least) one field longer than this size, the error pops up.
To get rid of the error, the size limit should be increased (to avoid any worries, the maximum possible value is attempted).

Behind the scenes (check [GitHub]: python/cpython - (master) cpython/Modules/_csv.c for implementation details), the variable that holds this value is a C long ([Wikipedia]: C data types), whose size varies depending on CPU architecture and OS (ILP). The classical difference: for a 64bit OS (and Python build), the long type size (in bits) is:

  • Nix: 64
  • Win: 32

When attempting to set it, the new value is checked to be in the long boundaries, that's why in some cases another exception pops up (because sys.maxsize is typically 64bit wide - encountered on Win):

>>> import sys, ctypes as ct
>>>
>>>
>>> sys.platform, sys.maxsize, ct.sizeof(ct.c_void_p) * 8, ct.sizeof(ct.c_long) * 8
('win32', 9223372036854775807, 64, 32)
>>>
>>> csv.field_size_limit(sys.maxsize)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long

To avoid running into this problem, set the (maximum possible) limit (LONG_MAX), using an artifice (thanks to [Python 3.Docs]: ctypes - A foreign function library for Python). It should work on Python 3 and Python 2, on any CPU / OS.

>>> csv.field_size_limit(int(ct.c_ulong(-1).value // 2))
131072
>>> limit1 = csv.field_size_limit()
>>> limit1
2147483647
>>> "0x{0:016X}".format(limit1)
'0x000000007FFFFFFF'

64bit Python on a Nix like OS:

>>> import sys, csv, ctypes as ct
>>>
>>>
>>> sys.platform, sys.maxsize, ct.sizeof(ct.c_void_p) * 8, ct.sizeof(ct.c_long) * 8
('linux', 9223372036854775807, 64, 64)
>>>
>>> csv.field_size_limit()
131072
>>>
>>> csv.field_size_limit(int(ct.c_ulong(-1).value // 2))
131072
>>> limit1 = csv.field_size_limit()
>>> limit1
9223372036854775807
>>> "0x{0:016X}".format(limit1)
'0x7FFFFFFFFFFFFFFF'

For 32bit Python, things should run smoothly without the artifice (as both sys.maxsize and LONG_MAX are 32bit wide).
If this maximum value is still not enough, then the .csv would need manual intervention in order to be processed from Python.

Check the following resources for more details on:

Attach the Source in Eclipse of a jar

I have faced same problem and resolved it by using following scenario.

1 ) First we have to determine which jar file's source code we want along with version number. For Example "Spring Core » 4.0.6.RELEASE" 2 ) open https://mvnrepository.com/ and search file with name "Spring Core » 4.0.6.RELEASE". 3 ) Now Maven repository will show the the details of that jar file. 4 ) In that details there is one option "View All" just click on that. 5 ) Then we will navigate to URL "https://repo1.maven.org/maven2/org/springframework/spring-core/4.0.6.RELEASE/".

6) there so many options so select and download "spring-core-4.0.6.RELEASE-sources.jar " in our our system and attach same jar file as a source attachment in eclipse.

How to convert milliseconds to seconds with precision

I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.

double time_seconds = time_milliseconds / 1000.0;   // add the decimal
System.out.println(time_milliseconds);              // Now this should give you the right value.

read word by word from file in C++

I have edited the function for you,

void readFile()
{
    ifstream file;
    file.open ("program.txt");
    if (!file.is_open()) return;

    string word;
    while (file >> word)
    {
        cout<< word << '\n';
    }
}

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

To inject an Object, its class must be known to the CDI mechanism. Usualy adding the @Named annotation will do the trick.

How to make System.out.println() shorter

Use log4j or JDK logging so you can just create a static logger in the class and call it like this:

LOG.info("foo")

Excel VBA select range at last row and column

Another simple way:

ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).Select    
Selection.EntireRow.Delete

or simpler:

ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).EntireRow.Delete

How do I split a string with multiple separators in JavaScript?

I will provide a classic implementation for a such function. The code works in almost all versions of JavaScript and is somehow optimum.

  • It doesn't uses regex, which is hard to maintain
  • It doesn't uses new features of JavaScript
  • It doesn't uses multiple .split() .join() invocation which require more computer memory

Just pure code:

var text = "Create a function, that will return an array (of string), with the words inside the text";

println(getWords(text));

function getWords(text)
{
    let startWord = -1;
    let ar = [];

    for(let i = 0; i <= text.length; i++)
    {
        let c = i < text.length ? text[i] : " ";

        if (!isSeparator(c) && startWord < 0)
        {
            startWord = i;
        }

        if (isSeparator(c) && startWord >= 0)
        {
            let word = text.substring(startWord, i);
            ar.push(word);

            startWord = -1;
        }
    }

    return ar;
}

function isSeparator(c)
{
    var separators = [" ", "\t", "\n", "\r", ",", ";", ".", "!", "?", "(", ")"];
    return separators.includes(c);
}

You can see the code running in playground: https://codeguppy.com/code.html?IJI0E4OGnkyTZnoszAzf

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

What is the difference between old style and new style classes in Python?

Guido has written The Inside Story on New-Style Classes, a really great article about new-style and old-style class in Python.

Python 3 has only new-style class. Even if you write an 'old-style class', it is implicitly derived from object.

New-style classes have some advanced features lacking in old-style classes, such as super, the new C3 mro, some magical methods, etc.

Concatenating Matrices in R

cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:

http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html

It takes multiple comma separated matrices and data.frames as input :) You just need to

install.packages("gdata", dependencies=TRUE)

and then

library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)

What is the best way to uninstall gems from a rails3 project?

You must use 'gem uninstall gem_name' to uninstall a gem.

Note that if you installed the gem system-wide (ie. sudo bundle install) then you may need to specify the binary directory using the -n option, to ensure binaries belonging to the gem are removed. For example

sudo gem uninstall gem_name  -n /usr/lib/ruby/gems/1.9.1/bin

Split column at delimiter in data frame

Hadley has a very elegant solution to do this inside data frames in his reshape package, using the function colsplit.

require(reshape)
> df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
> df
  ID FOO
1 11 a|b
2 12 b|c
3 13 x|y
> df = transform(df, FOO = colsplit(FOO, split = "\\|", names = c('a', 'b')))
> df
  ID FOO.a FOO.b
1 11     a     b
2 12     b     c
3 13     x     y

function is not defined error in Python

if working with IDLE installed version of Python

>>>def any(a,b):
...    print(a+b)
...
>>>any(1,2)
3

Batch file include external file for variables

If the external configuration file is also valid batch file, you can just use:

call externalconfig.bat

inside your script. Try creating following a.bat:

@echo off
call b.bat
echo %MYVAR%

and b.bat:

set MYVAR=test

Running a.bat should generate output:

test

Git with SSH on Windows

Since this keeps coming up in search results for making git and github work with SSH on Windows (and because I didn't need anything from the guides above), I'm adding the following, simple solution.

(Microsoft says they are working on adding SSH to Visual Studio, and GitHub for Windows still doesn't support SSH...)

1. I installed "git for Windows" (which includes ssh and a bash shell)

https://git-scm.com/download/win

2. From the included bash shell (which, for me, was installed at: C:\Program Files\Git\git-bash.exe)

cd to the root level of where you want your repo saved (something like: C:\code\github\), and

Type:

eval $(ssh-agent -s) && ssh-add "C:\Users\YOURNAMEHERE\.ssh\github_rsa"

3. Type: (the SSH link from the repo)

git clone [email protected]:RepoName/Project.git

Converting a Date object to a calendar object

it's so easy...converting a date to calendar like this:

Calendar cal=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("yyyy/mm/dd");
format.format(date);
cal=format.getCalendar();

How to know which is running in Jupyter notebook?

Creating a virtual environment for Jupyter Notebooks

A minimal Python install is

sudo apt install python3.7 python3.7-venv python3.7-minimal python3.7-distutils python3.7-dev python3.7-gdbm python3-gdbm-dbg python3-pip

Then you can create and use the environment

/usr/bin/python3.7 -m venv test
cd test
source test/bin/activate
pip install jupyter matplotlib seaborn numpy pandas scipy
# install other packages you need with pip/apt
jupyter notebook
deactivate

You can make a kernel for Jupyter with

ipython3 kernel install --user --name=test

How can I trigger a Bootstrap modal programmatically?

The same thing happened to me. I wanted to open the Bootstrap modal by clicking on the table rows and get more details about each row. I used a trick to do this, Which I call the virtual button! Compatible with the latest version of Bootstrap (v5.0.0-alpha2). It might be useful for others as well.

See this code snippet with preview: https://gist.github.com/alireza-rezaee/c60da1429c36351ef4f071dec0ea9aba

Summary:

let exampleButton = document.createElement("button");
exampleButton.classList.add("d-none");
document.body.appendChild(exampleButton);
exampleButton.dataset.toggle = "modal";
exampleButton.dataset.target = "#exampleModal";

//AddEventListener to all rows
document.querySelectorAll('#exampleTable tr').forEach(row => {
    row.addEventListener('click', e => {
        //Set parameteres (clone row dataset)
        exampleButton.dataset.whatever = e.target.closest('tr').dataset.whatever;
        //Button click simulation
        //Now we can use relatedTarget
        exampleButton.click();
    })
});

All this is to use the relatedTarget property. (See Bootstrap docs)

getContext is not a function

I got the same error because I had accidentally used <div> instead of <canvas> as the element on which I attempt to call getContext.

No grammar constraints (DTD or XML schema) detected for the document

I used a relative path in the xsi:noNamespaceSchemaLocation to provide the local xsd file (because I could not use a namespace in the instance xml).

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../project/schema.xsd">
</root>

Validation works and the warning is fixed (not ignored).

https://www.w3schools.com/xml/schema_example.asp

PHP function to get the subdomain of a URL

Uses the parse_url function.

$url = 'http://en.example.com';

$parsedUrl = parse_url($url);

$host = explode('.', $parsedUrl['host']);

$subdomain = $host[0];
echo $subdomain;

For multiple subdomains

$url = 'http://usa.en.example.com';

$parsedUrl = parse_url($url);

$host = explode('.', $parsedUrl['host']);

$subdomains = array_slice($host, 0, count($host) - 2 );
print_r($subdomains);