Programs & Examples On #Virus scanning

Virus-scanning is the process of finding and eliminating malicious software on a computer. Use this tag for programming questions related to virus scanning on any platform/OS.

Print: Entry, ":CFBundleIdentifier", Does Not Exist

This is may occurs if you are missing config.h file,

For update config.h file,

1) Close your Xcode.

2) Open Terminal, go to your project's root folder and do:

cd node_modules/react-native/third-party/glog-{X}.{X}.{X}/

3) Run the configure script:

./configure

4) Open Xcode and try to run your app.

{X}: version number glog

Mockito: Trying to spy on method is calling the original method

I've found yet another reason for spy to call the original method.

Someone had the idea to mock a final class, and found about MockMaker:

As this works differently to our current mechanism and this one has different limitations and as we want to gather experience and user feedback, this feature had to be explicitly activated to be available ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line: mock-maker-inline

Source: https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#mock-the-unmockable-opt-in-mocking-of-final-classesmethods

After I merged and brought that file to my machine, my tests failed.

I just had to remove the line (or the file), and spy() worked.

How to use color picker (eye dropper)?

Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.

However, I'm able to grab colors easily in Firefox.

  1. Open page in Firefox
  2. Hamburger Menu -> Web Developer -> Eyedropper
  3. Drag eyedropper tool over the image... Click.
    Color is copied to your clipboard, and eyedropper tool goes away.
  4. Paste color code

In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)

How can I get dictionary key as variable directly in Python (not by searching from value)?

For python 3 If you want to get only the keys use this. Replace print(key) with print(values) if you want the values.

for key,value in my_dict:
  print(key)

Return background color of selected cell

The code below gives the HEX and RGB value of the range whether formatted using conditional formatting or otherwise. If the range is not formatted using Conditional Formatting and you intend to use iColor function in the Excel as UDF. It won't work. Read the below excerpt from MSDN.

Note that the DisplayFormat property does not work in user defined functions. For example, in a worksheet function that returns the interior color of a cell, if you use a line similar to:

Range.DisplayFormat.Interior.ColorIndex

then the worksheet function executes to return a #VALUE! error. If you are not finding color of the conditionally formatted range, then I encourage you to rather use

Range.Interior.ColorIndex

as then the function can also be used as UDF in Excel. Such as iColor(B1,"HEX")

Public Function iColor(rng As Range, Optional formatType As String) As Variant
'formatType: Hex for #RRGGBB, RGB for (R, G, B) and IDX for VBA Color Index
    Dim colorVal As Variant
    colorVal = rng.DisplayFormat.Interior.Color
    Select Case UCase(formatType)
        Case "HEX"
            iColor = "#" & Format(Hex(colorVal Mod 256),"00") & _
                           Format(Hex((colorVal \ 256) Mod 256),"00") & _
                           Format(Hex((colorVal \ 65536)),"00")
        Case "RGB"
            iColor = Format((colorVal Mod 256),"00") & ", " & _
                     Format(((colorVal \ 256) Mod 256),"00") & ", " & _
                     Format((colorVal \ 65536),"00")
        Case "IDX"
            iColor = rng.Interior.ColorIndex
        Case Else
            iColor = colorVal
    End Select
End Function

'Example use of the iColor function
Sub Get_Color_Format()
    Dim rng As Range

    For Each rng In Selection.Cells
        rng.Offset(0, 1).Value = iColor(rng, "HEX")
        rng.Offset(0, 2).Value = iColor(rng, "RGB")
    Next
End Sub

Can you call Directory.GetFiles() with multiple filters?

If you have a large list of extensions to check you can use the following. I didn't want to create a lot of OR statements so i modified what lette wrote.

string supportedExtensions = "*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg,*.wmf,*.emf,*.xbm,*.ico,*.eps,*.tif,*.tiff,*.g01,*.g02,*.g03,*.g04,*.g05,*.g06,*.g07,*.g08";
foreach (string imageFile in Directory.GetFiles(_tempDirectory, "*.*", SearchOption.AllDirectories).Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower())))
{
    //do work here
}

How can I align YouTube embedded video in the center in bootstrap

Youtube uses iframe. You can simply set it to:

iframe {
   display: block;
   margin: 0 auto;
}

How do you find out the caller function in JavaScript?

I'm attempting to address both the question and the current bounty with this question.

The bounty requires that the caller be obtained in strict mode, and the only way I can see this done is by referring to a function declared outside of strict mode.

For example, the following is non-standard but has been tested with previous (29/03/2016) and current (1st August 2018) versions of Chrome, Edge and Firefox.

_x000D_
_x000D_
function caller()_x000D_
{_x000D_
   return caller.caller.caller;_x000D_
}_x000D_
_x000D_
'use strict';_x000D_
function main()_x000D_
{_x000D_
   // Original question:_x000D_
   Hello();_x000D_
   // Bounty question:_x000D_
   (function() { console.log('Anonymous function called by ' + caller().name); })();_x000D_
}_x000D_
_x000D_
function Hello()_x000D_
{_x000D_
   // How do you find out the caller function is 'main'?_x000D_
   console.log('Hello called by ' + caller().name);_x000D_
}_x000D_
_x000D_
main();
_x000D_
_x000D_
_x000D_

Combine several images horizontally with Python

If all image’s heights are same,

imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
  np.concatenate(
    [np.array(Image.open(x)) for x in imgs],
    axis=1
  )
)

maybe you can resize images before the concatenation like this,

imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
  np.concatenate(
    [np.array(Image.open(x).resize((640,480)) for x in imgs],
    axis=1
  )
)

Shuffle DataFrame rows

What is also useful, if you use it for Machine_learning and want to seperate always the same data, you could use:

df.sample(n=len(df), random_state=42)

this makes sure, that you keep your random choice always replicatable

Export a list into a CSV or TXT file in R

I think the most straightforward way to do this is using capture.output, thus;

capture.output(summary(mylist), file = "My New File.txt")

Easy!

Making LaTeX tables smaller?

There is also the singlespace environment:

\begin{singlespace}
\end{singlespace}

Bootstrap 4 - Glyphicons migration?

Go to

https://github.com/Darkseal/bootstrap4-glyphicons

download and include in your code

<link href="bootstrap4-glyphicons/css/bootstrap-glyphicons.css" rel="stylesheet">

Console.log(); How to & Debugging javascript

I like to add these functions in the head.

window.log=function(){if(this.console){console.log(Array.prototype.slice.call(arguments));}};
jQuery.fn.log=function (msg){console.log("%s: %o", msg,this);return this;};

Now log won't break IE I can enable it or disable it in one place I can log inline

$(".classname").log(); //show an array of all elements with classname class

ListView inside ScrollView is not scrolling on Android

The best solution is to use NestedScrollVew with RecyclerView or if you want to go with Listview then you can add header and footer view to this. For example:

View footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.outofoffice_footer_view, null, false);
infoListView.addFooterView(footerView);

How to easily resize/optimize an image size with iOS?

For Swift 3, the below code scales the image keeping the aspect ratio. You can read more about the ImageContext in Apple's documentation:

extension UIImage {
    class func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {
        let scale = newHeight / image.size.height
        let newWidth = image.size.width * scale
        UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
        image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
}

To use it, call resizeImage() method:

UIImage.resizeImage(image: yourImageName, newHeight: yourImageNewHeight)

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

If none of the answers worked for you. You might be in the wrong "Window". I was in "Package explorer" and switching to "Project Explorer" showed me the folders.

Named colors in matplotlib

To get a full list of colors to use in plots:

import matplotlib.colors as colors
colors_list = list(colors._colors_full_map.values())

So, you can use in that way quickly:

scatter(X,Y, color=colors_list[0])
scatter(X,Y, color=colors_list[1])
scatter(X,Y, color=colors_list[2])
...
scatter(X,Y, color=colors_list[-1])

ReactJs: What should the PropTypes be for this.props.children?

Example:

import React from 'react';
import PropTypes from 'prop-types';

class MenuItem extends React.Component {
    render() {
        return (
            <li>
                <a href={this.props.href}>{this.props.children}</a>
            </li>
        );
    }
}

MenuItem.defaultProps = {
    href: "/",
    children: "Main page"
};

MenuItem.propTypes = {
    href: PropTypes.string.isRequired,
    children: PropTypes.string.isRequired
};

export default MenuItem;

Picture: Shows you error in console if the expected type is different

Picture: Shows you error in console if the expected type is different

Propagation Delay vs Transmission delay

Transmission Delay : Amount of time required to pump all bits/packets into the electric wire/optic fibre.

Propagation delay : It's the amount of time needed for a packet to reach the destination.

If propagation delay is very high than transmission delay the chance of losing the packet is high.

How to display a list of images in a ListView in Android?

I came up with a solution that I call “BatchImageDownloader” that has served well. Here’s a quick summary of how it is used:

  • Keep a global HashMap (ideally in your Application object) that serves as a cache of drawable objects

  • In the getView() method of your List Adapter, use the drawable from the cache for populating the ImageView in your list item.

  • Create an instance of BatchImageDownloader, passing in your ListView Adapter

  • Call addUrl() for each image that needs to be fetched/displayed

  • When done, call execute(). This fires an AsyncTask that fetches all images, and as each image is fetched and added to the cache, it refreshes your ListView (by calling notifyDataSetChanged())

The approach has the following advantages:

  • A single worker thread is used to fetch all images, rather than a separate thread for each image/view
  • Once an image is fetched, all list items that use it are instantly updated
  • The code does not access the Image View in your List Item directly – instead it triggers a listview refresh by calling notifyDataSetChanged() on your List Adapter, and the getView() implementation simply pulls the drawable from the cache and displays it. This avoids the problems associated with recycled View objects used in ListViews.

Here is the source code of BatchImageDownloader:

package com.mobrite.androidutils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.widget.BaseAdapter;

public class BatchImageDownloader extends AsyncTask<Void, Void, Void> {

    List<String> imgUrls = new ArrayList<String>();
    BaseAdapter adapter;
    HashMap<String, Drawable> imageCache;

    public BatchImageDownloader(BaseAdapter adapter,
            HashMap<String, Drawable> imageCache) {
        this.adapter = adapter;
        this.imageCache = imageCache;
    }

    public void addUrl(String url) {
        imgUrls.add(url);
    }

    @Override
    protected Void doInBackground(Void... params) {
        for (String url : imgUrls) {
            if (!imageCache.containsKey(url)) {
                Drawable bm = downloadImage(url);
                if (null != bm) {
                    imageCache.put(url, bm);
                    publishProgress();
                }
            }
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onPostExecute(Void result) {
        adapter.notifyDataSetChanged();
    }

    public Drawable downloadImage(String url) {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(request);
            InputStream stream = response.getEntity().getContent();
            Drawable drawable = Drawable.createFromStream(stream, "src");
            return drawable;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

}

Why does overflow:hidden not work in a <td>?

I've just had a similar problem, and had to use the <div> inside the <td> at first (John MacIntyre's solution didn't work for me for various reasons).

Note though that <td><div>...</div></td> isn't valid placement for a div so instead I'm using a <span> with display:block; set. It validates fine now and works.

How to execute a shell script from C in Linux?

I prefer fork + execlp for "more fine-grade" control as doron mentioned. Example code shown below.

Store you command in a char array parameters, and malloc space for the result.

int fd[2];
pipe(fd);
if ( (childpid = fork() ) == -1){
   fprintf(stderr, "FORK failed");
   return 1;
} else if( childpid == 0) {
   close(1);
   dup2(fd[1], 1);
   close(fd[0]);
   execlp("/bin/sh","/bin/sh","-c",parameters,NULL);
}
wait(NULL);
read(fd[0], result, RESULT_SIZE);
printf("%s\n",result);

Proper use of mutexes in Python

You have to unlock your Mutex at sometime...

List all employee's names and their managers by manager name using an inner join

SELECT DISTINCT e.Ename AS Employee, 
    m.mgr AS reports_to, 
    m.Ename AS manager 
FROM Employees e, Employees m 
WHERE e.mgr=m.EmpID;

Calling other function in the same controller?

Yes. Problem is in wrong notation. Use:

$this->sendRequest($uri)

Instead. Or

self::staticMethod()

for static methods. Also read this for getting idea of OOP - http://www.php.net/manual/en/language.oop5.basic.php

Javascript to display the current date and time

var today = new Date(); 
    var dd = today.getDate(); 
    var mm = today.getMonth()+1;//January is 0! 
    var yyyy = today.getFullYear(); 
    var h = today.getHours();
       var m = today.getMinutes();
       var s = today.getSeconds();
    if(dd<10){dd='0'+dd} 
    if(mm<10){mm='0'+mm} 
    if(h<10){h='0'+h}
    if(m<10){m='0'+m} 
    if(s<10){s='0'+s}  
    onload = function(){ 
        $scope.currentTime=+dd+'/'+mm+'/'+yyyy+' '+h+':'+m+':'+s;
    }  

Change the color of cells in one column when they don't match cells in another column

In my case I had to compare column E and I.

I used conditional formatting with new rule. Formula was "=IF($E1<>$I1,1,0)" for highlights in orange and "=IF($E1=$I1,1,0)" to highlight in green.

Next problem is how many columns you want to highlight. If you open Conditional Formatting Rules Manager you can edit for each rule domain of applicability: Check "Applies to"

In my case I used "=$E:$E,$I:$I" for both rules so I highlight only two columns for differences - column I and column E.

htaccess redirect to https://www

To first force HTTPS, you must check the correct environment variable %{HTTPS} off, but your rule above then prepends the www. Since you have a second rule to enforce www., don't use it in the first rule.

RewriteEngine On
RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
# [NC] is a case-insensitive match
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

About proxying

When behind some forms of proxying, whereby the client is connecting via HTTPS to a proxy, load balancer, Passenger application, etc., the %{HTTPS} variable may never be on and cause a rewrite loop. This is because your application is actually receiving plain HTTP traffic even though the client and the proxy/load balancer are using HTTPS. In these cases, check the X-Forwarded-Proto header instead of the %{HTTPS} variable. This answer shows the appropriate process

How to change a particular element of a C++ STL vector

I prefer

l.at(4)= -1;

while [4] is your index

How to get length of a list of lists in python

This saves the data in a list of lists.

text = open("filetest.txt", "r")
data = [ ]
for line in text:
    data.append( line.strip().split() )

print "number of lines ", len(data)
print "number of columns ", len(data[0])

print "element in first row column two ", data[0][1]

Creating an R dataframe row-by-row

Dirk Eddelbuettel's answer is the best; here I just note that you can get away with not pre-specifying the dataframe dimensions or data types, which is sometimes useful if you have multiple data types and lots of columns:

row1<-list("a",1,FALSE) #use 'list', not 'c' or 'cbind'!
row2<-list("b",2,TRUE)  

df<-data.frame(row1,stringsAsFactors = F) #first row
df<-rbind(df,row2) #now this works as you'd expect.

Loop through all the rows of a temp table and call a stored procedure for each row

You can do something like this

    Declare @min int=0, @max int =0 --Initialize variable here which will be use in loop 
    Declare @Recordid int,@TO nvarchar(30),@Subject nvarchar(250),@Body nvarchar(max)  --Initialize variable here which are useful for your

    select ROW_NUMBER() OVER(ORDER BY [Recordid] )  AS Rownumber, Recordid, [To], [Subject], [Body], [Flag]
            into #temp_Mail_Mstr FROM Mail_Mstr where Flag='1'  --select your condition with row number & get into a temp table

    set @min = (select MIN(Rownumber) from #temp_Mail_Mstr); --Get minimum row number from temp table
    set @max = (select Max(Rownumber) from #temp_Mail_Mstr);  --Get maximum row number from temp table

   while(@min <= @max)
   BEGIN
        select @Recordid=Recordid, @To=[To], @Subject=[Subject], @Body=Body from #temp_Mail_Mstr where Rownumber=@min

        -- You can use your variables (like @Recordid,@To,@Subject,@Body) here  
        -- Do your work here 

        set @min=@min+1 --Increment of current row number
    END

How to find out what character key is pressed?

There are a million duplicates of this question on here, but here goes again anyway:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.keyCode || evt.which;
    var charStr = String.fromCharCode(charCode);
    alert(charStr);
};

The best reference on key events I've seen is http://unixpapa.com/js/key.html.

How to keep the local file or the remote file during merge using Git and the command line?

git checkout {branch-name} -- {file-name}

This will use the file from the branch of choice.

I like this because posh-git autocomplete works great with this. It also removes any ambiguity as to which branch is remote and which is local. And --theirs didn't work for me anyways.

Referencing a string in a string array resource with xml

In short: I don't think you can, but there seems to be a workaround:.

If you take a look into the Android Resource here:

http://developer.android.com/guide/topics/resources/string-resource.html

You see than under the array section (string array, at least), the "RESOURCE REFERENCE" (as you get from an XML) does not specify a way to address the individual items. You can even try in your XML to use "@array/yourarrayhere". I know that in design time you will get the first item. But that is of no practical use if you want to use, let's say... the second, of course.

HOWEVER, there is a trick you can do. See here:

Referencing an XML string in an XML Array (Android)

You can "cheat" (not really) the array definition by addressing independent strings INSIDE the definition of the array. For example, in your strings.xml:

<string name="earth">Earth</string>
<string name="moon">Moon</string>

<string-array name="system">
    <item>@string/earth</item>
    <item>@string/moon</item>
</string-array>

By using this, you can use "@string/earth" and "@string/moon" normally in your "android:text" and "android:title" XML fields, and yet you won't lose the ability to use the array definition for whatever purposes you intended in the first place.

Seems to work here on my Eclipse. Why don't you try and tell us if it works? :-)

python - find index position in list based of partial string

indices = [i for i, s in enumerate(mylist) if 'aa' in s]

Collision Detection between two images in Java

You don't want to have the collision check code inside the painting code. The painting needs to be fast. Collision can go in the game loop. Therefore you need an internal representation of the objects independent of their sprites.

correct PHP headers for pdf file download

Example 2 on w3schools shows what you are trying to achieve.

<?php
header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in original.pdf
readfile("original.pdf");
?>

Also remember that,

It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)

Converting an object to a string

function objToString (obj) {
    var str = '{';
    if(typeof obj=='object')
      {

        for (var p in obj) {
          if (obj.hasOwnProperty(p)) {
              str += p + ':' + objToString (obj[p]) + ',';
          }
      }
    }
      else
      {
         if(typeof obj=='string')
          {
            return '"'+obj+'"';
          }
          else
          {
            return obj+'';
          }
      }



    return str.substring(0,str.length-1)+"}";
}

How to read a large file line by line?

To strip newlines:

with open(file_path, 'rU') as f:
    for line_terminated in f:
        line = line_terminated.rstrip('\n')
        ...

With universal newline support all text file lines will seem to be terminated with '\n', whatever the terminators in the file, '\r', '\n', or '\r\n'.

EDIT - To specify universal newline support:

  • Python 2 on Unix - open(file_path, mode='rU') - required [thanks @Dave]
  • Python 2 on Windows - open(file_path, mode='rU') - optional
  • Python 3 - open(file_path, newline=None) - optional

The newline parameter is only supported in Python 3 and defaults to None. The mode parameter defaults to 'r' in all cases. The U is deprecated in Python 3. In Python 2 on Windows some other mechanism appears to translate \r\n to \n.

Docs:

To preserve native line terminators:

with open(file_path, 'rb') as f:
    with line_native_terminated in f:
        ...

Binary mode can still parse the file into lines with in. Each line will have whatever terminators it has in the file.

Thanks to @katrielalex's answer, Python's open() doc, and iPython experiments.

Equation for testing if a point is inside a circle

As said above -- use Euclidean distance.

from math import hypot

def in_radius(c_x, c_y, r, x, y):
    return math.hypot(c_x-x, c_y-y) <= r

Stretch background image css?

Just paste this into your line of codes:

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

Create a menu Bar in WPF?

Yes, a menu gives you the bar but it doesn't give you any items to put in the bar. You need something like (from one of my own projects):

<!-- Menu. -->
<Menu Width="Auto" Height="20" Background="#FFA9D1F4" DockPanel.Dock="Top">
    <MenuItem Header="_Emulator">
    <MenuItem Header="Load..." Click="MenuItem_Click" />
    <MenuItem Header="Load again" Click="menuEmulLoadLast" />
    <Separator />
    <MenuItem Click="MenuItem_Click">
        <MenuItem.Header>
            <DockPanel>
                <TextBlock>Step</TextBlock>
                <TextBlock Width="10"></TextBlock>
                <TextBlock HorizontalAlignment="Right">F2</TextBlock>
            </DockPanel>
        </MenuItem.Header>
    </MenuItem>
    :

How to resolve merge conflicts in Git repository?

For Emacs users which want to resolve merge conflicts semi-manually:

git diff --name-status --diff-filter=U

shows all files which require conflict resolution.

Open each of those files one by one, or all at once by:

emacs $(git diff --name-only --diff-filter=U)

When visiting a buffer requiring edits in Emacs, type

ALT+x vc-resolve-conflicts

This will open three buffers (mine, theirs, and the output buffer). Navigate by pressing 'n' (next region), 'p' (prevision region). Press 'a' and 'b' to copy mine or theirs region to the output buffer, respectively. And/or edit the output buffer directly.

When finished: Press 'q'. Emacs asks you if you want to save this buffer: yes. After finishing a buffer mark it as resolved by running from the teriminal:

git add FILENAME

When finished with all buffers type

git commit

to finish the merge.

How to automatically insert a blank row after a group of data

Select your array, including column labels, DATA > Outline -Subtotal, At each change in: column1, Use function: Count, Add subtotal to: column3, check Replace current subtotals and Summary below data, OK.

Filter and select for Column1, Text Filters, Contains..., Count, OK. Select all visible apart from the labels and delete contents. Remove filter and, if desired, ungroup rows.

Angular expression if array contains

You shouldn't overload the templates with complex logic, it's a bad practice. Remember to always keep it simple!

The better approach would be to extract this logic into reusable function on your $rootScope:

.run(function ($rootScope) {
  $rootScope.inArray = function (item, array) {
    return (-1 !== array.indexOf(item));
  };
})

Then, use it in your template:

<li ng-class="{approved: inArray(jobSet, selectedForApproval)}"></li>

I think everyone will agree that this example is much more readable and maintainable.

How to change Format of a Cell to Text using VBA

for large numbers that display with scientific notation set format to just '#'

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

In one reusable piece of code I use the directive <%@include file="reuse.html"%> and in the second I use the standard action <jsp:include page="reuse.html" />.

Let the code in the reusable file be:

<html>
<head>
    <title>reusable</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <img src="candle.gif" height="100" width="50"/> <br />
    <p><b>As the candle burns,so do I</b></p>
</body>

After running both the JSP files you see the same output and think if there was any difference between the directive and the action tag. But if you look at the generated servlet of the two JSP files, you will see the difference.

Here is what you will see when you use the directive:

out.write("<html>\r\n");
out.write("    <head>\r\n");
out.write("        <title>reusable</title>\r\n");
out.write("        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write("    </head>\r\n");
out.write("    <body>\r\n");
out.write("        <img src=\"candle.gif\" height=\"100\" width=\"50\"/> <br />\r\n");
out.write("        <p><b>As the candle burns,so do I</b></p>\r\n");
out.write("    </body>\r\n");
out.write("</html>\r\n");
 

And this is what you will see for the used standard action in the second JSP file :

org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "reusable.html", out, false);

So now you know that the include directive inserts the source of reuse.html at translation time, but the action tag inserts the response of reuse.html at runtime.

If you think about it, there is an extra performance hit with every action tag (<jsp:include>). It means you can guarantee you will always have the latest content, but it increases performance cost.

Pytorch tensor to numpy array

While other answers perfectly explained the question I will add some real life examples converting tensors to numpy array:

Example: Shared storage

PyTorch tensor residing on CPU shares the same storage as numpy array na

import torch
a = torch.ones((1,2))
print(a)
na = a.numpy()
na[0][0]=10
print(na)
print(a)

Output:

tensor([[1., 1.]])
[[10.  1.]]
tensor([[10.,  1.]])

Example: Eliminate effect of shared storage, copy numpy array first

To avoid the effect of shared storage we need to copy() the numpy array na to a new numpy array nac. Numpy copy() method creates the new separate storage.

import torch
a = torch.ones((1,2))
print(a)
na = a.numpy()
nac = na.copy()
nac[0][0]=10
?print(nac)
print(na)
print(a)

Output:

tensor([[1., 1.]])
[[10.  1.]]
[[1. 1.]]
tensor([[1., 1.]])

Now, just the nac numpy array will be altered with the line nac[0][0]=10, na and a will remain as is.

Example: CPU tensor with requires_grad=True

import torch
a = torch.ones((1,2), requires_grad=True)
print(a)
na = a.detach().numpy()
na[0][0]=10
print(na)
print(a)

Output:

tensor([[1., 1.]], requires_grad=True)
[[10.  1.]]
tensor([[10.,  1.]], requires_grad=True)

In here we call:

na = a.numpy() 

This would cause: RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead., because tensors that require_grad=True are recorded by PyTorch AD. Note that tensor.detach() is the new way for tensor.data.

This explains why we need to detach() them first before converting using numpy().

Example: CUDA tensor with requires_grad=False

a = torch.ones((1,2), device='cuda')
print(a)
na = a.to('cpu').numpy()
na[0][0]=10
print(na)
print(a)

Output:

tensor([[1., 1.]], device='cuda:0')
[[10.  1.]]
tensor([[1., 1.]], device='cuda:0')

?

Example: CUDA tensor with requires_grad=True

a = torch.ones((1,2), device='cuda', requires_grad=True)
print(a)
na = a.detach().to('cpu').numpy()
na[0][0]=10
?print(na)
print(a)

Output:

tensor([[1., 1.]], device='cuda:0', requires_grad=True)
[[10.  1.]]
tensor([[1., 1.]], device='cuda:0', requires_grad=True)

Without detach() method the error RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead. will be set.

Without .to('cpu') method TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first. will be set.

You could use cpu() but instead of to('cpu') but I prefer the newer to('cpu').

Tkinter understanding mainloop

while 1:
    root.update()

... is (very!) roughly similar to:

root.mainloop()

The difference is, mainloop is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop is a much cleaner solution. After all, calling mainloop is essentially this under the covers:

while the_window_has_not_been_destroyed():
    wait_until_the_event_queue_is_not_empty()
    event = event_queue.pop()
    event.handle()

... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?

Put in the simplest terms possible: always call mainloop as the last logical line of code in your program. That's how Tkinter was designed to be used.

Bootstrap collapse animation not smooth

Jerking happens when the parent div ".collapse" has padding.

Padding goes on the child div, not the parent. jQuery is animating the height, not the padding.

Example:

  <div class="form-group">
       <a for="collapseOne" data-toggle="collapse" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">+ addInfo</a>
       <div class="collapse" id="collapseOne" style="padding: 0;">
          <textarea class="form-control" rows="4" style="padding: 20px;"></textarea>
       </div>
  </div>

  <div class="form-group">
    <a for="collapseTwo" data-toggle="collapse" href="#collapseTwo" aria-expanded="true" aria-controls="collapseOne">+ subtitle</a>
    <input type="text" class="form-control collapse" id="collapseTwo">
  </div>

Fiddle Showing Both

Hope this helps.

Change / Add syntax highlighting for a language in Sublime 2/3

Syntax highlighting is controlled by the theme you use, accessible through Preferences -> Color Scheme. Themes highlight different keywords, functions, variables, etc. through the use of scopes, which are defined by a series of regular expressions contained in a .tmLanguage file in a language's directory/package. For example, the JavaScript.tmLanguage file assigns the scopes source.js and variable.language.js to the this keyword. Since Sublime Text 3 is using the .sublime-package zip file format to store all the default settings it's not very straightforward to edit the individual files.

Unfortunately, not all themes contain all scopes, so you'll need to play around with different ones to find one that looks good, and gives you the highlighting you're looking for. There are a number of themes that are included with Sublime Text, and many more are available through Package Control, which I highly recommend installing if you haven't already. Make sure you follow the ST3 directions.

As it so happens, I've developed the Neon Color Scheme, available through Package Control, that you might want to take a look at. My main goal, besides trying to make a broad range of languages look as good as possible, was to identify as many different scopes as I could - many more than are included in the standard themes. While the JavaScript language definition isn't as thorough as Python's, for example, Neon still has a lot more diversity than some of the defaults like Monokai or Solarized.

jQuery highlighted with Neon Theme

I should note that I used @int3h's Better JavaScript language definition for this image instead of the one that ships with Sublime. It can be installed via Package Control.

UPDATE

Of late I've discovered another JavaScript replacement language definition - JavaScriptNext - ES6 Syntax. It has more scopes than the base JavaScript or even Better JavaScript. It looks like this on the same code:

JavaScriptNext

Also, since I originally wrote this answer, @skuroda has released PackageResourceViewer via Package Control. It allows you to seamlessly view, edit and/or extract parts of or entire .sublime-package packages. So, if you choose, you can directly edit the color schemes included with Sublime.

ANOTHER UPDATE

With the release of nearly all of the default packages on Github, changes have been coming fast and furiously. The old JS syntax has been completely rewritten to include the best parts of JavaScript Next ES6 Syntax, and now is as fully ES6-compatible as can be. A ton of other changes have been made to cover corner and edge cases, improve consistency, and just overall make it better. The new syntax has been included in the (at this time) latest dev build 3111.

If you'd like to use any of the new syntaxes with the current beta build 3103, simply clone the Github repo someplace and link the JavaScript (or whatever language(s) you want) into your Packages directory - find it on your system by selecting Preferences -> Browse Packages.... Then, simply do a git pull in the original repo directory from time to time to refresh any changes, and you can enjoy the latest and greatest! I should note that the repo uses the new .sublime-syntax format instead of the old .tmLanguage one, so they will not work with ST3 builds prior to 3084, or with ST2 (in both cases, you should have upgraded to the latest beta or dev build anyway).

I'm currently tweaking my Neon Color Scheme to handle all of the new scopes in the new JS syntax, but most should be covered already.

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

It might be a network issue. If you are running inside a virtual machine (e.g. VMWare or VirtualBox), try setting the network adapter mode from the default NAT to Bridged.

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

Post installation of postgres, in my case version is 12.2, I did run the below command createdb.

$ createdb `whoami`

$ psql

psql (12.2)
Type "help" for help.

macuser=# 

How can I change Eclipse theme?

Eclipse... To just get everything done goto Window>Preferences>General and goto theme menu and change it... Then re-start to apply...

How to echo text during SQL script execution in SQLPLUS

The prompt command will echo text to the output:

prompt A useful comment.
select(*) from TableA;

Will be displayed as:

SQL> A useful comment.
SQL> 
  COUNT(*)
----------
     0

How can I output a UTF-8 CSV in PHP that Excel will read properly?

I have the same (or similar) problem.

In my case, if I add a BOM to the output, it works:

header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename=Customers_Export.csv');
echo "\xEF\xBB\xBF"; // UTF-8 BOM

I believe this is a pretty ugly hack, but it worked for me, at least for Excel 2007 Windows. Not sure it'll work on Mac.

Adding subscribers to a list using Mailchimp's API v3

Based on the List Members Instance docs, the easiest way is to use a PUT request which according to the docs either "adds a new list member or updates the member if the email already exists on the list".

Furthermore apikey is definitely not part of the json schema and there's no point in including it in your json request.

Also, as noted in @TooMuchPete's comment, you can use CURLOPT_USERPWD for basic http auth as illustrated in below.

I'm using the following function to add and update list members. You may need to include a slightly different set of merge_fields depending on your list parameters.

$data = [
    'email'     => '[email protected]',
    'status'    => 'subscribed',
    'firstname' => 'john',
    'lastname'  => 'doe'
];

syncMailchimp($data);

function syncMailchimp($data) {
    $apiKey = 'your api key';
    $listId = 'your list id';

    $memberId = md5(strtolower($data['email']));
    $dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
    $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;

    $json = json_encode([
        'email_address' => $data['email'],
        'status'        => $data['status'], // "subscribed","unsubscribed","cleaned","pending"
        'merge_fields'  => [
            'FNAME'     => $data['firstname'],
            'LNAME'     => $data['lastname']
        ]
    ]);

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);                                                                                                                 

    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $httpCode;
}

How to have git log show filenames like svn log -v

If you want to get the file names only without the rest of the commit message you can use:

git log --name-only --pretty=format: <branch name>

This can then be extended to use the various options that contain the file name:

git log --name-status --pretty=format: <branch name>

git log --stat --pretty=format: <branch name>

One thing to note when using this method is that there are some blank lines in the output that will have to be ignored. Using this can be useful if you'd like to see the files that have been changed on a local branch, but is not yet pushed to a remote branch and there is no guarantee the latest from the remote has already been pulled in. For example:

git log --name-only --pretty=format: my_local_branch --not origin/master

Would show all the files that have been changed on the local branch, but not yet merged to the master branch on the remote.

webpack is not recognized as a internal or external command,operable program or batch file

I had this issue when upgrading to React 16.12.0.

I had two errors one regarding webpack and the other regarding the store when rendering the DOM.

Webpack Error:

webpack is not recognized as a internal or external command,operable program or batch file

Webpack Solution:

  1. Close related VS Solution
  2. Delete node_modules folder
  3. Deleted package-lock.json
  4. npm install
  5. npm rebuild
  6. Repeated this 2-3 times

Store Error:

Type Store<()> is not assignable to type Store<any, AnyAction>

Store Solution:

Suggestions to update my React version didn't fix this error for me, but irrespective I would recommend doing it.

My code ended up looking like this:

ReactDOM.render(
        <Provider store={store as any}>
            <ConnectedApp />
        </Provider>,
        document.getElementById('app')
    );

As per this solution

creating a table in ionic

Simply, for me, I used ion-row and ion-col to achieve it. You can make it more neater by doing some changes by CSS.

<ion-row style="border-bottom: groove;">
      <ion-col col-4>
      <ion-label >header</ion-label>
    </ion-col>
    <ion-col col-4>
      <ion-label >header</ion-label>
    </ion-col>
      <ion-col col-4>
      <ion-label >header</ion-label>
    </ion-col>
  </ion-row>
  <ion-row style="border-bottom: groove;">
      <ion-col col-4>
      <ion-label >row</ion-label>
    </ion-col>
    <ion-col col-4>
      <ion-label >02/02/2018</ion-label>
    </ion-col>
      <ion-col col-4>
      <ion-label >row</ion-label>
    </ion-col>
  </ion-row>
  <ion-row style="border-bottom: groove;">
      <ion-col col-4>
      <ion-label >row</ion-label>
    </ion-col>
    <ion-col col-4>
      <ion-label >02/02/2018</ion-label>
    </ion-col>
      <ion-col col-4>
      <ion-label >row</ion-label>
    </ion-col>
  </ion-row>
  <ion-row >
      <ion-col col-4>
      <ion-label >row</ion-label>
    </ion-col>
    <ion-col col-4>
      <ion-label >02/02/2018</ion-label>
    </ion-col>
      <ion-col col-4>
      <ion-label >row</ion-label>
    </ion-col>
  </ion-row>

Facebook share link - can you customize the message body text?

You can't do this using sharer.php, but you can do something similar using the Dialog API. http://developers.facebook.com/docs/reference/dialogs/

http://www.facebook.com/dialog/feed?  
app_id=123050457758183&  
link=http://developers.facebook.com/docs/reference/dialogs/&
picture=http://fbrell.com/f8.jpg&  
name=Facebook%20Dialogs&  
caption=Reference%20Documentation& 
description=Dialogs%20provide%20a%20simple,%20consistent%20interface%20for%20applications%20to%20interact%20with%20users.&
message=Facebook%20Dialogs%20are%20so%20easy!&
redirect_uri=http://www.example.com/response

Facebook dialog example

The catch is you must create a dummy Facebook application just to have an app_id. Note that your Facebook application doesn't have to do ANYTHING at all. Just be sure that it is properly configured, and you should be all set.

Get generic type of class at runtime

As others mentioned, it's only possible via reflection in certain circumstances.

If you really need the type, this is the usual (type-safe) workaround pattern:

public class GenericClass<T> {

     private final Class<T> type;

     public GenericClass(Class<T> type) {
          this.type = type;
     }

     public Class<T> getMyType() {
         return this.type;
     }
}

Populate unique values into a VBA array from Excel

Profiting from the MS Excel 365 function UNIQUE()

In order to enrich the valid solutions above:

Sub ExampleCall()
Dim rng As Range: Set rng = Sheet1.Range("A2:A11")   ' << change to your sheet's Code(Name)
Dim a: a = rng
a = getUniques(a)
arrInfo a
End Sub
Function getUniques(a, Optional ZeroBased As Boolean = True)
Dim tmp: tmp = Application.Transpose(WorksheetFunction.Unique(a))
If ZeroBased Then ReDim Preserve tmp(0 To UBound(tmp) - 1)
getUniques = tmp
End Function

macro run-time error '9': subscript out of range

Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

An unmodifiable map may still change. It is only a view on a modifiable map, and changes in the backing map will be visible through the unmodifiable map. The unmodifiable map only prevents modifications for those who only have the reference to the unmodifiable view:

Map<String, String> realMap = new HashMap<String, String>();
realMap.put("A", "B");

Map<String, String> unmodifiableMap = Collections.unmodifiableMap(realMap);

// This is not possible: It would throw an 
// UnsupportedOperationException
//unmodifiableMap.put("C", "D");

// This is still possible:
realMap.put("E", "F");

// The change in the "realMap" is now also visible
// in the "unmodifiableMap". So the unmodifiableMap
// has changed after it has been created.
unmodifiableMap.get("E"); // Will return "F". 

In contrast to that, the ImmutableMap of Guava is really immutable: It is a true copy of a given map, and nobody may modify this ImmutableMap in any way.

Update:

As pointed out in a comment, an immutable map can also be created with the standard API using

Map<String, String> immutableMap = 
    Collections.unmodifiableMap(new LinkedHashMap<String, String>(realMap)); 

This will create an unmodifiable view on a true copy of the given map, and thus nicely emulates the characteristics of the ImmutableMap without having to add the dependency to Guava.

Django - iterate number in for loop of a template

[Django HTML template doesn't support index as of now], but you can achieve the goal:

If you use Dictionary inside Dictionary in views.py then iteration is possible using key as index. example:

{% for key, value in DictionartResult.items %} <!-- dictionartResult is a dictionary having key value pair-->
<tr align="center">
    <td  bgcolor="Blue"><a href={{value.ProjectName}}><b>{{value.ProjectName}}</b></a></td>
    <td> {{ value.atIndex0 }} </td>         <!-- atIndex0 is a key which will have its value , you can treat this key as index to resolve-->
    <td> {{ value.atIndex4 }} </td>
    <td> {{ value.atIndex2 }} </td>
</tr>
{% endfor %}

Elseif you use List inside dictionary then not only first and last iteration can be controlled, but all index can be controlled. example:

{% for key, value in DictionaryResult.items %}
    <tr align="center">
    {% for project_data in value %}
        {% if  forloop.counter <= 13 %}  <!-- Here you can control the iteration-->
            {% if forloop.first %}
                <td bgcolor="Blue"><a href={{project_data}}><b> {{ project_data }} </b></a></td> <!-- it will always refer to project_data[0]-->
            {% else %}
                <td> {{ project_data }} </td> <!-- it will refer to all items in project_data[] except at index [0]-->
            {% endif %}
            {% endif %}
    {% endfor %}
    </tr>
{% endfor %}

End If ;)

// Hope have covered the solution with Dictionary, List, HTML template, For Loop, Inner loop, If Else. Django HTML Documentaion for more methods: https://docs.djangoproject.com/en/2.2/ref/templates/builtins/

Get elements by attribute when querySelectorAll is not available without using libraries?

I played a bit around and ended up with this crude solution:

function getElementsByAttribute(attribute, context) {
  var nodeList = (context || document).getElementsByTagName('*');
  var nodeArray = [];
  var iterator = 0;
  var node = null;

  while (node = nodeList[iterator++]) {
    if (node.hasAttribute(attribute)) nodeArray.push(node);
  }

  return nodeArray;
}

The usage is quite simple, and works even in IE8:

getElementsByAttribute('data-foo');
// or with parentNode
getElementsByAttribute('data-foo', document);

http://fiddle.jshell.net/9xaxf6jr/

But I recommend to use querySelector / All for this (and to support older browsers use a polyfill):

document.querySelectorAll('[data-foo]');

Java Command line arguments

Your main method has a String[] argument. That contain the arguments that have been passed to your applications (it's often called args, but that's not a requirement).

Python: converting a list of dictionaries to json

To convert it to a single dictionary with some decided keys value, you can use the code below.

data = ListOfDict.copy()
PrecedingText = "Obs_"
ListOfDictAsDict = {}
for i in range(len(data)):
    ListOfDictAsDict[PrecedingText + str(i)] = data[i]

SQL Server : converting varchar to INT

This is more for someone Searching for a result, than the original post-er. This worked for me...

declare @value varchar(max) = 'sad';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));

returns 0

declare @value varchar(max) = '3';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));

returns 3

Replace comma with newline in sed on MacOS?

Though I am late to this post, just updating my findings. This answer is only for Mac OS X.

$ sed 's/new/
> /g' m1.json > m2.json
sed: 1: "s/new/
/g": unescaped newline inside substitute pattern

In the above command I tried with Shift+Enter to add new line which didn't work. So this time I tried with "escaping" the "unescaped newline" as told by the error.

$ sed 's/new/\
> /g' m1.json > m2.json 

Worked! (in Mac OS X 10.9.3)

Copying text to the clipboard using Java

I found a better way of doing it so you can get a input from a txtbox or have something be generated in that text box and be able to click a button to do it.!

import java.awt.datatransfer.*;
import java.awt.Toolkit;

private void /* Action performed when the copy to clipboard button is clicked */ {
    String ctc = txtCommand.getText().toString();
    StringSelection stringSelection = new StringSelection(ctc);
    Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
    clpbrd.setContents(stringSelection, null);
}

// txtCommand is the variable of a text box

Check if an object belongs to a class in Java

Use the instanceof operator:

if(a instanceof MyClass)
{
    //do something
}

How do you use the "WITH" clause in MySQL?

I followed the link shared by lisachenko and found another link to this blog: http://guilhembichot.blogspot.co.uk/2013/11/with-recursive-and-mysql.html

The post lays out ways of emulating the 2 uses of SQL WITH. Really good explanation on how these work to do a similar query as SQL WITH.

1) Use WITH so you don't have to perform the same sub query multiple times

CREATE VIEW D AS (SELECT YEAR, SUM(SALES) AS S FROM T1 GROUP BY YEAR);
SELECT D1.YEAR, (CASE WHEN D1.S>D2.S THEN 'INCREASE' ELSE 'DECREASE' END) AS TREND
FROM
 D AS D1,
 D AS D2
WHERE D1.YEAR = D2.YEAR-1;
DROP VIEW D;

2) Recursive queries can be done with a stored procedure that makes the call similar to a recursive with query.

CALL WITH_EMULATOR(
"EMPLOYEES_EXTENDED",
"
  SELECT ID, NAME, MANAGER_ID, 0 AS REPORTS
  FROM EMPLOYEES
  WHERE ID NOT IN (SELECT MANAGER_ID FROM EMPLOYEES WHERE MANAGER_ID IS NOT NULL)
",
"
  SELECT M.ID, M.NAME, M.MANAGER_ID, SUM(1+E.REPORTS) AS REPORTS
  FROM EMPLOYEES M JOIN EMPLOYEES_EXTENDED E ON M.ID=E.MANAGER_ID
  GROUP BY M.ID, M.NAME, M.MANAGER_ID
",
"SELECT * FROM EMPLOYEES_EXTENDED",
0,
""
);

And this is the code or the stored procedure

# Usage: the standard syntax:
#   WITH RECURSIVE recursive_table AS
#    (initial_SELECT
#     UNION ALL
#     recursive_SELECT)
#   final_SELECT;
# should be translated by you to 
# CALL WITH_EMULATOR(recursive_table, initial_SELECT, recursive_SELECT,
#                    final_SELECT, 0, "").

# ALGORITHM:
# 1) we have an initial table T0 (actual name is an argument
# "recursive_table"), we fill it with result of initial_SELECT.
# 2) We have a union table U, initially empty.
# 3) Loop:
#   add rows of T0 to U,
#   run recursive_SELECT based on T0 and put result into table T1,
#   if T1 is empty
#      then leave loop,
#      else swap T0 and T1 (renaming) and empty T1
# 4) Drop T0, T1
# 5) Rename U to T0
# 6) run final select, send relult to client

# This is for *one* recursive table.
# It would be possible to write a SP creating multiple recursive tables.

delimiter |

CREATE PROCEDURE WITH_EMULATOR(
recursive_table varchar(100), # name of recursive table
initial_SELECT varchar(65530), # seed a.k.a. anchor
recursive_SELECT varchar(65530), # recursive member
final_SELECT varchar(65530), # final SELECT on UNION result
max_recursion int unsigned, # safety against infinite loop, use 0 for default
create_table_options varchar(65530) # you can add CREATE-TABLE-time options
# to your recursive_table, to speed up initial/recursive/final SELECTs; example:
# "(KEY(some_column)) ENGINE=MEMORY"
)

BEGIN
  declare new_rows int unsigned;
  declare show_progress int default 0; # set to 1 to trace/debug execution
  declare recursive_table_next varchar(120);
  declare recursive_table_union varchar(120);
  declare recursive_table_tmp varchar(120);
  set recursive_table_next  = concat(recursive_table, "_next");
  set recursive_table_union = concat(recursive_table, "_union");
  set recursive_table_tmp   = concat(recursive_table, "_tmp"); 
  # Cleanup any previous failed runs
  SET @str =
    CONCAT("DROP TEMPORARY TABLE IF EXISTS ", recursive_table, ",",
    recursive_table_next, ",", recursive_table_union,
    ",", recursive_table_tmp);
  PREPARE stmt FROM @str;
  EXECUTE stmt; 
 # If you need to reference recursive_table more than
  # once in recursive_SELECT, remove the TEMPORARY word.
  SET @str = # create and fill T0
    CONCAT("CREATE TEMPORARY TABLE ", recursive_table, " ",
    create_table_options, " AS ", initial_SELECT);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  SET @str = # create U
    CONCAT("CREATE TEMPORARY TABLE ", recursive_table_union, " LIKE ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  SET @str = # create T1
    CONCAT("CREATE TEMPORARY TABLE ", recursive_table_next, " LIKE ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  if max_recursion = 0 then
    set max_recursion = 100; # a default to protect the innocent
  end if;
  recursion: repeat
    # add T0 to U (this is always UNION ALL)
    SET @str =
      CONCAT("INSERT INTO ", recursive_table_union, " SELECT * FROM ", recursive_table);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    # we are done if max depth reached
    set max_recursion = max_recursion - 1;
    if not max_recursion then
      if show_progress then
        select concat("max recursion exceeded");
      end if;
      leave recursion;
    end if;
    # fill T1 by applying the recursive SELECT on T0
    SET @str =
      CONCAT("INSERT INTO ", recursive_table_next, " ", recursive_SELECT);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    # we are done if no rows in T1
    select row_count() into new_rows;
    if show_progress then
      select concat(new_rows, " new rows found");
    end if;
    if not new_rows then
      leave recursion;
    end if;
    # Prepare next iteration:
    # T1 becomes T0, to be the source of next run of recursive_SELECT,
    # T0 is recycled to be T1.
    SET @str =
      CONCAT("ALTER TABLE ", recursive_table, " RENAME ", recursive_table_tmp);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    # we use ALTER TABLE RENAME because RENAME TABLE does not support temp tables
    SET @str =
      CONCAT("ALTER TABLE ", recursive_table_next, " RENAME ", recursive_table);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    SET @str =
      CONCAT("ALTER TABLE ", recursive_table_tmp, " RENAME ", recursive_table_next);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
    # empty T1
    SET @str =
      CONCAT("TRUNCATE TABLE ", recursive_table_next);
    PREPARE stmt FROM @str;
    EXECUTE stmt;
  until 0 end repeat;
  # eliminate T0 and T1
  SET @str =
    CONCAT("DROP TEMPORARY TABLE ", recursive_table_next, ", ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  # Final (output) SELECT uses recursive_table name
  SET @str =
    CONCAT("ALTER TABLE ", recursive_table_union, " RENAME ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  # Run final SELECT on UNION
  SET @str = final_SELECT;
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  # No temporary tables may survive:
  SET @str =
    CONCAT("DROP TEMPORARY TABLE ", recursive_table);
  PREPARE stmt FROM @str;
  EXECUTE stmt;
  # We are done :-)
END|

delimiter ;

how to remove untracked files in Git?

You may also return to the previous state of the local repo in another way:

  1. Add the untracked files to the staging area with git add.
  2. return to the previous state of the local repo with git reset --hard.

Drop all data in a pandas dataframe

My favorite:

df = df.iloc[0:0]

But be aware df.index.max() will be nan. To add items I use:

df.loc[0 if math.isnan(df.index.max()) else df.index.max() + 1] = data

Can't use System.Windows.Forms

go to the side project panel, right click on references -> add reference and find System.Windows.Forms

Any time some error like this occurs (some namespace you added is missing that is obviously there) the solution is probably this - adding a reference.

This is needed because your default project does not include everything because you probably wont need it so it saves space. A good practice is to exclude things you're not using.

How to properly make a http web GET request

Another way is using 'HttpClient' like this:

using System;
using System.Net;
using System.Net.Http;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Making API Call...");
            using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
            {
                client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
                HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
                response.EnsureSuccessStatusCode();
                string result = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine("Result: " + result);
            }
            Console.ReadLine();
        }
    }
}

Check HttpClient vs HttpWebRequest from stackoverflow and this from other.

Update June 22, 2020: It's not recommended to use httpclient in a 'using' block as it might cause port exhaustion.

private static HttpClient client = null;
    
ContructorMethod()
{
   if(client == null)
   {
        HttpClientHandler handler = new HttpClientHandler()
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        };        
        client = new HttpClient(handler);
   }
   client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
   HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
   response.EnsureSuccessStatusCode();
   string result = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine("Result: " + result);           
 }

If using .Net Core 2.1+, consider using IHttpClientFactory and injecting like this in your startup code.

 var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
            TimeSpan.FromSeconds(60));

 services.AddHttpClient<XApiClient>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        }).AddPolicyHandler(request => timeout);

open resource with relative path in Java

I had problems with using the getClass().getResource("filename.txt") method. Upon reading the Java docs instructions, if your resource is not in the same package as the class you are trying to access the resource from, then you have to give it relative path starting with '/'. The recommended strategy is to put your resource files under a "resources" folder in the root directory. So for example if you have the structure:

src/main/com/mycompany/myapp

then you can add a resources folder as recommended by maven in:

src/main/resources

furthermore you can add subfolders in the resources folder

src/main/resources/textfiles

and say that your file is called myfile.txt so you have

src/main/resources/textfiles/myfile.txt

Now here is where the stupid path problem comes in. Say you have a class in your com.mycompany.myapp package, and you want to access the myfile.txt file from your resource folder. Some say you need to give the:

"/main/resources/textfiles/myfile.txt" path

or

"/resources/textfiles/myfile.txt"

both of these are wrong. After I ran mvn clean compile, the files and folders are copied in the:

myapp/target/classes 

folder. But the resources folder is not there, just the folders in the resources folder. So you have:

myapp/target/classes/textfiles/myfile.txt

myapp/target/classes/com/mycompany/myapp/*

so the correct path to give to the getClass().getResource("") method is:

"/textfiles/myfile.txt"

here it is:

getClass().getResource("/textfiles/myfile.txt")

This will no longer return null, but will return your class. I hope this helps somebody. It is strange to me, that the "resources" folder is not copied as well, but only the subfolders and files directly in the "resources" folder. It would seem logical to me that the "resources" folder would also be found under "myapp/target/classes"

What's the difference between "super()" and "super(props)" in React when using es6 classes?

There is only one reason when one needs to pass props to super():

When you want to access this.props in constructor.

Passing:

class MyComponent extends React.Component {    
    constructor(props) {
        super(props)

        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

Not passing:

class MyComponent extends React.Component {    
    constructor(props) {
        super()

        console.log(this.props)
        // -> undefined

        // Props parameter is still available
        console.log(props)
        // -> { icon: 'home', … }
    }

    render() {
        // No difference outside constructor
        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

Note that passing or not passing props to super has no effect on later uses of this.props outside constructor. That is render, shouldComponentUpdate, or event handlers always have access to it.

This is explicitly said in one Sophie Alpert's answer to a similar question.


The documentation—State and Lifecycle, Adding Local State to a Class, point 2—recommends:

Class components should always call the base constructor with props.

However, no reason is provided. We can speculate it is either because of subclassing or for future compatibility.

(Thanks @MattBrowne for the link)

How do I implement interfaces in python?

My understanding is that interfaces are not that necessary in dynamic languages like Python. In Java (or C++ with its abstract base class) interfaces are means for ensuring that e.g. you're passing the right parameter, able to perform set of tasks.

E.g. if you have observer and observable, observable is interested in subscribing objects that supports IObserver interface, which in turn has notify action. This is checked at compile time.

In Python, there is no such thing as compile time and method lookups are performed at runtime. Moreover, one can override lookup with __getattr__() or __getattribute__() magic methods. In other words, you can pass, as observer, any object that can return callable on accessing notify attribute.

This leads me to the conclusion, that interfaces in Python do exist - it's just their enforcement is postponed to the moment in which they are actually used

How to remove elements from a generic list while iterating over it?

The best way to remove items from a list while iterating over it is to use RemoveAll(). But the main concern written by people is that they have to do some complex things inside the loop and/or have complex compare cases.

The solution is to still use RemoveAll() but use this notation:

var list = new List<int>(Enumerable.Range(1, 10));
list.RemoveAll(item => 
{
    // Do some complex operations here
    // Or even some operations on the items
    SomeFunction(item);
    // In the end return true if the item is to be removed. False otherwise
    return item > 5;
});

How to get to Model or Viewbag Variables in a Script Tag

Use single quotation marks ('):

var val = '@ViewBag.ForSection';
alert(val);

Regex Explanation ^.*$

  • ^ matches position just before the first character of the string
  • $ matches position just after the last character of the string
  • . matches a single character. Does not matter what character it is, except newline
  • * matches preceding match zero or more times

So, ^.*$ means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string. This regex pattern is not very useful.

Let's take a regex pattern that may be a bit useful. Let's say I have two strings The bat of Matt Jones and Matthew's last name is Jones. The pattern ^Matt.*Jones$ will match Matthew's last name is Jones. Why? The pattern says - the string should start with Matt and end with Jones and there can be zero or more characters (any characters) in between them.

Feel free to use an online tool like https://regex101.com/ to test out regex patterns and strings.

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

changing the Binding Type from wsHttpbinding to basichttp binding in the endpoint tag and from wsHttpbinding to mexhttpbinginding in metadata endpoint tag helped to overcome the error. Thank you...

How can I debug my JavaScript code?

Although alert(msg); works in those "I just want to find out whats going on" scenarios... every developer has encountered that case where you end up in a (very large or endless) loop that you can't break out of.

I'd recommend that during development if you want a very in-your-face debug option, use a debug option that lets you break out. (PS Opera, Safari? and Chrome? all have this available in their native dialogs)

//global flag
_debug = true;
function debug(msg){
  if(_debug){
    if(!confirm(msg + '\n\nPress Cancel to stop debugging.')){
      _debug = false;
    }
  }
}

With the above you can get your self into a large loop of popup debugging, where pressing Enter/Ok lets you jump through each message, but pressing Escape/Cancel lets you break out nicely.

Remove an item from an IEnumerable<T> collection

You can't. IEnumerable<T> can only be iterated.

In your second example, you can remove from original collection by iterating over a copy of it

foreach(var u in users.ToArray()) // ToArray creates a copy
{
   if(u.userId != 1233)
   {
        users.Remove(u);
   }
}

how to mysqldump remote db from local machine

One can invoke mysqldump locally against a remote server.

Example that worked for me:

mysqldump -h hostname-of-the-server -u mysql_user -p database_name > file.sql

I followed the mysqldump documentation on connection options.

Prevent jQuery UI dialog from setting focus to first textbox

You may provide this option, to focus the close button instead.

.dialog({
      open: function () {
              $(".ui-dialog-titlebar-close").focus();
            }
   });

generate random double numbers in c++

If accuracy is an issue here you can create random numbers with a finer graduation by randomizing the significant bits. Let's assume we want to have a double between 0.0 and 1000.0.

On MSVC (12 / Win32) RAND_MAX is 32767 for example.

If you use the common rand()/RAND_MAX scheme your gaps will be as large as

1.0 / 32767.0 * ( 1000.0 - 0.0) = 0.0305 ...

In case of IEE 754 double variables (53 significant bits) and 53 bit randomization the smallest possible randomization gap for the 0 to 1000 problem will be

2^-53 * (1000.0 - 0.0) = 1.110e-13

and therefore significantly lower.

The downside is that 4 rand() calls will be needed to obtain the randomized integral number (assuming a 15 bit RNG).

double random_range (double const range_min, double const range_max)
{
  static unsigned long long const mant_mask53(9007199254740991);
  static double const i_to_d53(1.0/9007199254740992.0);
  unsigned long long const r( (unsigned long long(rand()) | (unsigned long long(rand()) << 15) | (unsigned long long(rand()) << 30) | (unsigned long long(rand()) << 45)) & mant_mask53 );
  return range_min + i_to_d53*double(r)*(range_max-range_min);
}

If the number of bits for the mantissa or the RNG is unknown the respective values need to be obtained within the function.

#include <limits>
using namespace std;
double random_range_p (double const range_min, double const range_max)
{
  static unsigned long long const num_mant_bits(numeric_limits<double>::digits), ll_one(1), 
    mant_limit(ll_one << num_mant_bits);
  static double const i_to_d(1.0/double(mant_limit));
  static size_t num_rand_calls, rng_bits;
  if (num_rand_calls == 0 || rng_bits == 0)
  {
    size_t const rand_max(RAND_MAX), one(1);
    while (rand_max > (one << rng_bits))
    {
      ++rng_bits;
    }
    num_rand_calls = size_t(ceil(double(num_mant_bits)/double(rng_bits)));
  }
  unsigned long long r(0);
  for (size_t i=0; i<num_rand_calls; ++i)
  {
    r |= (unsigned long long(rand()) << (i*rng_bits));
  }
  r = r & (mant_limit-ll_one);
  return range_min + i_to_d*double(r)*(range_max-range_min);
}

Note: I don't know whether the number of bits for unsigned long long (64 bit) is greater than the number of double mantissa bits (53 bit for IEE 754) on all platforms or not. It would probably be "smart" to include a check like if (sizeof(unsigned long long)*8 > num_mant_bits) ... if this is not the case.

Android: How to Programmatically set the size of a Layout

my sample code

wv = (WebView) findViewById(R.id.mywebview);
wv.getLayoutParams().height = LayoutParams.MATCH_PARENT; // LayoutParams: android.view.ViewGroup.LayoutParams
// wv.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
wv.requestLayout();//It is necesary to refresh the screen

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

"Case" can return single value only, but you can use complex type:

create type foo as (a int, b text);
select (case 1 when 1 then (1,'qq')::foo else (2,'ww')::foo end).*;

AngularJS - value attribute for select

It appears it's not possible to actually use the "value" of a select in any meaningful way as a normal HTML form element and also hook it up to Angular in the approved way with ng-options. As a compromise, I ended up having to put a hidden input alongside my select and have it track the same model as my select, like this (all very much simplified from real production code for brevity):

HTML:

<select ng-model="profile" ng-options="o.id as o.name for o in profiles" name="something_i_dont_care_about">
</select>
<input name="profile_id" type="text" style="margin-left:-10000px;" ng-model="profile"/>

Javascript:

App.controller('ConnectCtrl',function ConnectCtrl($scope) {
$scope.profiles = [{id:'xyz', name:'a profile'},{id:'abc', name:'another profile'}];
$scope.profile = -1;
}

Then, in my server-side code I just looked for params[:profile_id] (this happened to be a Rails app, but the same principle applies anywhere). Because the hidden input tracks the same model as the select, they stay in sync automagically (no additional javascript necessary). This is the cool part of Angular. It almost makes up for what it does to the value attribute as a side effect.

Interestingly, I found this technique only worked with input tags that were not hidden (which is why I had to use the margin-left:-10000px; trick to move the input off the page). These two variations did not work:

<input name="profile_id" type="text" style="display:none;" ng-model="profile"/>

and

<input name="profile_id" type="hidden" ng-model="profile"/>

I feel like that must mean I'm missing something. It seems too weird for it to be a problem with Angular.

How to check if current thread is not main thread

Summarizing the solutions, I think that's the best one:

boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M 
    ? Looper.getMainLooper().isCurrentThread()
    : Thread.currentThread() == Looper.getMainLooper().getThread();

And, if you wish to run something on the UI thread, you can use this:

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
       //this runs on the UI thread
    }
});

Can you display HTML5 <video> as a full screen background?

Just a comment on this - I've used HTML5 video for a full-screen background and it works a treat - but make sure to use either Height:100% and width:auto or the other way around - to ensure you keep aspect ratio.

As for Ipads -you can (apparently) do this, by having a hidden and then forcing the click event to fire, and having the function of the click event kick off the Load/Play().

P.s - this shouldn't require any plugins and can be done with minimal JS - If you're targeting any mobile device (I would assume you might be..) staying away from any such framework is the way forward.

If statement in aspx page

if the purpose is to show or hide a part of the page then you can do the following things

1) wrap it in markup with

<% if(somecondition) { %>
   some html
<% } %>

2) Wrap the parts in a Panel control and in codebehind use the if statement to set the Visible property of the Panel.

Converting .NET DateTime to JSON

What is returned is milliseconds since epoch. You could do:

var d = new Date();
d.setTime(1245398693390);
document.write(d);

On how to format the date exactly as you want, see full Date reference at http://www.w3schools.com/jsref/jsref_obj_date.asp

You could strip the non-digits by either parsing the integer (as suggested here):

var date = new Date(parseInt(jsonDate.substr(6)));

Or applying the following regular expression (from Tominator in the comments):

var jsonDate = jqueryCall();  // returns "/Date(1245398693390)/"; 
var re = /-?\d+/; 
var m = re.exec(jsonDate); 
var d = new Date(parseInt(m[0]));

What are some great online database modeling tools?

I like Clay Eclipse plugin. I've only used it with MySQL, but it claims Firebird support.

How to scale an Image in ImageView to keep the aspect ratio

If you want an ImageView that both scales up and down while keeping the proper aspect ratio, add this to your XML:

android:adjustViewBounds="true"
android:scaleType="fitCenter"

Add this to your code:

// We need to adjust the height if the width of the bitmap is
// smaller than the view width, otherwise the image will be boxed.
final double viewWidthToBitmapWidthRatio = (double)image.getWidth() / (double)bitmap.getWidth();
image.getLayoutParams().height = (int) (bitmap.getHeight() * viewWidthToBitmapWidthRatio);

It took me a while to get this working, but this appears to work in the cases both where the image is smaller than the screen width and larger than the screen width, and it does not box the image.

Doctrine 2: Update query with query builder

With a small change, it worked fine for me

$qb=$this->dm->createQueryBuilder('AppBundle:CSSDInstrument')
               ->update()
               ->field('status')->set($status)
               ->field('id')->equals($instrumentId)
               ->getQuery()
               ->execute();

Why can't I display a pound (£) symbol in HTML?

Educated guess: You have a ISO-8859-1 encoded pound sign in a UTF-8 encoded page.

Make sure your data is in the right encoding and everything will work fine.

XAMPP permissions on Mac OS X?

if you use one line folder or file

chmod 755 $(find /yourfolder -type d)
chmod 644 $(find /yourfolder -type f)

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

How to add a ScrollBar to a Stackpanel

It works like this:

<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" Width="340" HorizontalAlignment="Left" Margin="12,0,0,0">
        <StackPanel Name="stackPanel1" Width="311">

        </StackPanel>
</ScrollViewer>

TextBox tb = new TextBox();
tb.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
stackPanel1.Children.Add(tb);

MessageBox with YesNoCancel - No & Cancel triggers same event

Closing conformation alert:

Private Sub cmd_exit_click()

    ' By clicking on the button the MsgBox will appear
    If MsgBox("Are you sure want to exit now?", MsgBoxStyle.YesNo, "closing warning") = MsgBoxResult.Yes Then ' If you select yes in the MsgBox then it will close the window
               Me.Close() ' Close the window
    Else
        ' Will not close the application
    End If
End Sub

How can I change the image of an ImageView?

Just to go a little bit further in the matter, you can also set a bitmap directly, like this:

ImageView imageView = new ImageView(this);  
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);

Of course, this technique is only useful if you need to change the image.

How do I properly set the permgen size?

So you are doing the right thing concerning "-XX:MaxPermSize=512m": it is indeed the correct syntax. You could try to set these options directly to the Catalyna server files so they are used on server start.

Maybe this post will help you!

How to make sure that Tomcat6 reads CATALINA_OPTS on Windows?

What is the difference between substr and substring?

substring(): It has 2 parameters "start" and "end".

  • start parameter is required and specifies the position where to start the extraction.
  • end parameter is optional and specifies the position where the extraction should end.

If the end parameter is not specified, all the characters from the start position till the end of the string are extracted.

_x000D_
_x000D_
var str = "Substring Example";_x000D_
var result = str.substring(0, 10);_x000D_
alert(result);_x000D_
_x000D_
Output : Substring
_x000D_
_x000D_
_x000D_

If the value of start parameter is greater than the value of the end parameter, this method will swap the two arguments. This means start will be used as end and end will be used as start.

_x000D_
_x000D_
var str = "Substring Example";_x000D_
var result = str.substring(10, 0);_x000D_
alert(result);_x000D_
_x000D_
Output : Substring
_x000D_
_x000D_
_x000D_

substr(): It has 2 parameters "start" and "count".

  • start parameter is required and specifies the position where to start the extraction.

  • count parameter is optional and specifies the number of characters to extract.

_x000D_
_x000D_
var str = "Substr Example";_x000D_
var result = str.substr(0, 10);_x000D_
alert(result);_x000D_
_x000D_
_x000D_
Output : Substr Exa
_x000D_
_x000D_
_x000D_

If the count parameter is not specified, all the characters from the start position till the end of the string are extracted. If count is 0 or negative, an empty string is returned.

_x000D_
_x000D_
var str = "Substr Example";_x000D_
var result = str.substr(11);_x000D_
alert(result);_x000D_
_x000D_
Output : ple
_x000D_
_x000D_
_x000D_

Selector on background color of TextView

An even simpler solution to the above:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <color android:color="@color/semitransparent_white" />
    </item>
    <item>
        <color android:color="@color/transparent" />
    </item>
</selector>

Save that in the drawable folder and you're good to go.

select2 changing items dynamically

I'm successfully using the following to update options dynamically:

$control.select2('destroy').empty().select2({data: [{id: 1, text: 'new text'}]});

Server.MapPath - Physical path given, virtual path expected

if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...

How to check if a table contains an element in Lua?

You can put the values as the table's keys. For example:

function addToSet(set, key)
    set[key] = true
end

function removeFromSet(set, key)
    set[key] = nil
end

function setContains(set, key)
    return set[key] ~= nil
end

There's a more fully-featured example here.

Can you do a partial checkout with Subversion?

I wrote a script to automate complex sparse checkouts.

#!/usr/bin/env python

'''
This script makes a sparse checkout of an SVN tree in the current working directory.

Given a list of paths in an SVN repository, it will:
1. Checkout the common root directory
2. Update with depth=empty for intermediate directories
3. Update with depth=infinity for the leaf directories
'''

import os
import getpass
import pysvn

__author__ = "Karl Ostmo"
__date__ = "July 13, 2011"

# =============================================================================

# XXX The os.path.commonprefix() function does not behave as expected!
# See here: http://mail.python.org/pipermail/python-dev/2002-December/030947.html
# and here: http://nedbatchelder.com/blog/201003/whats_the_point_of_ospathcommonprefix.html
# and here (what ever happened?): http://bugs.python.org/issue400788
from itertools import takewhile
def allnamesequal(name):
    return all(n==name[0] for n in name[1:])

def commonprefix(paths, sep='/'):
    bydirectorylevels = zip(*[p.split(sep) for p in paths])
    return sep.join(x[0] for x in takewhile(allnamesequal, bydirectorylevels))

# =============================================================================
def getSvnClient(options):

    password = options.svn_password
    if not password:
        password = getpass.getpass('Enter SVN password for user "%s": ' % options.svn_username)

    client = pysvn.Client()
    client.callback_get_login = lambda realm, username, may_save: (True, options.svn_username, password, True)
    return client

# =============================================================================
def sparse_update_with_feedback(client, new_update_path):
    revision_list = client.update(new_update_path, depth=pysvn.depth.empty)

# =============================================================================
def sparse_checkout(options, client, repo_url, sparse_path, local_checkout_root):

    path_segments = sparse_path.split(os.sep)
    path_segments.reverse()

    # Update the middle path segments
    new_update_path = local_checkout_root
    while len(path_segments) > 1:
        path_segment = path_segments.pop()
        new_update_path = os.path.join(new_update_path, path_segment)
        sparse_update_with_feedback(client, new_update_path)
        if options.verbose:
            print "Added internal node:", path_segment

    # Update the leaf path segment, fully-recursive
    leaf_segment = path_segments.pop()
    new_update_path = os.path.join(new_update_path, leaf_segment)

    if options.verbose:
        print "Will now update with 'recursive':", new_update_path
    update_revision_list = client.update(new_update_path)

    if options.verbose:
        for revision in update_revision_list:
            print "- Finished updating %s to revision: %d" % (new_update_path, revision.number)

# =============================================================================
def group_sparse_checkout(options, client, repo_url, sparse_path_list, local_checkout_root):

    if not sparse_path_list:
        print "Nothing to do!"
        return

    checkout_path = None
    if len(sparse_path_list) > 1:
        checkout_path = commonprefix(sparse_path_list)
    else:
        checkout_path = sparse_path_list[0].split(os.sep)[0]



    root_checkout_url = os.path.join(repo_url, checkout_path).replace("\\", "/")
    revision = client.checkout(root_checkout_url, local_checkout_root, depth=pysvn.depth.empty)

    checkout_path_segments = checkout_path.split(os.sep)
    for sparse_path in sparse_path_list:

        # Remove the leading path segments
        path_segments = sparse_path.split(os.sep)
        start_segment_index = 0
        for i, segment in enumerate(checkout_path_segments):
            if segment == path_segments[i]:
                start_segment_index += 1
            else:
                break

        pruned_path = os.sep.join(path_segments[start_segment_index:])
        sparse_checkout(options, client, repo_url, pruned_path, local_checkout_root)

# =============================================================================
if __name__ == "__main__":

    from optparse import OptionParser
    usage = """%prog  [path2] [more paths...]"""

    default_repo_url = "http://svn.example.com/MyRepository"
    default_checkout_path = "sparse_trunk"

    parser = OptionParser(usage)
    parser.add_option("-r", "--repo_url", type="str", default=default_repo_url, dest="repo_url", help='Repository URL (default: "%s")' % default_repo_url)
    parser.add_option("-l", "--local_path", type="str", default=default_checkout_path, dest="local_path", help='Local checkout path (default: "%s")' % default_checkout_path)

    default_username = getpass.getuser()
    parser.add_option("-u", "--username", type="str", default=default_username, dest="svn_username", help='SVN login username (default: "%s")' % default_username)
    parser.add_option("-p", "--password", type="str", dest="svn_password", help="SVN login password")

    parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help="Verbose output")
    (options, args) = parser.parse_args()

    client = getSvnClient(options)
    group_sparse_checkout(
        options,
        client,
        options.repo_url,
        map(os.path.relpath, args),
        options.local_path)

Java method to swap primitives

AFAIS, no one mentions of atomic reference.

Integer

public void swap(AtomicInteger a, AtomicInteger b){
    a.set(b.getAndSet(a.get()));
}

String

public void swap(AtomicReference<String> a, AtomicReference<String> b){
    a.set(b.getAndSet(a.get()));
}

Turn off display errors using file "php.ini"

In file php.ini you should try this for all errors:

error_reporting = off

sql delete statement where date is greater than 30 days

Instead of converting to varchar to get just the day (convert(varchar(8), [Date], 112)), I prefer keeping it a datetime field and making it only the date (without the time).

SELECT * FROM Results 
WHERE CONVERT(date, [Date]) >= CONVERT(date, GETDATE())

Fixed footer in Bootstrap

Add z-index:-9999; to this method, or it will cover your top bar if you have 1.

How to get the last char of a string in PHP?

I can't leave comments, but in regard to FastTrack's answer, also remember that the line ending may be only single character. I would suggest

substr(trim($string), -1)

EDIT: My code below was edited by someone, making it not do what I indicated. I have restored my original code and changed the wording to make it more clear.

trim (or rtrim) will remove all whitespace, so if you do need to check for a space, tab, or other whitespace, manually replace the various line endings first:

$order = array("\r\n", "\n", "\r");
$string = str_replace($order, '', $string);
$lastchar = substr($string, -1);

Why is Maven downloading the maven-metadata.xml every time?

I suppose because you didn't specify plugin version so it triggers the download of associated metadata in order to get the last one.

Otherwise did you try to force local repo usage using -o ?

How can I change the value of the elements in a vector?

Just use:

for (int i = 0; i < v.size(); i++)
{
    v[i] -= valueToSubstract;
}

Or its equivalent (and more readable?):

for (int i = 0; i < v.size(); i++)
    v[i] = v[i] - valueToSubstract;

Declaring and initializing arrays in C

There is no such particular way in which you can initialize the array after declaring it once.

There are three options only:

1.) initialize them in different lines :

int array[SIZE];

array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
//...
//...
//...

But thats not what you want i guess.

2.) Initialize them using a for or while loop:

for (i = 0; i < MAX ; i++)  {
    array[i] = i;
}

This is the BEST WAY by the way to achieve your goal.

3.) In case your requirement is to initialize the array in one line itself, you have to define at-least an array with initialization. And then copy it to your destination array, but I think that there is no benefit of doing so, in that case you should define and initialize your array in one line itself.

And can I ask you why specifically you want to do so???

How do I exit a WPF application programmatically?

Caliburn micro flavoured

public class CloseAppResult : CancelResult
{
    public override void Execute(CoroutineExecutionContext context)
    {
        Application.Current.Shutdown();
        base.Execute(context);
    }
}

public class CancelResult : Result
{
    public override void Execute(CoroutineExecutionContext context)
    {
        OnCompleted(this, new ResultCompletionEventArgs { WasCancelled = true });
    }
}

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

Your module and your class AthleteList have the same name. The line

import AthleteList

imports the module and creates a name AthleteList in your current scope that points to the module object. If you want to access the actual class, use

AthleteList.AthleteList

In particular, in the line

return(AthleteList(templ.pop(0), templ.pop(0), templ))

you are actually accessing the module object and not the class. Try

return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))

Remove old Fragment from fragment manager

I had the same issue. I came up with a simple solution. Use fragment .replace instead of fragment .add. Replacing fragment doing the same thing as adding fragment and then removing it manually.

getFragmentManager().beginTransaction().replace(fragment).commit();

instead of

getFragmentManager().beginTransaction().add(fragment).commit();

How to add leading zeros for for-loop in shell?

I'm not interested in outputting it to the screen (that's what printf is mainly used for, right?) The variable $num is going to be used as a parameter for another program but let me see what I can do with this.

You can still use printf:

for num in {1..5}
do
   value=$(printf "%02d" $num)
   ... Use $value for your purposes
done

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

Another solution from the manual:

Composer also respects a memory limit defined by the COMPOSER_MEMORY_LIMIT environment variable:

COMPOSER_MEMORY_LIMIT=-1 composer.phar <...>

Or in my case

export COMPOSER_MEMORY_LIMIT=-1
composer <...>

Entity Framework vs LINQ to SQL

Neither yet supports the unique SQL 2008 datatypes. The difference from my perspective is that Entity still has a chance to construct a model around my geographic datatype in some future release, and Linq to SQL, being abandoned, never will.

Wonder what's up with nHibernate, or OpenAccess...

Preferred method to store PHP arrays (json_encode vs serialize)

I augmented the test to include unserialization performance. Here are the numbers I got.

Serialize

JSON encoded in 2.5738489627838 seconds
PHP serialized in 5.2861361503601 seconds
Serialize: json_encode() was roughly 105.38% faster than serialize()


Unserialize

JSON decode in 10.915472984314 seconds
PHP unserialized in 7.6223039627075 seconds
Unserialize: unserialize() was roughly 43.20% faster than json_decode() 

So json seems to be faster for encoding but slow in decoding. So it could depend upon your application and what you expect to do the most.

Multiple Python versions on the same machine?

How to install different Python versions is indeed OS dependent.

However, if you're on linux, you can use a tool like pythonbrew or pythonz to help you easily manage and switch between different versions.

Filtering a list based on a list of booleans

To do this using numpy, ie, if you have an array, a, instead of list_a:

a = np.array([1, 2, 4, 6])
my_filter = np.array([True, False, True, False], dtype=bool)
a[my_filter]
> array([1, 4])

Is the Javascript date object always one day off?

if you need a simple solution for this see:

new Date('1993-01-20'.split('-')); 

enter image description here

App can't be opened because it is from an unidentified developer

Terminal type:

Last login: Thu Dec 20 08:28:43 on console
 ~ ? sudo spctl --master-disable
Password:
 ~ ? spctl --status
assessments disabled
 ~ ?

System Preferences->Security & Privacy

enter image description here

How to get a password from a shell script without echoing

One liner:

read -s -p "Password: " password

Under Linux (and cygwin) this form works in bash and sh. It may not be standard Unix sh, though.

For more info and options, in bash, type "help read".

$ help read
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
Read a line from the standard input and split it into fields.
  ...
  -p prompt output the string PROMPT without a trailing newline before
            attempting to read
  ...
  -s                do not echo input coming from a terminal

What's the maximum value for an int in PHP?

Although PHP_INT_* constants exist for a very long time, the same MIN / MAX values could be found programmatically by left shifting until reaching the negative number:

$x = 1;
while ($x > 0 && $x <<= 1);
echo "MIN: ", $x;
echo PHP_EOL;
echo "MAX: ", ~$x;

W3WP.EXE using 100% CPU - where to start?

If your CPU is spiking to 100% and staying there, it's quite likely that you either have a deadlock scenario or an infinite loop. A profiler seems like a good choice for finding an infinite loop. Deadlocks are much more difficult to track down, however.

Is it necessary to use # for creating temp tables in SQL server?

Yes. You need to prefix the table name with "#" (hash) to create temporary tables.

If you do NOT need the table later, go ahead & create it. Temporary Tables are very much like normal tables. However, it gets created in tempdb. Also, it is only accessible via the current session i.e. For EG: if another user tries to access the temp table created by you, he'll not be able to do so.

"##" (double-hash creates "Global" temp table that can be accessed by other sessions as well.

Refer the below link for the Basics of Temporary Tables: http://www.codeproject.com/Articles/42553/Quick-Overview-Temporary-Tables-in-SQL-Server-2005

If the content of your table is less than 5000 rows & does NOT contain data types such as nvarchar(MAX), varbinary(MAX), consider using Table Variables.

They are the fastest as they are just like any other variables which are stored in the RAM. They are stored in tempdb as well, not in RAM.

DECLARE @ItemBack1 TABLE
(
 column1 int,
 column2 int,
 someInt int,
 someVarChar nvarchar(50)
);

INSERT INTO @ItemBack1
SELECT column1, 
       column2, 
       someInt, 
       someVarChar 
  FROM table2
 WHERE table2.ID = 7;

More Info on Table Variables: http://odetocode.com/articles/365.aspx

Using "word-wrap: break-word" within a table

You can try this:

td p {word-break:break-all;}

This, however, makes it appear like this when there's enough space, unless you add a <br> tag:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

So, I would then suggest adding <br> tags where there are newlines, if possible.

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

http://jsfiddle.net/LLyH3/3/

Also, if this doesn't solve your problem, there's a similar thread here.

How to make an authenticated web request in Powershell?

The PowerShell is almost exactly the same.

$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)

Select all child elements recursively in CSS

The rule is as following :

A B 

B as a descendant of A

A > B 

B as a child of A

So

div.dropdown *

and not

div.dropdown > *

Parsing JSON from URL

I use java 1.8 with com.fasterxml.jackson.databind.ObjectMapper

ObjectMapper mapper = new ObjectMapper();
Integer      value = mapper.readValue(new URL("your url here"), Integer.class);

Integer.class can be also a complex type. Just for example used.

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

Jupyter has its own PATH variable, JUPYTER_PATH.

Adding this line to the .bashrc file worked for me:

export JUPYTER_PATH=<directory_for_your_module>:$JUPYTER_PATH

How to send an email using PHP?

You could also use PHPMailer class at https://github.com/PHPMailer/PHPMailer .

It allows you to use the mail function or use an smtp server transparently. It also handles HTML based emails and attachments so you don't have to write your own implementation.

The class is stable and it is used by many other projects like Drupal, SugarCRM, Yii, and Joomla!

Here is an example from the page above:

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '[email protected]';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted

$mail->From = '[email protected]';
$mail->FromName = 'Mailer';
$mail->addAddress('[email protected]', 'Joe User');     // Add a recipient
$mail->addAddress('[email protected]');               // Name is optional
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');

$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

How to Access Hive via Python?

Simplest method | Using sqlalchemy

Requirements:

  • pip install pyhive

Code:

import pandas as pd
from sqlalchemy import create_engine

SECRET = {'username':'lol', 'password': 'lol'}
user_name = SECRET.get('username')
passwd = SECRET.get('password')

host_server = 'x.x.x.x'
port = '10000'
database = 'default'
conn = f'hive://{user_name}:{passwd}@{host_server}:{port}/{database}'
engine = create_engine(conn, connect_args={'auth': 'LDAP'})

query = "select * from tablename limit 100"
data = pd.read_sql(query, con=engine)
print(data)

Clear contents of cells in VBA using column reference

The issue is not with the with statement, it is on the Range function, it doesn't accept the absolute cell value.. it should be like Range("A4:B100").. you can refer the following thread for reference..

following code should work.. Convert cells(1,1) into "A1" and vice versa

LastColData = Sheets(WSNAME).Range("A4").End(xlToRight).Column
            LastRowData = Sheets(WSNAME).Range("A4").End(xlDown).Row
            Rng = "A4:" & Sheets(WSNAME).Cells(LastRowData, LastColData).Address(RowAbsolute:=False, ColumnAbsolute:=False)

 Worksheets(WSNAME).Range(Rng).ClearContents

C# Creating an array of arrays

The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.

int[,] list = new int[4,4] {
 {1,2,3,4},
 {5,6,7,8},
 {1,3,2,1},
 {5,4,3,2}};

You could also do

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[,] lists = new int[4,4] {
 {list1[0],list1[1],list1[2],list1[3]},
 {list2[0],list2[1],list2[2],list2[3]},
 etc...};

libstdc++-6.dll not found

This error also occurred when I compiled with MinGW using gcc with the following options: -lstdc++ -lm, rather than g++

I did not notice these options, and added: -static-libgcc -static-libstdc++

I still got the error, and finally realized I was using gcc, and changed the compiler to g++ and removed -stdc++ and -lm, and everything linked fine.

(I was using LINK.c rather than LINK.cpp... use make -pn | less to see what everything does!)

I don't know why the previous author was using gcc with -stdc++. I don't see any reason not to use g++ which will link with stdc++ automatically... and as far as I know, provide other benefits (it is the c++ compiler after all).

Android 6.0 multiple permissions

In a Fragment

public class Homefragment extends Fragment {
    View hfrag;
   Context context;
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

//first we must check the permissions are already granted

        hfrag = inflater.inflate(R.layout.home, container, false);
        context = getActivity();
checkAndRequestPermissions();

}




}


private boolean checkAndRequestPermissions() {
        int permissionSendMessage = ContextCompat.checkSelfPermission(context,
                Manifest.permission.READ_SMS);
        int contactpermission = ContextCompat.checkSelfPermission(context, Manifest.permission.GET_ACCOUNTS);

        int writepermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        int callpermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE);

        int receivepermission = ContextCompat.checkSelfPermission(context, Manifest.permission.RECEIVE_SMS);
        int locationpermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);

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

        if (locationpermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        if (contactpermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.GET_ACCOUNTS);
        }
        if (writepermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.READ_SMS);
        }
        if (receivepermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.RECEIVE_SMS);
        }

        if (callpermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.CALL_PHONE);
        }
        if (!listPermissionsNeeded.isEmpty()) {
            requestPermissions(listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }



 @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);


    if (requestCode == REQUEST_ID_MULTIPLE_PERMISSIONS) {


        if (grantResults.length > 0) {
            for (int i = 0; i < permissions.length; i++) {


                if (permissions[i].equals(Manifest.permission.GET_ACCOUNTS)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "accounts granted");

                    }
                } else if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "storage granted");

                    }
                } else if (permissions[i].equals(Manifest.permission.CALL_PHONE)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "call granted");

                    }
                } else if (permissions[i].equals(Manifest.permission.RECEIVE_SMS)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "sms granted");

                    }
                } else if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.e("msg", "location granted");

                    }
                }


            }

        }


    }
}

}

Changing Shell Text Color (Windows)

This is extremely simple! Rather than importing odd modules for python or trying long commands you can take advantage of windows OS commands.

In windows, commands exist to change the command prompt text color. You can use this in python by starting with a: import os

Next you need to have a line changing the text color, place it were you want in your code. os.system('color 4')

You can figure out the other colors by starting cmd.exe and typing color help.

The good part? Thats all their is to it, to simple lines of code. -Day

How do you install Boost on MacOS?

Just get the source, and compile Boost yourself; it has become very easy. Here is an example for the current version of Boost on the current macOS as of this writing:

  1. Download the the .tar.gz from https://www.boost.org/users/download/#live
  2. Unpack and go into the directory:

    tar -xzf boost_1_50_0.tar.gz
    cd boost_1_50_0

  3. Configure (and build bjam):

    ./bootstrap.sh --prefix=/some/dir/you/would/like/to/prefix
  4. Build:

    ./b2
  5. Install:

    ./b2 install

Depending on the prefix you choose in Step 3, you might need to sudo Step 5, if the script tries copy files to a protected location.

Spring MVC - How to get all request params in a map in Spring controller?

Here is the simple example of getting request params in a Map.

 @RequestMapping(value="submitForm.html", method=RequestMethod.POST)
     public ModelAndView submitForm(@RequestParam Map<String, String> reqParam) 
       {
          String name  = reqParam.get("studentName");
          String email = reqParam.get("studentEmail");

          ModelAndView model = new ModelAndView("AdmissionSuccess");
          model.addObject("msg", "Details submitted by you::
          Name: " + name + ", Email: " + email );
       }

In this case, it will bind the value of studentName and studentEmail with name and email variables respectively.

Javascript Append Child AFTER Element

You could also do

function insertAfter(node1, node2) {
    node1.outerHTML += node2.outerHTML;
}

or

function insertAfter2(node1, node2) {
    var wrap = document.createElement("div");
    wrap.appendChild(node2.cloneNode(true));
    var node2Html = wrap.innerHTML;
    node1.insertAdjacentHTML('afterend', node2Html);
}

Understanding repr( ) function in Python

The feedback you get on the interactive interpreter uses repr too. When you type in an expression (let it be expr), the interpreter basically does result = expr; if result is not None: print repr(result). So the second line in your example is formatting the string foo into the representation you want ('foo'). And then the interpreter creates the representation of that, leaving you with double quotes.

Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I'd write it in my .py file but not the way I'd like to see it?

I'm not sure what you're asking here. The text single ' and double " quotes, when run through repr, includes escapes for one kind of quote. Of course it does, otherwise it wouldn't be a valid string literal by Python rules. That's precisely what you asked for by calling repr.

Also note that the eval(repr(x)) == x analogy isn't meant literal. It's an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical "value" from looking the the repr output.

How to make a GridLayout fit screen size

After many attempts I found what I was looking for in this layout. Even spaced LinearLayouts with automatically fitted ImageViews, with maintained aspect ratio. Works with landscape and portrait with any screen and image resolution.

Nexus 7 Nexus 5 Nexus 10

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffcc5d00" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">


        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_weight="1"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image1"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image2"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_weight="1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image3"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image4"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</FrameLayout>

How to install pip in CentOS 7?

curl https://bootstrap.pypa.io/get-pip.py | python3.4

Or if you don't have curl for some reason:

wget https://bootstrap.pypa.io/get-pip.py
python3.4 get-pip.py

After this you should be able to run

$ pip3

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

If you're USING a date then I strongly advise that you use jodatime, http://joda-time.sourceforge.net/. Using System.currentTimeMillis() for fields that are dates sounds like a very bad idea because you'll end up with a lot of useless code.

Both date and calendar are seriously borked, and Calendar is definitely the worst performer of them all.

I'd advise you to use System.currentTimeMillis() when you are actually operating with milliseconds, for instance like this

 long start = System.currentTimeMillis();
    .... do something ...
 long elapsed = System.currentTimeMillis() -start;

How I can filter a Datatable?

use it:

.CopyToDataTable()

example:

string _sqlWhere = "Nachname = 'test'";
string _sqlOrder = "Nachname DESC";

DataTable _newDataTable = yurDateTable.Select(_sqlWhere, _sqlOrder).CopyToDataTable();

Why is 22 the default port number for SFTP?

It's the default SSH port and SFTP is usually carried over an SSH tunnel.

How to fill background image of an UIView

You need to process the image beforehand, to make a centered and stretched image. Try this:

UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"image.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.view.backgroundColor = [UIColor colorWithPatternImage:image];

Take the content of a list and append it to another list

Using the map() and reduce() built-in functions

def file_to_list(file):
     #stuff to parse file to a list
     return list

files = [...list of files...]

L = map(file_to_list, files)

flat_L = reduce(lambda x,y:x+y, L)

Minimal "for looping" and elegant coding pattern :)

Postman: How to make multiple requests at the same time

In postman's collection runner you can't make simultaneous asynchronous requests, so instead use Apache JMeter instead. It allows you to add multiple threads and add synchronizing timer to it

Visual Studio move project to a different folder

  1. Copy the project folder to new destination
  2. Remove your project from solution (Right-click the project in "Solution Explorer" and choose "Remove")
  3. Then add existing project to solution (Right-click the project in "Solution Explorer" and choose "Add" then "Existing project")
  4. Change path to "packages" folder in "YourProjectName.csproj" file (Open in notepad and change paths for linked packages)

How to fill a datatable with List<T>

I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable and the underlying data was a IEnumerable and the properties couldn't be enumerated. This did the trick:

// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
    List<IDataRecord> list = data.Cast<IDataRecord>().ToList();

    PropertyDescriptorCollection props = null;
    DataTable table = new DataTable();
    if (list != null && list.Count > 0)
    {
        props = TypeDescriptor.GetProperties(list[0]);
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }
    }
    if (props != null)
    {
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item) ?? DBNull.Value;
            }
            table.Rows.Add(values);
        }
    }
    return table;
}

How to read a CSV file into a .NET Datatable

Here's an excellent class that will copy CSV data into a datatable using the structure of the data to create the DataTable:

A portable and efficient generic parser for flat files

It's easy to configure and easy to use. I urge you to take a look.

Styling the last td in a table with css

Not a direct answer to your question, but using <tfoot> might help you achieve what you need, and of course you can style tfoot.

Using the Jersey client to do a POST operation

Starting from Jersey 2.x, the MultivaluedMapImpl class is replaced by MultivaluedHashMap. You can use it to add form data and send it to the server:

    WebTarget webTarget = client.target("http://www.example.com/some/resource");
    MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
    formData.add("key1", "value1");
    formData.add("key2", "value2");
    Response response = webTarget.request().post(Entity.form(formData));

Note that the form entity is sent in the format of "application/x-www-form-urlencoded".

html "data-" attribute as javascript parameter

JS:

function fun(obj) {
    var uid= $(obj).data('uid');
    var name= $(obj).data('name');
    var value= $(obj).data('value');
}

What is the difference between window, screen, and document in Javascript?

The window is the actual global object.

The screen is the screen, it contains properties about the user's display.

The document is where the DOM is.

How do you check if a string is not equal to an object or other string value in java?

Change your || to && so it will only exit if the answer is NEITHER "AM" nor "PM".

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

PHP function to get the subdomain of a URL

$REFERRER = $_SERVER['HTTP_REFERER']; // Or other method to get a URL for decomposition

$domain = substr($REFERRER, strpos($REFERRER, '://')+3);
$domain = substr($domain, 0, strpos($domain, '/'));
// This line will return 'en' of 'en.example.com'
$subdomain = substr($domain, 0, strpos($domain, '.')); 

Iterate through object properties

if(Object.keys(obj).length) {
    Object.keys(obj).forEach(key => {
        console.log("\n" + key + ": " + obj[key]);
    });
}

// *** Explanation line by line ***

// Explaining the bellow line
// It checks if obj has at least one property. Here is how:
// Object.keys(obj) will return an array with all keys in obj.
// Keys are just the regular incremental numbers starting from 0.
// If there is no keys in obj, it will return empty array = []
// Then it will get its length. At this point, it checks: 
// If it has at least one element, it means it's bigger than 0 
// which evaluates to true and the bellow code will be executed.
// Else means it's length = 0 which evaluates to false
// NOTE: you can use Object.hasOwnProperty() instead of Object.keys(obj).length
if(Object.keys(obj).length) {

    // Explaining the bellow line
    // Just like in the previous line, this returns an array with
    // all keys in obj (because if code execution got here, it means 
    // obj has keys.) 
    // Then just invoke built-in javascript forEach() to loop
    // over each key in returned array and calls a call back function 
    // on each array element (key), using ES6 arrow function (=>)
    // Or you can just use a normal function ((key) { blah blah }).
    Object.keys(obj).forEach(key => {

        // The bellow line prints out all keys with their 
        // respective value in obj.
        // key comes from the returned array in Object.keys(obj)
        // obj[key] returns the value of key in obj
        console.log("\n" + key + ": " + obj[key]);
    });
}

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Is there a pure CSS way to make an input transparent?

The two methods previously described are not enough today. I personnally use :

input[type="text"]{
    background-color: transparent;
    border: 0px;
    outline: none;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
    width:5px;
    color:transparent;
    cursor:default;
}

It also removes the shadow set on some browsers, hide the text that could be input and make the cursor behave as if the input was not there.

You may want to set width to 0px also.

indexOf and lastIndexOf in PHP?

<?php
// sample array
$fruits3 = [
    "iron",
    1,
    "ascorbic",
    "potassium",
    "ascorbic",
    2,
    "2",
    "1",
];

// Let's say we are looking for the item "ascorbic", in the above array

//a PHP function matching indexOf() from JS
echo(array_search("ascorbic", $fruits3, true)); //returns "2"

// a PHP function matching lastIndexOf() from JS world
function lastIndexOf($needle, $arr)
{
    return array_search($needle, array_reverse($arr, true), true);
}

echo(lastIndexOf("ascorbic", $fruits3)); //returns "4"

// so these (above) are the two ways to run a function similar to indexOf and lastIndexOf()

Returning unique_ptr from functions

I think it's perfectly explained in item 25 of Scott Meyers' Effective Modern C++. Here's an excerpt:

The part of the Standard blessing the RVO goes on to say that if the conditions for the RVO are met, but compilers choose not to perform copy elision, the object being returned must be treated as an rvalue. In effect, the Standard requires that when the RVO is permitted, either copy elision takes place or std::move is implicitly applied to local objects being returned.

Here, RVO refers to return value optimization, and if the conditions for the RVO are met means returning the local object declared inside the function that you would expect to do the RVO, which is also nicely explained in item 25 of his book by referring to the standard (here the local object includes the temporary objects created by the return statement). The biggest take away from the excerpt is either copy elision takes place or std::move is implicitly applied to local objects being returned. Scott mentions in item 25 that std::move is implicitly applied when the compiler choose not to elide the copy and the programmer should not explicitly do so.

In your case, the code is clearly a candidate for RVO as it returns the local object p and the type of p is the same as the return type, which results in copy elision. And if the compiler chooses not to elide the copy, for whatever reason, std::move would've kicked in to line 1.

How can I kill whatever process is using port 8080 so that I can vagrant up?

You can also use the Activity Monitor to identify and quit the process using the port.

How to update parent's state in React?

I've used a top rated answer from this page many times, but while learning React, i've found a better way to do that, without binding and without inline function inside props.

Just look here:

class Parent extends React.Component {

  constructor() {
    super();
    this.state={
      someVar: value
    }
  }

  handleChange=(someValue)=>{
    this.setState({someVar: someValue})
  }

  render() {
    return <Child handler={this.handleChange} />
  }

}

export const Child = ({handler}) => {
  return <Button onClick={handler} />
}

The key is in an arrow function:

handleChange=(someValue)=>{
  this.setState({someVar: someValue})
}

You can read more here. Hope this will be useful for somebody =)

How to get current time in python and break up into year, month, day, hour, minute?

This is an older question, but I came up with a solution I thought others might like.

def get_current_datetime_as_dict():
n = datetime.now()
t = n.timetuple()
field_names = ["year",
               "month",
               "day",
               "hour",
               "min",
               "sec",
               "weekday",
               "md",
               "yd"]
return dict(zip(field_names, t))

timetuple() can be zipped with another array, which creates labeled tuples. Cast that to a dictionary and the resultant product can be consumed with get_current_datetime_as_dict()['year'].

This has a little more overhead than some of the other solutions on here, but I've found it's so nice to be able to access named values for clartiy's sake in the code.

how to automatically scroll down a html page?

You can use two different techniques to achieve this.

The first one is with javascript: set the scrollTop property of the scrollable element (e.g. document.body.scrollTop = 1000;).

The second is setting the link to point to a specific id in the page e.g.

<a href="mypage.html#sectionOne">section one</a>

Then if in your target page you'll have that ID the page will be scrolled automatically.

PHP ternary operator vs null coalescing operator

Ran the below on php interactive mode (php -a on terminal). The comment on each line shows the result.

var_export (false ?? 'value2');   // false
var_export (true  ?? 'value2');   // true
var_export (null  ?? 'value2');   // value2
var_export (''    ?? 'value2');   // ""
var_export (0     ?? 'value2');   // 0

var_export (false ?: 'value2');   // value2
var_export (true  ?: 'value2');   // true
var_export (null  ?: 'value2');   // value2
var_export (''    ?: 'value2');   // value2
var_export (0     ?: 'value2');   // value2

The Null Coalescing Operator ??

  • ?? is like a "gate" that only lets NULL through.
  • So, it always returns first parameter, unless first parameter happens to be NULL.
  • This means ?? is same as ( !isset() || is_null() )

Use of ??

  • shorten !isset() || is_null() check
  • e.g $object = $object ?? new objClassName();

Stacking Null Coalese Operator

        $v = $x ?? $y ?? $z; 

        // This is a sequence of "SET && NOT NULL"s:

        if( $x  &&  !is_null($x) ){ 
            return $x; 
        } else if( $y && !is_null($y) ){ 
            return $y; 
        } else { 
            return $z; 
        }

The Ternary Operator ?:

  • ?: is like a gate that lets anything falsy through - including NULL
  • Anything falsy: 0, empty string, NULL, false, !isset(), empty()
  • Same like old ternary operator: X ? Y : Z
  • Note: ?: will throw PHP NOTICE on undefined (unset or !isset()) variables

Use of ?:

  • checking empty(), !isset(), is_null() etc
  • shorten ternary operation like !empty($x) ? $x : $y to $x ?: $y
  • shorten if(!$x) { echo $x; } else { echo $y; } to echo $x ?: $y

Stacking Ternary Operator

        echo 0 ?: 1 ?: 2 ?: 3; //1
        echo 1 ?: 0 ?: 3 ?: 2; //1
        echo 2 ?: 1 ?: 0 ?: 3; //2
        echo 3 ?: 2 ?: 1 ?: 0; //3
    
        echo 0 ?: 1 ?: 2 ?: 3; //1
        echo 0 ?: 0 ?: 2 ?: 3; //2
        echo 0 ?: 0 ?: 0 ?: 3; //3

    
        // Source & Credit: http://php.net/manual/en/language.operators.comparison.php#95997
   
        // This is basically a sequence of:

 
        if( truthy ) {}
        else if(truthy ) {}
        else if(truthy ) {}
        ..
        else {}

Stacking both, we can shorten this:

        if( isset($_GET['name']) && !is_null($_GET['name'])) {
            $name = $_GET['name'];
        } else if( !empty($user_name) ) {
             $name = $user_name; 
        } else {
            $name = 'anonymous';
        }

To this:

        $name = $_GET['name'] ?? $user_name ?: 'anonymous';

Cool, right? :-)

How to recursively find the latest modified file in a directory?

I found the command above useful, but for my case I needed to see the date and time of the file as well I had an issue with several files that have spaces in the names. Here is my working solution.

find . -type f -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d" " | sed 's/.*/"&"/' | xargs ls -l

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

I had this problem with only one service with constructor based dependency injection with 2019.2.4 version of IntelliJ. I found it helpful to change the name of the service (shift + f6) and then discard the changes from the git level.

Rails where condition using NOT NIL

The canonical way to do this with Rails 3:

Foo.includes(:bar).where("bars.id IS NOT NULL")

ActiveRecord 4.0 and above adds where.not so you can do this:

Foo.includes(:bar).where.not('bars.id' => nil)
Foo.includes(:bar).where.not(bars: { id: nil })

When working with scopes between tables, I prefer to leverage merge so that I can use existing scopes more easily.

Foo.includes(:bar).merge(Bar.where.not(id: nil))

Also, since includes does not always choose a join strategy, you should use references here as well, otherwise you may end up with invalid SQL.

Foo.includes(:bar)
   .references(:bar)
   .merge(Bar.where.not(id: nil))

Clear text from textarea with selenium

It is general syntax

driver.find_element_by_id('Locator value').clear();
driver.find_element_by_name('Locator value').clear();

Regex (grep) for multi-line search needed

Your fundamental problem is that grep works one line at a time - so it cannot find a SELECT statement spread across lines.

Your second problem is that the regex you are using doesn't deal with the complexity of what can appear between SELECT and FROM - in particular, it omits commas, full stops (periods) and blanks, but also quotes and anything that can be inside a quoted string.

I would likely go with a Perl-based solution, having Perl read 'paragraphs' at a time and applying a regex to that. The downside is having to deal with the recursive search - there are modules to do that, of course, including the core module File::Find.

In outline, for a single file:

$/ = "\n\n";    # Paragraphs

while (<>)
{
     if ($_ =~ m/SELECT.*customerName.*FROM/mi)
     {
         printf file name
         go to next file
     }
}

That needs to be wrapped into a sub that is then invoked by the methods of File::Find.

How do I load an HTML page in a <div> using JavaScript?

I finally found the answer to my problem. The solution is

function load_home() {
     document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}

getActionBar() returns null

android.support.v7.app.ActionBar actionBar = getSupportActionBar();

works pretty quickly

how to always round up to the next integer

A proper benchmark or how the number may lie

Following the argument about Math.ceil(value/10d) and (value+9)/10 I ended up coding a proper non-dead code, non-interpret mode benchmark. I've been telling that writing micro benchmark is not an easy task. The code below illustrates this:

00:21:40.109 starting up....
00:21:40.140 doubleCeil: 19444599
00:21:40.140 integerCeil: 19444599
00:21:40.140 warming up...
00:21:44.375 warmup doubleCeil: 194445990000
00:21:44.625 warmup integerCeil: 194445990000
00:22:27.437 exec doubleCeil: 1944459900000, elapsed: 42.806s
00:22:29.796 exec integerCeil: 1944459900000, elapsed: 2.363s

The benchmark is in Java since I know well how Hotspot optimizes and ensures it's a fair result. With such results, no statistics, noise or anything can taint it.

Integer ceil is insanely much faster.

The code

package t1;

import java.math.BigDecimal;

import java.util.Random;

public class Div {
    static int[] vals;

    static long doubleCeil(){
        int[] v= vals;
        long sum = 0;
        for (int i=0;i<v.length;i++){
            int value = v[i];
            sum+=Math.ceil(value/10d);
        }
        return sum;
    }

    static long integerCeil(){      
        int[] v= vals;
        long sum = 0;
        for (int i=0;i<v.length;i++){
            int value = v[i];
            sum+=(value+9)/10;
        }
        return sum;     
    }

    public static void main(String[] args) {
        vals = new  int[7000];
        Random r= new Random(77);
        for (int i = 0; i < vals.length; i++) {
            vals[i] = r.nextInt(55555);
        }
        log("starting up....");

        log("doubleCeil: %d", doubleCeil());
        log("integerCeil: %d", integerCeil());
        log("warming up...");       

        final int warmupCount = (int) 1e4;
        log("warmup doubleCeil: %d", execDoubleCeil(warmupCount));
        log("warmup integerCeil: %d", execIntegerCeil(warmupCount));

        final int execCount = (int) 1e5;

        {       
        long time = System.nanoTime();
        long s = execDoubleCeil(execCount);
        long elapsed = System.nanoTime() - time;
        log("exec doubleCeil: %d, elapsed: %.3fs",  s, BigDecimal.valueOf(elapsed, 9));
        }

        {
        long time = System.nanoTime();
        long s = execIntegerCeil(execCount);
        long elapsed = System.nanoTime() - time;
        log("exec integerCeil: %d, elapsed: %.3fs",  s, BigDecimal.valueOf(elapsed, 9));            
        }
    }

    static long execDoubleCeil(int count){
        long sum = 0;
        for(int i=0;i<count;i++){
            sum+=doubleCeil();
        }
        return sum;
    }


    static long execIntegerCeil(int count){
        long sum = 0;
        for(int i=0;i<count;i++){
            sum+=integerCeil();
        }
        return sum;
    }

    static void log(String msg, Object... params){
        String s = params.length>0?String.format(msg, params):msg;
        System.out.printf("%tH:%<tM:%<tS.%<tL %s%n", new Long(System.currentTimeMillis()), s);
    }   
}

Target class controller does not exist - Laravel 8

  • Yes in laravel 8 this error is occur..
  • After try many solutions I got these perfect solution
  • Just follow the steps...

CASE - 1

We can change in api.php and in web.php files like below..
The current way we write syntax is

Route::get('login', 'LoginController@login');

should be changed to

Route::get('login', [LoginController::class, 'login']);

CASE - 2

  1. First go to the file: app > Providers > RouteServiceProvider.php
  2. In that file replace the line
    protected $namespace = null; with protected $namespace = 'App\Http\Controllers'; enter image description here
  3. Then After add line ->namespace($this->namespace) as shown in image..
    enter image description here

how to check if a datareader is null or empty

Try this simpler equivalent syntax:

ltlAdditional.Text = (myReader["Additional"] == DBNull.Value) ? "is null" : "contains data";

How do you import an Eclipse project into Android Studio now?

Simple steps: 1.Go to Android Studio. 2.Close all open projects if any. 3.There will be an option which says import non Android Studio Projects(Eclipse ect). 4.Click on it and choose ur project Thats't it enjoy!!!

How to include !important in jquery

It is also possible to add more important properties:

inputObj.attr('style', 'color:black !important; background-color:#428bca !important;');

How do I find the date a video (.AVI .MP4) was actually recorded?

Have a try to exiftools or mediainfo, which provides you an export function as text. Just pay attention to daylight saving.

C# Test if user has write access to a folder

Your code gets the DirectorySecurity for a given directory, and handles an exception (due to your not having access to the security info) correctly. However, in your sample you don't actually interrogate the returned object to see what access is allowed - and I think you need to add this in.

How do I add all new files to SVN

If svn add whatever/directory/* doesn't work, you can do it the tough way:

svn st | grep ^\? | cut -c 2- | xargs svn add