Programs & Examples On #Unmanaged

Unmanaged refers to Windows code that is independent of the Common Language Runtime(CLR). COM components, ActiveX components, and Win32 API functions are examples of unmanaged code.

What is managed or unmanaged code in programming?

This is a good article about the subject.

To summarize,

  1. Managed code is not compiled to machine code but to an intermediate language which is interpreted and executed by some service on a machine and is therefore operating within a (hopefully!) secure framework which handles dangerous things like memory and threads for you. In modern usage this frequently means .NET but does not have to.

An application program that is executed within a runtime engine installed in the same machine. The application cannot run without it. The runtime environment provides the general library of software routines that the program uses and typically performs memory management. It may also provide just-in-time (JIT) conversion from source code to executable code or from an intermediate language to executable code. Java, Visual Basic and .NET's Common Language Runtime (CLR) are examples of runtime engines. (Read more)

  1. Unmanaged code is compiled to machine code and therefore executed by the OS directly. It therefore has the ability to do damaging/powerful things Managed code does not. This is how everything used to work, so typically it's associated with old stuff like .dlls.

An executable program that runs by itself. Launched from the operating system, the program calls upon and uses the software routines in the operating system, but does not require another software system to be used. Assembly language programs that have been assembled into machine language and C/C++ programs compiled into machine language for a particular platform are examples of unmanaged code.(Read more)

  1. Native code is often synonymous with Unmanaged, but is not identical.

Difference between "managed" and "unmanaged"

Managed Code

Managed code is what Visual Basic .NET and C# compilers create. It runs on the CLR (Common Language Runtime), which, among other things, offers services like garbage collection, run-time type checking, and reference checking. So, think of it as, "My code is managed by the CLR."

Visual Basic and C# can only produce managed code, so, if you're writing an application in one of those languages you are writing an application managed by the CLR. If you are writing an application in Visual C++ .NET you can produce managed code if you like, but it's optional.

Unmanaged Code

Unmanaged code compiles straight to machine code. So, by that definition all code compiled by traditional C/C++ compilers is 'unmanaged code'. Also, since it compiles to machine code and not an intermediate language it is non-portable.

No free memory management or anything else the CLR provides.

Since you cannot create unmanaged code with Visual Basic or C#, in Visual Studio all unmanaged code is written in C/C++.

Mixing the two

Since Visual C++ can be compiled to either managed or unmanaged code it is possible to mix the two in the same application. This blurs the line between the two and complicates the definition, but it's worth mentioning just so you know that you can still have memory leaks if, for example, you're using a third party library with some badly written unmanaged code.

Here's an example I found by googling:

#using <mscorlib.dll>
using namespace System;

#include "stdio.h"

void ManagedFunction()
{
    printf("Hello, I'm managed in this section\n");
}

#pragma unmanaged
UnmanagedFunction()
{
    printf("Hello, I am unmanaged through the wonder of IJW!\n");
    ManagedFunction();
}

#pragma managed
int main()
{
    UnmanagedFunction();
    return 0;
}

How do I grant myself admin access to a local SQL Server instance?

Yes - it appears you forgot to add yourself to the sysadmin role when installing SQL Server. If you are a local administrator on your machine, this blog post can help you use SQLCMD to get your account into the SQL Server sysadmin group without having to reinstall. It's a bit of a security hole in SQL Server, if you ask me, but it'll help you out in this case.

Eclipse/Maven error: "No compiler is provided in this environment"

This worked for me. 1. Click on Window-> Preferences -> Installed JRE. 2. Check if you reference is for JDK as shown in the image below. enter image description here

If not, Click on Add-> Standard VM -> Give the JDK path by selecting the directory and click on finish as shown in the image enter image description here

  1. Last step, click on Installed JREs -> Execution Environments -> select your JDE as shown in the image below enter image description here

  2. Maven -> Clean

How to set background color of an Activity to white programmatically?

final View rootView = findViewById(android.R.id.content);
rootView.setBackgroundResource(...);

Parsing domain from a URL

Check out parse_url():

$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
echo $parse['host']; // prints 'google.com'

parse_url doesn't handle really badly mangled urls very well, but is fine if you generally expect decent urls.

Testing web application on Mac/Safari when I don't own a Mac

Meanwhile, MacOS High Sierra can be run in VirtualBox (on a PC) for Free. It's not really fast but it works for general browser testing.

How to setup see here: https://www.howtogeek.com/289594/how-to-install-macos-sierra-in-virtualbox-on-windows-10/

I'm using this for a while now and it works quite well

How to pretty print XML from the command line?

You can also use tidy, which may need to be installed first (e.g. on Ubuntu: sudo apt-get install tidy).

For this, you would issue something like following:

tidy -xml -i your-file.xml > output.xml

Note: has many additional readability flags, but word-wrap behavior is a bit annoying to untangle (http://tidy.sourceforge.net/docs/quickref.html).

How do I declare and use variables in PL/SQL like I do in T-SQL?

In Oracle PL/SQL, if you are running a query that may return multiple rows, you need a cursor to iterate over the results. The simplest way is with a for loop, e.g.:

declare
  myname varchar2(20) := 'tom';
begin
  for result_cursor in (select * from mytable where first_name = myname) loop
    dbms_output.put_line(result_cursor.first_name);
    dbms_output.put_line(result_cursor.other_field);
  end loop;
end;

If you have a query that returns exactly one row, then you can use the select...into... syntax, e.g.:

declare 
  myname varchar2(20);
begin
  select first_name into myname 
    from mytable 
    where person_id = 123;
end;

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

Unset($array[0]); 

Sort($array); 

I don't know why this is being downvoted, but if anyone has bothered to try it, you will notice that it works. Using sort on an array reassigns the keys of the the array. The only drawback is it sorts the values. Since the keys will obviously be reassigned, even with array_values, it does not matter is the values are being sorted or not.

Fastest way to determine if record exists

For those stumbling upon this from MySQL or Oracle background - MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses ROWNUM.

Get IP address of visitors using Flask for Python

If You are using Gunicorn and Nginx environment then the following code template works for you.

addr_ip4 = request.remote_addr

How to find the parent element using javascript

Use the change event of the select:

$('#my_select').change(function()
{
   $(this).parents('td').css('background', '#000000');
});

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address.

  1. Edit tomcat/conf/server.xml.
  2. Specify a bind address for that connector:
    <Connector 
        port="8080" 
        protocol="HTTP/1.1" 
        address="127.0.0.1"
        connectionTimeout="20000" 
        redirectPort="8443" 
      />
    

C/C++ check if one bit is set in, i.e. int variable

You could "simulate" shifting and masking: if((0x5e/(2*2*2))%2) ...

Modifying a query string without reloading the page

I want to improve Fabio's answer and create a function which adds custom key to the URL string without reloading the page.

function insertUrlParam(key, value) {
    if (history.pushState) {
        let searchParams = new URLSearchParams(window.location.search);
        searchParams.set(key, value);
        let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
        window.history.pushState({path: newurl}, '', newurl);
    }
}

How to inspect FormData?

I use the formData.entries() method. I'm not sure about all browser support, but it works fine on Firefox.

Taken from https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries

// Create a test FormData object
var formData = new FormData();
formData.append('key1','value1');
formData.append('key2','value2');

// Display the key/value pairs
for (var pair of formData.entries())
{
 console.log(pair[0]+ ', '+ pair[1]); 
}

There is also formData.get() and formData.getAll() with wider browser support, but they only bring up the Values and not the Key. See the link for more info.

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

As Microsoft.ReportViewer.2012.Runtime has Microsoft.ReportViewer.WebForms, Microsoft.ReportViewer.Common and Microsoft.ReportViewer.ProcessingObjectModel libraries, just run this command on PM Console:

Install-Package Microsoft.ReportViewer.2012.Runtime

Note : If you want to completely remove the old Microsoft.ReportViewer.xxx references, you can remove them from Manage NuGet Packages>Installed Packages menu and then remove the related lines from packages.config file in your project. After that it will not comeback again during building of the project.

Hope this helps...

how to write value into cell with vba code without auto type conversion?

Indeed, just as commented by Tim Williams, the way to make it work is pre-formatting as text. Thus, to do it all via VBA, just do that:

Cells(1, 1).NumberFormat = "@"
Cells(1, 1).Value = "1234,56"

Reading column names alone in a csv file

How about

with open(csv_input_path + file, 'r') as ft:
    header = ft.readline() # read only first line; returns string
    header_list = header.split(',') # returns list

I am assuming your input file is CSV format. If using pandas, it takes more time if the file is big size because it loads the entire data as the dataset.

Non-Static method cannot be referenced from a static context with methods and variables

You should place Scanner input = new Scanner (System.in); into the main method rather than creating the input object outside.

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

My issue was that I was trying to give my ssh key a SPECIFIC NAME every time I entered ssh-keygen on my mac terminal.

I solved the issue by just leaving the name that "ssh-keygen" generates = id_rsa. You'll end up with 2 keys in your .ssh folder on a mac, id_rsa, which is your private key, and the id_rsa.pub, which is your public key. Then I copied and saved the code from id_rsa.pub into my GitHub account settings, and that was it. Problem solved.

Delete everything in a MongoDB database

I had the same problem, when I needed to reset all the collections but didn't want to loose any database users. Use the following line of code, if you would like to save the user configuration for the database:

use <whichever database>
db.getCollectionNames().forEach(function(c) { if (c.indexOf("system.") == -1) db[c].drop(); })

This code will go through all collection names from one database and drop those which do not start with "system.".

How to test Spring Data repositories?

When you really want to write an i-test for a spring data repository you can do it like this:

@RunWith(SpringRunner.class)
@DataJpaTest
@EnableJpaRepositories(basePackageClasses = WebBookingRepository.class)
@EntityScan(basePackageClasses = WebBooking.class)
public class WebBookingRepositoryIntegrationTest {

    @Autowired
    private WebBookingRepository repository;

    @Test
    public void testSaveAndFindAll() {
        WebBooking webBooking = new WebBooking();
        webBooking.setUuid("some uuid");
        webBooking.setItems(Arrays.asList(new WebBookingItem()));
        repository.save(webBooking);

        Iterable<WebBooking> findAll = repository.findAll();

        assertThat(findAll).hasSize(1);
        webBooking.setId(1L);
        assertThat(findAll).containsOnly(webBooking);
    }
}

To follow this example you have to use these dependencies:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.197</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.9.1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Get the Id of current table row with Jquery

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>Untitled</title>

<script type="text/javascript"><!--

function getVal(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    alert(targ.innerHTML);
}

onload = function() {
    var t = document.getElementById("main").getElementsByTagName("td");
    for ( var i = 0; i < t.length; i++ )
        t[i].onclick = getVal;
}

</script>



<body>

<table id="main"><tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
</tr><tr>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
</tr><tr>
    <td>9</td>
    <td>10</td>
    <td>11</td>
    <td>12</td>
</tr></table>

</body>
</html>

writing a batch file that opens a chrome URL

assuming chrome is his default browser: start http://url.site.you.com/path/to/joke should open that url in his browser.

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Try the following statement to check for existence of a table in the database:

If not exists (select name from sysobjects where name = 'tablename')

You may create the table inside the if block.

TypeError: argument of type 'NoneType' is not iterable

If a function does not return anything, e.g.:

def test():
    pass

it has an implicit return value of None.

Thus, as your pick* methods do not return anything, e.g.:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")

the lines that call them, e.g.:

word = pickEasy()

set word to None, so wordInput in getInput is None. This means that:

if guess in wordInput:

is the equivalent of:

if guess in None:

and None is an instance of NoneType which does not provide iterator/iteration functionality, so you get that type error.

The fix is to add the return type:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

Classes cannot be accessed from outside package

public SmartSaverCals(Context context)
{
    this.context= context;
}

add public to Your constructor.in my case problem solved

Using a PagedList with a ViewModel ASP.Net MVC

For anyone who is trying to do it without modifying your ViewModels AND not loading all your records from the database.

Repository

    public List<Order> GetOrderPage(int page, int itemsPerPage, out int totalCount)
    {
        List<Order> orders = new List<Order>();
        using (DatabaseContext db = new DatabaseContext())
        {
            orders = (from o in db.Orders
                      orderby o.Date descending //use orderby, otherwise Skip will throw an error
                      select o)
                      .Skip(itemsPerPage * page).Take(itemsPerPage)
                      .ToList();
            totalCount = db.Orders.Count();//return the number of pages
        }
        return orders;//the query is now already executed, it is a subset of all the orders.
    }

Controller

    public ActionResult Index(int? page)
    {
        int pagenumber = (page ?? 1) -1; //I know what you're thinking, don't put it on 0 :)
        OrderManagement orderMan = new OrderManagement(HttpContext.ApplicationInstance.Context);
        int totalCount = 0;
        List<Order> orders = orderMan.GetOrderPage(pagenumber, 5, out totalCount);
        List<OrderViewModel> orderViews = new List<OrderViewModel>();
        foreach(Order order in orders)//convert your models to some view models.
        {
            orderViews.Add(orderMan.GenerateOrderViewModel(order));
        }
        //create staticPageList, defining your viewModel, current page, page size and total number of pages.
        IPagedList<OrderViewModel> pageOrders = new StaticPagedList<OrderViewModel>(orderViews, pagenumber + 1, 5, totalCount);
        return View(pageOrders);
    }

View

@using PagedList.Mvc;
@using PagedList; 

@model IPagedList<Babywatcher.Core.Models.OrderViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div class="container-fluid">
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    @if (Model.Count > 0)
    {


        <table class="table">
          <tr>
            <th>
                @Html.DisplayNameFor(model => model.First().orderId)
            </th>
            <!--rest of your stuff-->
        </table>

    }
    else
    {
        <p>No Orders yet.</p>
    }
    @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</div>

Bonus

Do above first, then perhaps use this!

Since this question is about (view) models, I'm going to give away a little solution for you that will not only be useful for paging, but for the rest of your application if you want to keep your entities separate, only used in the repository, and have the rest of the application deal with models (which can be used as view models).

Repository

In your order repository (in my case), add a static method to convert a model:

public static OrderModel ConvertToModel(Order entity)
{
    if (entity == null) return null;
    OrderModel model = new OrderModel
    {
        ContactId = entity.contactId,
        OrderId = entity.orderId,
    }
    return model;
}

Below your repository class, add this:

public static partial class Ex
{
    public static IEnumerable<OrderModel> SelectOrderModel(this IEnumerable<Order> source)
    {
        bool includeRelations = source.GetType() != typeof(DbQuery<Order>);
        return source.Select(x => new OrderModel
        {
            OrderId = x.orderId,
            //example use ConvertToModel of some other repository
            BillingAddress = includeRelations ? AddressRepository.ConvertToModel(x.BillingAddress) : null,
            //example use another extension of some other repository
            Shipments = includeRelations && x.Shipments != null ? x.Shipments.SelectShipmentModel() : null
        });
    }
}

And then in your GetOrderPage method:

    public IEnumerable<OrderModel> GetOrderPage(int page, int itemsPerPage, string searchString, string sortOrder, int? partnerId,
        out int totalCount)
    {
        IQueryable<Order> query = DbContext.Orders; //get queryable from db
        .....//do your filtering, sorting, paging (do not use .ToList() yet)

        return queryOrders.SelectOrderModel().AsEnumerable();
        //or, if you want to include relations
        return queryOrders.Include(x => x.BillingAddress).ToList().SelectOrderModel();
        //notice difference, first ToList(), then SelectOrderModel().
    }

Let me explain:

The static ConvertToModel method can be accessed by any other repository, as used above, I use ConvertToModel from some AddressRepository.

The extension class/method lets you convert an entity to a model. This can be IQueryable or any other list, collection.

Now here comes the magic: If you have executed the query BEFORE calling SelectOrderModel() extension, includeRelations inside the extension will be true because the source is NOT a database query type (not an linq-to-sql IQueryable). When this is true, the extension can call other methods/extensions throughout your application for converting models.

Now on the other side: You can first execute the extension and then continue doing LINQ filtering. The filtering will happen in the database eventually, because you did not do a .ToList() yet, the extension is just an layer of dealing with your queries. Linq-to-sql will eventually know what filtering to apply in the Database. The inlcudeRelations will be false so that it doesn't call other c# methods that SQL doesn't understand.

It looks complicated at first, extensions might be something new, but it's really useful. Eventually when you have set this up for all repositories, simply an .Include() extra will load the relations.

String concatenation in MySQL

Try:

select concat(first_name,last_name) as "Name" from test.student

or, better:

select concat(first_name," ",last_name) as "Name" from test.student

Using Chrome's Element Inspector in Print Preview Mode?

If you are debugging your CSS using Print As PDF in Google Chrome and your CSS element background colors are not showing, then make sure the 'Background graphics' checkbox is ticked. I spent almost 30 minutes debugging my CSS and wondering what is causing my CSS background being ignored.

Google Chrome Print background color ignored

How do you run a single query through mysql from the command line?

echo "select * from users;" | mysql -uroot -p -hslavedb.mydomain.com mydb_production

How to copy Outlook mail message into excel using VBA or Macros

Since you have not mentioned what needs to be copied, I have left that section empty in the code below.

Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.

This will get you started. I have commented the code so that you will not face any problem understanding it.

First paste the below mentioned code in the outlook module.

Then

  1. Click on Tools~~>Rules and Alerts
  2. Click on "New Rule"
  3. Click on "start from a blank rule"
  4. Select "Check messages When they arrive"
  5. Under conditions, click on "with specific words in the subject"
  6. Click on "specific words" under rules description.
  7. Type the word that you want to check in the dialog box that pops up and click on "add".
  8. Click "Ok" and click next
  9. Select "move it to specified folder" and also select "run a script" in the same box
  10. In the box below, specify the specific folder and also the script (the macro that you have in module) to run.
  11. Click on finish and you are done.

When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.

UNTESTED

Const xlUp As Long = -4162

Sub ExportToExcel(MyMail As MailItem)
    Dim strID As String, olNS As Outlook.Namespace
    Dim olMail As Outlook.MailItem
    Dim strFileName As String

    '~~> Excel Variables
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object
    Dim lRow As Long

    strID = MyMail.EntryID
    Set olNS = Application.GetNamespace("MAPI")
    Set olMail = olNS.GetItemFromID(strID)

    '~~> Establish an EXCEL application object
    On Error Resume Next
    Set oXLApp = GetObject(, "Excel.Application")

    '~~> If not found then create new instance
    If Err.Number <> 0 Then
        Set oXLApp = CreateObject("Excel.Application")
    End If
    Err.Clear
    On Error GoTo 0

    '~~> Show Excel
    oXLApp.Visible = True

    '~~> Open the relevant file
    Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")

    '~~> Set the relevant output sheet. Change as applicable
    Set oXLws = oXLwb.Sheets("Sheet1")

    lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1

    '~~> Write to outlook
    With oXLws
        '
        '~~> Code here to output data from email to Excel File
        '~~> For example
        '
        .Range("A" & lRow).Value = olMail.Subject
        .Range("B" & lRow).Value = olMail.SenderName
        '
    End With

    '~~> Close and Clean up Excel
    oXLwb.Close (True)
    oXLApp.Quit
    Set oXLws = Nothing
    Set oXLwb = Nothing
    Set oXLApp = Nothing

    Set olMail = Nothing
    Set olNS = Nothing
End Sub

FOLLOWUP

To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example

Dim MyAr() As String

MyAr = Split(olMail.body, vbCrLf)

For i = LBound(MyAr) To UBound(MyAr)
    '~~> This will give you the contents of your email
    '~~> on separate lines
    Debug.Print MyAr(i)
Next i

Show ImageView programmatically

If you add to RelativeLayout, don't forget to set imageView's position. For instance:

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(200, 200);
lp.addRule(RelativeLayout.CENTER_IN_PARENT); // A position in layout.
ImageView imageView = new ImageView(this); // initialize ImageView
imageView.setLayoutParams(lp);
// imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(R.drawable.photo);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);
layout.addView(imageView);

Installing PG gem on OS X - failure to build native extension

For those who are not interested to use brew.

  1. Download PostgreSQL application.
  2. Follow the macOS default instruction to install it.
  3. It is advisable to run PostgreSQl.
  4. Run gem install pg -- --with-pg-config=/path/to/postgress/in/your/applications/folder/`
    • For example, in my machine it is /Applications/Postgres.app/Contents/Versions/12/bin/pg_config

How to tell PowerShell to wait for each command to end before starting the next?

Normally, for internal commands PowerShell does wait before starting the next command. One exception to this rule is external Windows subsystem based EXE. The first trick is to pipeline to Out-Null like so:

Notepad.exe | Out-Null

PowerShell will wait until the Notepad.exe process has been exited before continuing. That is nifty but kind of subtle to pick up from reading the code. You can also use Start-Process with the -Wait parameter:

Start-Process <path to exe> -NoNewWindow -Wait

If you are using the PowerShell Community Extensions version it is:

$proc = Start-Process <path to exe> -NoNewWindow -PassThru
$proc.WaitForExit()

Another option in PowerShell 2.0 is to use a background job:

$job = Start-Job { invoke command here }
Wait-Job $job
Receive-Job $job

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

I use the following maven dependencies to get java mail working. The first one includes the javax.mail API (with no implementation) and the second one is the SUN implementation of the javax.mail API.

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.5.5</version>
</dependency>
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.5.5</version>
</dependency>

SQL Server Operating system error 5: "5(Access is denied.)"

The actual server permissions will not matter at this point; all looks ok. SQL Server itself needs folder permissions.
depending on your version, you can add SERVERNAME$MSSQLSERVER permissions to touch your folder. Othewise, it has to be in the default BACKUP directory (either where you installed it or default to c:\programfiles(x)\MSSQL\BACKUP.

Closing Twitter Bootstrap Modal From Angular Controller

We can achieve the same without using angular-ui. This can be done using angular directives.

First add the directive to the modal.

<div class="modal fade" my-modal ....>...</div>

Create a new angular directive:

app.directive('myModal', function() {
   return {
     restrict: 'A',
     link: function(scope, element, attr) {
       scope.dismiss = function() {
           element.modal('hide');
       };
     }
   } 
});

Now call the dismiss() method from your controller.

app.controller('MyCtrl', function($scope, $http) {
    // You can call dismiss() here
    $scope.dismiss();
});

I am still in my early days with angular js. I know that we should not manipulate the DOM inside the controllers. So I have the DOM manipulation in the directive. I am not sure if this is equally bad. If I have a better alternative, I shall post it here.

The important thing to note is that we cannot simply use ng-hide or ng-show in the view to hide or show the modal. That simply hides the modal and not the modal backdrop. We have to call the modal() instance method to completely remove the modal.

How do you check "if not null" with Eloquent?

If you want to search deleted record (Soft Deleted Record), do't user Eloquent Model Query. Instead use Db::table query e.g Instead of using Below:

$stu = Student::where('rollNum', '=', $rollNum . '-' . $nursery)->first();

Use:

$stu = DB::table('students')->where('rollNum', '=', $newRollNo)->first();

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

You need to set JDK 1.5 to your project and also all dependent project or jar file should also compiled with JDK 1.5

How can I count the number of elements with same class?

I'd like to write explicitly two methods which allow accomplishing this in pure JavaScript:

document.getElementsByClassName('realClasssName').length

Note 1: Argument of this method needs a string with the real class name, without the dot at the begin of this string.

document.querySelectorAll('.realClasssName').length

Note 2: Argument of this method needs a string with the real class name but with the dot at the begin of this string.

Note 3: This method works also with any other CSS selectors, not only with class selector. So it's more universal.


I also write one method, but using two name conventions to solve this problem using jQuery:

jQuery('.realClasssName').length

or

$('.realClasssName').length

Note 4: Here we also have to remember about the dot, before the class name, and we can also use other CSS selectors.

Pass data from Activity to Service using an Intent

If you are using kotlin you can try the following code,

In the sending activity,

  val intent = Intent(context, RecorderService::class.java);
  intent.putExtra("filename", filename);
  context.startService(intent)

In the service,

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    super.onStartCommand(intent, flags, startId)

    if (intent != null && intent.extras != null)
       val filename = intent.getStringExtra("filename")

}

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

this work for me

compile 'com.android.support:appcompat-v7:26.0.0'

change 26.0.0 to 26.0.1

compile 'com.android.support:appcompat-v7:26.0.1'

Received fatal alert: handshake_failure through SSLHandshakeException

Installing Java Cryptography Extension (JCE) Unlimited Strength (for JDK7 | for JDK8) might fix this bug. Unzip the file and follow the readme to install it.

Joining 2 SQL SELECT result sets into one

Use a FULL OUTER JOIN:

select 
   a.col_a,
   a.col_b,
   b.col_c
from
   (select col_a,col_bfrom tab1) a
join 
   (select col_a,col_cfrom tab2) b 
on a.col_a= b.col_a

How to remove focus without setting focus to another control?

You could try turning off the main Activity's ability to save its state (thus making it forget what control had text and what had focus). You will need to have some other way of remembering what your EditText's have and repopulating them onResume(). Launch your sub-Activities with startActivityForResult() and create an onActivityResult() handler in your main Activity that will update the EditText's correctly. This way you can set the proper button you want focused onResume() at the same time you repopulate the EditText's by using a myButton.post(new Runnable(){ run() { myButton.requestFocus(); } });

The View.post() method is useful for setting focus initially because that runnable will be executed after the window is created and things settle down, allowing the focus mechanism to function properly by that time. Trying to set focus during onCreate/Start/Resume() usually has issues, I've found.

Please note this is pseudo-code and non-tested, but it's a possible direction you could try.

Column standard deviation R

Use colSds function from matrixStats library.

library(matrixStats)
set.seed(42)
M <- matrix(rnorm(40),ncol=4)
colSds(M)

[1] 0.8354488 1.6305844 1.1560580 1.1152688

Creating an IFRAME using JavaScript

You can use:

<script type="text/javascript">
    function prepareFrame() {
        var ifrm = document.createElement("iframe");
        ifrm.setAttribute("src", "http://google.com/");
        ifrm.style.width = "640px";
        ifrm.style.height = "480px";
        document.body.appendChild(ifrm);
    }
</script> 

also check basics of the iFrame element

Change a web.config programmatically with C# (.NET)

Since web.config file is xml file you can open web.config using xmldocument class. Get the node from that xml file that you want to update and then save xml file.

here is URL that explains in more detail how you can update web.config file programmatically.

http://patelshailesh.com/index.php/update-web-config-programmatically

Note: if you make any changes to web.config, ASP.NET detects that changes and it will reload your application(recycle application pool) and effect of that is data kept in Session, Application, and Cache will be lost (assuming session state is InProc and not using a state server or database).

When adding a Javascript library, Chrome complains about a missing source map, why?

I get this warning in Angular if I run:

ng serve --sourceMap=false

To fix:

ng serve

Print directly from browser without print popup window

For IE browsers, the "VBScript solution" works.

But as mentioned by @purefusion at Bypass Printdialog in IE9, Use Print() rather than window.print()

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

The article previously mentioned is good. http://forums.oracle.com/forums/thread.jspa?threadID=191750 (as far as it goes)

If this is not something that runs frequently (don't do it on your home page), you can turn off connection pooling.

There is one other "gotcha" that is not mentioned in the article. If the first thing you try to do with the connection is call a stored procedure, ODP will HANG!!!! You will not get back an error condition to manage, just a full bore HANG! The only way to fix it is to turn OFF connection pooling. Once we did that, all issues went away.

Pooling is good in some situations, but at the cost of increased complexity around the first statement of every connection.

If the error handling approach is so good, why don't they make it an option for ODP to handle it for us????

What is the Simplest Way to Reverse an ArrayList?

Reversing a ArrayList in a recursive way and without creating a new list for adding elements :

   public class ListUtil {

    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("1");
        arrayList.add("2");
        arrayList.add("3");
        arrayList.add("4");
        arrayList.add("5");
        System.out.println("Reverse Order: " + reverse(arrayList));

    }

    public static <T> List<T> reverse(List<T> arrayList) {
        return reverse(arrayList,0,arrayList.size()-1);
    }
    public static <T> List<T> reverse(List<T> arrayList,int startIndex,int lastIndex) {

        if(startIndex<lastIndex) {
            T t=arrayList.get(lastIndex);
            arrayList.set(lastIndex,arrayList.get(startIndex));
            arrayList.set(startIndex,t);
            startIndex++;
            lastIndex--;
            reverse(arrayList,startIndex,lastIndex);
        }
        return arrayList;
    }

}

How to inject Javascript in WebBrowser control?

Also, in .NET 4 this is even easier if you use the dynamic keyword:

dynamic document = this.browser.Document;
dynamic head = document.GetElementsByTagName("head")[0];
dynamic scriptEl = document.CreateElement("script");
scriptEl.text = ...;
head.AppendChild(scriptEl);

Accessing items in an collections.OrderedDict by index

Here is a special case if you want the first entry (or close to it) in an OrderedDict, without creating a list. (This has been updated to Python 3):

>>> from collections import OrderedDict
>>> 
>>> d = OrderedDict()
>>> d["foo"] = "one"
>>> d["bar"] = "two"
>>> d["baz"] = "three"
>>> next(iter(d.items()))
('foo', 'one')
>>> next(iter(d.values()))
'one'

(The first time you say "next()", it really means "first.")

In my informal test, next(iter(d.items())) with a small OrderedDict is only a tiny bit faster than items()[0]. With an OrderedDict of 10,000 entries, next(iter(d.items())) was about 200 times faster than items()[0].

BUT if you save the items() list once and then use the list a lot, that could be faster. Or if you repeatedly { create an items() iterator and step through it to to the position you want }, that could be slower.

T-SQL XOR Operator

As clarified in your comment, Spacemoses, you stated an example: WHERE (Note is null) ^ (ID is null). I do not see why you chose to accept any answer given here as answering that. If i needed an xor for that, i think i'd have to use the AND/OR equivalent logic:

WHERE (Note is null and ID is not null) OR (Note is not null and ID is null)

That is equivalent to:

WHERE (Note is null) XOR (ID is null)

when 'XOR' is not available.

Need to ZIP an entire directory using Node.js

Since archiver is not compatible with the new version of webpack for a long time, I recommend using zip-lib.

var zl = require("zip-lib");

zl.archiveFolder("path/to/folder", "path/to/target.zip").then(function () {
    console.log("done");
}, function (err) {
    console.log(err);
});

How to give a pattern for new line in grep?

As for the workaround (without using non-portable -P), you can temporary replace a new-line character with the different one and change it back, e.g.:

grep -o "_foo_" <(paste -sd_ file) | tr -d '_'

Basically it's looking for exact match _foo_ where _ means \n (so __ = \n\n). You don't have to translate it back by tr '_' '\n', as each pattern would be printed in the new line anyway, so removing _ is enough.

Root password inside a Docker container

By default docker containers run as the root user.

If you are still using the container you can use exit command to get back to root (default user) user instead of running the container again.

Example -

[dev@6c4c86bccf93 ~]$ ls
[dev@6c4c86bccf93 ~]$ other-commands..
[dev@6c4c86bccf93 ~]$ exit
[root@6c4c86bccf93 /]# ls

Spring configure @ResponseBody JSON format

For Spring version 4.1.3+

I tried Jama's solution, but then all responses were returned with Content-type 'application/json', including the main, generated HTML page.

Overriding configureMessageConverters(...) prevents spring from setting up the default converters. Spring 4.1.3 allows modification of already configured converters by overriding extendMessageConverters(...):

@Configuration
public class ConverterConfig extends WebMvcConfigurerAdapter {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof AbstractJackson2HttpMessageConverter) {
                AbstractJackson2HttpMessageConverter c = (AbstractJackson2HttpMessageConverter) converter;
                ObjectMapper objectMapper = c.getObjectMapper();
                objectMapper.setSerializationInclusion(Include.NON_NULL);
            }
        }

        super.extendMessageConverters(converters);
    }
}

see org.springframework..WebMvcConfigurationSupport#getMessageConverters()

see org.springframework..WebMvcConfigurationSupport#addDefaultHttpMessageConverters(...)

syntax error near unexpected token `('

Since you've got both the shell that you're typing into and the shell that sudo -s runs, you need to quote or escape twice. (EDITED fixed quoting)

sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'

or

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)

Out of curiosity, why do you need -s? Can't you just do this:

sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

Find files containing a given text

find . -type f -name '*php' -o -name '*js' -o -name '*html' |\
xargs grep -liE 'document\.cookie|setcookie'

Calling startActivity() from outside of an Activity context

In addition: if you show links in listview in fragment, do not create it like this

adapter = new ListAdapter(getActivity().getApplicationContext(),mStrings);

instead call

adapter = new ListAdapter(getActivity(),mStrings);

adapter works fine in both cases, but links work only in last one.

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

In this case a[4] is the 5th integer in the array a, ap is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap now holds 45 and when you try to de-reference it (by doing *ap) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.

You should do ap = &(a[4]); or ap = a + 4;

In c array names decays to pointer, so a points to the 1st element of the array.
In this way, a is equivalent to &(a[0]).

Pure CSS scroll animation

And for webkit enabled browsers I've had good results with:

.myElement {
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth; // Added in from answer from Felix
    overflow-x: scroll;
}

This makes scrolling behave much more like the standard browser behavior - at least it works well on the iPhone we were testing on!

Hope that helps,

Ed

C# Numeric Only TextBox Control

try
{
    int temp=Convert.ToInt32(TextBox1.Text);
}
catch(Exception h)
{
    MessageBox.Show("Please provide number only");
}

How do I check if a string is a number (float)?

import re
def is_number(num):
    pattern = re.compile(r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$')
    result = pattern.match(num)
    if result:
        return True
    else:
        return False


?>>>: is_number('1')
True

>>>: is_number('111')
True

>>>: is_number('11.1')
True

>>>: is_number('-11.1')
True

>>>: is_number('inf')
False

>>>: is_number('-inf')
False

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

It's worth noting that this error can also happen if the target table or column you're using in the REFERENCES portion simply doesn't exist.

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

I had the same problem and I solved as follows define an interface like mine

export class Notification {
    id: number;
    heading: string;
    link: string;
}

and in nofificationService write

allNotifications: Notification[]; 
  //NotificationDetail: Notification;  
  private notificationsUrl = 'assets/data/notification.json';  // URL to web api 
  private downloadsUrl = 'assets/data/download.json';  // URL to web api 

  constructor(private httpClient: HttpClient ) { }

  getNotifications(): Observable<Notification[]> {    
       //return this.allNotifications = this.NotificationDetail.slice(0);  
     return this.httpClient.get<Notification[]>

(this.notificationsUrl).pipe(map(res => this.allNotifications = res))
      } 

and in component write

 constructor(private notificationService: NotificationService) {
   }

  ngOnInit() {
      /* get Notifications */
      this.notificationService.getNotifications().subscribe(data => this.notifications = data);
}

How to measure height, width and distance of object using camera?

For measuring distances with a single camera, you need to know some numbers. To measure height of something, say a chair, the only thing you have is the the size of it in the camera (which is in pixels, and can be converted to inches using screen size), that is all. The chance of measuring the height and width is using a reference, say a 6 foot tall person standing next to the chair.

This way you can work out in reverse using say a 10 foot tall object, using its size as appearing in the camera, you can work out the size of things at the same distance, on a surface that is not flat, even ensuring that they are at the same distance is a challenge.

So using the camera and just the camera, it is not possible. You need to know distance somehow, or need a reference.

If you are using the application to measure height of items you know the location of, then using GPS, you can find distance, and rest is math.

I have found some links using Google, they may help.

  1. http://forestjohnson.blogspot.com/2010/01/how-to-measure-size-of-object-using.html
  2. http://gigaom.com/mobile/how_to_measure_/
  3. http://www.iphonelife.com/blog/5/cameasure-use-your-camera-measure-size-or-distance

They may help you to find out what other information is needed other than what the camera can provide, so that you can think about your application as well regarding what can be done and what are the limitations.

One way is using multiple cameras, and that can be compensated using multiple pictures taken a known distance away. So the application can ask the user to take multiple images, track the distance using GPS, and probably it can work.

See these links as well:

  1. http://iopscience.iop.org/1742-6596/48/1/074/pdf/1742-6596_48_1_074.pdf
  2. http://www.optical-metrology-centre.com/Downloads/Papers/Photogrammetric%20Record%201994%20Automated%203-D%20measurement.pdf

How to show row number in Access query like ROW_NUMBER in SQL

One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:

SELECT a.ID, 
       a.AText, 
       (SELECT Count(ID) 
        FROM table1 b WHERE b.ID <= a.ID 
        AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;

Run a JAR file from the command line and specify classpath

You can do these in unix shell:

java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

You can do these in windows powershell:

java -cp "MyJar.jar;lib\*" com.somepackage.subpackage.Main

How to test the `Mosquitto` server?

To test and see if you can access your MQTT server from outside world (outside of your VM or local machine), you can install one of the MQTT publishing and monitoring tools such as MQTT-Spy on your outside-world machine and then subscribe for '#" (meaning all the topics).

You can follow this by the method @hardillb mentioned in his answer above and test back and forth such as this:

On the machine with Mosquitto Server running, enter image description here

On the outside-word machine with mqtt-spy running, enter image description here

I have mainly mentioned mqtt-spy since it's multi-platform and easy to use. You can go with any other tool really. And also to my knowledge to run the mosquitto_sub and mosquitto_pub you need to have mosquitto-clients installed on your Linux machine running the test (in my case Ubuntu) which can be done easily by,

sudo apt-get install mosquitto-clients

HTTP Status 504

CheckUpDown has a nice explanation of the 504 error:

A server (not necessarily a Web server) is acting as a gateway or proxy to fulfil the request by the client (e.g. your Web browser or our CheckUpDown robot) to access the requested URL. This server did not receive a timely response from an upstream server it accessed to deal with your HTTP request.

This usually means that the upstream server is down (no response to the gateway/proxy), rather than that the upstream server and the gateway/proxy do not agree on the protocol for exchanging data.

This problem is entirely due to slow IP communication between back-end computers, possibly including the Web server. Only the people who set up the network at the site which hosts the Web server can fix this problem.

Type definition in object literal in TypeScript

If you're trying to write a type annotation, the syntax is:

var x: { property: string; } = { property: 'hello' };

If you're trying to write an object literal, the syntax is:

var x = { property: 'hello' };

Your code is trying to use a type name in a value position.

How to print a debug log?

If you don't want to integrate a framework like Zend, then you can use the trigger_error method to log to the php error log.

@Autowired - No qualifying bean of type found for dependency

 <context:component-scan base-package="com.*" />

same issue arrived , i solved it by keeping the annotations intact and in dispatcher servlet :: keeping the base package scan as com.*. this worked for me.

Saving a high resolution image in R

A simpler way is

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)

Convert String to Uri

Java's parser in java.net.URI is going to fail if the URI isn't fully encoded to its standards. For example, try to parse: http://www.google.com/search?q=cat|dog. An exception will be thrown for the vertical bar.

urllib makes it easy to convert a string to a java.net.URI. It will pre-process and escape the URL.

assertEquals("http://www.google.com/search?q=cat%7Cdog",
    Urls.createURI("http://www.google.com/search?q=cat|dog").toString());

How do I resize a Google Map with JavaScript after it has loaded?

The popular answer google.maps.event.trigger(map, "resize"); didn't work for me alone.

Here was a trick that assured that the page had loaded and that the map had loaded as well. By setting a listener and listening for the idle state of the map you can then call the event trigger to resize.

$(document).ready(function() {
    google.maps.event.addListener(map, "idle", function(){
        google.maps.event.trigger(map, 'resize'); 
    });
}); 

This was my answer that worked for me.

Converting between datetime, Timestamp and datetime64

This post has been up for 4 years and I still struggled with this conversion problem - so the issue is still active in 2017 in some sense. I was somewhat shocked that the numpy documentation does not readily offer a simple conversion algorithm but that's another story.

I have come across another way to do the conversion that only involves modules numpy and datetime, it does not require pandas to be imported which seems to me to be a lot of code to import for such a simple conversion. I noticed that datetime64.astype(datetime.datetime) will return a datetime.datetime object if the original datetime64 is in micro-second units while other units return an integer timestamp. I use module xarray for data I/O from Netcdf files which uses the datetime64 in nanosecond units making the conversion fail unless you first convert to micro-second units. Here is the example conversion code,

import numpy as np
import datetime

def convert_datetime64_to_datetime( usert: np.datetime64 )->datetime.datetime:
    t = np.datetime64( usert, 'us').astype(datetime.datetime)
return t

Its only tested on my machine, which is Python 3.6 with a recent 2017 Anaconda distribution. I have only looked at scalar conversion and have not checked array based conversions although I'm guessing it will be good. Nor have I looked at the numpy datetime64 source code to see if the operation makes sense or not.

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

There are many related problems with a similar error message. Check the second line of this particular stack trace. This exception is specifically related to the call to FragmentManagerImpl.popBackStackImmediate.

This method call, like popBackStack, will always fail with IllegalStateException if the session state has already been saved. Check the source. There is nothing you can do to stop this exception being thrown.

  • Removing the call to super.onSaveInstanceState will not help.
  • Creating the Fragment with commitAllowingStateLoss will not help.

Here's how I observed the problem:

  • There's a form with a submit button.
  • When the button is clicked a dialog is created and an async process starts.
  • The user clicks the home key before the process is finished - onSaveInstanceState is called.
  • The process completes, a callback is made and popBackStackImmediate is attempted.
  • IllegalStateException is thrown.

Here's what I did to solve it:

As it is not possible to avoid the IllegalStateException in the callback, catch & ignore it.

try {
    activity.getSupportFragmentManager().popBackStackImmediate(name);
} catch (IllegalStateException ignored) {
    // There's no way to avoid getting this if saveInstanceState has already been called.
}

This is enough to stop the app from crashing. But now the user will restore the app and see that the button they thought they'd pressed hasn't been pressed at all (they think). The form fragment is still showing!

To fix this, when the dialog is created, make some state to indicate the process has started.

progressDialog.show(fragmentManager, TAG);
submitPressed = true;

And save this state in the bundle.

@Override
public void onSaveInstanceState(Bundle outState) {
    ...
    outState.putBoolean(SUBMIT_PRESSED, submitPressed);
}

Don't forget to load it back again in onViewCreated

Then, when resuming, rollback the fragments if submit was previously attempted. This prevents the user from coming back to what seems like an un-submitted form.

@Override
public void onResume() {
    super.onResume();
    if (submitPressed) {
        // no need to try-catch this, because we are not in a callback
        activity.getSupportFragmentManager().popBackStackImmediate(name);
        submitPressed = false;
    }
}

How can I check for an empty/undefined/null string in JavaScript?

Performance

I perform tests on macOS v10.13.6 (High Sierra) for 18 chosen solutions. Solutions works slightly different (for corner-case input data) which was presented in the snippet below.

Conclusions

  • the simple solutions based on !str,==,=== and length are fast for all browsers (A,B,C,G,I,J)
  • the solutions based on the regular expression (test,replace) and charAt are slowest for all browsers (H,L,M,P)
  • the solutions marked as fastest was fastest only for one test run - but in many runs it changes inside 'fast' solutions group

Enter image description here

Details

In the below snippet I compare results of chosen 18 methods by use different input parameters

  • "" "a" " "- empty string, string with letter and string with space
  • [] {} f- array, object and function
  • 0 1 NaN Infinity - numbers
  • true false - Boolean
  • null undefined

Not all tested methods support all input cases.

_x000D_
_x000D_
function A(str) {_x000D_
  let r=1;_x000D_
  if (!str)_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function B(str) {_x000D_
  let r=1;_x000D_
  if (str == "")_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function C(str) {_x000D_
  let r=1;_x000D_
  if (str === "")_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function D(str) {_x000D_
  let r=1;_x000D_
  if(!str || 0 === str.length)_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function E(str) {_x000D_
  let r=1;_x000D_
  if(!str || /^\s*$/.test(str))_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function F(str) {_x000D_
  let r=1;_x000D_
  if(!Boolean(str))_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function G(str) {_x000D_
  let r=1;_x000D_
  if(! ((typeof str != 'undefined') && str) )_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function H(str) {_x000D_
  let r=1;_x000D_
  if(!/\S/.test(str))_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function I(str) {_x000D_
  let r=1;_x000D_
  if (!str.length)_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function J(str) {_x000D_
  let r=1;_x000D_
  if(str.length <= 0)_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function K(str) {_x000D_
  let r=1;_x000D_
  if(str.length === 0 || !str.trim())_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function L(str) {_x000D_
  let r=1;_x000D_
  if ( str.replace(/\s/g,"") == "")_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function M(str) {_x000D_
  let r=1;_x000D_
  if((/^\s*$/).test(str))_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
_x000D_
function N(str) {_x000D_
  let r=1;_x000D_
  if(!str || !str.trim().length)_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function O(str) {_x000D_
  let r=1;_x000D_
  if(!str || !str.trim())_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function P(str) {_x000D_
  let r=1;_x000D_
  if(!str.charAt(0))_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function Q(str) {_x000D_
  let r=1;_x000D_
  if(!str || (str.trim()==''))_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
function R(str) {_x000D_
  let r=1;_x000D_
  if (typeof str == 'undefined' ||_x000D_
      !str ||_x000D_
      str.length === 0 ||_x000D_
      str === "" ||_x000D_
      !/[^\s]/.test(str) ||_x000D_
      /^\s*$/.test(str) ||_x000D_
      str.replace(/\s/g,"") === "")_x000D_
_x000D_
    r=0;_x000D_
  return r;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
// --- TEST ---_x000D_
_x000D_
console.log(                  '   ""  "a"  " " [] {} 0 1 NaN Infinity f true false null undefined ');_x000D_
let log1 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}   ${f([])}  ${f({})}  ${f(0)} ${f(1)} ${f(NaN)}   ${f(Infinity)}        ${f(f)} ${f(true)}    ${f(false)}     ${f(null)}    ${f(undefined)}`);_x000D_
let log2 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}   ${f([])}  ${f({})}  ${f(0)} ${f(1)} ${f(NaN)}   ${f(Infinity)}        ${f(f)} ${f(true)}    ${f(false)}`);_x000D_
let log3 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}`);_x000D_
_x000D_
log1('A', A);_x000D_
log1('B', B);_x000D_
log1('C', C);_x000D_
log1('D', D);_x000D_
log1('E', E);_x000D_
log1('F', F);_x000D_
log1('G', G);_x000D_
log1('H', H);_x000D_
_x000D_
log2('I', I);_x000D_
log2('J', J);_x000D_
_x000D_
log3('K', K);_x000D_
log3('L', L);_x000D_
log3('M', M);_x000D_
log3('N', N);_x000D_
log3('O', O);_x000D_
log3('P', P);_x000D_
log3('Q', Q);_x000D_
log3('R', R);
_x000D_
_x000D_
_x000D_

And then for all methods I perform speed test case str = "" for browsers Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0 - you can run tests on your machine here

Enter image description here

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

I was going into the same problem so I created a Mixin that seems to work for my use cases.

class ReadOnlyFieldsMixin(object):
    readonly_fields =()

    def __init__(self, *args, **kwargs):
        super(ReadOnlyFieldsMixin, self).__init__(*args, **kwargs)
        for field in (field for name, field in self.fields.iteritems() if name in self.readonly_fields):
            field.widget.attrs['disabled'] = 'true'
            field.required = False

    def clean(self):
        cleaned_data = super(ReadOnlyFieldsMixin,self).clean()
        for field in self.readonly_fields:
           cleaned_data[field] = getattr(self.instance, field)

        return cleaned_data

Usage, just define which ones must be read only:

class MyFormWithReadOnlyFields(ReadOnlyFieldsMixin, MyForm):
    readonly_fields = ('field1', 'field2', 'fieldx')

How to get the URL of the current page in C#

A search landed me at this page, but it wasn't quite what I was looking for. Posting here in case someone else looking for what I was lands at this page too.

There is two ways to do it if you only have a string value.

.NET way:

Same as @Canavar, but you can instantiate a new Uri Object

String URL = "http://localhost:1302/TESTERS/Default6.aspx";
System.Uri uri = new System.Uri(URL);

which means you can use the same methods, e.g.

string url = uri.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx

string host = uri.host
// localhost

Regex way:

Getting parts of a URL (Regex)

How can I use Helvetica Neue Condensed Bold in CSS?

You would have to turn your font into a web font as shown in these SO questions:

However, you may run into copyright issues with this: Not every font allows distribution as a web font. Check your font license to see whether it is allowed.

One of the easiest free and legal ways to use web fonts is Google Web Fonts. However, sadly, they don't have Helvetica Neue in their portfolio.

One of the easiest non-free and legal ways is to purchase the font from a foundry that offers web licenses. I happen to know that the myFonts foundry does this; they even give you a full package with all the JavaScript and CSS pre-prepared. I'm sure other foundries do the same.

Edit: MyFonts have Helvetica neue in Stock, but apparently not with a web license. Check out this list of similar fonts of which some have a web license. Also, Ray Larabie has some nice fonts there, with web licenses, some of them are free.

How do I get a file name from a full path with PHP?

There are several ways to get the file name and extension. You can use the following one which is easy to use.

$url = 'http://www.nepaltraveldoor.com/images/trekking/nepal/annapurna-region/Annapurna-region-trekking.jpg';
$file = file_get_contents($url); // To get file
$name = basename($url); // To get file name
$ext = pathinfo($url, PATHINFO_EXTENSION); // To get extension
$name2 =pathinfo($url, PATHINFO_FILENAME); // File name without extension

Is there a way I can retrieve sa password in sql server 2005

There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).

Start the SQL service again and use the new created login (recovery in my example) Go via the security panel to the properties and change the password of the SA account.

enter image description here

Now write down the new SA password.

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:

see https://github.com/karma-runner/karma/issues/1731#issuecomment-174227054

The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)

References

How to define two fields "unique" as couple

There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

Create database from command line

Try:

sudo -u postgres psql -c 'create database test;'

Adding Http Headers to HttpClient

When it can be the same header for all requests or you dispose the client after each request you can use the DefaultRequestHeaders.Add option:

client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");      

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

Exporting the DISPLAY variable is definitely the solution but depending on your setup you may have to do this in a slightly different way.

In my case, I have two different processes: the first one starts Xvfb, the other one launches the tests. So my shell scripting knowledge is a bit rusty but I figured out that exporting the DISPLAY variable from the first process didn't make it available in the second process.

Fortunately, Selenium WebDriver allows you to 'redefine' your environment. This is my function for creating a driver for Chrome in JS. Pretty sure the equivalent exists for your programming language:

const caps = require('selenium-webdriver/lib/capabilities');
const chrome = require('selenium-webdriver/chrome');
const chromedriver = require('chromedriver');

module.exports = function (cfg) {
    let serviceBuilder = new chrome.ServiceBuilder(chromedriver.path);
    let options = chrome.Options.fromCapabilities(caps.Capabilities.chrome());
    let service;
    let myENV = new Map();

    // 're-export' the `DISPLAY` variable
    myENV.set('DISPLAY', ':1');
    serviceBuilder.setEnvironment(myENV);

    service = serviceBuilder.build();

    options.addArguments('disable-setuid-sandbox');
    options.addArguments('no-sandbox');
    options.addArguments('allow-insecure-localhost');
    options.excludeSwitches('test-type');

    return chrome.Driver.createSession(options, service);
};

How do I add target="_blank" to a link within a specified div?

I use this for every external link:

window.onload = function(){
  var anchors = document.getElementsByTagName('a');
  for (var i=0; i<anchors.length; i++){
    if (anchors[i].hostname != window.location.hostname) {
        anchors[i].setAttribute('target', '_blank');
    }
  }
}

string.Replace in AngularJs

The easiest way is:

var oldstr="Angular isn't easy";
var newstr=oldstr.toString().replace("isn't","is");

What's the syntax for mod in java

if (a % 2 == 0) {
} else {
}

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

AttributeError: 'module' object has no attribute 'model'

It's called models.Model and not models.model (case sensitive). Fix your Poll model like this -

class Poll(models.Model):
    question = models.CharField(max_length=200) 
    pub_date = models.DateTimeField('date published')

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

How to split a string and assign it to variables

Golang does not support implicit unpacking of an slice (unlike python) and that is the reason this would not work. Like the examples given above, we would need to workaround it.

One side note:

The implicit unpacking happens for variadic functions in go:

func varParamFunc(params ...int) {

}

varParamFunc(slice1...)

Select a date from date picker using Selenium webdriver

This code should work properly to get the current date from the calendar.

String today=getCurrentDay(); //function 
driver.findElement(By.xpath("here xpath of textbox")).click();
Thread.sleep(5000);
WebElement dateWidgetForm= driver.findElement(By.xpath("here xpath of calender"));
List<WebElement> columns = dateWidgetForm.findElements(By.tagName("td"));

    for (WebElement cell: columns) {
      String z=cell.getAttribute("class").toString();
      if(z.equalsIgnoreCase("day")){
      if (cell.getText().equals(today)) {
        cell.click();
        break;
      }
    }

private String getCurrentDay() {
 Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
 //Get Current Day as a number
 int todayInt = calendar.get(Calendar.DAY_OF_MONTH);
 System.out.println("Today Int: " + todayInt +"\n");

 //Integer to String Conversion
 String todayStr = Integer.toString(todayInt);
 return todayStr;
}

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

This should work.

SELECT a.[CUSTOMER ID], a.[NAME], SUM(b.[AMOUNT]) AS [TOTAL AMOUNT]
FROM RES_DATA a INNER JOIN INV_DATA b
ON a.[CUSTOMER ID]=b.[CUSTOMER ID]
GROUP BY a.[CUSTOMER ID], a.[NAME]

I tested it with SQL Fiddle against SQL Server 2008: http://sqlfiddle.com/#!3/1cad5/1

Basically what's happening here is that, because of the join, you are getting the same row on the "left" (i.e. from the RES_DATA table) for every row on the "right" (i.e. the INV_DATA table) that has the same [CUSTOMER ID] value. When you group by just the columns on the left side, and then do a sum of just the [AMOUNT] column from the right side, it keeps the one row intact from the left side, and sums up the matching values from the right side.

What is the Python equivalent of static variables inside a function?

Instead of creating a function having a static local variable, you can always create what is called a "function object" and give it a standard (non-static) member variable.

Since you gave an example written C++, I will first explain what a "function object" is in C++. A "function object" is simply any class with an overloaded operator(). Instances of the class will behave like functions. For example, you can write int x = square(5); even if square is an object (with overloaded operator()) and not technically not a "function." You can give a function-object any of the features that you could give a class object.

# C++ function object
class Foo_class {
    private:
        int counter;     
    public:
        Foo_class() {
             counter = 0;
        }
        void operator() () {  
            counter++;
            printf("counter is %d\n", counter);
        }     
   };
   Foo_class foo;

In Python, we can also overload operator() except that the method is instead named __call__:

Here is a class definition:

class Foo_class:
    def __init__(self): # __init__ is similair to a C++ class constructor
        self.counter = 0
        # self.counter is like a static member
        # variable of a function named "foo"
    def __call__(self): # overload operator()
        self.counter += 1
        print("counter is %d" % self.counter);
foo = Foo_class() # call the constructor

Here is an example of the class being used:

from foo import foo

for i in range(0, 5):
    foo() # function call

The output printed to the console is:

counter is 1
counter is 2
counter is 3
counter is 4
counter is 5

If you want your function to take input arguments, you can add those to __call__ as well:

# FILE: foo.py - - - - - - - - - - - - - - - - - - - - - - - - -

class Foo_class:
    def __init__(self):
        self.counter = 0
    def __call__(self, x, y, z): # overload operator()
        self.counter += 1
        print("counter is %d" % self.counter);
        print("x, y, z, are %d, %d, %d" % (x, y, z));
foo = Foo_class() # call the constructor

# FILE: main.py - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

from foo import foo

for i in range(0, 5):
    foo(7, 8, 9) # function call

# Console Output - - - - - - - - - - - - - - - - - - - - - - - - - - 

counter is 1
x, y, z, are 7, 8, 9
counter is 2
x, y, z, are 7, 8, 9
counter is 3
x, y, z, are 7, 8, 9
counter is 4
x, y, z, are 7, 8, 9
counter is 5
x, y, z, are 7, 8, 9

MySQL Removing Some Foreign keys

Hey I followed some sequence above, and found some solution.

SHOW CREATE TABLE footable;

You will get FK Constrain Name like

ProjectsInfo_ibfk_1

Now you need to remove this constraints. by alter table commantd

alter table ProjectsInfo drop foreign key ProjectsInfo_ibfk_1;

Then drop the table column,

alter table ProjectsInfo drop column clientId;

Current user in Magento?

Have a look at the helper class: Mage_Customer_Helper_Data

To simply get the customer name, you can write the following code:-

$customerName = Mage::helper('customer')->getCustomerName();

For more information about the customer's entity id, website id, email, etc. you can use getCustomer function. The following code shows what you can get from it:-

echo "<pre>"; print_r(Mage::helper('customer')->getCustomer()->getData()); echo "</pre>";

From the helper class, you can also get information about customer login url, register url, logout url, etc.

From the isLoggedIn function in the helper class, you can also check whether a customer is logged in or not.

Resetting Select2 value in dropdown with reset button

Select2 uses a specific CSS class, so an easy way to reset it is:

$('.select2-container').select2('val', '');

And you have the advantage of if you have multiple Select2 at the same form, all them will be reseted with this single command.

How to POST JSON data with Python Requests?

It turns out I was missing the header information. The following works:

url = "http://localhost:8080"
data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)

How to filter Android logcat by application?

Edit: The original is below. When one Android Studio didn't exist. But if you want to filter on your entire application I would use pidcat for terminal viewing or Android Studio. Using pidcat instead of logcat then the tags don't need to be the application. You can just call it with pidcat com.your.application

You should use your own tag, look at: http://developer.android.com/reference/android/util/Log.html

Like.

Log.d("AlexeysActivity","what you want to log");

And then when you want to read the log use>

adb logcat -s AlexeysActivity 

That filters out everything that doesn't use the same tag.

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

Having attempted to follow Valros.nu's answer, i discovered that the sdk download is now bundeled with androind studio, in an 840MB exe installer.

As all you need for this particular program is the adb program, you can get this in a standalone installer from the xda guys:

http://forum.xda-developers.com/showthread.php?t=2317790

Note that you do not need to type adb.exe, simply type adb devices into the command prompt that is launched after install.

Also, i had to unplug and replug in my samsung s4 to get the remote debugging prompt to appear on the phone

Simple function to sort an array of objects

This is how simply I sort from previous examples:

if my array is items:

0: {id: 14, auctionID: 76, userID: 1, amount: 39}
1: {id: 1086, auctionID: 76, userID: 1, amount: 55}
2: {id: 1087, auctionID: 76, userID: 1, amount: 55}

I thought simply calling items.sort() would sort it it, but there was two problems: 1. Was sorting them strings 2. Was sorting them first key

This is how I modified the sort function:

for(amount in items){
if(item.hasOwnProperty(amount)){

i.sort((a, b) => a.amount - b.amount);
}
}

Convert list to tuple in Python

I find many answers up to date and properly answered but will add something new to stack of answers.

In python there are infinite ways to do this, here are some instances
Normal way

>>> l= [1,2,"stackoverflow","python"]
>>> l
[1, 2, 'stackoverflow', 'python']
>>> tup = tuple(l)
>>> type(tup)
<type 'tuple'>
>>> tup
(1, 2, 'stackoverflow', 'python')

smart way

>>>tuple(item for item in l)
(1, 2, 'stackoverflow', 'python')

Remember tuple is immutable ,used for storing something valuable. For example password,key or hashes are stored in tuples or dictionaries. If knife is needed why to use sword to cut apples. Use it wisely, it will also make your program efficient.

How can I use a carriage return in a HTML tooltip?

As a contribution to the &#013; solution, we can also use &#009 for tabs if you ever need to do something like this.

_x000D_
_x000D_
<button title="My to-do list:&#013;&#009;-Item 2&#013;&#009;-Item 3&#013;&#009;-Item 4&#013;&#009;&#009;-Subitem 1">TEST</button>
_x000D_
_x000D_
_x000D_

Demo

enter image description here

Python for and if on one line

You are producing a filtered list by using a list comprehension. i is still being bound to each and every element of that list, and the last element is still 'three', even if it was subsequently filtered out from the list being produced.

You should not use a list comprehension to pick out one element. Just use a for loop, and break to end it:

for elem in my_list:
    if elem == 'two':
        break

If you must have a one-liner (which would be counter to Python's philosophy, where readability matters), use the next() function and a generator expression:

i = next((elem for elem in my_list if elem == 'two'), None)

which will set i to None if there is no such matching element.

The above is not that useful a filter; your are essentially testing if the value 'two' is in the list. You can use in for that:

elem = 'two' if 'two' in my_list else None

Django. Override save for model

In new version it is like this:

def validate(self, attrs):
    has_unknown_fields = set(self.initial_data) - set(self.fields.keys())
    if has_unknown_fields:
        raise serializers.ValidationError("Do not send extra fields")
    return attrs

How to call a method function from another class?

You need to instantiate the other classes inside the main class;

Date d = new Date(params);
TemperatureRange t = new TemperatureRange(params);

You can then call their methods with:

object.methodname(params);
d.method();

You currently have constructors in your other classes. You should not return anything in these.

public Date(params){
    set variables for date object
}

Next you need a method to reference.

public returnType methodName(params){
  return something;
}

In Powershell what is the idiomatic way of converting a string to an int?

For me $numberAsString -as [int] of @Shay Levy is the best practice, I also use [type]::Parse(...) or [type]::TryParse(...)

But, depending on what you need you can just put a string containing a number on the right of an arithmetic operator with a int on the left the result will be an Int32:

PS > $b = "10"
PS > $a = 0 + $b
PS > $a.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

You can use Exception (try/parse) to behave in case of Problem

How to write a foreach in SQL Server?

This generally (almost always) performs better than a cursor and is simpler:

DECLARE @PractitionerList TABLE(PracticionerID INT)
DECLARE @PracticionerID INT
    
INSERT @PractitionerList(PracticionerID)
SELECT PracticionerID
FROM Practitioner
    
WHILE(1 = 1)
BEGIN
            
    SET @PracticionerID = NULL
    SELECT TOP(1) @PracticionerID = PracticionerID
    FROM @PractitionerList
    
    IF @PracticionerID IS NULL
        BREAK
            
    PRINT 'DO STUFF'
    
    DELETE TOP(1) FROM @PractitionerList
    
END

PHP to search within txt file and echo the whole line

And a PHP example, multiple matching lines will be displayed:

<?php
$file = 'somefile.txt';
$searchfor = 'name';

// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No matches found";
}

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

Here's a method I wrote to check if an URL exists or not. I had a requirement to add a request header. It's Groovy but should be fairly simple to adapt to Java. Essentially I'm using the org.springframework.web.client.RestTemplate#execute(java.lang.String, org.springframework.http.HttpMethod, org.springframework.web.client.RequestCallback, org.springframework.web.client.ResponseExtractor<T>, java.lang.Object...) API method. I guess the solution you arrive at depends at least in part on the HTTP method you want to execute. The key take away from example below is that I'm passing a Groovy closure (The third parameter to method restTemplate.execute(), which is more or less, loosely speaking a Lambda in Java world) that is executed by the Spring API as a callback to be able to manipulate the request object before Spring executes the command,

boolean isUrlExists(String url) {
    try {
      return (restTemplate.execute(url, HttpMethod.HEAD,
              { ClientHttpRequest request -> request.headers.add('header-name', 'header-value') },
              { ClientHttpResponse response -> response.headers }) as HttpHeaders)?.get('some-response-header-name')?.contains('some-response-header-value')
    } catch (Exception e) {
      log.warn("Problem checking if $url exists", e)
    }
    false
  }

How to uninstall with msiexec using product id guid without .msi file present

"Reference-Style" Answer: This is an alternative answer to the one below with several different options shown. Uninstalling an MSI file from the command line without using msiexec.


The command you specify is correct: msiexec /x {A4BFF20C-A21E-4720-88E5-79D5A5AEB2E8}

If you get "This action is only valid for products that are currently installed" you have used an unrecognized product or package code, and you must find the right one. Often this can be caused by using an erroneous package code instead of a product code to uninstall - a package code changes with every rebuild of an MSI file, and is the only guid you see when you view an msi file's property page. It should work for uninstall, provided you use the right one. No room for error. If you want to find the product code instead, you need to open the MSI. The product code is found in the Property table.


UPDATE, Jan 2018:

With all the registry redirects going on, I am not sure the below registry-based approach is a viable option anymore. I haven't checked properly because I now rely on the following approach using PowerShell: How can I find the product GUID of an installed MSI setup?

Also check this reference-style answer describing different ways to uninstall an MSI package and ways to determine what product version you have installed: Uninstalling an MSI file from the command line without using msiexec


Legacy, registry option:

You can also find the product code by perusing the registry from this base key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall . Press F3 and search for your product name. (If it's a 32-bit installer on a 64-bit machine, it might be under HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall instead).

Legacy, PowerShell option: (largely similar to the new, linked answer above)

Finally, you can find the product code by using PowerShell:

get-wmiobject Win32_Product | Format-Table IdentifyingNumber, Name

enter image description here

Similar post: WiX - Doing a major upgrade on a multi instance install (screenshot of how to find the product code in the MSI).

android.os.NetworkOnMainThreadException with android 4.2

This is the correct way:

public class JSONParser extends AsyncTask <String, Void, String>{

    static InputStream is = null;

static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}
@Override
protected String doInBackground(String... params) {


    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(url);

            HttpResponse getResponse = httpClient.execute(httpPost);
           final int statusCode = getResponse.getStatusLine().getStatusCode();

           if (statusCode != HttpStatus.SC_OK) { 
              Log.w(getClass().getSimpleName(), 
                  "Error " + statusCode + " for URL " + url); 
              return null;
           }

           HttpEntity getResponseEntity = getResponse.getEntity();

        //HttpResponse httpResponse = httpClient.execute(httpPost);
        //HttpEntity httpEntity = httpResponse.getEntity();
        is = getResponseEntity.getContent();            

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        Log.d("IO", e.getMessage().toString());
        e.printStackTrace();

    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;


}
protected void onPostExecute(String page)
{   
    //onPostExecute
}   
}

To call it (from main):

mJSONParser = new JSONParser();
mJSONParser.execute();

how to convert numeric to nvarchar in sql command

select convert(nvarchar(255), 4343)

Should do the trick.

How do relative file paths work in Eclipse?

A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.

New run configurations default to using the project directory for the working directory, though this can also be changed.

This code shows the difference between the working directory, and the location of where the class was loaded from:

public class TellMeMyWorkingDirectory {
    public static void main(String[] args) {
        System.out.println(new java.io.File("").getAbsolutePath());
        System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath());
    }
}

The output is likely to be something like:

C:\your\project\directory
/C:/your/project/directory/bin/

How to get Git to clone into current directory

shopt -s dotglob
git clone ssh://[email protected]/home/user/private/repos/project_hub.git tmp && mv tmp/* . && rm -rf tmp

Remove git mapping in Visual Studio 2015

You cant delete local git repository when its already connected. so close the solution, open another solution and then remove the local git repository. dont forget to delete .git hidden folder works for me

compression and decompression of string data in java

Another example of correct compression and decompression:

@Slf4j
public class GZIPCompression {
    public static byte[] compress(final String stringToCompress) {
        if (isNull(stringToCompress) || stringToCompress.length() == 0) {
            return null;
        }

        try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOutput = new GZIPOutputStream(baos)) {
            gzipOutput.write(stringToCompress.getBytes(UTF_8));
            gzipOutput.finish();
            return baos.toByteArray();
        } catch (IOException e) {
            throw new UncheckedIOException("Error while compression!", e);
        }
    }

    public static String decompress(final byte[] compressed) {
        if (isNull(compressed) || compressed.length == 0) {
            return null;
        }

        try (final GZIPInputStream gzipInput = new GZIPInputStream(new ByteArrayInputStream(compressed));
             final StringWriter stringWriter = new StringWriter()) {
            IOUtils.copy(gzipInput, stringWriter, UTF_8);
            return stringWriter.toString();
        } catch (IOException e) {
            throw new UncheckedIOException("Error while decompression!", e);
        }
    }
}

How can I get the external SD card path for Android 4.0+?

       File[] files = null;
    File file = new File("/storage");// /storage/emulated
if (file.exists()) {
        files = file.listFiles();
            }
            if (null != files)
                for (int j = 0; j < files.length; j++) {
                    Log.e(TAG, "" + files[j]);
                    Log.e(TAG, "//--//--// " +             files[j].exists());

                    if (files[j].toString().replaceAll("_", "")
                            .toLowerCase().contains("extsdcard")) {
                        external_path = files[j].toString();
                        break;
                    } else if (files[j].toString().replaceAll("_", "")
                            .toLowerCase()
                            .contains("sdcard".concat(Integer.toString(j)))) {
                        // external_path = files[j].toString();
                    }
                    Log.e(TAG, "--///--///--  " + external_path);
                }

Collection was modified; enumeration operation may not execute

The accepted answer is imprecise and incorrect in the worst case . If changes are made during ToList(), you can still end up with an error. Besides lock, which performance and thread-safety needs to be taken into consideration if you have a public member, a proper solution can be using immutable types.

In general, an immutable type means that you can't change the state of it once created. So your code should look like:

public class SubscriptionServer : ISubscriptionServer
{
    private static ImmutableDictionary<Guid, Subscriber> subscribers = ImmutableDictionary<Guid, Subscriber>.Empty;
    public void SubscribeEvent(string id)
    {
        subscribers = subscribers.Add(Guid.NewGuid(), new Subscriber());
    }
    public void NotifyEvent()
    {
        foreach(var sub in subscribers.Values)
        {
            //.....This is always safe
        }
    }
    //.........
}

This can be especially useful if you have a public member. Other classes can always foreach on the immutable types without worrying about the collection being modified.

How do I assign a null value to a variable in PowerShell?

Use $dec = $null

From the documentation:

$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

scikit-learn random state in splitting dataset

It doesn't matter if the random_state is 0 or 1 or any other integer. What matters is that it should be set the same value, if you want to validate your processing over multiple runs of the code. By the way I have seen random_state=42 used in many official examples of scikit as well as elsewhere also.

random_state as the name suggests, is used for initializing the internal random number generator, which will decide the splitting of data into train and test indices in your case. In the documentation, it is stated that:

If random_state is None or np.random, then a randomly-initialized RandomState object is returned.

If random_state is an integer, then it is used to seed a new RandomState object.

If random_state is a RandomState object, then it is passed through.

This is to check and validate the data when running the code multiple times. Setting random_state a fixed value will guarantee that same sequence of random numbers are generated each time you run the code. And unless there is some other randomness present in the process, the results produced will be same as always. This helps in verifying the output.

Android Studio Stuck at Gradle Download on create new project

Quick Fix: Just turn off your firewall, it seems that android studio wants to download something and because our firewall prevents it from downloading the file that it wants it becomes stuck.

Note: Turning your firewall off can lower your security, if you have time you can just allow android studio in your firewall. By doing this you can turn on your firewall while allowing android studio to download anything that it wants.

phpmyadmin logs out after 1440 secs

If you have phpmyadmin configuration storage setup, the settings will be pulled out of your phpmyadmin.pma__userconfig table, and will override anything you have in config.inc.php. In this table, each MYSQL user can be assigned a different set of phpmyadmin settings.

"No backupset selected to be restored" SQL Server 2012

For me, it was because the backup file was still open by another process. Here's the event log:

BackupDiskFile::OpenMedia: Backup device 'X:\Backups\MyDatabase\MyDatabase_backup_2014_08_22_132234_8270986.bak' failed to open. Operating system error 32(The process cannot access the file because it is being used by another process.).

Simply closing and reopening Sql Server Management Studio resolved it (so obviously it was ssms.exe that had the handle..)

Compress files while reading data from STDIN

gzip > stdin.gz perhaps? Otherwise, you need to flesh out your question.

bad operand types for binary operator "&" java

You have to be more precise, using parentheses, otherwise Java will not use the order of operands that you want it to use.

if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){

Becomes

if (((a[0] & 1) == 0) && ((a[1] & 1) == 0) && ((a[2] & 1) == 0)){

How to continue the code on the next line in VBA

To have newline in code you use _

Example:

Dim a As Integer
a = 500 _
  + 80 _
  + 90

MsgBox a

How to query first 10 rows and next time query other 10 rows from table

Ok. So I think you just need to implement Pagination.

$perPage = 10;

$pageNo = $_GET['page'];

Now find total rows in database.

$totalRows = Get By applying sql query;

$pages = ceil($totalRows/$perPage);    

$offset = ($pageNo - 1) * $perPage + 1

$sql = "SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT ".$offset." ,".$perPage

What are the differences between "=" and "<-" assignment operators in R?

The difference in assignment operators is clearer when you use them to set an argument value in a function call. For example:

median(x = 1:10)
x   
## Error: object 'x' not found

In this case, x is declared within the scope of the function, so it does not exist in the user workspace.

median(x <- 1:10)
x    
## [1]  1  2  3  4  5  6  7  8  9 10

In this case, x is declared in the user workspace, so you can use it after the function call has been completed.


There is a general preference among the R community for using <- for assignment (other than in function signatures) for compatibility with (very) old versions of S-Plus. Note that the spaces help to clarify situations like

x<-3
# Does this mean assignment?
x <- 3
# Or less than?
x < -3

Most R IDEs have keyboard shortcuts to make <- easier to type. Ctrl + = in Architect, Alt + - in RStudio (Option + - under macOS), Shift + - (underscore) in emacs+ESS.


If you prefer writing = to <- but want to use the more common assignment symbol for publicly released code (on CRAN, for example), then you can use one of the tidy_* functions in the formatR package to automatically replace = with <-.

library(formatR)
tidy_source(text = "x=1:5", arrow = TRUE)
## x <- 1:5

The answer to the question "Why does x <- y = 5 throw an error but not x <- y <- 5?" is "It's down to the magic contained in the parser". R's syntax contains many ambiguous cases that have to be resolved one way or another. The parser chooses to resolve the bits of the expression in different orders depending on whether = or <- was used.

To understand what is happening, you need to know that assignment silently returns the value that was assigned. You can see that more clearly by explicitly printing, for example print(x <- 2 + 3).

Secondly, it's clearer if we use prefix notation for assignment. So

x <- 5
`<-`(x, 5)  #same thing

y = 5
`=`(y, 5)   #also the same thing

The parser interprets x <- y <- 5 as

`<-`(x, `<-`(y, 5))

We might expect that x <- y = 5 would then be

`<-`(x, `=`(y, 5))

but actually it gets interpreted as

`=`(`<-`(x, y), 5)

This is because = is lower precedence than <-, as shown on the ?Syntax help page.

Apply CSS rules if browser is IE

I prefer using a separate file for ie rules, as described earlier.

<!--[if IE]><link rel="stylesheet" type="text/css" href="ie-style.css"/><![endif]-->

And inside it you can set up rules for different versions of ie using this:

.abc {...} /* ALL MSIE */
*html *.abc {...} /* MSIE 6 */
*:first-child+html .abc {...} /* MSIE 7 */

Efficient way to insert a number into a sorted array of numbers?

I know this is an old question that has an answer already, and there are a number of other decent answers. I see some answers that propose that you can solve this problem by looking up the correct insertion index in O(log n) - you can, but you can't insert in that time, because the array needs to be partially copied out to make space.

Bottom line: If you really need O(log n) inserts and deletes into a sorted array, you need a different data structure - not an array. You should use a B-Tree. The performance gains you will get from using a B-Tree for a large data set, will dwarf any of the improvements offered here.

If you must use an array. I offer the following code, based on insertion sort, which works, if and only if the array is already sorted. This is useful for the case when you need to resort after every insert:

function addAndSort(arr, val) {
    arr.push(val);
    for (i = arr.length - 1; i > 0 && arr[i] < arr[i-1]; i--) {
        var tmp = arr[i];
        arr[i] = arr[i-1];
        arr[i-1] = tmp;
    }
    return arr;
}

It should operate in O(n), which I think is the best you can do. Would be nicer if js supported multiple assignment. here's an example to play with:

Update:

this might be faster:

function addAndSort2(arr, val) {
    arr.push(val);
    i = arr.length - 1;
    item = arr[i];
    while (i > 0 && item < arr[i-1]) {
        arr[i] = arr[i-1];
        i -= 1;
    }
    arr[i] = item;
    return arr;
}

Updated JS Bin link

WSDL vs REST Pros and Cons

The two protocols have very different uses in the real world.

SOAP(using WSDL) is a heavy-weight XML standard that is centered around document passing. The advantage with this is that your requests and responses can be very well structured, and can even use a DTD. The downside is it is XML, and is very verbose. However, this is good if two parties need to have a strict contract(say for inter-bank communication). SOAP also lets you layer things like WS-Security on your documents. SOAP is generally transport-agnostic, meaning you don't necessarily need to use HTTP.

REST is very lightweight, and relies upon the HTTP standard to do it's work. It is great to get a useful web service up and running quickly. If you don't need a strict API definition, this is the way to go. Most web services fall into this category. You can version your API so that updates to the API do not break it for people using old versions(as long as they specify a version). REST essentially requires HTTP, and is format-agnostic(meaning you can use XML, JSON, HTML, whatever).

Generally I use REST, because I don't need fancy WS-* features. SOAP is good though if you want computers to understand your webservice using a WSDL. REST specifications are generally human-readable only.

How can I turn a DataTable to a CSV?

Here is my solution, based on previous answers by Paul Grimshaw and Anthony VO. I've submitted the code in a C# project on Github.

My main contribution is to eliminate explicitly creating and manipulating a StringBuilder and instead working only with IEnumerable. This avoids the allocation of a big buffer in memory.

public static class Util
{
    public static string EscapeQuotes(this string self) {
        return self?.Replace("\"", "\"\"") ?? "";
    }

    public static string Surround(this string self, string before, string after) {
        return $"{before}{self}{after}";
    }

    public static string Quoted(this string self, string quotes = "\"") {
        return self.Surround(quotes, quotes);
    }

    public static string QuotedCSVFieldIfNecessary(this string self) {
        return (self == null) ? "" : self.Contains('"') ? self.Quoted() : self; 
    }

    public static string ToCsvField(this string self) {
        return self.EscapeQuotes().QuotedCSVFieldIfNecessary();
    }

    public static string ToCsvRow(this IEnumerable<string> self){
        return string.Join(",", self.Select(ToCsvField));
    }

    public static IEnumerable<string> ToCsvRows(this DataTable self) {          
        yield return self.Columns.OfType<object>().Select(c => c.ToString()).ToCsvRow();
        foreach (var dr in self.Rows.OfType<DataRow>())
            yield return dr.ItemArray.Select(item => item.ToString()).ToCsvRow();
    }

    public static void ToCsvFile(this DataTable self, string path) {
        File.WriteAllLines(path, self.ToCsvRows());
    }
}

This approach combines nicely with converting IEnumerable to DataTable as asked here.

Java ElasticSearch None of the configured nodes are available

This means we are not able to instantiate ES transportClient and throw this exception. There are couple of possibilities that cause this issue.

  • Cluster name is incorrect. So open ES_HOME_DIR/config/elasticserach.yml file and check the cluster name value OR use this command: curl -XGET 'http://localhost:9200/_nodes'
  • Verify port 9200 is http port but elasticsearch service is using tcp port 9300 [by default]. So verify that the port is not blocked.
  • Authentication issue: set the header in transportClient's context for authentication:

    client.threadPool().getThreadContext()
      .putHeader("Authorization", "Basic " + encodeBase64String(basicHeader.getBytes()));
    

If you are still facing this issue then add the following property:

put("client.transport.ignore_cluster_name", true)

The below basic code is working fine for me:

Settings settings = Settings.builder()
            .put("cluster.name", "my-application").put("client.transport.sniff", true).put("client.transport.ignore_cluster_name", false).build();
    TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

Renaming columns in Pandas

Another option is to rename using a regular expression:

import pandas as pd
import re

df = pd.DataFrame({'$a':[1,2], '$b':[3,4], '$c':[5,6]})

df = df.rename(columns=lambda x: re.sub('\$','',x))
>>> df
   a  b  c
0  1  3  5
1  2  4  6

How can I insert a line break into a <Text> component in React Native?

Simple use backticks (ES 6 feature)

SOLUTION 1

const Message = 'This is a message';

<Text>
{`
  Hi~
  ${Message}
`}
</Text>

SOLUTION 2 Add "\n" in Text

<Text>
Hi~{"\n"}
This is a message.
</Text>

How do I keep two side-by-side divs the same height?

I'm surprised that nobody has mentioned the (very old but reliable) Absolute Columns technique: http://24ways.org/2008/absolute-columns/

In my opinion, it is far superior to both Faux Columns and One True Layout's technique.

The general idea is that an element with position: absolute; will position against the nearest parent element that has position: relative;. You then stretch a column to fill 100% height by assigning both a top: 0px; and bottom: 0px; (or whatever pixels/percentages you actually need.) Here's an example:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #container
      {
        position: relative;
      }

      #left-column
      {
        width: 50%;
        background-color: pink;
      }

      #right-column
      {
        position: absolute;
        top: 0px;
        right: 0px;
        bottom: 0px;
        width: 50%;
        background-color: teal;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <div id="left-column">
        <ul>
          <li>Foo</li>
          <li>Bar</li>
          <li>Baz</li>
        </ul>
      </div>
      <div id="right-column">
        Lorem ipsum
      </div>
    </div>
  </body>
</html>

How to create an Array, ArrayList, Stack and Queue in Java?

I am guessing you're confused with the parameterization of the types:

// This works, because there is one class/type definition in the parameterized <> field
ArrayList<String> myArrayList = new ArrayList<String>(); 


// This doesn't work, as you cannot use primitive types here
ArrayList<char> myArrayList = new ArrayList<char>();

Calculate execution time of a SQL query?

try this

DECLARE @StartTime DATETIME
SET @StartTime = GETDATE()

  SET @EndTime = GETDATE()
  PRINT 'StartTime = ' + CONVERT(VARCHAR(30),@StartTime,121)
  PRINT '  EndTime = ' + CONVERT(VARCHAR(30),@EndTime,121)
  PRINT ' Duration = ' + CONVERT(VARCHAR(30),@EndTime -@starttime,114)

If that doesn't do it, then try SET STATISTICS TIME ON

Width equal to content

Set display:inline-block and then adjust your margins.

fiddle here: http://jsfiddle.net/Q2MrC/

Java 8 forEach with index

Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:

IntStream.range(0, params.size())
  .forEach(idx ->
    query.bind(
      idx,
      params.get(idx)
    )
  )
;

The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).

How to add 20 minutes to a current date?

Just get the millisecond timestamp and add 20 minutes to it:

twentyMinutesLater = new Date(currentDate.getTime() + (20*60*1000))

Unable to cast object of type 'System.DBNull' to type 'System.String`

String.Concat transforms DBNull and null values to an empty string.

public string GetCustomerNumber(Guid id)
{
   object accountNumber =  
          (object)DBSqlHelperFactory.ExecuteScalar(connectionStringSplendidCRM, 
                                CommandType.StoredProcedure, 
                                "spx_GetCustomerNumber", 
                                new SqlParameter("@id", id));

    return String.Concat(accountNumber);

 }

However, I think you lose something on code understandability

Handling warning for possible multiple enumeration of IEnumerable

If you only need to check the first element you can peek on it without iterating the whole collection:

public List<object> Foo(IEnumerable<object> objects)
{
    object firstObject;
    if (objects == null || !TryPeek(ref objects, out firstObject))
        throw new ArgumentException();

    var list = DoSomeThing(firstObject);
    var secondList = DoSomeThingElse(objects);
    list.AddRange(secondList);

    return list;
}

public static bool TryPeek<T>(ref IEnumerable<T> source, out T first)
{
    if (source == null)
        throw new ArgumentNullException(nameof(source));

    IEnumerator<T> enumerator = source.GetEnumerator();
    if (!enumerator.MoveNext())
    {
        first = default(T);
        source = Enumerable.Empty<T>();
        return false;
    }

    first = enumerator.Current;
    T firstElement = first;
    source = Iterate();
    return true;

    IEnumerable<T> Iterate()
    {
        yield return firstElement;
        using (enumerator)
        {
            while (enumerator.MoveNext())
            {
                yield return enumerator.Current;
            }
        }
    }
}

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

Old one but I would add my answer as per my findings:

var ancestralState = context.findAncestorStateOfType<ParentState>();
      ancestralState.setState(() {
        // here you can access public vars and update state.
        ...
      });

Change default date time format on a single database in SQL Server

You do realize that format has nothing to do with how SQL Server stores datetime, right?

You can use set dateformat for each session. There is no setting for database only.

If you use parameters for data insert or update or where filtering you won't have any problems with that.

Oracle SQL, concatenate multiple columns + add text

You have two options for concatenating strings in Oracle:

CONCAT example:

CONCAT(
  CONCAT(
    CONCAT(
      CONCAT(
        CONCAT('I like ', t.type_desc_column), 
        ' cake with '), 
      t.icing_desc_column),
    ' and a '),
  t.fruit_desc_column)

Using || example:

'I like ' || t.type_desc_column || ' cake with ' || t.icing_desc_column || ' and a ' || t.fruit_desc_column

Swift UIView background color opacity

The question is old, but it seems that there are people who have the same concerns.

What do you think of the opinion that 'the alpha property of UIColor and the opacity property of Interface Builder are applied differently in code'?


The two views created in Interface Builder were initially different colors, but had to be the same color when the conditions changed. So, I had to set the background color of one view in code, and set a different value to make the background color of both views the same.

As an actual example, the background color of Interface Builder was 0x121212 and the Opacity value was 80%(in Amani Elsaed's image :: Red: 18, Green: 18, Blue: 18, Hex Color #: [121212], Opacity: 80), In the code, I set the other view a background color of 0x121212 with an alpha value of 0.8.

self.myFuncView.backgroundColor = UIColor(red: 18, green: 18, blue: 18, alpha: 0.8)

extension is

extension UIColor {
    convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat = 1.0) {
        self.init(red: CGFloat(red) / 255.0,
                  green: CGFloat(green) / 255.0,
                  blue: CGFloat(blue) / 255.0,
                  alpha: alpha)
    }
}

However, the actual view was

  • 'View with background color specified in Interface Builder': R 0.09 G 0.09 B 0.09 alpha 0.8.
  • 'View with background color by code': R 0.07 G 0.07 B 0.07 alpha 0.8

Calculating it,

  • 0x12 = 18(decimal)
  • 18/255 = 0.07058...
  • 255 * 0.09 = 22.95
  • 23(decimal) = 0x17

So, I was able to match the colors similarly by setting the UIColor values ??to 17, 17, 17 and alpha 0.8.

self.myFuncView.backgroundColor = UIColor(red: 17, green: 17, blue: 17, alpha: 0.8)

Or can anyone tell me what I'm missing?

What is the python "with" statement designed for?

See PEP 343 - The 'with' statement, there is an example section at the end.

... new statement "with" to the Python language to make it possible to factor out standard uses of try/finally statements.

Generate sha256 with OpenSSL and C++

std based

#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>

using namespace std;

#include <openssl/sha.h>
string sha256(const string str)
{
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, str.c_str(), str.size());
    SHA256_Final(hash, &sha256);
    stringstream ss;
    for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
    {
        ss << hex << setw(2) << setfill('0') << (int)hash[i];
    }
    return ss.str();
}

int main() {
    cout << sha256("1234567890_1") << endl;
    cout << sha256("1234567890_2") << endl;
    cout << sha256("1234567890_3") << endl;
    cout << sha256("1234567890_4") << endl;
    return 0;
}

Add UIPickerView & a Button in Action sheet - How?

Even though this question is old, I'll quickly mention that I've thrown together an ActionSheetPicker class with a convenience function, so you can spawn an ActionSheet with a UIPickerView in one line. It's based on code from answers to this question.

Edit: It now also supports the use of a DatePicker and DistancePicker.


UPD:

This version is deprecated: use ActionSheetPicker-3.0 instead.

animation

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

Should I use Vagrant or Docker for creating an isolated environment?

If your purpose is the isolation, I think Docker is what you want.

Vagrant is a virtual machine manager. It allows you to script the virtual machine configuration as well as the provisioning. However, it is still a virtual machine depending on VirtualBox (or others) with a huge overhead. It requires you to have a hard drive file that can be huge, it takes a lot of ram, and performance may be not very good.

Docker on the other hand uses kernel cgroup and namespacing via LXC. It means that you are using the same kernel as the host and the same file system. You can use Dockerfile with the docker build command in order to handle the provisioning and configuration of your container. You have an example at docs.docker.com on how to make your Dockerfile; it is very intuitive.

The only reason you could want to use Vagrant is if you need to do BSD, Windows or other non-Linux development on your Ubuntu box. Otherwise, go for Docker.

The simplest way to resize an UIImage?

Effective approach without stretching image Swift 4

// Method to resize image
func resize(image: UIImage, toScaleSize:CGSize) -> UIImage {
                UIGraphicsBeginImageContextWithOptions(toScaleSize, true, image.scale)
                        image.draw(in: CGRect(x: 0, y: 0, width: toScaleSize.width, height: toScaleSize.height))
                        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
                        UIGraphicsEndImageContext()
                        return scaledImage!
                }

// Call method

    let resizedImage = self.resize(image: UIImage(named: "YourImageName")!, toScaleSize: CGSize(width: 290, height: 390))

SQL alias for SELECT statement

You can do this using the WITH clause of the SELECT statement:

;
WITH my_select As (SELECT ... FROM ...) 
SELECT * FROM foo
WHERE id IN (SELECT MAX(id) FROM my_select GROUP BY name)

That's the ANSI/ISO SQL Syntax. I know that SQL Server, Oracle and DB2 support it. Not sure about the others...

How can I access the MySQL command line with XAMPP for Windows?

To access the mysql command in Windows without manually changing directories, do this:

  • Go to Control Panel > System > Advanced system settings.
  • System Properties will appear.
  • Click on the 'Advanced' tab.
  • Click 'Environment Variables'.
  • Under System Variables, locate 'Path' and click Edit.
  • Append the path to your MySQL installation to the end of the exisiting 'Variable value'. Example:

    %systemDrive%\xampp\mysql\bin\ 

    or, if you prefer

    c:\xampp\mysql\bin\ 
  • Finally, open a new command prompt to make this change take effect.

Note that MySQL's documentation on Setting Environment Variables has little to say about handling this in Windows.

How would I check a string for a certain letter in Python?

Use the in keyword without is.

if "x" in dog:
    print "Yes!"

If you'd like to check for the non-existence of a character, use not in:

if "x" not in dog:
    print "No!"

Sieve of Eratosthenes - Finding Primes Python

I figured it must be possible to simply use the empty list as the terminating condition for the loop and came up with this:

limit = 100
ints = list(range(2, limit))   # Will end up empty

while len(ints) > 0:
    prime = ints[0]
    print prime
    ints.remove(prime)
    i = 2
    multiple = prime * i
    while multiple <= limit:
        if multiple in ints:
            ints.remove(multiple)
        i += 1
        multiple = prime * i

node.js remove file

It's very easy with fs.

var fs = require('fs');
try{
 var sourceUrls = "/sampleFolder/sampleFile.txt";
 fs.unlinkSync(sourceUrls);
}catch(err){
 console.log(err);
}

How to add double quotes to a string that is inside a variable?

Start each row with \"-\" to create bullet list.

Multiple inheritance for an anonymous class

An anonymous class is extending or implementing while creating its object For example :

Interface in = new InterFace()
{

..............

}

Here anonymous class is implementing Interface.

Class cl = new Class(){

.................

}

here anonymous Class is extending a abstract Class.

When to use margin vs padding in CSS

The margin clears an area around an element (outside the border), but the padding clears an area around the content (inside the border) of an element.

enter image description here

it means that your element does not know about its outside margins, so if you are developing dynamic web controls, I recommend that to use padding vs margin if you can.

note that some times you have to use margin.

SQL Current month/ year question

In SQL Server you can use YEAR, MONTH and DAY instead of DATEPART.
(at least in SQL Server 2005/2008, I'm not sure about SQL Server 2000 and older)

I prefer using these "short forms" because to me, YEAR(getdate()) is shorter to type and better to read than DATEPART(yyyy, getdate()).

So you could also query your table like this:

select *
from your_table
where month_column = MONTH(getdate())
and year_column = YEAR(getdate())

Cannot open include file 'afxres.h' in VC2010 Express

This header is a part of the MFC Library. VS Express edition doesn't contain MFC. If your project doesn't use MFC you can safely replace afxres.h with windows.h in your terrain2.rc.

Select value from list of tuples where condition

Yes, you can use filter if you know at which position in the tuple the desired column resides. If the case is that the id is the first element of the tuple then you can filter the list like so:

filter(lambda t: t[0]==10, mylist)

This will return the list of corresponding tuples. If you want the age, just pick the element you want. Instead of filter you could also use list comprehension and pick the element in the first go. You could even unpack it right away (if there is only one result):

[age] = [t[1] for t in mylist if t[0]==10]

But I would strongly recommend to use dictionaries or named tuples for this purpose.

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

You may have come to this question with MySQL version 8 installed (like me) and not found a satisfactory answer. You can no longer create users like this in version 8:

GRANT ALL PRIVILEGES ON *.* TO 'steves'@'[hostname].com' IDENTIFIED BY '[OBSCURED]' WITH GRANT OPTION;

The rather confusing error message that you get back is: ERROR 1410 (42000): You are not allowed to create a user with GRANT

In order to create users in version 8 you have to do it in two steps:

CREATE USER 'steves'@'[hostname].com' IDENTIFIED BY '[OBSCURED]';
GRANT ALL PRIVILEGES ON *.* TO 'steves'@'[hostname].com' WITH GRANT OPTION;

Of course, if you prefer, you can also supply a limited number of privileges (instead of GRANT ALL PRIVILEGES), e.g. GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

Regarding C++ Include another class

What is the basic problem in your code?

Your code needs to be separated out in to interfaces(.h) and Implementations(.cpp).
The compiler needs to see the composition of a type when you write something like

ClassTwo obj;

This is because the compiler needs to reserve enough memory for object of type ClassTwo to do so it needs to see the definition of ClassTwo. The most common way to do this in C++ is to split your code in to header files and source files.
The class definitions go in the header file while the implementation of the class goes in to source files. This way one can easily include header files in to other source files which need to see the definition of class who's object they create.

Why can't I simply put all code in cpp files and include them in other files?

You cannot simple put all the code in source file and then include that source file in other files.C++ standard mandates that you can declare a entity as many times as you need but you can define it only once(One Definition Rule(ODR)). Including the source file would violate the ODR because a copy of the entity is created in every translation unit where the file is included.

How to solve this particular problem?

Your code should be organized as follows:

//File1.h

Define ClassOne 

//File2.h

#include <iostream>
#include <string>


class ClassTwo
{
private:
   string myType;
public:
   void setType(string);
   std::string getType();
}; 

//File1.cpp

#include"File1.h"

Implementation of ClassOne 

//File2.cpp

#include"File2.h"

void ClassTwo::setType(std::string sType)
{
    myType = sType;
}

void ClassTwo::getType(float fVal)
{
    return myType;
} 

//main.cpp

#include <iostream>
#include <string>
#include "file1.h"
#include "file2.h"
using namespace std;

int main()
{

    ClassOne cone;
    ClassTwo ctwo;

    //some codes
}

Is there any alternative means rather than including header files?

If your code only needs to create pointers and not actual objects you might as well use Forward Declarations but note that using forward declarations adds some restrictions on how that type can be used because compiler sees that type as an Incomplete type.

PostgreSQL: Modify OWNER on all tables simultaneously in PostgreSQL

For tables you must loop that:

for tbl in `psql -qAt -c "select tablename from pg_tables where schemaname = 'public';" YOUR_DB` ; do  psql -U postgres -c "alter table \"$tbl\" owner to NEW_USER" YOUR_DB ; done

HTML <input type='file'> File Selection Event

That's the way I did it with pure JS:

_x000D_
_x000D_
var files = document.getElementById('filePoster');_x000D_
var submit = document.getElementById('submitFiles');_x000D_
var warning = document.getElementById('warning');_x000D_
files.addEventListener("change", function () {_x000D_
  if (files.files.length > 10) {_x000D_
    submit.disabled = true;_x000D_
    warning.classList += "warn"_x000D_
    return;_x000D_
  }_x000D_
  submit.disabled = false;_x000D_
});
_x000D_
#warning {_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
#warning.warn {_x000D_
 color: red;_x000D_
 transform: scale(1.5);_x000D_
 transition: 1s all;_x000D_
}
_x000D_
<section id="shortcode-5" class="shortcode-5 pb-50">_x000D_
    <p id="warning">Please do not upload more than 10 images at once.</p>_x000D_
    <form class="imagePoster" enctype="multipart/form-data" action="/gallery/imagePoster" method="post">_x000D_
        <div class="input-group">_x000D_
       <input id="filePoster" type="file" class="form-control" name="photo" required="required" multiple="multiple" />_x000D_
     <button id="submitFiles" class="btn btn-primary" type="submit" name="button">Submit</button>_x000D_
        </div>_x000D_
    </form>_x000D_
</section>
_x000D_
_x000D_
_x000D_

How to set height property for SPAN

Use

.title{
  display: inline-block;
  height: 25px;
}

The only trick is browser support. Check if your list of supported browsers handles inline-block here.

ProcessStartInfo hanging on "WaitForExit"? Why?

None of the answers above is doing the job.

Rob solution hangs and 'Mark Byers' solution get the disposed exception.(I tried the "solutions" of the other answers).

So I decided to suggest another solution:

public void GetProcessOutputWithTimeout(Process process, int timeoutSec, CancellationToken token, out string output, out int exitCode)
{
    string outputLocal = "";  int localExitCode = -1;
    var task = System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
        outputLocal = process.StandardOutput.ReadToEnd();
        process.WaitForExit();
        localExitCode = process.ExitCode;
    }, token);

    if (task.Wait(timeoutSec, token))
    {
        output = outputLocal;
        exitCode = localExitCode;
    }
    else
    {
        exitCode = -1;
        output = "";
    }
}

using (var process = new Process())
{
    process.StartInfo = ...;
    process.Start();
    string outputUnicode; int exitCode;
    GetProcessOutputWithTimeout(process, PROCESS_TIMEOUT, out outputUnicode, out exitCode);
}

This code debugged and works perfectly.

How do I increase the RAM and set up host-only networking in Vagrant?

You can modify various VM properties by adding the following configuration (see the Vagrant docs for a bit more info):

  # Configure VM Ram usage
  config.vm.customize [
                        "modifyvm", :id,
                        "--name", "Test_Environment",
                        "--memory", "1024"
                      ]

You can obtain the properties that you want to change from the documents for VirtualBox command-line options:

The vagrant documentation has the section on how to change IP address:

Vagrant::Config.run do |config|
  config.vm.network :hostonly, "192.168.50.4"
end

Also you can restructure the configuration like this, ending is do with end without nesting it. This is simpler.

config.vm.define :web do |web_config|
    web_config.vm.box = "lucid32"
    web_config.vm.forward_port 80, 8080
end
web_config.vm.provision :puppet do |puppet|
    puppet.manifests_path = "manifests"
    puppet.manifest_file = "lucid32.pp"
end

How to get query parameters from URL in Angular 5?

When you have an empty route object, it's mainly due to the fact that you are not using a router-outlet in your app.component.html.

Without this, you won't be able to get a meaningful route object with non empty subObjects, particularly params & queryParams.

Try to add <router-outlet><router-outlet>just before calling your <app-main-component></app-main-component>

Before that, make sure you have your query param ready in app-routing > which export the class Route used by App component :

param: '/param/:dynamicParam', path: MyMainComponent

Last thing of course, to get your param, I personnaly use this.route.snapshot.params.dynamicParam where dynamicParam is the name used in your app-routing component :)

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

  1. Open the config.inc.php file from C:\xampp\phpmyadmin

  2. Put the "//" characters in config.inc.php at the start of below line:

    $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';

    Example: // $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';

  3. Reload your phpmyadmin at localhost.

Calling another different view from the controller using ASP.NET MVC 4

You can directly return a different view like:

return View("NameOfView", Model);

Or you can make a partial view and can return like:

return PartialView("PartialViewName", Model);

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

The two calls have different meanings that have nothing to do with performance; the fact that it speeds up the execution time is (or might be) just a side effect. You should understand what each of them does and not blindly include them in every program because they look like an optimization.

ios_base::sync_with_stdio(false);

This disables the synchronization between the C and C++ standard streams. By default, all standard streams are synchronized, which in practice allows you to mix C- and C++-style I/O and get sensible and expected results. If you disable the synchronization, then C++ streams are allowed to have their own independent buffers, which makes mixing C- and C++-style I/O an adventure.

Also keep in mind that synchronized C++ streams are thread-safe (output from different threads may interleave, but you get no data races).

cin.tie(NULL);

This unties cin from cout. Tied streams ensure that one stream is flushed automatically before each I/O operation on the other stream.

By default cin is tied to cout to ensure a sensible user interaction. For example:

std::cout << "Enter name:";
std::cin >> name;

If cin and cout are tied, you can expect the output to be flushed (i.e., visible on the console) before the program prompts input from the user. If you untie the streams, the program might block waiting for the user to enter their name but the "Enter name" message is not yet visible (because cout is buffered by default, output is flushed/displayed on the console only on demand or when the buffer is full).

So if you untie cin from cout, you must make sure to flush cout manually every time you want to display something before expecting input on cin.

In conclusion, know what each of them does, understand the consequences, and then decide if you really want or need the possible side effect of speed improvement.

Play audio file from the assets directory

this works for me:

public static class eSound_Def
{
  private static Android.Media.MediaPlayer mpBeep;

  public static void InitSounds( Android.Content.Res.AssetManager Assets )
  {
    mpBeep = new Android.Media.MediaPlayer();

    InitSound_Beep( Assets );
  }

  private static void InitSound_Beep( Android.Content.Res.AssetManager Assets )
  {
    Android.Content.Res.AssetFileDescriptor AFD;

    AFD = Assets.OpenFd( "Sounds/beep-06.mp3" );
    mpBeep.SetDataSource( AFD.FileDescriptor, AFD.StartOffset, AFD.Length );
    AFD.Close();

    mpBeep.Prepare();
    mpBeep.SetVolume( 1f, 1f );
    mpBeep.Looping = false;
  }

  public static void PlaySound_Beep()
  {
    if (mpBeep.IsPlaying == true) 
    {
      mpBeep.Stop();
      mpBeep.Reset();
      InitSound_Beep(); 
    }
    mpBeep.Start();
  }
}

In main activity, on create:

protected override void OnCreate( Bundle savedInstanceState )
{
  base.OnCreate( savedInstanceState );
  SetContentView( Resource.Layout.lmain_activity );
  ...
  eSound_Def.InitSounds( Assets );
  ...
}

how to use in code (on button click):

private void bButton_Click( object sender, EventArgs e )
{
  eSound_Def.PlaySound_Beep();
}

Git - Ignore node_modules folder everywhere

Use the universal one-liner in terminal in the project directory:

touch .gitignore && echo "node_modules/" >> .gitignore && git rm -r --cached node_modules ; git status

It works no matter if you've created a .gitignore or not, no matter if you've added node_modules to git tracking or not.

Then commit and push the .gitignore changes.

Explanation

touch will generate the .gitignore file if it doesn't already exist.

echo and >> will append node_modules/ at the end of .gitignore, causing the node_modules folder and all subfolders to be ignored.

git rm -r --cached removes the node_modules folder from git control if it was added before. Otherwise, this will show a warning pathspec 'node_modules' did not match any files, which has no side effects and you can safely ignore. The flags cause the removal to be recursive and include the cache.

git status displays the new changes. A change to .gitignore will appear, while node_modules will not appear as it is no longer being tracked by git.

JSON Naming Convention (snake_case, camelCase or PascalCase)

There is no SINGLE standard, but I have seen 3 styles you mention ("Pascal/Microsoft", "Java" (camelCase) and "C" (underscores, snake_case)) -- as well as at least one more, kebab-case like longer-name).

It mostly seems to depend on what background developers of the service in question had; those with c/c++ background (or languages that adopt similar naming, which includes many scripting languages, ruby etc) often choose underscore variant; and rest similarly (Java vs .NET). Jackson library that was mentioned, for example, assumes Java bean naming convention (camelCase)

UPDATE: my definition of "standard" is a SINGLE convention. So while one could claim "yes, there are many standards", to me there are multiple Naming Conventions, none of which is "The" standard overall. One of them could be considered the standard for specific platform, but given that JSON is used for interoperability between platforms that may or may not make much sense.

Get name of current class?

I think, it should be like this:

    class foo():
        input = get_input(__qualname__)

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

Using atan2 to find angle between two vectors

 atan2(vector1.y - vector2.y, vector1.x - vector2.x)

is the angle between the difference vector (connecting vector2 and vector1) and the x-axis, which is problably not what you meant.

The (directed) angle from vector1 to vector2 can be computed as

angle = atan2(vector2.y, vector2.x) - atan2(vector1.y, vector1.x);

and you may want to normalize it to the range [0, 2 p):

if (angle < 0) { angle += 2 * M_PI; }

or to the range (-p, p]:

if (angle > M_PI)        { angle -= 2 * M_PI; }
else if (angle <= -M_PI) { angle += 2 * M_PI; }

What is "Linting"?

Linting is the process of checking the source code for Programmatic as well as Stylistic errors. This is most helpful in identifying some common and uncommon mistakes that are made during coding.

A Lint or a Linter is a program that supports linting (verifying code quality). They are available for most languages like JavaScript, CSS, HTML, Python, etc..

Some of the useful linters are JSLint, CSSLint, JSHint, Pylint

C# adding a character in a string

I had to do something similar, trying to convert a string of numbers into a timespan by adding in : and .. Basically I was taking 235959999 and needing to convert it to 23:59:59.999. For me it was easy because I knew where I needed to "insert" said characters.

ts = ts.Insert(6,".");
ts = ts.Insert(4,":");
ts = ts.Insert(2,":");

Basically reassigning ts to itself with the inserted character. I worked my way from the back to front, because I was lazy and didn't want to do additional math for the other inserted characters.

You could try something similar by doing:

alpha = alpha.Insert(5,"-");
alpha = alpha.Insert(11,"-"); //add 1 to account for 1 -
alpha = alpha.Insert(17,"-"); //add 2 to account for 2 -
...

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.

You can use the following approach.

$data = [
    ['user_id'=>'Coder 1', 'subject_id'=> 4096],
    ['user_id'=>'Coder 2', 'subject_id'=> 2048],
    //...
];

Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach

In your case you already have the data within the $query variable.

Apache Spark: map vs mapPartitions?

Imp. TIP :

Whenever you have heavyweight initialization that should be done once for many RDD elements rather than once per RDD element, and if this initialization, such as creation of objects from a third-party library, cannot be serialized (so that Spark can transmit it across the cluster to the worker nodes), use mapPartitions() instead of map(). mapPartitions() provides for the initialization to be done once per worker task/thread/partition instead of once per RDD data element for example : see below.

val newRd = myRdd.mapPartitions(partition => {
  val connection = new DbConnection /*creates a db connection per partition*/

  val newPartition = partition.map(record => {
    readMatchingFromDB(record, connection)
  }).toList // consumes the iterator, thus calls readMatchingFromDB 

  connection.close() // close dbconnection here
  newPartition.iterator // create a new iterator
})

Q2. does flatMap behave like map or like mapPartitions?

Yes. please see example 2 of flatmap.. its self explanatory.

Q1. What's the difference between an RDD's map and mapPartitions

map works the function being utilized at a per element level while mapPartitions exercises the function at the partition level.

Example Scenario : if we have 100K elements in a particular RDD partition then we will fire off the function being used by the mapping transformation 100K times when we use map.

Conversely, if we use mapPartitions then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.

There will be performance gain since map works on a particular function so many times, especially if the function is doing something expensive each time that it wouldn't need to do if we passed in all the elements at once(in case of mappartitions).

map

Applies a transformation function on each item of the RDD and returns the result as a new RDD.

Listing Variants

def map[U: ClassTag](f: T => U): RDD[U]

Example :

val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
 val b = a.map(_.length)
 val c = a.zip(b)
 c.collect
 res0: Array[(String, Int)] = Array((dog,3), (salmon,6), (salmon,6), (rat,3), (elephant,8)) 

mapPartitions

This is a specialized map that is called only once for each partition. The entire content of the respective partitions is available as a sequential stream of values via the input argument (Iterarator[T]). The custom function must return yet another Iterator[U]. The combined result iterators are automatically converted into a new RDD. Please note, that the tuples (3,4) and (6,7) are missing from the following result due to the partitioning we chose.

preservesPartitioning indicates whether the input function preserves the partitioner, which should be false unless this is a pair RDD and the input function doesn't modify the keys.

Listing Variants

def mapPartitions[U: ClassTag](f: Iterator[T] => Iterator[U], preservesPartitioning: Boolean = false): RDD[U]

Example 1

val a = sc.parallelize(1 to 9, 3)
 def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = {
   var res = List[(T, T)]()
   var pre = iter.next
   while (iter.hasNext)
   {
     val cur = iter.next;
     res .::= (pre, cur)
     pre = cur;
   }
   res.iterator
 }
 a.mapPartitions(myfunc).collect
 res0: Array[(Int, Int)] = Array((2,3), (1,2), (5,6), (4,5), (8,9), (7,8)) 

Example 2

val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
 def myfunc(iter: Iterator[Int]) : Iterator[Int] = {
   var res = List[Int]()
   while (iter.hasNext) {
     val cur = iter.next;
     res = res ::: List.fill(scala.util.Random.nextInt(10))(cur)
   }
   res.iterator
 }
 x.mapPartitions(myfunc).collect
 // some of the number are not outputted at all. This is because the random number generated for it is zero.
 res8: Array[Int] = Array(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 7, 7, 7, 9, 9, 10) 

The above program can also be written using flatMap as follows.

Example 2 using flatmap

val x  = sc.parallelize(1 to 10, 3)
 x.flatMap(List.fill(scala.util.Random.nextInt(10))(_)).collect

 res1: Array[Int] = Array(1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10) 

Conclusion :

mapPartitions transformation is faster than map since it calls your function once/partition, not once/element..

Further reading : foreach Vs foreachPartitions When to use What?