Programs & Examples On #Assembly references

Why is System.Web.Mvc not listed in Add References?

The desired assembly has appeared in the list now.

I can only speculate what caused it to appear, but I suspect it is the fact that I went File ? New ? Project ? ASP.NET Web Application, which I had never done before. It is possible that this caused some sort of late initialisation to happen and the list to be populated with additional assemblies for Web development.

Get the current first responder without using a private API

With a category on UIResponder, it is possible to legally ask the UIApplication object to tell you who the first responder is.

See this:

Is there any way of asking an iOS view which of its children has first responder status?

How can I get the last day of the month in C#?

try this. It will solve your problem.

 var lastDayOfMonth = DateTime.DaysInMonth(int.Parse(ddlyear.SelectedValue), int.Parse(ddlmonth.SelectedValue));
DateTime tLastDayMonth = Convert.ToDateTime(lastDayOfMonth.ToString() + "/" + ddlmonth.SelectedValue + "/" + ddlyear.SelectedValue);

Declaring a boolean in JavaScript using just var

You can use and test uninitialized variables at least for their 'definedness'. Like this:

var iAmNotDefined;
alert(!iAmNotDefined); //true
//or
alert(!!iAmNotDefined); //false

Furthermore, there are many possibilites: if you're not interested in exact types use the '==' operator (or ![variable] / !![variable]) for comparison (that is what Douglas Crockford calls 'truthy' or 'falsy' I think). In that case assigning true or 1 or '1' to the unitialized variable always returns true when asked. Otherwise [if you need type safe comparison] use '===' for comparison.

var thisMayBeTrue;

thisMayBeTrue = 1;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false

thisMayBeTrue = '1';
alert(thisMayBeTrue == true); //=> true 
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, in this case, using == or !! '1' is implicitly 
// converted to 1 and 1 is implicitly converted to true)

thisMayBeTrue = true;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> true

thisMayBeTrue = 'true';
alert(thisMayBeTrue == true); //=> false
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, here's no implicit conversion of the string 'true'
// it's also a demonstration of the fact that the 
// ! or !! operator tests the 'definedness' of a variable.

PS: you can't test 'definedness' for nonexisting variables though. So:

alert(!!HelloWorld);

gives a reference Error ('HelloWorld is not defined')

(is there a better word for 'definedness'? Pardon my dutch anyway;~)

Passing a variable to a powershell script via command line

Make this in your test.ps1, at the first line

param(
[string]$a
)

Write-Host $a

Then you can call it with

./Test.ps1 "Here is your text"

Found here (English)

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

While trace flag 272 may work for many, it definitely won't work for hosted Sql Server Express installations. So, I created an identity table, and use this through an INSTEAD OF trigger. I'm hoping this helps someone else, and/or gives others an opportunity to improve my solution. The last line allows returning the last identity column added. Since I typically use this to add a single row, this works to return the identity of a single inserted row.

The identity table:

CREATE TABLE [dbo].[tblsysIdentities](
[intTableId] [int] NOT NULL,
[intIdentityLast] [int] NOT NULL,
[strTable] [varchar](100) NOT NULL,
[tsConcurrency] [timestamp] NULL,
CONSTRAINT [PK_tblsysIdentities] PRIMARY KEY CLUSTERED 
(
    [intTableId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,  ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

and the insert trigger:

-- INSERT --
IF OBJECT_ID ('dbo.trgtblsysTrackerMessagesIdentity', 'TR') IS NOT NULL
   DROP TRIGGER dbo.trgtblsysTrackerMessagesIdentity;
GO
CREATE TRIGGER trgtblsysTrackerMessagesIdentity
ON dbo.tblsysTrackerMessages
INSTEAD OF INSERT AS 
BEGIN
    DECLARE @intTrackerMessageId INT
    DECLARE @intRowCount INT

    SET @intRowCount = (SELECT COUNT(*) FROM INSERTED)

    SET @intTrackerMessageId = (SELECT intIdentityLast FROM tblsysIdentities WHERE intTableId=1)
    UPDATE tblsysIdentities SET intIdentityLast = @intTrackerMessageId + @intRowCount WHERE intTableId=1

    INSERT INTO tblsysTrackerMessages( 
    [intTrackerMessageId],
    [intTrackerId],
    [strMessage],
    [intTrackerMessageTypeId],
    [datCreated],
    [strCreatedBy])
    SELECT @intTrackerMessageId + ROW_NUMBER() OVER (ORDER BY [datCreated]) AS [intTrackerMessageId], 
    [intTrackerId],
   [strMessage],
   [intTrackerMessageTypeId],
   [datCreated],
   [strCreatedBy] FROM INSERTED;

   SELECT TOP 1 @intTrackerMessageId + @intRowCount FROM INSERTED;
END

How to make audio autoplay on chrome

Just add this small script as depicted in https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio

<head>
<script>
window.onload = function() {
  var context = new AudioContext();
}
</script>
</head>

Than this will work as you want:

<audio autoplay>
      <source src="hal_9000_sorry_dave.mp3">
</audio>

PHP order array by date?

He was considering having the date as a key, but worried that values will be written one above other, all I wanted to show (maybe not that obvious, that why I do edit) is that he can still have values intact, not written one above other, isn't this okay?!

<?php
 $data['may_1_2002']=
 Array(
 'title_id_32'=>'Good morning', 
 'title_id_21'=>'Blue sky',
 'title_id_3'=>'Summer',
 'date'=>'1 May 2002'
 );

 $data['may_2_2002']=
 Array(
 'title_id_34'=>'Leaves', 
 'title_id_20'=>'Old times',
  'date'=>'2 May   2002 '
 );


 echo '<pre>';
 print_r($data);
?>

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

There only two things that MapReduce does NATIVELY: Sort and (implemented by sort) scalable GroupBy.

Most of applications and Design Patterns over MapReduce are built over these two operations, which are provided by shuffle and sort.

Getting a 'source: not found' error when using source in a bash script

If you're writing a bash script, call it by name:

#!/bin/bash

/bin/sh is not guaranteed to be bash. This caused a ton of broken scripts in Ubuntu some years ago (IIRC).

The source builtin works just fine in bash; but you might as well just use dot like Norman suggested.

must declare a named package eclipse because this compilation unit is associated to the named module

The "delete module-info.java at your Project Explorer tab" answer is the easiest and most straightforward answer, but

for those who would want a little more understanding or control of what's happening, the following alternate methods may be desirable;

  • make an ever so slightly more realistic application; com.YourCompany.etc or just com.HelloWorld (Project name: com.HelloWorld and class name: HelloWorld)

or

  • when creating the java project; when in the Create Java Project dialog, don't choose Finish but Next, and deselect Create module-info.java file

How to align an image dead center with bootstrap

Assuming there is nothing else alongside the image, the best way is to use text-align: center in the img parent:

.row .span4 {
    text-align: center;
}

Edit

As mentioned in the other answers, you can add the bootstrap CSS class .text-center to the parent element. This does exactly the same thing and is available in both v2.3.3 and v3

What tools do you use to test your public REST API?

We are using Groovy to test our RestFUL API, using a series of helper functions to build the xml put/post/gets and then a series of tests on the nodes of the XML to check that the data is manipulated correctly.

We use Poster (for Firefox, Chrome seems to be lacking a similar tool) for hand testing single areas, or simply to poll the API at times when we need to create further tests, or check the status of things.

What does "\r" do in the following script?

\r is the ASCII Carriage Return (CR) character.

There are different newline conventions used by different operating systems. The most common ones are:

  • CR+LF (\r\n);
  • LF (\n);
  • CR (\r).

The \n\r (LF+CR) looks unconventional.

edit: My reading of the Telnet RFC suggests that:

  1. CR+LF is the standard newline sequence used by the telnet protocol.
  2. LF+CR is an acceptable substitute:

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

Purpose of ESI & EDI registers?

In addition to the string operations (MOVS/INS/STOS/CMPS/SCASB/W/D/Q etc.) mentioned in the other answers, I wanted to add that there are also more "modern" x86 assembly instructions that implicitly use at least EDI/RDI:

The SSE2 MASKMOVDQU (and the upcoming AVX VMASKMOVDQU) instruction selectively write bytes from an XMM register to memory pointed to by EDI/RDI.

How to redirect to Index from another controller?

Complete answer (.Net Core 3.1)

Most answers here are correct but taken a bit out of context, so I will provide a full-fledged answer which works for Asp.Net Core 3.1. For completeness' sake:

[Route("health")]
[ApiController]
public class HealthController : Controller
{
    [HttpGet("some_health_url")]
    public ActionResult SomeHealthMethod() {}
}

[Route("v2")]
[ApiController]
public class V2Controller : Controller
{
    [HttpGet("some_url")]
    public ActionResult SomeV2Method()
    {
        return RedirectToAction("SomeHealthMethod", "Health"); // omit "Controller"
    }
}

If you try to use any of the url-specific strings, e.g. "some_health_url", it will not work!

Is it possible to open a Windows Explorer window from PowerShell?

I wanted to write this as a comment but I do not have 50 reputation.

All of the answers in this thread are essentially to use Invoke-Item or to use explorer.exe directly; however, this isn't completely synonymous with "open containing folder", so in terms of opening an Explorer window as the question states, if we wanted to apply the answer to a particular file the question still hasn't really been answered.

e.g.,

Invoke-Item C:\Users\Foo\bar.txt
explorer.exe C:\Users\Foo\bar.html

^ those two commands would result in Notepad.exe or Firefox.exe being invoked on the two files respectively, not an explorer.exe window on C:\Users\Foo\ (the containing directory).

Whereas if one was issuing this command from powershell, this would be no big deal (less typing anyway), if one is scripting and needs to "open containing folder" on a variable, it becomes a matter of string matching to extract the directory from the full path to the file.

Is there no simple command "Open-Containing-Folder" such that a variable could be substituted?

e.g.,

$foo = "C:\Users\Foo\foo.txt"    
[some code] $fooPath
# opens C:\Users\Foo\ and not the default program for .txt file extension

Automatically deleting related rows in Laravel (Eloquent ORM)

I would iterate through the collection detaching everything before deleting the object itself.

here's an example:

try {
        $user = User::findOrFail($id);
        if ($user->has('photos')) {
            foreach ($user->photos as $photo) {

                $user->photos()->detach($photo);
            }
        }
        $user->delete();
        return 'User deleted';
    } catch (Exception $e) {
        dd($e);
    }

I know it is not automatic but it is very simple.

Another simple approach would be to provide the model with a method. Like this:

public function detach(){
       try {
            
            if ($this->has('photos')) {
                foreach ($this->photos as $photo) {
    
                    $this->photos()->detach($photo);
                }
            }
           
        } catch (Exception $e) {
            dd($e);
        }
}

Then you can simply call this where you need:

$user->detach();
$user->delete();

How to automate browsing using python?

selenium will do exactly what you want and it handles javascript

Program to find prime numbers

You can do also this:

class Program
  {
    static void Main(string[] args)
    {
      long numberToTest = 350124;
      bool isPrime = NumberIsPrime(numberToTest);
      Console.WriteLine(string.Format("Number {0} is prime? {1}", numberToTest, isPrime));
      Console.ReadLine();
    }

    private static bool NumberIsPrime(long n)
    {
      bool retVal = true;

      if (n <= 3)
      {
        retVal = n > 1;
      } else if (n % 2 == 0 || n % 3 == 0)
      {
        retVal = false;
      }

      int i = 5;

      while (i * i <= n)
      {
        if (n % i == 0 || n % (i + 2) == 0)
        {
          retVal = false;
        }
        i += 6;
      }

      return retVal;
    }
  }

Razor View throwing "The name 'model' does not exist in the current context"

I solved the problem by using @Model instead of just model when printing the variables.

jQuery toggle CSS?

You might want to use jQuery's .addClass and .removeClass commands, and create two different classes for the states. This, to me, would be the best practice way of doing it.

dispatch_after - GCD in Swift?

Another way is to extend Double like this:

extension Double {
   var dispatchTime: dispatch_time_t {
       get {
           return dispatch_time(DISPATCH_TIME_NOW,Int64(self * Double(NSEC_PER_SEC)))
       }
   }
}

Then you can use it like this:

dispatch_after(Double(2.0).dispatchTime, dispatch_get_main_queue(), { () -> Void in
            self.dismissViewControllerAnimated(true, completion: nil)
    })

I like matt's delay function but just out of preference I'd rather limit passing closures around.

"Failed to install the following Android SDK packages as some licences have not been accepted" error

I tried many solutions but didn't work for me. The below solution works for me.

locate the sdkmanager file in android SDK.

In my case : ~/Android/Sdk/tools/bin

go to that path : cd ~/Android/Sdk/tools/bin

Accept licenses manually : ./sdkmanager --licenses Enter Yes or y

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

First of all its not the Notepad++ problem for sure. Its your "String Matching problem"

The common string throughout all IE version is MSIE Check out the various userAgent strings at http://www.useragentstring.com/pages/Internet%20Explorer/

if(navigator.userAgent.indexOf("MSIE") != -1){
   alert('I am Internet Explorer!!');
}

How to debug stored procedures with print statements?

If you're using MSSQL Server management studio print statements will print out under the messages tab not under the Results tab.

enter image description here

Print statements will appear there.

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

Send email from localhost running XAMMP in PHP using GMAIL mail server

Don't forget to generate a second password for your Gmail account. You will use this new password in your code. Read this:

https://support.google.com/accounts/answer/185833

Under the section "How to generate an App password" click on "App passwords", then under "Select app" choose "Mail", select your device and click "Generate". Your second password will be printed on the screen.

Pagination response payload from a RESTful API

ReSTful APIs are consumed primarily by other systems, which is why I put paging data in the response headers. However, some API consumers may not have direct access to the response headers, or may be building a UX over your API, so providing a way to retrieve (on demand) the metadata in the JSON response is a plus.

I believe your implementation should include machine-readable metadata as a default, and human-readable metadata when requested. The human-readable metadata could be returned with every request if you like or, preferably, on-demand via a query parameter, such as include=metadata or include_metadata=true.

In your particular scenario, I would include the URI for each product with the record. This makes it easy for the API consumer to create links to the individual products. I would also set some reasonable expectations as per the limits of my paging requests. Implementing and documenting default settings for page size is an acceptable practice. For example, GitHub's API sets the default page size to 30 records with a maximum of 100, plus sets a rate limit on the number of times you can query the API. If your API has a default page size, then the query string can just specify the page index.

In the human-readable scenario, when navigating to /products?page=5&per_page=20&include=metadata, the response could be:

{
  "_metadata": 
  {
      "page": 5,
      "per_page": 20,
      "page_count": 20,
      "total_count": 521,
      "Links": [
        {"self": "/products?page=5&per_page=20"},
        {"first": "/products?page=0&per_page=20"},
        {"previous": "/products?page=4&per_page=20"},
        {"next": "/products?page=6&per_page=20"},
        {"last": "/products?page=26&per_page=20"},
      ]
  },
  "records": [
    {
      "id": 1,
      "name": "Widget #1",
      "uri": "/products/1"
    },
    {
      "id": 2,
      "name": "Widget #2",
      "uri": "/products/2"
    },
    {
      "id": 3,
      "name": "Widget #3",
      "uri": "/products/3"
    }
  ]
}

For machine-readable metadata, I would add Link headers to the response:

Link: </products?page=5&perPage=20>;rel=self,</products?page=0&perPage=20>;rel=first,</products?page=4&perPage=20>;rel=previous,</products?page=6&perPage=20>;rel=next,</products?page=26&perPage=20>;rel=last

(the Link header value should be urlencoded)

...and possibly a custom total-count response header, if you so choose:

total-count: 521

The other paging data revealed in the human-centric metadata might be superfluous for machine-centric metadata, as the link headers let me know which page I am on and the number per page, and I can quickly retrieve the number of records in the array. Therefore, I would probably only create a header for the total count. You can always change your mind later and add more metadata.

As an aside, you may notice I removed /index from your URI. A generally accepted convention is to have your ReST endpoint expose collections. Having /index at the end muddies that up slightly.

These are just a few things I like to have when consuming/creating an API. Hope that helps!

Git command to show which specific files are ignored by .gitignore

Here's how to print the complete list of files in the working tree which match patterns located anywhere in Git's multiple gitignore sources (if you're using GNU find):

$ cd {your project directory}
$ find . -path ./.git -prune -o -print \
| git check-ignore --no-index --stdin --verbose

It will check all the files in the current branch of the repository (unless you've deleted them locally).

And it identifies the particular gitignore source lines, as well.

Git continues to track changes in some files which match gitignore patterns, simply because those files were added already. Usefully, the above command displays those files, too.

Negative gitignore patterns are also matched. However, these are easily distinguishable in the listing, because they begin with !.

If you're using Windows, Git Bash includes GNU find (as revealed by find --version).

If the list is long (and you have rev), you can display them by extension (somewhat), too:

$ cd {your project directory}
$ find . -path ./.git -prune -o -print \
| git check-ignore --no-index --stdin --verbose \
| rev | sort | rev

For more details, see man find, man git-check-ignore, man rev, and man sort.

The point of this whole approach is that Git (the software) is changing rapidly and is highly complex. By contrast, GNU's find is extremely stable (at least, in its features used here). So, anyone who desires to be competitive by displaying their in-depth knowledge of Git will answer the question in a different way.

What's the best answer? This answer deliberately minimizes its reliance on Git knowledge, toward achieving the goal of stability and simplicity through modularity (information isolation), and is designed to last a long time.

Closing database connections in Java

Actually, it is best if you use a try-with-resources block and Java will close all of the connections for you when you exit the try block.

You should do this with any object that implements AutoClosable.

try (Connection connection = getDatabaseConnection(); Statement statement = connection.createStatement()) {
    String sqlToExecute = "SELECT * FROM persons";
    try (ResultSet resultSet = statement.execute(sqlToExecute)) {
        if (resultSet.next()) {
            System.out.println(resultSet.getString("name");
        }
    }
} catch (SQLException e) {
    System.out.println("Failed to select persons.");
}

The call to getDatabaseConnection is just made up. Replace it with a call that gets you a JDBC SQL connection or a connection from a pool.

Algorithm: efficient way to remove duplicate integers from an array

If you are looking for the superior O-notation, then sorting the array with an O(n log n) sort then doing a O(n) traversal may be the best route. Without sorting, you are looking at O(n^2).

Edit: if you are just doing integers, then you can also do radix sort to get O(n).

Reset/remove CSS styles for element only

Let me answer this question thoroughly, because it's been a source of pain for me for several years and very few people really understand the problem and why it's important for it to be solved. If I were at all responsible for the CSS spec I'd be embarrassed, frankly, for having not addressed this in the last decade.

The Problem

You need to insert markup into an HTML document, and it needs to look a specific way. Furthermore, you do not own this document, so you cannot change existing style rules. You have no idea what the style sheets could be, or what they may change to.

Use cases for this are when you are providing a displayable component for unknown 3rd party websites to use. Examples of this would be:

  1. An ad tag
  2. Building a browser extension that inserts content
  3. Any type of widget

Simplest Fix

Put everything in an iframe. This has it's own set of limitations:

  1. Cross Domain limitations: Your content will not have access to the original document at all. You cannot overlay content, modify the DOM, etc.
  2. Display Limitations: Your content is locked inside of a rectangle.

If your content can fit into a box, you can get around problem #1 by having your content write an iframe and explicitly set the content, thus skirting around the issue, since the iframe and document will share the same domain.

CSS Solution

I've search far and wide for the solution to this, but there are unfortunately none. The best you can do is explicitly override all possible properties that can be overridden, and override them to what you think their default value should be.

Even when you override, there is no way to ensure a more targeted CSS rule won't override yours. The best you can do here is to have your override rules target as specifically as possible and hope the parent document doesn't accidentally best it: use an obscure or random ID on your content's parent element, and use !important on all property value definitions.

How to copy sheets to another workbook using vba?

Here is one you might like it uses the Windows FileDialog(msoFileDialogFilePicker) to browse to a closed workbook on your desktop, then copies all of the worksheets to your open workbook:

Sub CopyWorkBookFullv2()
Application.ScreenUpdating = False

Dim ws As Worksheet
Dim x As Integer
Dim closedBook As Workbook
Dim cell As Range
Dim numSheets As Integer
Dim LString As String
Dim LArray() As String
Dim dashpos As Long
Dim FileName As String

numSheets = 0

For Each ws In Application.ActiveWorkbook.Worksheets
    If ws.Name <> "Sheet1" Then
       Sheets.Add.Name = "Sheet1"
   End If
Next

Dim fileExplorer As FileDialog
Set fileExplorer = Application.FileDialog(msoFileDialogFilePicker)
Dim MyString As String

fileExplorer.AllowMultiSelect = False

  With fileExplorer
     If .Show = -1 Then 'Any file is selected
     MyString = .SelectedItems.Item(1)

     Else ' else dialog is cancelled
        MsgBox "You have cancelled the dialogue"
        [filePath] = "" ' when cancelled set blank as file path.
        End If
    End With

    LString = Range("A1").Value
    dashpos = InStr(1, LString, "\") + 1
    LArray = Split(LString, "\")
    'MsgBox LArray(dashpos - 1)
    FileName = LArray(dashpos)

strFileName = CreateObject("WScript.Shell").specialfolders("Desktop") & "\" & FileName

Set closedBook = Workbooks.Open(strFileName)
closedBook.Application.ScreenUpdating = False
numSheets = closedBook.Sheets.Count

        For x = 1 To numSheets
            closedBook.Sheets(x).Copy After:=ThisWorkbook.Sheets(1)
        x = x + 1
                 If x = numSheets Then
                    GoTo 1000
                 End If
Next

1000

closedBook.Application.ScreenUpdating = True
closedBook.Close
Application.ScreenUpdating = True

End Sub

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

Better way to find last used row

I use the following function extensively. As pointed out above, using other methods can sometimes give inaccurate results due to used range updates, gaps in the data, or different columns having different row counts.

Example of use:

lastRow=FindRange("Sheet1","A1:A1000")

would return the last occupied row number of the entire range. You can specify any range you want from single columns to random rows, eg FindRange("Sheet1","A100:A150")

Public Function FindRange(inSheet As String, inRange As String) As Long
    Set fr = ThisWorkbook.Sheets(inSheet).Range(inRange).find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
    If Not fr Is Nothing Then FindRange = fr.row Else FindRange = 0
End Function

Copy file(s) from one project to another using post build event...VS2010

Like the previous replies, I'm also suggesting xcopy. However, I would like to add to Hallgeir Engen's answer with the /exclude parameter. There seems to be a bug with the parameter preventing it from working with path names that are long or that contain spaces, as quotes will not work. The path names need to be in the "DOS"-format with "Documents" translating to "DOCUME~1" (according to this source).

So, if you want to use the \exclude parameter, there is a workaround here:

cd $(SolutionDir)
xcopy "source-relative-to-path-above" "destination-relative-to-path-above
/exclude:exclude-file-relative-path

Note that the source and destination paths can (and should, if they contain spaces) be within quotes, but not the path to the exclude file.

Importing class/java files in Eclipse

I had the same problem. But What I did is I imported the .java files and then I went to Search->File-> and then changed the package name to whatever package it should belong in this way I fixed a lot of java files which otherwise would require to go to every file and change them manually.

How to print an exception in Python?

The traceback module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:

import traceback

try:
    1/0
except Exception:
    traceback.print_exc()

Output:

Traceback (most recent call last):
  File "C:\scripts\divide_by_zero.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero

Start ssh-agent on login

On Arch Linux, the following works really great (should work on all systemd-based distros):

Create a systemd user service, by putting the following to ~/.config/systemd/user/ssh-agent.service:

[Unit]
Description=SSH key agent

[Service]
Type=simple
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket
ExecStart=/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK

[Install]
WantedBy=default.target

Setup shell to have an environment variable for the socket (.bash_profile, .zshrc, ...):

export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/ssh-agent.socket"

Enable the service, so it'll be started automatically on login, and start it:

systemctl --user enable ssh-agent
systemctl --user start ssh-agent

Add the following configuration setting to your local ssh config file ~/.ssh/config (this works since SSH 7.2):

AddKeysToAgent  yes

This will instruct the ssh client to always add the key to a running agent, so there's no need to ssh-add it beforehand.

How to set editor theme in IntelliJ Idea

For IntelliJ in Mac

View -> Quick Switch theme (^`)-> color schema

Get the client's IP address in socket.io

Very easy. First put

io.sockets.on('connection', function (socket) {

console.log(socket);

You will see all fields of socket. then use CTRL+F and search the word address. Finally, when you find the field remoteAddress use dots to filter data. in my case it is

console.log(socket.conn.remoteAddress);

Requested registry access is not allowed

You can't write to the HKCR (or HKLM) hives in Vista and newer versions of Windows unless you have administrative privileges. Therefore, you'll either need to be logged in as an Administrator before you run your utility, give it a manifest that says it requires Administrator level (which will prompt the user for Admin login info), or quit changing things in places that non-Administrators shouldn't be playing. :-)

JavaScript equivalent to printf/String.Format

If you are looking to handle the thousands separator, you should really use toLocaleString() from the JavaScript Number class since it will format the string for the user's region.

The JavaScript Date class can format localized dates and times.

Bootstrap 3 select input form inline

Based on spacebean's answer, this modification also changes the displayed text when the user selects a different item (just as a <select> would do):

http://www.bootply.com/VxVlaebtnL

HTML:

<div class="container">
  <div class="col-sm-7 pull-right well">
    <form class="form-inline" action="#" method="get">
      <div class="input-group col-sm-8">
        <input class="form-control" type="text" value="" placeholder="Search" name="q">
        <div class="input-group-btn">
          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span id="mydropdowndisplay">Choice 1</span> <span class="caret"></span></button>
          <ul class="dropdown-menu" id="mydropdownmenu">
            <li><a href="#">Choice 1</a></li>
            <li><a href="#">Choice 2</a></li>
            <li><a href="#">Choice 3</a></li>
          </ul>
          <input type="hidden" id="mydropwodninput" name="category">
        </div><!-- /btn-group -->
      </div>
    <button class="btn btn-primary col-sm-3 pull-right" type="submit">Search</button>
    </form>
  </div>
</div>

Jquery:

$('#mydropdownmenu > li').click(function(e){
  e.preventDefault();
  var selected = $(this).text();
  $('#mydropwodninput').val(selected);
  $('#mydropdowndisplay').text(selected);
});

Java: Convert String to TimeStamp

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

Date date = formatter.parse(dateString);

Timestamp timestamp = new Timestamp(date.getTime());

System.out.println(timestamp);

How do I read all classes from a Java package in the classpath?

If you have Spring in you classpath then the following will do it.

Find all classes in a package that are annotated with XmlRootElement:

private List<Class> findMyTypes(String basePackage) throws IOException, ClassNotFoundException
{
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    List<Class> candidates = new ArrayList<Class>();
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                               resolveBasePackage(basePackage) + "/" + "**/*.class";
    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            if (isCandidate(metadataReader)) {
                candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
            }
        }
    }
    return candidates;
}

private String resolveBasePackage(String basePackage) {
    return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage));
}

private boolean isCandidate(MetadataReader metadataReader) throws ClassNotFoundException
{
    try {
        Class c = Class.forName(metadataReader.getClassMetadata().getClassName());
        if (c.getAnnotation(XmlRootElement.class) != null) {
            return true;
        }
    }
    catch(Throwable e){
    }
    return false;
}

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

Second Update

The FAQ is not available anymore.

From the documentation of shrinkwrap:

If you wish to lock down the specific bytes included in a package, for example to have 100% confidence in being able to reproduce a deployment or build, then you ought to check your dependencies into source control, or pursue some other mechanism that can verify contents rather than versions.

Shannon and Steven mentioned this before but I think, it should be part of the accepted answer.


Update

The source listed for the below recommendation has been updated. They are no longer recommending the node_modules folder be committed.

Usually, no. Allow npm to resolve dependencies for your packages.

For packages you deploy, such as websites and apps, you should use npm shrinkwrap to lock down your full dependency tree:

https://docs.npmjs.com/cli/shrinkwrap


Original Post

For reference, npm FAQ answers your question clearly:

Check node_modules into git for things you deploy, such as websites and apps. Do not check node_modules into git for libraries and modules intended to be reused. Use npm to manage dependencies in your dev environment, but not in your deployment scripts.

and for some good rationale for this, read Mikeal Rogers' post on this.


Source: https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git

Dictionary of dictionaries in Python?

Using collections.defaultdict is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.

Here it's used twice: for the resulting dict, and for each of the values in the dict.

import collections

def aggregate_names(errors):
    result = collections.defaultdict(lambda: collections.defaultdict(list))
    for real_name, false_name, location in errors:
        result[real_name][false_name].append(location)
    return result

Combining this with your code:

dictionary = aggregate_names(previousFunction(string))

Or to test:

EXAMPLES = [
    ('Fred', 'Frad', 123),
    ('Jim', 'Jam', 100),
    ('Fred', 'Frod', 200),
    ('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)

How to use sed to remove all double quotes within a file

Are you sure you need to use sed? How about:

tr -d "\""

Cannot call getSupportFragmentManager() from activity

I used FragmentActivity

TabAdapter = new TabPagerAdapter(((FragmentActivity) getActivity()).getSupportFragmentManager());

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

What is causing this error - "Fatal error: Unable to find local grunt"

You can simply run this command:

npm install grunt --save-dev

Is the Javascript date object always one day off?

If you want to get hour 0 of some date in the local time zone, pass the individual date parts to the Date constructor.

new Date(2011,08,24); // month value is 0 based, others are 1 based.

How do I "select Android SDK" in Android Studio?

Sync didn't help me. Neither helped invalidating cache. I simply removed and cloned again the repository and it worked:

  1. Make sure you have no uncommitted changes
  2. Sync your local repository with remote github
  3. Delete folder with the local repository
  4. Clone the repository from github to local again
  5. Open the cloned repository in the Android Studio
  6. Build and run it again.

How to add a reference programmatically

Here is how to get the Guid's programmatically! You can then use these guids/filepaths with an above answer to add the reference!

Reference: http://www.vbaexpress.com/kb/getarticle.php?kb_id=278

Sub ListReferencePaths()
'Lists path and GUID (Globally Unique Identifier) for each referenced library.
'Select a reference in Tools > References, then run this code to get GUID etc.
    Dim rw As Long, ref
    With ThisWorkbook.Sheets(1)
        .Cells.Clear
        rw = 1
        .Range("A" & rw & ":D" & rw) = Array("Reference","Version","GUID","Path")
        For Each ref In ThisWorkbook.VBProject.References
            rw = rw + 1
            .Range("A" & rw & ":D" & rw) = Array(ref.Description, _
                   "v." & ref.Major & "." & ref.Minor, ref.GUID, ref.FullPath)
        Next ref
        .Range("A:D").Columns.AutoFit
    End With
End Sub

Here is the same code but printing to the terminal if you don't want to dedicate a worksheet to the output.

Sub ListReferencePaths() 
 'Macro purpose:  To determine full path and Globally Unique Identifier (GUID)
 'to each referenced library.  Select the reference in the Tools\References
 'window, then run this code to get the information on the reference's library

On Error Resume Next 
Dim i As Long 

Debug.Print "Reference name" & " | " & "Full path to reference" & " | " & "Reference GUID" 

For i = 1 To ThisWorkbook.VBProject.References.Count 
  With ThisWorkbook.VBProject.References(i) 
    Debug.Print .Name & " | " & .FullPath  & " | " & .GUID 
  End With 
Next i 
On Error GoTo 0 
End Sub 

How to add image that is on my computer to a site in css or html?

Upload the image on your server or in images hosting site where you get image link and then add the line on your website page where you get that image the line is

<img src="paste here your image full path"/>

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

I got the same exception when I locally tested. The problem was a URL schema in my request.

Change https:// to http:// in your client url.

Probably it helps.

Android ListView Divider

Add android:dividerHeight="1px" and it will work:

<ListView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:id="@+id/cashItemsList"
     android:cacheColorHint="#00000000"
     android:divider="@drawable/list_divider" android:dividerHeight="1px"></ListView>

How to run a .jar in mac?

Make Executable your jar and after that double click on it on Mac OS then it works successfully.

sudo chmod +x filename.jar

Try this, I hope this works.

Placing an image to the top right corner - CSS

Position the div relatively, and position the ribbon absolutely inside it. Something like:

#content {
  position:relative;
}

.ribbon {
  position:absolute;
  top:0;
  right:0;
}

How to easily consume a web service from PHP

Well, those features are specific to a tool that you are using for development in those languages.

You wouldn't have those tools if (for example) you were using notepad to write code. So, maybe you should ask the question for the tool you are using.

For PHP: http://webservices.xml.com/pub/a/ws/2004/03/24/phpws.html

Solving Quadratic Equation

one liner solve quadratic equation

from math import sqrt
s = lambda a,b,c: {(-b-sqrt(d))/2*a,(-b+sqrt(d))/2*a} if (d:=b**2-4*a*c)>=0 else {}
roots_set = s(int(input('a=')),int(input('b=')),int(input('c=')))
print(roots_set,f'number of roots {len(roots_set)}')

one line python solve quadratic equations video

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

You might try boost::lexical_cast. It throws an bad_lexical_cast exception if it fails.

In your case:

int number;
try
{
  number = boost::lexical_cast<int>(word);
}
catch(boost::bad_lexical_cast& e)
{
  std::cout << word << "isn't a number" << std::endl;
}

Simplest way to wait some asynchronous tasks complete, in Javascript?

I see you are using mongoose so you are talking about server-side JavaScript. In that case I advice looking at async module and use async.parallel(...). You will find this module really helpful - it was developed to solve the problem you are struggling with. Your code may look like this

var async = require('async');

var calls = [];

['aaa','bbb','ccc'].forEach(function(name){
    calls.push(function(callback) {
        conn.collection(name).drop(function(err) {
            if (err)
                return callback(err);
            console.log('dropped');
            callback(null, name);
        });
    }
)});

async.parallel(calls, function(err, result) {
    /* this code will run after all calls finished the job or
       when any of the calls passes an error */
    if (err)
        return console.log(err);
    console.log(result);
});

Cast Object to Generic Type for returning

I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException.

I have the code which is pretty much the same as OP's code:

public static <T> T convertInstanceOfObject(Object o) {
    try {
       return (T) o;
    } catch (ClassCastException e) {
        return null;
    }
}

public static void main(String[] args) {
    String k = convertInstanceOfObject(345435.34);
    System.out.println(k);
}

and the corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object);
    Code:
       0: aload_0
       1: areturn
       2: astore_1
       3: aconst_null
       4: areturn
    Exception table:
       from    to  target type
           0     1     2   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #3                  // double 345435.34d
       3: invokestatic  #5                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: invokestatic  #6                  // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
       9: checkcast     #7                  // class java/lang/String
      12: astore_1
      13: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
      16: aload_1
      17: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      20: return

Notice that checkcast byte code instruction happens in the main method not the convertInstanceOfObject and convertInstanceOfObject method does not have any instruction that can throw ClassCastException. Because the main method does not catch the ClassCastException hence when you execute the main method you will get a ClassCastException and not the expectation of printing null.

Now I modify the code to the accepted answer:

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
        try {
            return clazz.cast(o);
        } catch (ClassCastException e) {
            return null;
        }
    }
    public static void main(String[] args) {
        String k = convertInstanceOfObject(345435.34, String.class);
        System.out.println(k);
    }

The corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
    Code:
       0: aload_1
       1: aload_0
       2: invokevirtual #2                  // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
       5: areturn
       6: astore_2
       7: aconst_null
       8: areturn
    Exception table:
       from    to  target type
           0     5     6   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #4                  // double 345435.34d
       3: invokestatic  #6                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: ldc           #7                  // class java/lang/String
       8: invokestatic  #8                  // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
      11: checkcast     #7                  // class java/lang/String
      14: astore_1
      15: getstatic     #9                  // Field java/lang/System.out:Ljava/io/PrintStream;
      18: aload_1
      19: invokevirtual #10                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      22: return

Notice that there is an invokevirtual instruction in the convertInstanceOfObject method that calls Class.cast() method which throws ClassCastException which will be catch by the catch(ClassCastException e) bock and return null; hence, "null" is printed to console without any exception.

Get selected value from combo box in C# WPF

Well.. I found a simpler solution.

String s = comboBox1.Text;

This way I get the selected value as string.

How to include *.so library in Android Studio?

Current Solution

Create the folder project/app/src/main/jniLibs, and then put your *.so files within their abi folders in that location. E.g.,

project/
+--libs/
|  +-- *.jar       <-- if your library has jar files, they go here
+--src/
   +-- main/
       +-- AndroidManifest.xml
       +-- java/
       +-- jniLibs/ 
           +-- arm64-v8a/                       <-- ARM 64bit
           ¦   +-- yourlib.so
           +-- armeabi-v7a/                     <-- ARM 32bit
           ¦   +-- yourlib.so
           +-- x86/                             <-- Intel 32bit
               +-- yourlib.so

Deprecated solution

Add both code snippets in your module gradle.build file as a dependency:

compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

How to create this custom jar:

task nativeLibsToJar(type: Jar, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}

Same answer can also be found in related question: Include .so library in apk in android studio

Empty brackets '[]' appearing when using .where

You can use the lower function:

Guide.where("lower(title)='attack'") 

As a comment: Work on your question. The title isn't terribly informative, and you drop a big chunk of code at the end that is irrelevant to your question.

Disable a link in Bootstrap

I think you need the btn class.
It would be like this:

<a class="btn disabled" href="#">Disabled link</a>

How do I restart a program based on user input?

Using one while loop:

In [1]: start = 1
   ...: 
   ...: while True:
   ...:     if start != 1:        
   ...:         do_run = raw_input('Restart?  y/n:')
   ...:         if do_run == 'y':
   ...:             pass
   ...:         elif do_run == 'n':
   ...:             break
   ...:         else: 
   ...:             print 'Invalid input'
   ...:             continue
   ...: 
   ...:     print 'Doing stuff!!!'
   ...: 
   ...:     if start == 1:
   ...:         start = 0
   ...:         
Doing stuff!!!

Restart?  y/n:y
Doing stuff!!!

Restart?  y/n:f
Invalid input

Restart?  y/n:n

In [2]:

Detect if the device is iPhone X

SWIFT 4/5 reusable extension with iPhone 12 support

    extension UIDevice {
    
    enum `Type` {
        case iPhone_5_5S_5C_SE1
        case iPhone_6_6S_7_8_SE2
        case iPhone_6_6S_7_8_PLUS
        case iPhone_X_XS_12mini
        case iPhone_XR_11
        case iPhone_XS_11Pro_Max
        case iPhone_12_Pro
        case iPhone_12_Pro_Max
    }
    
    var hasHomeButton: Bool {
        switch type {
        case . iPhone_X_XS_12mini, . iPhone_XR_11, .iPhone_XS_11Pro_Max, . iPhone_XS_11Pro_Max, .iPhone_12_Pro, .iPhone_12_Pro_Max:
            return false
        default:
            return true
        }
    }
    
    var type: Type {
        if UI_USER_INTERFACE_IDIOM() == .phone {
        switch UIScreen.main.nativeBounds.height {
        case 1136:
            return .iPhone_5_5S_5C_SE1
        case 1334:
            return .iPhone_6_6S_7_8_SE2
        case 1920, 2208:
            return .iPhone_6_6S_7_8_PLUS
        case 2436:
            return .iPhone_X_XS_12mini
        case 2532:
            return .iPhone_12_Pro
        case 2688:
            return .iPhone_XS_11Pro_Max
        case 2778:
            return .iPhone_12_Pro_Max
        case 1792:
            return .iPhone_XR_11
        default:
            assertionFailure("Unknown phone device detected!")
            return .iPhone_6_6S_7_8_SE2
        }
    } else {
        assertionFailure("Unknown idiom device detected!")
        return .iPhone_6_6S_7_8_SE2
    }
   }
}

How to use absolute path in twig functions

The following works for me:

<img src="{{ asset('bundle/myname/img/image.gif', null, true) }}" />

Load JSON text into class object in c#

To create a json class off a string, copy the string.

In Visual Sudio, click Edit > Paste special > Paste Json as classes.

Validate fields after user has left a field

Regarding @lambinator's solution... I was getting the following error in angular.js 1.2.4:

Error: [$rootScope:inprog] $digest already in progress

I'm not sure if I did something wrong or if this is a change in Angular, but removing the scope.$apply statements resolved the problem and the classes/states are still getting updated.

If you are also seeing this error, give the following a try:

var blurFocusDirective = function () {
  return {
    restrict: 'E',
    require: '?ngModel',
    link: function (scope, elm, attr, ctrl) {
      if (!ctrl) {
        return;
      }
      elm.on('focus', function () {
        elm.addClass('has-focus');
        ctrl.$hasFocus = true;
      });

      elm.on('blur', function () {
        elm.removeClass('has-focus');
        elm.addClass('has-visited');
        ctrl.$hasFocus = false;
        ctrl.$hasVisited = true;
      });

      elm.closest('form').on('submit', function () {
        elm.addClass('has-visited');

        scope.$apply(function () {
          ctrl.hasFocus = false;
          ctrl.hasVisited = true;
        });
      });
    }
  };
};
app.directive('input', blurFocusDirective);
app.directive('select', blurFocusDirective);

Postgresql, update if row with some unique value exists, else insert

If INSERTS are rare, I would avoid doing a NOT EXISTS (...) since it emits a SELECT on all updates. Instead, take a look at wildpeaks answer: https://dba.stackexchange.com/questions/5815/how-can-i-insert-if-key-not-exist-with-postgresql

CREATE OR REPLACE FUNCTION upsert_tableName(arg1 type, arg2 type) RETURNS VOID AS $$ 
    DECLARE 
    BEGIN 
        UPDATE tableName SET col1 = value WHERE colX = arg1 and colY = arg2; 
        IF NOT FOUND THEN 
        INSERT INTO tableName values (value, arg1, arg2); 
        END IF; 
    END; 
    $$ LANGUAGE 'plpgsql'; 

This way Postgres will initially try to do a UPDATE. If no rows was affected, it will fall back to emitting an INSERT.

Any way to clear python's IDLE window?

ctrl + L clears the screen on Ubuntu Linux.

Getting the PublicKeyToken of .Net assemblies

Open a command prompt and type one of the following lines according to your Visual Studio version and Operating System Architecture :

VS 2008 on 32bit Windows :

"%ProgramFiles%\Microsoft SDKs\Windows\v6.0A\bin\sn.exe" -T <assemblyname>

VS 2008 on 64bit Windows :

"%ProgramFiles(x86)%\Microsoft SDKs\Windows\v6.0A\bin\sn.exe" -T <assemblyname>

VS 2010 on 32bit Windows :

"%ProgramFiles%\Microsoft SDKs\Windows\v7.0A\bin\sn.exe" -T <assemblyname>

VS 2010 on 64bit Windows :

"%ProgramFiles(x86)%\Microsoft SDKs\Windows\v7.0A\bin\sn.exe" -T <assemblyname>

VS 2012 on 32bit Windows :

"%ProgramFiles%\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\sn.exe" -T <assemblyname>

VS 2012 on 64bit Windows :

"%ProgramFiles(x86)%\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\sn.exe" -T <assemblyname>

VS 2015 on 64bit Windows :

"%ProgramFiles(x86)%\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\sn.exe" -T <assemblyname>

Note that for the versions VS2012+, sn.exe application isn't anymore in bin but in a sub-folder. Also, note that for 64bit you need to specify (x86) folder.

If you prefer to use Visual Studio command prompt, just type :

sn -T <assembly> 

where <assemblyname> is a full file path to the assembly you're interested in, surrounded by quotes if it has spaces.

You can add this as an external tool in VS, as shown here:
http://blogs.msdn.com/b/miah/archive/2008/02/19/visual-studio-tip-get-public-key-token-for-a-stong-named-assembly.aspx

ssh : Permission denied (publickey,gssapi-with-mic)

Nobody has mention this in. above answers so i am mentioning it.

This error can also come if you're in the wrong folder or path of your pem file is not correct. I was having similar issue and found that my pem file was not there from where i am executing the ssh command

cd KeyPair
ssh -i Keypair.pem [email protected]

Add single element to array in numpy

This might be a bit overkill, but I always use the the np.take function for any wrap-around indexing:

>>> a = np.array([1, 2, 3])
>>> np.take(a, range(0, len(a)+1), mode='wrap')
array([1, 2, 3, 1])

>>> np.take(a, range(-1, len(a)+1), mode='wrap')
array([3, 1, 2, 3, 1])

How to script FTP upload and download?

I had this same issue, and solved it with a solution similar to what Cheeso provided, above.

"doesn't work, says password is srequire, tried it a couple different ways "

Yep, that's because FTP sessions via a command file don't require the username to be prefaced with the string "user". Drop that, and try it.

Or, you could be seeing this because your FTP command file is not properly encoded (that bit me, too). That's the crappy part about generating a FTP command file at runtime. Powershell's out-file cmdlet does not have an encoding option that Windows FTP will accept (at least not one that I could find).

Regardless, as doing a WebClient.DownloadFile is the way to go.

What is an optional value in Swift?

When i started to learn Swift it was very difficult to realize why optional.

Lets think in this way. Let consider a class Person which has two property name and company.

class Person: NSObject {
    
    var name : String //Person must have a value so its no marked as optional
    var companyName : String? ///Company is optional as a person can be unemployed that is nil value is possible
    
    init(name:String,company:String?) {
        
        self.name = name
        self.companyName = company
        
    }
}

Now lets create few objects of Person

var tom:Person = Person.init(name: "Tom", company: "Apple")//posible
var bob:Person = Person.init(name: "Bob", company:nil) // also Possible because company is marked as optional so we can give Nil

But we can not pass Nil to name

var personWithNoName:Person = Person.init(name: nil, company: nil)

Now Lets talk about why we use optional?. Lets consider a situation where we want to add Inc after company name like apple will be apple Inc. We need to append Inc after company name and print.

print(tom.companyName+" Inc") ///Error saying optional is not unwrapped.
print(tom.companyName!+" Inc") ///Error Gone..we have forcefully unwrap it which is wrong approach..Will look in Next line
print(bob.companyName!+" Inc") ///Crash!!!because bob has no company and nil can be unwrapped.

Now lets study why optional takes into place.

if let companyString:String = bob.companyName{///Compiler safely unwrap company if not nil.If nil,no unwrap.
    
    print(companyString+" Inc") //Will never executed and no crash!!!
}

Lets replace bob with tom

if let companyString:String = tom.companyName{///Compiler safely unwrap company if not nil.If nil,no unwrap.
    
    print(companyString+" Inc") //Will executed and no crash!!!
}

And Congratulation! we have properly deal with optional?

So the realization points are

  1. We will mark a variable as optional if its possible to be nil
  2. If we want to use this variable somewhere in code compiler will remind you that we need to check if we have proper deal with that variable if it contain nil.

Thank you...Happy Coding

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

Batch command to move files to a new directory

Something like this might help:

SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=

The important part is the first line. It takes the output of the internal DATE value and parses it into an environmental variable named Today, in the format CCYYMMDD, as in '20110407`.

The %Date:~10,4% says to extract a *substring of the Date environmental variable 'Thu 04/07/2011' (built in - type echo %Date% at a command prompt) starting at position 10 for 4 characters (2011). It then concatenates another substring of Date: starting at position 4 for 2 chars (04), and then concats two additional characters starting at position 7 (07).

*The substring value starting points are 0-based.

You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

Closing Twitter Bootstrap Modal From Angular Controller

You can do it like this:

angular.element('#modal').modal('hide');

How to set HTTP headers (for cache-control)?

This is the best .htaccess I have used in my actual website:

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

##Tweaks##
Header set X-Frame-Options SAMEORIGIN

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##

<IfModule mod_headers.c>
    Header set Connection keep-alive
    <filesmatch "\.(ico|flv|gif|swf|eot|woff|otf|ttf|svg)$">
        Header set Cache-Control "max-age=2592000, public"
    </filesmatch>
    <filesmatch "\.(jpg|jpeg|png)$">
        Header set Cache-Control "max-age=1209600, public"
    </filesmatch>
    # css and js should use private for proxy caching https://developers.google.com/speed/docs/best-practices/caching#LeverageProxyCaching
    <filesmatch "\.(css)$">
        Header set Cache-Control "max-age=31536000, private"
    </filesmatch>
    <filesmatch "\.(js)$">
        Header set Cache-Control "max-age=1209600, private"
    </filesmatch>
    <filesMatch "\.(x?html?|php)$">
        Header set Cache-Control "max-age=600, private, must-revalidate"
      </filesMatch>
</IfModule>

Using Panel or PlaceHolder

I weird bug* in visual studio 2010, if you put controls inside a Placeholder it does not render them in design view mode.

This is especially true for Hidenfields and Empty labels.

I would love to use placeholders instead of panels but I hate the fact I cant put other controls inside placeholders at design time in the GUI.

Focus Input Box On Load

very simple one line solution:

<body onLoad="document.getElementById('myinputbox').focus();">

How to execute two mysql queries as one in PHP/MYSQL?

Using SQL_CALC_FOUND_ROWS you can't.

The row count available through FOUND_ROWS() is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS statement.

As someone noted in your earlier question, using SQL_CALC_FOUND_ROWS is frequently slower than just getting a count.

Perhaps you'd be best off doing this as as subquery:

SELECT 
 (select count(*) from my_table WHERE Name LIKE '%prashant%') 
as total_rows,
Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;

undefined offset PHP error

How to reproduce this error in PHP:

Create an empty array and ask for the value given a key like this:

php> $foobar = array();

php> echo gettype($foobar);
array

php> echo $foobar[0];

PHP Notice:  Undefined offset: 0 in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) : 
eval()'d code on line 1

What happened?

You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.

It looked for your key in the array, and found undefined.

How to make the error not happen?

Ask if the key exists first before you go asking for its value.

php> echo array_key_exists(0, $foobar) == false;
1

If the key exists, then get the value, if it doesn't exist, no need to query for its value.

PHP to search within txt file and echo the whole line

looks like you're better off systeming out to system("grep \"$QUERY\"") since that script won't be particularly high performance either way. Otherwise http://php.net/manual/en/function.file.php shows you how to loop over lines and you can use http://php.net/manual/en/function.strstr.php for finding matches.

How to run a program automatically as admin on Windows 7 at startup?

schtasks /create /sc onlogon /tn MyProgram /rl highest /tr "exeFullPath"

Curl not recognized as an internal or external command, operable program or batch file

Here you can find the direct download link for Curl.exe

I was looking for the download process of Curl and every where they said copy curl.exe file in System32 but they haven't provided the direct link but after digging little more I Got it. so here it is enjoy, find curl.exe easily in bin folder just

unzip it and then go to bin folder there you get exe file

link to download curl generic

Detect & Record Audio in Python

You might want to look at csounds, also. It has several API's, including Python. It might be able to interact with an A-D interface and gather sound samples.

How can I brew link a specific version?

brew switch libfoo mycopy

You can use brew switch to switch between versions of the same package, if it's installed as versioned subdirectories under Cellar/<packagename>/

This will list versions installed ( for example I had Cellar/sdl2/2.0.3, I've compiled into Cellar/sdl2/2.0.4)

brew info sdl2

Then to switch between them

brew switch sdl2 2.0.4
brew info 

Info now shows * next to the 2.0.4

To install under Cellar/<packagename>/<version> from source you can do for example

cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make

check where it gets installed with

make install -n

if all looks correct

make install

Then from cd $(brew --Cellar) do the switch between version.

I'm using brew version 0.9.5

Random character generator with a range of (A..Z, 0..9) and punctuation

You should first make a String that holds all of the letters/numbers that you want.
Then, make a Random. e. g. Random rnd = new Random;
Finally, make something that actually gets a random character from your String containing your alphabet.
For example,

import java.util.Random;

public class randomCharacter {
    public static void main(String[] args) {
        String alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ?/.,";
        Random rnd = new Random();
        char char = alphabet.charAt(rnd.nextInt(alphabet.length()));
        // do whatever you want with the character
    }
}

See this.
It's where I got this info from.

Difference between Static and final?

I won't try to give a complete answer here. My recommendation would be to focus on understanding what each one of them does and then it should be cleare to see that their effects are completely different and why sometimes they are used together.

static is for members of a class (attributes and methods) and it has to be understood in contrast to instance (non static) members. I'd recommend reading "Understanding Instance and Class Members" in The Java Tutorials. I can also be used in static blocks but I would not worry about it for a start.

final has different meanings according if its applied to variables, methods, classes or some other cases. Here I like Wikipedia explanations better.

What is the correct wget command syntax for HTTPS with username and password?

By specifying the option --user and --ask-password wget will ask for the credentials. Below is an example. Change the username and download link to your needs.

wget --user=username --ask-password https://xyz.com/changelog-6.40.txt

Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView

This error can be thrown when you import a different library for @Id than Javax.persistance.Id ; You might need to pay attention this case too

In my case I had

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;

import org.springframework.data.annotation.Id;

@Entity
public class Status {

    @Id
    @GeneratedValue
    private int id;

when I change the code like this, it got worked

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;

import javax.persistence.Id;

@Entity
public class Status {

    @Id
    @GeneratedValue
    private int id;

Received fatal alert: handshake_failure through SSLHandshakeException

The handshake failure could be a buggy TLSv1 protocol implementation.

In our case this helped with java 7:

java -Dhttps.protocols=TLSv1.2,TLSv1.1,TLSv1 

The jvm will negotiate in this order. The servers with the latest update will do 1.2, the buggy ones will go down to v1 and that works with the similar v1 in java 7.

Remove multiple items from a Python list in just one statement

You can use filterfalse function from itertools module

Example

import random
from itertools import filterfalse

random.seed(42)

data = [random.randrange(5) for _ in range(10)]
clean = [*filterfalse(lambda i: i == 0, data)]
print(f"Remove 0s\n{data=}\n{clean=}\n")


clean = [*filterfalse(lambda i: i in (0, 1), data)]
print(f"Remove 0s and 1s\n{data=}\n{clean=}")

Output:

Remove 0s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 1, 1, 1, 4, 4]

Remove 0s and 1s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 4, 4]

What do 3 dots next to a parameter type mean in Java?

That feature is called varargs, and it's a feature introduced in Java 5. It means that function can receive multiple String arguments:

myMethod("foo", "bar");
myMethod("foo", "bar", "baz");
myMethod(new String[]{"foo", "var", "baz"}); // you can even pass an array

Then, you can use the String var as an array:

public void myMethod(String... strings){
    for(String whatever : strings){
        // do what ever you want
    }

    // the code above is equivalent to
    for( int i = 0; i < strings.length; i++){
        // classical for. In this case you use strings[i]
    }
}

This answer borrows heavily from kiswa's and Lorenzo's... and also from Graphain's comment.

Import cycle not allowed

I just encountered this. You may be accessing a method/type from within the same package using the package name itself.

Here is an example to illustrate what I mean:

In foo.go:

// foo.go
package foo

func Foo() {...}

In foo_test.go:

// foo_test.go
package foo

// try to access Foo()
foo.Foo() // WRONG <== This was the issue. You are already in package foo, there is no need to use foo.Foo() to access Foo()
Foo() // CORRECT

How to close form

Your closing your instance of the settings window right after you create it. You need to display the settings window first then wait for a dialog result. If it comes back as canceled then close the window. For Example:

private void button1_Click(object sender, EventArgs e)
{
    Settings newSettingsWindow = new Settings();

    if (newSettingsWindow.ShowDialog() == DialogResult.Cancel)
    {
        newSettingsWindow.Close();
    }
}

Can't create handler inside thread that has not called Looper.prepare()

This usually happens when something on the main thread is called from any background thread. Lets look at an example , for instance.

private class MyTask extends AsyncTask<Void, Void, Void> {


@Override
protected Void doInBackground(Void... voids) {
        textView.setText("Any Text");
        return null;
    }
}

In the above example , we are setting text on the textview which is in the main UI thread from doInBackground() method , which operates only on a worker thread.

In bootstrap how to add borders to rows without adding up?

You can remove the border from top if the element is sibling of the row . Add this to css :

.row + .row {
   border-top:0;
}

Here is the link to the fiddle http://jsfiddle.net/7cb3Y/3/

Get a random boolean in python?

Found a faster method:

$ python -m timeit -s "from random import getrandbits" "not getrandbits(1)"
10000000 loops, best of 3: 0.222 usec per loop
$ python -m timeit -s "from random import random" "True if random() > 0.5 else False"
10000000 loops, best of 3: 0.0786 usec per loop
$ python -m timeit -s "from random import random" "random() > 0.5"
10000000 loops, best of 3: 0.0579 usec per loop

How do you convert WSDLs to Java classes using Eclipse?

I wouldn't suggest using the Eclipse tool to generate the WS Client because I had bad experience with it:

I am not really sure if this matters but I had to consume a WS written in .NET. When I used the Eclipse's "New Web Service Client" tool it generated the Java classes using Axis (version 1.x) which as you can check is old (last version from 2006). There is a newer version though that is has some major changes but Eclipse doesn't use it.

Why the old version of Axis matters you'll say? Because when using OpenJDK you can run into some problems like missing cryptography algorithms in OpenJDK that are presented in the Oracle's JDK and some libraries like this one depend on them.

So I just used the wsimport tool and ended my headaches.

How to get time (hour, minute, second) in Swift 3 using NSDate?

swift 4

==> Getting iOS device current time:-

print(" ---> ",(Calendar.current.component(.hour, from: Date())),":",
               (Calendar.current.component(.minute, from: Date())),":",
               (Calendar.current.component(.second, from: Date())))

output: ---> 10 : 11: 34

How can I format a String number to have commas and round?

You might want to look at the DecimalFormat class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57 instead).

You also need to convert that string into a number, this can be done with:

double amount = Double.parseDouble(number);

Code sample:

String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");

System.out.println(formatter.format(amount));

Use a.empty, a.bool(), a.item(), a.any() or a.all()

solution is easy:

replace

 mask = (50  < df['heart rate'] < 101 &
            140 < df['systolic blood pressure'] < 160 &
            90  < df['dyastolic blood pressure'] < 100 &
            35  < df['temperature'] < 39 &
            11  < df['respiratory rate'] < 19 &
            95  < df['pulse oximetry'] < 100
            , "excellent", "critical")

by

mask = ((50  < df['heart rate'] < 101) &
        (140 < df['systolic blood pressure'] < 160) &
        (90  < df['dyastolic blood pressure'] < 100) &
        (35  < df['temperature'] < 39) &
        (11  < df['respiratory rate'] < 19) &
        (95  < df['pulse oximetry'] < 100)
        , "excellent", "critical")

Cordova - Error code 1 for command | Command failed for

I found answer myself; and if someone will face same issue, i hope my solution will work for them as well.

  • Downgrade NodeJs to 0.10.36
  • Upgrade Android SDK 22

Which version of CodeIgniter am I currently using?

Look for define in system/core/CodeIgniter.php:

define('CI_VERSION', '3.1.8');

How to get ID of button user just clicked?

You can also try this simple one-liner code. Just call the alert method on onclick attribute.

<button id="some_id1" onclick="alert(this.id)"></button>

View contents of database file in Android Studio

I'm actually very surprised that no one has given this solution:

Take a look at Stetho.

I've used Stetho on several occasions for different purposes (one of them being database inspection). On the actual website, they also talk about features for network inspection and looking through the view hierarchy.

It only requires a little setup: 1 gradle dependency addition (which you can comment out for production builds), a few lines of code to instantiate Stetho, and a Chrome browser (because it uses Chrome devtools for everything).

Update: You can now use Stetho to view Realm files (if you're using Realm instead of an SQLite DB): https://github.com/uPhyca/stetho-realm

Update #2: You can now use Stetho to view Couchbase documents: https://github.com/RobotPajamas/Stetho-Couchbase

Update #3: Facebook is focusing efforts on adding all Stetho features into its new tool, Flipper. Flipper already has many of the features that Stetho has. So, now may be a good time to make the switch. https://fbflipper.com/docs/stetho.html

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

data = "abcdefg hi j 12345"

digits_count = 0
letters_count = 0
others_count = 0

for i in userinput:

    if i.isdigit():
        digits_count += 1 
    elif i.isalpha():
        letters_count += 1
    else:
        others_count += 1

print("Result:")        
print("Letters=", letters_count)
print("Digits=", digits_count)

Output:

Please Enter Letters with Numbers:
abcdefg hi j 12345
Result:
Letters = 10
Digits = 5

By using str.isalpha() you can check if it is a letter.

Reading DataSet

DataSet resembles database. DataTable resembles database table, and DataRow resembles a record in a table. If you want to add filtering or sorting options, you then do so with a DataView object, and convert it back to a separate DataTable object.

If you're using database to store your data, then you first load a database table to a DataSet object in memory. You can load multiple database tables to one DataSet, and select specific table to read from the DataSet through DataTable object. Subsequently, you read a specific row of data from your DataTable through DataRow. Following codes demonstrate the steps:

SqlCeDataAdapter da = new SqlCeDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();

da.SelectCommand = new SqlCommand(@"SELECT * FROM FooTable", connString);
da.Fill(ds, "FooTable");
dt = ds.Tables["FooTable"];

foreach (DataRow dr in dt.Rows)
{
    MessageBox.Show(dr["Column1"].ToString());
}

To read a specific cell in a row:

int rowNum // row number
string columnName = "DepartureTime";  // database table column name
dt.Rows[rowNum][columnName].ToString();

How can I change the color of a Google Maps marker?

enter image description here enter image description here Material Design

EDITED MARCH 2019 now with programmatic pin color,

PURE JAVASCRIPT, NO IMAGES, SUPPORTS LABELS

no longer relies on deprecated Charts API

    var pinColor = "#FFFFFF";
    var pinLabel = "A";

    // Pick your pin (hole or no hole)
    var pinSVGHole = "M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z";
    var labelOriginHole = new google.maps.Point(12,15);
    var pinSVGFilled = "M 12,2 C 8.1340068,2 5,5.1340068 5,9 c 0,5.25 7,13 7,13 0,0 7,-7.75 7,-13 0,-3.8659932 -3.134007,-7 -7,-7 z";
    var labelOriginFilled =  new google.maps.Point(12,9);


    var markerImage = {  // https://developers.google.com/maps/documentation/javascript/reference/marker#MarkerLabel
        path: pinSVGFilled,
        anchor: new google.maps.Point(12,17),
        fillOpacity: 1,
        fillColor: pinColor,
        strokeWeight: 2,
        strokeColor: "white",
        scale: 2,
        labelOrigin: labelOriginFilled
    };
    var label = {
        text: pinLabel,
        color: "white",
        fontSize: "12px",
    }; // https://developers.google.com/maps/documentation/javascript/reference/marker#Symbol
    this.marker        = new google.maps.Marker({
        map: map.MapObject,
        //OPTIONAL: label: label,
        position: this.geographicCoordinates,
        icon: markerImage,
        //OPTIONAL: animation: google.maps.Animation.DROP,
    });

SQL Query to find the last day of the month

SQL Server 2012 introduces the eomonth function:

select eomonth('2013-05-31 00:00:00:000')
-->
2013-05-31

Initializing IEnumerable<string> In C#

IEnumerable is just an interface and so can't be instantiated directly.

You need to create a concrete class (like a List)

IEnumerable<string> m_oEnum = new List<string>() { "1", "2", "3" };

you can then pass this to anything expecting an IEnumerable.

" app-release.apk" how to change this default generated apk name

My solution may also be of help to someone.

Tested and Works on IntelliJ 2017.3.2 with Gradle 4.4

Scenario:

I have 2 flavours in my application, and so I wanted each release to be named appropriately according to each flavor.

The code below will be placed into your module gradle build file found in:

{app-root}/app/build.gradle

Gradle code to be added to android{ } block:

android {
    // ...

    defaultConfig {
        versionCode 10
        versionName "1.2.3_build5"
    }

    buildTypes {
        // ...

        release {
            // ...

            applicationVariants.all { 
                variant.outputs.each { output ->
                    output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace(output.outputFile.name, variant.flavorName + "-" + defaultConfig.versionName + "_v" + defaultConfig.versionCode + ".apk"))
                }
            }

        }
    }

    productFlavors {
        myspicyflavor {
            applicationIdSuffix ".MySpicyFlavor"
            signingConfig signingConfigs.debug
        }

        mystandardflavor {
            applicationIdSuffix ".MyStandardFlavor"
            signingConfig signingConfigs.config
        }
    }
}

The above provides the following APKs found in {app-root}/app/:

myspicyflavor-release-1.2.3_build5_v10.apk
mystandardflavor-release-1.2.3_build5_v10.apk

Hope it can be of use to someone.

For more info, see other answers mentioned in the question

Why does sed not replace all occurrences?

You should add the g modifier so that sed performs a global substitution of the contents of the pattern buffer:

echo dog dog dos | sed -e 's:dog:log:g'

For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6

The official documentation for GNU sed is available at http://www.gnu.org/software/sed/manual/

What does if __name__ == "__main__": do?

The code under if __name__ == '__main__': will be executed only if the module is invoked as a script.

As an example consider the following module my_test_module.py:

# my_test_module.py

print('This is going to be printed out, no matter what')

if __name__ == '__main__':
    print('This is going to be printed out, only if user invokes the module as a script')

1st possibility: Import my_test_module.py in another module

# main.py

import my_test_module

if __name__ == '__main__':
    print('Hello from main.py')

Now if you invoke main.py:

python main.py 

>> 'This is going to be printed out, no matter what'
>> 'Hello from main.py'

Note that only the top-level print() statement in my_test_module is executed.


2nd possibility: Invoke my_test_module.py as a script

Now if you run my_test_module.py as a Python script, both print() statements will be exectued:

python my_test_module.py

>>> 'This is going to be printed out, no matter what'
>>> 'This is going to be printed out, only if user invokes the module as a script'

For a more comprehensive explanation you can read this blog post.

Maximum number of threads per process in Linux?

Linux doesn't have a separate threads per process limit, just a limit on the total number of processes on the system (threads are essentially just processes with a shared address space on Linux) which you can view like this:

cat /proc/sys/kernel/threads-max

The default is the number of memory pages/4. You can increase this like:

echo 100000 > /proc/sys/kernel/threads-max

There is also a limit on the number of processes (and hence threads) that a single user may create, see ulimit/getrlimit for details regarding these limits.

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

You can use the template syntax of ngFor on groups and the usual syntax inside it for the actual rows like:

<table>
  <template let-group ngFor [ngForOf]="groups">
    <tr *ngFor="let row of group.items">{{row}}</tr>
  </template>
</table>

Check this plunk

Get just the filename from a path in a Bash script

Here is an easy way to get the file name from a path:

echo "$PATH" | rev | cut -d"/" -f1 | rev

To remove the extension you can use, assuming the file name has only ONE dot (the extension dot):

cut -d"." -f1

JDK was not found on the computer for NetBeans 6.5

For Netbeans 9.0

1)open netbeans.conf file using notepad inside etc folder

2)Search "netbeans_jdkhome" line and uncomment it by removing '#' from start

3)locate your jdk and replace file path

For example

enter image description here

Anaconda Installed but Cannot Launch Navigator

Try restarting the system! You will be able to find the navigator once you restart the system after installation.

jQuery addClass onClick

$(document).ready(function() {
    $('#Button').click(function() {
        $(this).addClass('active');
    });
});

should do the trick. unless you're loading the button with ajax. In which case you could do:

$('#Button').live('click', function() {...

Also remember not to use the same id more than once in your html code.

pyplot scatter plot marker size

This can be a somewhat confusing way of defining the size but you are basically specifying the area of the marker. This means, to double the width (or height) of the marker you need to increase s by a factor of 4. [because A = WH => (2W)(2H)=4A]

There is a reason, however, that the size of markers is defined in this way. Because of the scaling of area as the square of width, doubling the width actually appears to increase the size by more than a factor 2 (in fact it increases it by a factor of 4). To see this consider the following two examples and the output they produce.

# doubling the width of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*4**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()

gives

enter image description here

Notice how the size increases very quickly. If instead we have

# doubling the area of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*2**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()

gives

enter image description here

Now the apparent size of the markers increases roughly linearly in an intuitive fashion.

As for the exact meaning of what a 'point' is, it is fairly arbitrary for plotting purposes, you can just scale all of your sizes by a constant until they look reasonable.

Hope this helps!

Edit: (In response to comment from @Emma)

It's probably confusing wording on my part. The question asked about doubling the width of a circle so in the first picture for each circle (as we move from left to right) it's width is double the previous one so for the area this is an exponential with base 4. Similarly the second example each circle has area double the last one which gives an exponential with base 2.

However it is the second example (where we are scaling area) that doubling area appears to make the circle twice as big to the eye. Thus if we want a circle to appear a factor of n bigger we would increase the area by a factor n not the radius so the apparent size scales linearly with the area.

Edit to visualize the comment by @TomaszGandor:

This is what it looks like for different functions of the marker size:

Exponential, Square, or Linear size

x = [0,2,4,6,8,10,12,14,16,18]
s_exp = [20*2**n for n in range(len(x))]
s_square = [20*n**2 for n in range(len(x))]
s_linear = [20*n for n in range(len(x))]
plt.scatter(x,[1]*len(x),s=s_exp, label='$s=2^n$', lw=1)
plt.scatter(x,[0]*len(x),s=s_square, label='$s=n^2$')
plt.scatter(x,[-1]*len(x),s=s_linear, label='$s=n$')
plt.ylim(-1.5,1.5)
plt.legend(loc='center left', bbox_to_anchor=(1.1, 0.5), labelspacing=3)
plt.show()

Simple excel find and replace for formulas

If the formulas are identical you can use Find and Replace with Match entire cell contents checked and Look in: Formulas. Select the range, go into Find and Replace, make your entries and `Replace All.

enter image description here

Or do you mean that there are several formulas with this same form, but different cell references? If so, then one way to go is a regular expression match and replace. Regular expressions are not built into Excel (or VBA), but can be accessed via Microsoft's VBScript Regular Expressions library.

The following function provides the necessary match and replace capability. It can be used in a subroutine that would identify cells with formulas in the specified range and use the formulas as inputs to the function. For formulas strings that match the pattern you are looking for, the function will produce the replacement formula, which could then be written back to the worksheet.

Function RegexFormulaReplace(formula As String)
    Dim regex As New RegExp
    regex.Pattern = "=\(\(([A-Z]+\d+)-([A-Z]+\d+)\)/([A-Z]+\d+)\)"
'   Test if a match is found
    If regex.Test(formula) = True Then
        RegexFormulaReplace = regex.Replace(formula, "=(EXP((LN($1/$2)/14.32))-1")
    Else
        RegexFormulaReplace = CVErr(xlErrValue)
    End If
    Set regex = Nothing
End Function

In order for the function to work, you would need to add a reference to the Microsoft VBScript Regular Expressions 5.5 library. From the Developer tab of the main ribbon, select VBA and then References from the main toolbar. Scroll down to find the reference to the library and check the box next to it.

How to add an item to an ArrayList in Kotlin?

If you want to specifically use java ArrayList then you can do something like this:

fun initList(){
    val list: ArrayList<String> = ArrayList()
    list.add("text")
    println(list)
}

Otherwise @guenhter answer is the one you are looking for.

Angular2 Routing with Hashtag to page anchor

A little late but here's an answer I found that works:

<a [routerLink]="['/path']" fragment="test" (click)="onAnchorClick()">Anchor</a>

And in the component:

constructor( private route: ActivatedRoute, private router: Router ) {}

  onAnchorClick ( ) {
    this.route.fragment.subscribe ( f => {
      const element = document.querySelector ( "#" + f )
      if ( element ) element.scrollIntoView ( element )
    });
  }

The above doesn't automatically scroll to the view if you land on a page with an anchor already, so I used the solution above in my ngInit so that it could work with that as well:

ngOnInit() {
    this.router.events.subscribe(s => {
      if (s instanceof NavigationEnd) {
        const tree = this.router.parseUrl(this.router.url);
        if (tree.fragment) {
          const element = document.querySelector("#" + tree.fragment);
          if (element) { element.scrollIntoView(element); }
        }
      }
    });
  }

Make sure to import Router, ActivatedRoute and NavigationEnd at the beginning of your component and it should be all good to go.

Source

How to return a file using Web API?

Just a note for .Net Core: We can use the FileContentResult and set the contentType to application/octet-stream if we want to send the raw bytes. Example:

[HttpGet("{id}")]
public IActionResult GetDocumentBytes(int id)
{
    byte[] byteArray = GetDocumentByteArray(id);
    return new FileContentResult(byteArray, "application/octet-stream");
}

How can I add (simple) tracing in C#?

DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).

There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.

CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener

How to predict input image using trained model in Keras?

That's because you're getting the numeric value associated with the class. For example if you have two classes cats and dogs, Keras will associate them numeric values 0 and 1. To get the mapping between your classes and their associated numeric value, you can use

>>> classes = train_generator.class_indices    
>>> print(classes)
    {'cats': 0, 'dogs': 1}

Now you know the mapping between your classes and indices. So now what you can do is

if classes[0][0] == 1: prediction = 'dog' else: prediction = 'cat'

Way to insert text having ' (apostrophe) into a SQL table

In SQL, the way to do this is to double the apostrophe:

'he doesn''t work for me'

If you are doing this programmatically, you should use an API that accepts parameters and escapes them for you, like prepared statements or similar, rather that escaping and using string concatenation to assemble a query.

Removing character in list of strings

Here's a short one-liner using regular expressions:

print [re.compile(r"8").sub("", m) for m in mylist]

If we separate the regex operations and improve the namings:

pattern = re.compile(r"8") # Create the regular expression to match
res = [pattern.sub("", match) for match in mylist] # Remove match on each element
print res

Blur the edges of an image or background image with CSS

If what you're looking for is simply to blur the image edges you can simply use the box-shadow with an inset.

Working example: http://jsfiddle.net/d9Q5H/1/

Screenshot

HTML:

<div class="image-blurred-edge"></div>

CSS

.image-blurred-edge {
    background-image: url('http://lorempixel.com/200/200/city/9');
    width: 200px;
    height: 200px;
    /* you need to match the shadow color to your background or image border for the desired effect*/
    box-shadow: 0 0 8px 8px white inset;
}

How to access local files of the filesystem in the Android emulator?

Update! You can access the Android filesystem via Android Device Monitor. In Android Studio go to Tools >> Android >> Android Device Monitor.

Note that you can run your app in the simulator while using the Android Device Monitor. But you cannot debug you app while using the Android Device Monitor.

Char array in a struct - incompatible assignment?

This has nothing to do with structs - arrays in C are not assignable:

char a[20];
a = "foo";   // error

you need to use strcpy:

strcpy( a, "foo" );

or in your code:

strcpy( sara.first, "Sara" );

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

In Weblogic 9.2 the configuration via console is as follows:

enter image description here

I believe the default value was 60. Remember to use Release Configuration button after you edit the field.

How to use Ajax.ActionLink?

For me this worked after I downloaded AJAX Unobtrusive library via NuGet :

 Search and install via NuGet Packages:   Microsoft.jQuery.Unobtrusive.Ajax

Than add in the view the references to jquery and AJAX Unobtrusive:

@Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"> </script>

How do I write a custom init for a UIView subclass in Swift?

Here is how I do a Subview on iOS in Swift -

class CustomSubview : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        let windowHeight : CGFloat = 150;
        let windowWidth  : CGFloat = 360;

        self.backgroundColor = UIColor.whiteColor();
        self.frame = CGRectMake(0, 0, windowWidth, windowHeight);
        self.center = CGPoint(x: UIScreen.mainScreen().bounds.width/2, y: 375);

        //for debug validation
        self.backgroundColor = UIColor.grayColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

What is the best way to filter a Java Collection?

Java 8 (2014) solves this problem using streams and lambdas in one line of code:

List<Person> beerDrinkers = persons.stream()
    .filter(p -> p.getAge() > 16).collect(Collectors.toList());

Here's a tutorial.

Use Collection#removeIf to modify the collection in place. (Notice: In this case, the predicate will remove objects who satisfy the predicate):

persons.removeIf(p -> p.getAge() <= 16);

lambdaj allows filtering collections without writing loops or inner classes:

List<Person> beerDrinkers = select(persons, having(on(Person.class).getAge(),
    greaterThan(16)));

Can you imagine something more readable?

Disclaimer: I am a contributor on lambdaj

Why do I get a "permission denied" error while installing a gem?

I had the same problem using rvm on Ubuntu, was fixed by setting the source on my terminal as a short-term solution:

source $HOME/.rvm/scripts/rvm

or

source /home/$USER/.rvm/scripts/rvm

and configure a default Ruby Version, 2.3.3 in my case.

rvm use 2.3.3 --default


And a long-term Solution is to add your source to your .bashrc file to permanently make Ubuntu look in .rvm for all the Ruby files.

Add:

source .rvm/scripts/rvm

into

$HOME/.bashrc file.

nodemon not found in npm

--save, -g and changing package.json scripts did not work for me. Here's what did: running npm start (or using npx nodemon) within the command line. I use visual studio code terminal. When it is successful you will see this message:

[nodemon] 1.18.9
[nodemon] to restart at any time, enter rs
[nodemon] watching: .
[nodemon] starting node app.js

Good luck!

Increasing Google Chrome's max-connections-per-server limit to more than 6

There doesn't appear to be an external way to hack the behaviour of the executables.

You could modify the Chrome(ium) executables as this information is obviously compiled in. That approach brings a lot of problems with support and automatic upgrades so you probably want to avoid doing that. You also need to understand how to make the changes to the binaries which is not something most people can pick up in a few days.

If you compile your own browser you are creating a support issue for yourself as you are stuck with a specific revision. If you want to get new features and bug fixes you will have to recompile. All of this involves tracking Chrome development for bugs and build breakages - not something that a web developer should have to do.

I'd follow @BenSwayne's advice for now, but it might be worth thinking about doing some of the work outside of the client (the web browser) and putting it in a background process running on the same or different machines. This process can handle many more connections and you are just responsible for getting the data back from it. Since it is local(ish) you'll get results back quickly even with minimal connections.

Python: Append item to list N times

l = []
x = 0
l.extend([x]*100)

Contains case insensitive

if (referrer.toUpperCase().indexOf("RAL") == -1) { ...

android View not attached to window manager

Another option is not to start the async task until the dialog is attached to the window by overriding onAttachedToWindow() on the dialog, that way it is always dismissible.

Regex: Specify "space or start of string" and "space or end of string"

(^|\s) would match space or start of string and ($|\s) for space or end of string. Together it's:

(^|\s)stackoverflow($|\s)

Setting up and using environment variables in IntelliJ Idea

It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.

In 'Path Variables' create a variable for example ANALYTICS_VERSION.

In a 'Run Configuration' under 'Environment Variables' add for example the following:

ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin

To answer the original question you would need to add an APP_HOME environment variable to your run configuration which references the path variable:

APP_HOME=$APP_HOME$

EXEC sp_executesql with multiple parameters

This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.

DECLARE @Parmdef nvarchar (500)
DECLARE @SQL nvarchar (max)
DECLARE @xTxt1  nvarchar (100) = 'test1'
DECLARE @xTxt2  nvarchar (500) = 'test2' 
SET @parmdef = '@text1 nvarchar (100), @text2 nvarchar (500)'
SET @SQL = 'PRINT @text1 + '' '' + @text2'
EXEC sp_executeSQL @SQL, @Parmdef, @xTxt1, @xTxt2

Laravel: Get base url

You can use facades or helper function as per following.

echo URL::to('/');
echo url();

Laravel using Symfony Component for Request, Laravel internal logic as per following.

namespace Symfony\Component\HttpFoundation;
/**
* {@inheritdoc}
*/
protected function prepareBaseUrl()
{
    $baseUrl = $this->server->get('SCRIPT_NAME');

    if (false === strpos($this->server->get('REQUEST_URI'), $baseUrl)) {
        // assume mod_rewrite
        return rtrim(dirname($baseUrl), '/\\');
    }

    return $baseUrl;
}

How to convert Json array to list of objects in c#

Your data structure and your JSON do not match.

Your JSON is this:

{
    "JsonValues":{
        "id": "MyID",
        ...
    }
}

But the data structure you try to serialize it to is this:

class ValueSet
{
    [JsonProperty("id")]
    public string id
    {
        get;
        set;
    }
    ...
}

You are skipping a step: Your JSON is a class that has one property named JsonValues, which has an object of your ValueSet data structure as value.

Also inside your class your JSON is this:

"values": { ... }

Your data structure is this:

[JsonProperty("values")]
public List<Value> values
{
    get;
    set;
}

Note that { .. } in JSON defines an object, where as [ .. ] defines an array. So according to your JSON you don't have a bunch of values, but you have one values object with the properties value1 and value2 of type Value.

Since the deserializer expects an array but gets an object instead, it does the least non-destructive (Exception) thing it could do: skip the value. Your property values remains with it's default value: null.

If you can: Adjust your JSON. The following would match your data structure and is most likely what you actually want:

{
    "id": "MyID",

     "values": [
         {
            "id": "100",
            "diaplayName": "MyValue1"
         }, {
            "id": "200",
            "diaplayName": "MyValue2"
         }
     ]
}

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

What your missing here is that .Reverse() is a void method. It's not possible to assign the result of .Reverse() to a variable. You can however alter the order to use Enumerable.Reverse() and get your result

var x = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>()

The difference is that Enumerable.Reverse() returns an IEnumerable<T> instead of being void return

JSON to PHP Array using file_get_contents

The JSON sample you provided is not valid. Check it online with this JSON Validator http://jsonlint.com/. You need to remove the extra comma on line 59.

One you have valid json you can use this code to convert it to an array.

json_decode($json, true);

Array
(
    [bpath] => http://www.sampledomain.com/
    [clist] => Array
        (
            [0] => Array
                (
                    [cid] => 11
                    [display_type] => grid
                    [ctitle] => abc
                    [acount] => 71
                    [alist] => Array
                        (
                            [0] => Array
                                (
                                    [aid] => 6865
                                    [adate] => 2 Hours ago
                                    [atitle] => test
                                    [adesc] => test desc
                                    [aimg] => 
                                    [aurl] => ?nid=6865
                                    [weburl] => news.php?nid=6865
                                    [cmtcount] => 0
                                )

                            [1] => Array
                                (
                                    [aid] => 6857
                                    [adate] => 20 Hours ago
                                    [atitle] => test1
                                    [adesc] => test desc1
                                    [aimg] => 
                                    [aurl] => ?nid=6857
                                    [weburl] => news.php?nid=6857
                                    [cmtcount] => 0
                                )

                        )

                )

            [1] => Array
                (
                    [cid] => 1
                    [display_type] => grid
                    [ctitle] => test1
                    [acount] => 2354
                    [alist] => Array
                        (
                            [0] => Array
                                (
                                    [aid] => 6851
                                    [adate] => 1 Days ago
                                    [atitle] => test123
                                    [adesc] => test123 desc
                                    [aimg] => 
                                    [aurl] => ?nid=6851
                                    [weburl] => news.php?nid=6851
                                    [cmtcount] => 7
                                )

                            [1] => Array
                                (
                                    [aid] => 6847
                                    [adate] => 2 Days ago
                                    [atitle] => test12345
                                    [adesc] => test12345 desc
                                    [aimg] => 
                                    [aurl] => ?nid=6847
                                    [weburl] => news.php?nid=6847
                                    [cmtcount] => 7
                                )

                        )

                )

        )

)

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

I hope this helps somebody else. I was suffering with this while working on a project a few years ago and then a job in a newer project started failing a few days ago. I found this post and was trying to recollect what I had modified in my project and then I remembered that I had changed my maven pom and removed the entry for maven-jar-plugin. When you build a jar whose purpose is to be executable, you need to include this so that certain entries get written into the manifest. I opened the old project, copied that entry (with some modifications for project name) and it worked.

Is this a good way to clone an object in ES6?

if you don't want to use json.parse(json.stringify(object)) you could create recursively key-value copies:

function copy(item){
  let result = null;
  if(!item) return result;
  if(Array.isArray(item)){
    result = [];
    item.forEach(element=>{
      result.push(copy(element));
    });
  }
  else if(item instanceof Object && !(item instanceof Function)){ 
    result = {};
    for(let key in item){
      if(key){
        result[key] = copy(item[key]);
      }
    }
  }
  return result || item;
}

But the best way is to create a class that can return a clone of it self

class MyClass{
    data = null;
    constructor(values){ this.data = values }
    toString(){ console.log("MyClass: "+this.data.toString(;) }
    remove(id){ this.data = data.filter(d=>d.id!==id) }
    clone(){ return new MyClass(this.data) }
}

Caesar Cipher Function in Python

This solution is more intuitively without the use of ord function:

def caesar_cipher(raw_text, key):
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    shifted_alphabet = alphabet[26-key:]+alphabet[0:(26-key)]
    cipher_text = ""
    for i in range(len(raw_text)):
        char = raw_text[i]
        idx = alphabet.find(char.upper())
        if idx == -1:
            cipher_text = cipher_text + char
        elif char.islower():
            cipher_text = cipher_text + shifted_alphabet[idx].lower()
        else:
            cipher_text = cipher_text + shifted_alphabet[idx] 
    return(cipher_text)

And an example:

plain_text = "The quick brown fox jumps over the lazy dog!"
caesar_cipher(plain_text,3)

And we get:

'Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald!'

If we want to decrypt it:

caesar_cipher(caesar_cipher(plain_text,3),26-3)

and we get:

'The quick brown fox jumps over the lazy dog!'

More details here:https://predictivehacks.com/caesar-cipher-in-python/

Abort a Git Merge

Truth be told there are many, many resources explaining how to do this already out on the web:

Git: how to reverse-merge a commit?

Git: how to reverse-merge a commit?

Undoing Merges, from Git's blog (retrieved from archive.org's Wayback Machine)

So I guess I'll just summarize some of these:

  1. git revert <merge commit hash>
    This creates an extra "revert" commit saying you undid a merge

  2. git reset --hard <commit hash *before* the merge>
    This reset history to before you did the merge. If you have commits after the merge you will need to cherry-pick them on to afterwards.

But honestly this guide here is better than anything I can explain, with diagrams! :)

File path to resource in our war/WEB-INF folder?

There's a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .war file), you can use this API:

ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getRealPath(java.lang.String)

That will get you the full system path to the resource you are looking for. However, that won't work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext's getResource methods.

ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");

or alternatively if you just want the input stream:

InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getResource(java.lang.String)

The latter approach will work no matter what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.

EDIT: The getContext() method is obviously something you would have to implement. JSP pages make it available as the context field. In a servlet you get it from your ServletConfig which is passed into the servlet's init() method. If you store it at that time, you can get your ServletContext any time you want after that.

PHP str_replace replace spaces with underscores

For one matched character replace, use str_replace:

$string = str_replace(' ', '_', $string);

For all matched character replace, use preg_replace:

$string = preg_replace('/\s+/', '_', $string);

Java logical operator short-circuiting

There are a couple of differences between the & and && operators. The same differences apply to | and ||. The most important thing to keep in mind is that && is a logical operator that only applies to boolean operands, while & is a bitwise operator that applies to integer types as well as booleans.

With a logical operation, you can do short circuiting because in certain cases (like the first operand of && being false, or the first operand of || being true), you do not need to evaluate the rest of the expression. This is very useful for doing things like checking for null before accessing a filed or method, and checking for potential zeros before dividing by them. For a complex expression, each part of the expression is evaluated recursively in the same manner. For example, in the following case:

(7 == 8) || ((1 == 3) && (4 == 4))

Only the emphasized portions will evaluated. To compute the ||, first check if 7 == 8 is true. If it were, the right hand side would be skipped entirely. The right hand side only checks if 1 == 3 is false. Since it is, 4 == 4 does not need to be checked, and the whole expression evaluates to false. If the left hand side were true, e.g. 7 == 7 instead of 7 == 8, the entire right hand side would be skipped because the whole || expression would be true regardless.

With a bitwise operation, you need to evaluate all the operands because you are really just combining the bits. Booleans are effectively a one-bit integer in Java (regardless of how the internals work out), and it is just a coincidence that you can do short circuiting for bitwise operators in that one special case. The reason that you can not short-circuit a general integer & or | operation is that some bits may be on and some may be off in either operand. Something like 1 & 2 yields zero, but you have no way of knowing that without evaluating both operands.

Paste Excel range in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    .Display
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
    rng.Copy
    wdRange.Paste
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

Python one-line "for" expression

The keyword you're looking for is list comprehensions:

>>> x = [1, 2, 3, 4, 5]
>>> y = [2*a for a in x if a % 2 == 1]
>>> print(y)
[2, 6, 10]

Set environment variables from file of key/value pairs

Improving on Silas Paul's answer

exporting the variables on a subshell makes them local to the command.

(export $(cat .env | xargs) && rails c)

What does "hard coded" mean?

"Hard Coding" means something that you want to embeded with your program or any project that can not be changed directly. For example if you are using a database server, then you must hardcode to connect your database with your project and that can not be changed by user. Because you have hard coded.

Set "Homepage" in Asp.Net MVC

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",               
            defaults: new { controller = "Your Controller", action = "Your Action", id = UrlParameter.Optional }
        );
    }
}

How do I create a simple 'Hello World' module in Magento?

A Magento Module is a group of directories containing blocks, controllers, helpers, and models that are needed to create a specific store feature. It is the unit of customization in the Magento platform. Magento Modules can be created to perform multiple functions with supporting logic to influence user experience and storefront appearance. It has a life cycle that allows them to be installed, deleted, or disabled. From the perspective of both merchants and extension developers, modules are the central unit of the Magento platform.

Declaration of Module

We have to declare the module by using the configuration file. As Magento 2 search for configuration module in etc directory of the module. So now we will create configuration file module.xml.

The code will look like this:

<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Cloudways_Mymodule" setup_version="1.0.0"></module> </config>

Registration of Module The module must be registered in the Magento 2 system by using Magento Component Registrar class. Now we will create the file registration.php in the module root directory:

app/code/Cloudways/Mymodule/registration.php

The Code will look like this:

?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Cloudways_Mymodule',
__DIR__
);

Check Module Status After following the steps above, we would have created a simple module. Now we are going to check the status of the module and whether it is enabled or disabled by using the following command line:

php bin/magento module:status

php bin/magento module:enable Cloudways_Mymodule

Share your feedback once you have gone through complete process

How can I store the result of a system command in a Perl variable?

The easiest way is to use the `` feature in Perl. This will execute what is inside and return what was printed to stdout:

 my $pid = 5892;
 my $var = `top -H -p $pid -n 1 | grep myprocess | wc -l`;
 print "not = $var\n";

This should do it.

How to add a spinner icon to button when it's in the Loading state?

To make the solution by @flion look really great, you could adjust the center point for that icon so it doesn't wobble up and down. This looks right for me at a small font size:

.glyphicon-refresh.spinning {
  transform-origin: 48% 50%;
}

What does "subject" mean in certificate?

Subject is the certificate's common name and is a critical property for the certificate in a lot of cases if it's a server certificate and clients are looking for a positive identification.

As an example on an SSL certificate for a web site the subject would be the domain name of the web site.

git-upload-pack: command not found, when cloning remote Git repo

Building on Brian's answer, the upload-pack path can be set permanently by running the following commands after cloning, which eliminates the need for --upload-pack on subsequent pull/fetch requests. Similarly, setting receive-pack eliminates the need for --receive-pack on push requests.

git config remote.origin.uploadpack /path/to/git-upload-pack
git config remote.origin.receivepack /path/to/git-receive-pack

These two commands are equivalent to adding the following lines to a repo's .git/config.

[remote "origin"]
    uploadpack = /path/to/git-upload-pack
    receivepack = /path/to/git-receive-pack

Frequent users of clone -u may be interested in the following aliases. myclone should be self-explanatory. myfetch/mypull/mypush can be used on repos whose config hasn't been modified as described above by replacing git push with git mypush, and so on.

[alias]
    myclone = clone --upload-pack /path/to/git-upload-pack
    myfetch = fetch --upload-pack /path/to/git-upload-pack
    mypull  = pull --upload-pack /path/to/git-upload-pack
    mypush  = push --receive-pack /path/to/git-receive-pack

E: Unable to locate package mongodb-org

I had the same issue in 14.04, but I fixed it by these steps:

  1. sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
  2. echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb- org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
  3. sudo apt-get update
  4. sudo apt-get install -y mongodb

It worked like charm :)

How to remove Firefox's dotted outline on BUTTONS as well as links?

After trying many options from the above only the following worked for me.

*:focus, *:visited, *:active, *:hover  { outline:0 !important;}
*::-moz-focus-inner {border:0;}

Postgresql: Scripting psql execution with password

Given the security concerns about using the PGPASSWORD environment variable, I think the best overall solution is as follows:

  1. Write your own temporary pgpass file with the password you want to use.
  2. Use the PGPASSFILE environment variable to tell psql to use that file.
  3. Remove the temporary pgpass file

There are a couple points of note here. Step 1 is there to avoid mucking with the user's ~/.pgpass file that might exist. You also must make sure that the file has permissions 0600 or less.

Some have suggested leveraging bash to shortcut this as follows:

PGPASSFILE=<(echo myserver:5432:mydb:jdoe:password) psql -h myserver -U jdoe -p 5432 mydb

This uses the <() syntax to avoid needing to write the data to an actual file. But it doesn't work because psql checks what file is being used and will throw an error like this:

WARNING: password file "/dev/fd/63" is not a plain file

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

check boxlist selected values with seperator

 string items = string.Empty;
        foreach (ListItem i in CheckBoxList1.Items)
        {
            if (i.Selected == true)
            {
                items += i.Text + ",";
            }
        }
        Response.Write("selected items"+ items);

Excel VBA Password via Hex Editor

New version, now you also have the GC= try to replace both DPB and GC with those

DPB="DBD9775A4B774B77B4894C77DFE8FE6D2CCEB951E8045C2AB7CA507D8F3AC7E3A7F59012A2" GC="BAB816BBF4BCF4BCF4"

password will be "test"

Output ("echo") a variable to a text file

The simplest Hello World example...

$hello = "Hello World"
$hello | Out-File c:\debug.txt

What is callback in Android?

Callback can be very helpful in Java.

Using Callback you can notify another Class of an asynchronous action that has completed with success or error.

Callback to a Fragment from a DialogFragment

The correct way of setting a listener to a fragment is by setting it when it is attached. The problem I had was that onAttachFragment() was never called. After some investigation I realised that I had been using getFragmentManager instead of getChildFragmentManager

Here is how I do it:

MyDialogFragment dialogFragment = MyDialogFragment.newInstance("title", "body");
dialogFragment.show(getChildFragmentManager(), "SOME_DIALOG");

Attach it in onAttachFragment:

@Override
public void onAttachFragment(Fragment childFragment) {
    super.onAttachFragment(childFragment);

    if (childFragment instanceof MyDialogFragment) {
        MyDialogFragment dialog = (MyDialogFragment) childFragment;
        dialog.setListener(new MyDialogFragment.Listener() {
            @Override
            public void buttonClicked() {

            }
        });
    }
}

When is the init() function run?

When is the init() function run?

With Go 1.16 (Q1 2021), you will see precisely when it runs, and for how long.

See commit 7c58ef7 from CL (Change List) 254659, fixing issue 41378 .

Runtime: implement GODEBUG=inittrace=1 support

Setting inittrace=1 causes the runtime to emit a single line to standard error for each package with init work, summarizing the execution time and memory allocation.

The emitted debug information for init functions can be used to find bottlenecks or regressions in Go startup performance.

Packages with no init function work (user defined or compiler generated) are omitted.

Tracing plugin inits is not supported as they can execute concurrently. This would make the implementation of tracing more complex while adding support for a very rare use case. Plugin inits can be traced separately by testing a main package importing the plugins package imports explicitly.

$ GODEBUG=inittrace=1 go test
init internal/bytealg @0.008 ms, 0 ms clock, 0 bytes, 0 allocs
init runtime @0.059 ms, 0.026 ms clock, 0 bytes, 0 allocs
init math @0.19 ms, 0.001 ms clock, 0 bytes, 0 allocs
init errors @0.22 ms, 0.004 ms clock, 0 bytes, 0 allocs
init strconv @0.24 ms, 0.002 ms clock, 32 bytes, 2 allocs
init sync @0.28 ms, 0.003 ms clock, 16 bytes, 1 allocs
init unicode @0.44 ms, 0.11 ms clock, 23328 bytes, 24 allocs
...

Inspired by [email protected] who instrumented doInit in a prototype to measure init times with GDB.

How to make HTML element resizable using pure Javascript?

I have created a function that recieve an id of an html element and adds a border to it's right side the function is general and just recieves an id so you can copy it as it is and it will work

_x000D_
_x000D_
var myoffset;_x000D_
function resizeE(elem){_x000D_
    var borderDiv = document.createElement("div");_x000D_
    borderDiv.className = "border";_x000D_
    borderDiv.addEventListener("mousedown",myresize = function myrsize(e) {_x000D_
     myoffset = e.clientX - (document.getElementById(elem).offsetLeft + parseInt(window.getComputedStyle(document.getElementById(elem)).getPropertyValue("width")));_x000D_
     window.addEventListener("mouseup",mouseUp);_x000D_
     document.addEventListener("mousemove",mouseMove = function mousMove(e) {_x000D_
      document.getElementById(elem).style.width = `${e.clientX -  myoffset - document.getElementById(elem).offsetLeft}px`;_x000D_
  });_x000D_
 });_x000D_
    document.getElementById(elem).appendChild(borderDiv);_x000D_
}_x000D_
_x000D_
function mouseUp() {_x000D_
    document.removeEventListener("mousemove", mouseMove);_x000D_
    window.removeEventListener("mouseup",mouseUp);_x000D_
}_x000D_
_x000D_
function load() _x000D_
{_x000D_
 resizeE("resizeableDiv");_x000D_
 resizeE("anotherresizeableDiv");_x000D_
  resizeE("anotherresizeableDiv1");_x000D_
}
_x000D_
.border {_x000D_
_x000D_
  position: absolute;_x000D_
  cursor: e-resize;_x000D_
  width: 9px;_x000D_
  right: -5px;_x000D_
  top: 0;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
#resizeableDiv {_x000D_
  width: 30vw;_x000D_
  height: 30vh;_x000D_
  background-color: #84f4c6;_x000D_
  position: relative;_x000D_
}_x000D_
#anotherresizeableDiv {_x000D_
  width: 30vw;_x000D_
  height: 30vh;_x000D_
  background-color: #9394f4;_x000D_
  position: relative;_x000D_
}_x000D_
#anotherresizeableDiv1 {_x000D_
  width: 30vw;_x000D_
  height: 30vh;_x000D_
  background-color: #43f4f4;_x000D_
  position: relative;_x000D_
}_x000D_
#anotherresizeableDiv1 .border{_x000D_
  background-color: black;_x000D_
}_x000D_
#anotherresizeableDiv .border{_x000D_
  width: 30px;_x000D_
  right: -200px;_x000D_
  background-color: green;_x000D_
}
_x000D_
<body onload="load()">_x000D_
_x000D_
  <div id="resizeableDiv">change my size with the east border</div>_x000D_
  <div id="anotherresizeableDiv1">with visible border</div>_x000D_
</body>_x000D_
  <div id="anotherresizeableDiv">with editted outside border</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

resizeE("resizeableDiv"); //this calls a function that does the magic to the id inserted

How do I convert NSMutableArray to NSArray?

you try this code---

NSMutableArray *myMutableArray = [myArray mutableCopy];

and

NSArray *myArray = [myMutableArray copy];

Git keeps prompting me for a password

Use this: Replace github.com with the appropriate hostname

git remote set-url origin [email protected]:user/repo.git

How to get the azure account tenant Id?

The tenant id is also present in the management console URL when you browse to the given Active Directory instance, e.g.,

https://manage.windowsazure.com/<morestuffhere>/ActiveDirectoryExtension/Directory/BD848865-BE84-4134-91C6-B415927B3AB1

Azure Mgmt Console Active Directory

Split a large dataframe into a list of data frames based on common value in column

You can just as easily access each element in the list using e.g. path[[1]]. You can't put a set of matrices into an atomic vector and access each element. A matrix is an atomic vector with dimension attributes. I would use the list structure returned by split, it's what it was designed for. Each list element can hold data of different types and sizes so it's very versatile and you can use *apply functions to further operate on each element in the list. Example below.

#  For reproducibile data
set.seed(1)

#  Make some data
userid <- rep(1:2,times=4)
data1 <- replicate(8 , paste( sample(letters , 3 ) , collapse = "" ) )
data2 <- sample(10,8)
df <- data.frame( userid , data1 , data2 )

#  Split on userid
out <- split( df , f = df$userid )
#$`1`
#  userid data1 data2
#1      1   gjn     3
#3      1   yqp     1
#5      1   rjs     6
#7      1   jtw     5

#$`2`
#  userid data1 data2
#2      2   xfv     4
#4      2   bfe    10
#6      2   mrx     2
#8      2   fqd     9

Access each element using the [[ operator like this:

out[[1]]
#  userid data1 data2
#1      1   gjn     3
#3      1   yqp     1
#5      1   rjs     6
#7      1   jtw     5

Or use an *apply function to do further operations on each list element. For instance, to take the mean of the data2 column you could use sapply like this:

sapply( out , function(x) mean( x$data2 ) )
#   1    2 
#3.75 6.25 

List<T> or IList<T>

The less popular answer is programmers like to pretend their software is going to be re-used the world over, when infact the majority of projects will be maintained by a small amount of people and however nice interface-related soundbites are, you're deluding yourself.

Architecture Astronauts. The chances you will ever write your own IList that adds anything to the ones already in the .NET framework are so remote that it's theoretical jelly tots reserved for "best practices".

Software astronauts

Obviously if you are being asked which you use in an interview, you say IList, smile, and both look pleased at yourselves for being so clever. Or for a public facing API, IList. Hopefully you get my point.

Changing MongoDB data store directory

The short answer is that the --dbpath parameter in MongoDB will allow you to control what directory MongoDB reads and writes it's data from.

mongod --dbpath /usr/local/mongodb-data

Would start mongodb and put the files in /usr/local/mongodb-data.

Depending on your distribution and MongoDB installation, you can also configure the mongod.conf file to do this automatically:

# Store data in /usr/local/var/mongodb instead of the default /data/db
dbpath = /usr/local/var/mongodb

The official 10gen Linux packages (Ubuntu/Debian or CentOS/Fedora) ship with a basic configuration file which is placed in /etc/mongodb.conf, and the MongoDB service reads this when it starts up. You could make your change here.

How to change MySQL column definition?

Do you mean altering the table after it has been created? If so you need to use alter table, in particular:

ALTER TABLE tablename MODIFY COLUMN new-column-definition

e.g.

ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);

How to use ternary operator in razor (specifically on HTML attributes)?

For those of you who use ASP.net with VB razor the ternary operator is also possible.

It must be, as well, inside a razor expression:

@(Razor_Expression)

and the ternary operator works as follows:

If(BooleanTestExpression, "TruePart", "FalsePart")

The same code example shown here with VB razor looks like this:

<a class="@(If(User.Identity.IsAuthenticated, "auth", "anon"))">My link here</a>

Note: when writing a TextExpression remember that Boolean symbols are not the same between C# and VB.

how to fire event on file select

You could subscribe for the onchange event on the input field:

<input type="file" id="file" name="file" />

and then:

document.getElementById('file').onchange = function() {
    // fire the upload here
};

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

Sometimes a BEFORE trigger can be replaced with an AFTER one, but this doesn't appear to be the case in your situation, for you clearly need to provide a value before the insert takes place. So, for that purpose, the closest functionality would seem to be the INSTEAD OF trigger one, as @marc_s has suggested in his comment.

Note, however, that, as the names of these two trigger types suggest, there's a fundamental difference between a BEFORE trigger and an INSTEAD OF one. While in both cases the trigger is executed at the time when the action determined by the statement that's invoked the trigger hasn't taken place, in case of the INSTEAD OF trigger the action is never supposed to take place at all. The real action that you need to be done must be done by the trigger itself. This is very unlike the BEFORE trigger functionality, where the statement is always due to execute, unless, of course, you explicitly roll it back.

But there's one other issue to address actually. As your Oracle script reveals, the trigger you need to convert uses another feature unsupported by SQL Server, which is that of FOR EACH ROW. There are no per-row triggers in SQL Server either, only per-statement ones. That means that you need to always keep in mind that the inserted data are a row set, not just a single row. That adds more complexity, although that'll probably conclude the list of things you need to account for.

So, it's really two things to solve then:

  • replace the BEFORE functionality;

  • replace the FOR EACH ROW functionality.

My attempt at solving these is below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  INSERT INTO sub (super_id)
  SELECT super_id FROM @new_super;
END;

This is how the above works:

  1. The same number of rows as being inserted into sub1 is first added to super. The generated super_id values are stored in a temporary storage (a table variable called @new_super).

  2. The newly inserted super_ids are now inserted into sub1.

Nothing too difficult really, but the above will only work if you have no other columns in sub1 than those you've specified in your question. If there are other columns, the above trigger will need to be a bit more complex.

The problem is to assign the new super_ids to every inserted row individually. One way to implement the mapping could be like below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    rownum   int IDENTITY (1, 1),
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  WITH enumerated AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rownum
    FROM inserted
  )
  INSERT INTO sub1 (super_id, other columns)
  SELECT n.super_id, i.other columns
  FROM enumerated AS i
  INNER JOIN @new_super AS n
  ON i.rownum = n.rownum;
END;

As you can see, an IDENTIY(1,1) column is added to @new_user, so the temporarily inserted super_id values will additionally be enumerated starting from 1. To provide the mapping between the new super_ids and the new data rows, the ROW_NUMBER function is used to enumerate the INSERTED rows as well. As a result, every row in the INSERTED set can now be linked to a single super_id and thus complemented to a full data row to be inserted into sub1.

Note that the order in which the new super_ids are inserted may not match the order in which they are assigned. I considered that a no-issue. All the new super rows generated are identical save for the IDs. So, all you need here is just to take one new super_id per new sub1 row.

If, however, the logic of inserting into super is more complex and for some reason you need to remember precisely which new super_id has been generated for which new sub row, you'll probably want to consider the mapping method discussed in this Stack Overflow question:

Delete a row in Excel VBA

Change your line

ws.Range(Rand, 1).EntireRow.Delete

to

ws.Cells(Rand, 1).EntireRow.Delete