Programs & Examples On #Greybox

How to auto adjust the <div> height according to content in it?

Simple answer is to use overflow: hidden and min-height: x(any) px which will auto-adjust the size of div.

The height: auto won't work.

How do I choose grid and block dimensions for CUDA kernels?

The blocksize is usually selected to maximize the "occupancy". Search on CUDA Occupancy for more information. In particular, see the CUDA Occupancy Calculator spreadsheet.

PHP mPDF save file as PDF

The mPDF docs state that the first argument of Output() is the file path, second is the saving mode - you need to set it to 'F'.

$mpdf->Output('filename.pdf','F');

How to change current Theme at runtime in Android

You can finish the Acivity and recreate it afterwards in this way your activity will be created again and all the views will be created with the new theme.

Getting value of selected item in list box as string

Elaborating on previous answer by Pir Fahim, he's right but i'm using selectedItem.Text (only way to make it work to me)

Use the SelectedIndexChanged() event to store the data somewhere. In my case, i usually fill a custom class, something like:

class myItem {
    string name {get; set;}
    string price {get; set;}
    string desc {get; set;}
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
     myItem selected_item = new myItem();
     selected_item.name  = listBox1.SelectedItem.Text;
     Retrieve (selected_item.name);
}

And then you can retrieve the rest of data from a List of "myItems"..

myItem Retrieve (string wanted_item) {
    foreach (myItem item in my_items_list) {
        if (item.name == wanted_item) {
               // This is the selected item
               return item; 
        }
    }
    return null;
}

Average of multiple columns

If the data is stored as INT, you may want to try

Average = (R1 + R2 + R3 + R4 + R5) / 5.0

jquery variable syntax

This is pure JavaScript.

There is nothing special about $. It is just a character that may be used in variable names.

var $ = 1;
var $$ = 2;
alert($ + $$);

jQuery just assigns it's core function to a variable called $. The code you have assigns this to a local variable called self and the results of calling jQuery with this as an argument to a global variable called $self.

It's ugly, dirty, confusing, but $, self and $self are all different variables that happen to have similar names.

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

For Mac OS users:

Find the file named config.inc.php, usually located in /Applications/XAMPP/xamppfiles/phpmyadmin/config.inc.php

(this is the filepath on my Mac)

Then click the right mouse click -> Click on Get Info, at the bottom of the box you will find permissions-> click on the Lock icon (bottom right corner) -> Put your System Admin Password -> -> where it says everyone, modify this permission to READ ONLY -> click back on the Lock icon and try to open http://localhost/phpMyadmin

Hope this helps! ;)

How to verify Facebook access token?

Simply request (HTTP GET):

https://graph.facebook.com/USER_ID/access_token=xxxxxxxxxxxxxxxxx

That's it.

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

Try these steps

  1. Run this command in powershell --->bcdedit /set hypervisorlaunchtype auto
  2. Restart your PC
  3. Now try docker --version in cmd line

Do standard windows .ini files allow comments?

I have seen comments in INI files, so yes. Please refer to this Wikipedia article. I could not find an official specification, but that is the correct syntax for comments, as many game INI files had this as I remember.

Edit

The API returns the Value and the Comment (forgot to mention this in my reply), just construct and example INI file and call the API on this (with comments) and you can see how this is returned.

Default value in Doctrine

Update

One more reason why read the documentation for Symfony will never go out of trend. There is a simple solution for my specific case and is to set the field type option empty_data to a default value.

Again, this solution is only for the scenario where an empty input in a form sets the DB field to null.

Background

None of the previous answers helped me with my specific scenario but I found a solution.

I had a form field that needed to behave as follow:

  1. Not required, could be left blank. (Used 'required' => false)
  2. If left blank, it should default to a given value. For better user experience, I did not set the default value on the input field but rather used the html attribute 'placeholder' since it is less obtrusive.

I then tried all the recommendations given in here. Let me list them:

  • Set a default value when for the entity property:
<?php
/**
 * @Entity
 */
class myEntity {
    /**
     * @var string
     *
     * @Column(name="myColumn", type="string", length="50")
     */
    private $myColumn = 'myDefaultValue';
    ...
}
  • Use the options annotation:
@ORM\Column(name="foo", options={"default":"foo bar"})
  • Set the default value on the constructor:
/**
 * @Entity
 */
class myEntity {
    ...
    public function __construct()
    {
        $this->myColumn = 'myDefaultValue';
    }
    ...
}
None of it worked and all because of how Symfony uses your Entity class.

IMPORTANT

Symfony form fields override default values set on the Entity class. Meaning, your schema for your DB can have a default value defined but if you leave a non-required field empty when submitting your form, the form->handleRequest() inside your form->isValid() method will override those default values on your Entity class and set them to the input field values. If the input field values are blank, then it will set the Entity property to null.

http://symfony.com/doc/current/book/forms.html#handling-form-submissions

My Workaround

Set the default value on your controller after form->handleRequest() inside your form->isValid() method:

...
if ($myEntity->getMyColumn() === null) {
    $myEntity->setMyColumn('myDefaultValue');
}
...

Not a beautiful solution but it works. I could probably make a validation group but there may be people that see this issue as a data transformation rather than data validation, I leave it to you to decide.


Override Setter (Does Not Work)

I also tried to override the Entity setter this way:

...
/**
 * Set myColumn
 *
 * @param string $myColumn
 *
 * @return myEntity
 */
public function setMyColumn($myColumn)
{
    $this->myColumn = ($myColumn === null || $myColumn === '') ? 'myDefaultValue' : $myColumn;

    return $this;
}
...

This, even though it looks cleaner, it doesn't work. The reason being that the evil form->handleRequest() method does not use the Model's setter methods to update the data (dig into form->setData() for more details).

Disable/Enable button in Excel/VBA

too good !!! it's working and resolved my one day old problem easily

Dim b1 As Button

Set b1 = ActiveSheet.Buttons("Button 1")


b1.Enabled = False

How to properly -filter multiple strings in a PowerShell copy script

Something like this should work (it did for me). The reason for wanting to use -Filter instead of -Include is that include takes a huge performance hit compared to -Filter.

Below just loops each file type and multiple servers/workstations specified in separate files.

##  
##  This script will pull from a list of workstations in a text file and search for the specified string


## Change the file path below to where your list of target workstations reside
## Change the file path below to where your list of filetypes reside

$filetypes = gc 'pathToListOffiletypes.txt'
$servers = gc 'pathToListOfWorkstations.txt'

##Set the scope of the variable so it has visibility
set-variable -Name searchString -Scope 0
$searchString = 'whatYouAreSearchingFor'

foreach ($server in $servers)
    {

    foreach ($filetype in $filetypes)
    {

    ## below creates the search path.  This could be further improved to exclude the windows directory
    $serverString = "\\"+$server+"\c$\Program Files"


    ## Display the server being queried
    write-host “Server:” $server "searching for " $filetype in $serverString

    Get-ChildItem -Path $serverString -Recurse -Filter $filetype |
    #-Include "*.xml","*.ps1","*.cnf","*.odf","*.conf","*.bat","*.cfg","*.ini","*.config","*.info","*.nfo","*.txt" |
    Select-String -pattern $searchstring | group path | select name | out-file f:\DataCentre\String_Results.txt

    $os = gwmi win32_operatingsystem -computer $server
    $sp = $os | % {$_.servicepackmajorversion}
    $a = $os | % {$_.caption}

    ##  Below will list again the server name as well as its OS and SP
    ##  Because the script may not be monitored, this helps confirm the machine has been successfully scanned
        write-host $server “has completed its " $filetype "scan:” “|” “OS:” $a “SP:” “|” $sp


    }

}
#end script

When creating a service with sc.exe how to pass in context parameters?

Be sure to have quotes at beginning and end of your binPath value.

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

you can also try this trick:

ps aux | grep puma

sample output:

myname           77921   0.0  0.0  2433828   1972 s000  R+   11:17AM   0:00.00 grep puma
myname           67661   0.0  2.3  2680504 191204 s002  S+   11:00AM   0:18.38 puma 3.11.2 (tcp://localhost:3000) [my_proj]

then:

kill -9 67661

jQuery removeClass wildcard

$('div').attr('class', function(i, c){
    return c.replace(/(^|\s)color-\S+/g, '');
});

The import javax.servlet can't be resolved

You need to add the Servlet API to your classpath. In Tomcat 6.0, this is in a JAR called servlet-api.jar in Tomcat's lib folder. You can either add a reference to that JAR to the project's classpath, or put a copy of the JAR in your Eclipse project and add it to the classpath from there.

If you want to leave the JAR in Tomcat's lib folder:

  • Right-click the project, click Properties.
  • Choose Java Build Path.
  • Click the Libraries tab
  • Click Add External JARs...
  • Browse to find servlet-api.jar and select it.
  • Click OK to update the build path.

Or, if you copy the JAR into your project:

  • Right-click the project, click Properties.
  • Choose Java Build Path.
  • Click Add JARs...
  • Find servlet-api.jar in your project and select it.
  • Click OK to update the build path.

jquery drop down menu closing by clicking outside

Selected answer works for one drop down menu only. For multiple solution would be:

$('body').click(function(event){
   $dropdowns.not($dropdowns.has(event.target)).hide();
});

Android layout replacing a view with another view on run time

it work in my case, oldSensor and newSnsor - oldView and newView:

private void replaceSensors(View oldSensor, View newSensor) {
            ViewGroup parent = (ViewGroup) oldSensor.getParent();

            if (parent == null) {
                return;
            }

            int indexOldSensor = parent.indexOfChild(oldSensor);
            int indexNewSensor = parent.indexOfChild(newSensor);
            parent.removeView(oldSensor);
            parent.addView(oldSensor, indexNewSensor);
            parent.removeView(newSensor);
            parent.addView(newSensor, indexOldSensor);
        }

Using bind variables with dynamic SELECT INTO clause in PL/SQL

No you can't use bind variables that way. In your second example :into_bind in v_query_str is just a placeholder for value of variable v_num_of_employees. Your select into statement will turn into something like:

SELECT COUNT(*) INTO  FROM emp_...

because the value of v_num_of_employees is null at EXECUTE IMMEDIATE.

Your first example presents the correct way to bind the return value to a variable.

Edit

The original poster has edited the second code block that I'm referring in my answer to use OUT parameter mode for v_num_of_employees instead of the default IN mode. This modification makes the both examples functionally equivalent.

How to return multiple values in one column (T-SQL)?

Well... I see that an answer was already accepted... but I think you should see another solutions anyway:

/* EXAMPLE */
DECLARE @UserAliases TABLE(UserId INT , Alias VARCHAR(10))
INSERT INTO @UserAliases (UserId,Alias) SELECT 1,'MrX'
     UNION ALL SELECT 1,'MrY' UNION ALL SELECT 1,'MrA'
     UNION ALL SELECT 2,'Abc' UNION ALL SELECT 2,'Xyz'

/* QUERY */
;WITH tmp AS ( SELECT DISTINCT UserId FROM @UserAliases )
SELECT 
    LEFT(tmp.UserId, 10) +
    '/ ' +
    STUFF(
            (   SELECT ', '+Alias 
                FROM @UserAliases 
                WHERE UserId = tmp.UserId 
                FOR XML PATH('') 
            ) 
            , 1, 2, ''
        ) AS [UserId/Alias]
FROM tmp

/* -- OUTPUT
  UserId/Alias
  1/ MrX, MrY, MrA
  2/ Abc, Xyz    
*/

How can I check if a URL exists via PHP?

function urlIsOk($url)
{
    $headers = @get_headers($url);
    $httpStatus = intval(substr($headers[0], 9, 3));
    if ($httpStatus<400)
    {
        return true;
    }
    return false;
}

How to use LocalBroadcastManager?

localbroadcastmanager is deprecated, use implementations of the observable pattern instead.

androidx.localbroadcastmanager is being deprecated in version 1.1.0

Reason

LocalBroadcastManager is an application-wide event bus and embraces layer violations in your app; any component may listen to events from any other component. It inherits unnecessary use-case limitations of system BroadcastManager; developers have to use Intent even though objects live in only one process and never leave it. For this same reason, it doesn’t follow feature-wise BroadcastManager .

These add up to a confusing developer experience.

Replacement

You can replace usage of LocalBroadcastManager with other implementations of the observable pattern. Depending on your use case, suitable options may be LiveData or reactive streams.

Advantage of LiveData

You can extend a LiveData object using the singleton pattern to wrap system services so that they can be shared in your app. The LiveData object connects to the system service once, and then any observer that needs the resource can just watch the LiveData object.

 public class MyFragment extends Fragment {
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        LiveData<BigDecimal> myPriceListener = ...;
        myPriceListener.observe(this, price -> {
            // Update the UI.
        });
    }
}

The observe() method passes the fragment, which is an instance of LifecycleOwner, as the first argument. Doing so denotes that this observer is bound to the Lifecycle object associated with the owner, meaning:

  • If the Lifecycle object is not in an active state, then the observer isn't called even if the value changes.

  • After the Lifecycle object is destroyed, the observer is automatically removed

The fact that LiveData objects are lifecycle-aware means that you can share them between multiple activities, fragments, and services.

AppendChild() is not a function javascript

Just change

var div = '<div>top div</div>'; // you just created a text string

to

var div = document.createElement("div"); // we want a DIV element instead
div.innerHTML = "top div";

Display current time in 12 hour format with AM/PM

To put your current mobile date and time format in

Feb 9, 2018 10:36:59 PM

Date date = new Date();
 String stringDate = DateFormat.getDateTimeInstance().format(date);

you can show it to your Activity, Fragment, CardView, ListView anywhere by using TextView

` TextView mDateTime;

  mDateTime=findViewById(R.id.Your_TextViewId_Of_XML);

  Date date = new Date();
  String mStringDate = DateFormat.getDateTimeInstance().format(date);
  mDateTime.setText("My Device Current Date and Time is:"+date);

  `

Can't install Scipy through pip

I face same problem when install Scipy under ubuntu.
I had to use command:

$ sudo apt-get install libatlas-base-dev gfortran
$ sudo pip3 install scipy

You can get more details here Installing SciPy with pip
Sorry don't know how to do it under OS X Yosemite.

How to read/write files in .Net Core?

Works in Net Core 2.1

    var file = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "email", "EmailRegister.htm");

    string SendData = System.IO.File.ReadAllText(file);

How to pass optional parameters while omitting some other optional parameters?

Another approach is:

error(message: string, options?: {title?: string, autoHideAfter?: number});

So when you want to omit the title parameter, just send the data like that:

error('the message', { autoHideAfter: 1 })

I'd rather this options because allows me to add more parameter without having to send the others.

How to POST JSON request using Apache HttpClient?

As mentioned in the excellent answer by janoside, you need to construct the JSON string and set it as a StringEntity.

To construct the JSON string, you can use any library or method you are comfortable with. Jackson library is one easy example:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("name", "value"); // repeat as needed
String JSON_STRING = node.toString();
postMethod.setEntity(new StringEntity(JSON_STRING, ContentType.APPLICATION_JSON));

Inserting a value into all possible locations in a list

Use insert() to insert an element before a given position.

For instance, with

arr = ['A','B','C']
arr.insert(0,'D')

arr becomes ['D','A','B','C'] because D is inserted before the element at index 0.

Now, for

arr = ['A','B','C']
arr.insert(4,'D')

arr becomes ['A','B','C','D'] because D is inserted before the element at index 4 (which is 1 beyond the end of the array).

However, if you are looking to generate all permutations of an array, there are ways to do this already built into Python. The itertools package has a permutation generator.

Here's some example code:

import itertools
arr = ['A','B','C']
perms = itertools.permutations(arr)
for perm in perms:
    print perm

will print out

('A', 'B', 'C')
('A', 'C', 'B')
('B', 'A', 'C')
('B', 'C', 'A')
('C', 'A', 'B')
('C', 'B', 'A')

Handling a timeout error in python sockets

I had enough success just catchig socket.timeout and socket.error; although socket.error can be raised for lots of reasons. Be careful.

import socket
import logging

hostname='google.com'
port=443

try:
    sock = socket.create_connection((hostname, port), timeout=3)

except socket.timeout as err:
    logging.error(err)

except socket.error as err:
    logging.error(err)

How to have a a razor action link open in a new tab?

You are setting it't type as submit. That means that browser should post your <form> data to the server.

In fact a tag has no type attribute according to w3schools.

So remote type attribute and it should work for you.

How to compile and run C files from within Notepad++ using NppExec plugin?

You can actually compile and run C code even without the use of nppexec plugins. If you use MingW32 C compiler, use g++ for C++ language and gcc for C language.

Paste this code into the notepad++ run section

cmd /k cd $(CURRENT_DIRECTORY) && gcc $(FILE_NAME) -o $(NAME_PART).exe  && $(NAME_PART).exe && pause

It will compile your C code into exe and run it immediately. It's like a build and run feature in CodeBlock. All these are done with some cmd knowledge.

Explanation:

  1. cmd /k is used for testing.
  2. cd $(CURRENT_DIRECTORY)
    • change directory to where file is located
  3. && operators
    • to chain your commands in a single line
  4. gcc $(FILE_NAME)
    • use GCC to compile File with its file extension.
  5. -o $(NAME_PART).exe
    • this flag allow you to choose your output filename. $(NAME_PART) does not include file extension.
  6. $(NAME_PART).exe
    • this alone runs your program
  7. pause
    • this command is used to keep your console open after file has been executed.

For more info on notepad++ commands, go to

http://docs.notepad-plus-plus.org/index.php/External_Programs

Spring @Transactional read-only propagation

By default transaction propagation is REQUIRED, meaning that the same transaction will propagate from a transactional caller to transactional callee. In this case also the read-only status will propagate. E.g. if a read-only transaction will call a read-write transaction, the whole transaction will be read-only.

Could you use the Open Session in View pattern to allow lazy loading? That way your handle method does not need to be transactional at all.

Creating a textarea with auto-resize

This is a jQuery version of Moussawi7's answer.

_x000D_
_x000D_
$(function() {
  $("textarea.auto-grow").on("input", function() {
    var element = $(this)[0];
    element.style.height = "5px";
    element.style.height = (element.scrollHeight) + "px";
  });
})
_x000D_
textarea {
  resize: none;
  overflow: auto;
  width: 100%;
  min-height: 50px;
  max-height: 150px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="auto-grow"></textarea>
_x000D_
_x000D_
_x000D_

Cannot find Dumpbin.exe

In Visual Studio Professional 2017 Version 15.9.13:

  • First, either:

    • launch the "Visual Studio Installer" from the start menu, select your Visual Studio product, and click "Modify",

    or

    • from within Visual Studio go to "Tools" -> "Get Tools and Features..."
  • Then, wait for it while it is "getting things ready..." and being "almost there..."

  • Switch to the "Individual components" tab

  • Scroll down to the "Compilers, build tools, and runtimes" section

  • Check "VC++ 2017 version 15.9 v14.16 latest v141 tools"

like this:

enter image description here

After doing this, you will be blessed with not just one, but a whopping four instances of DUMPBIN:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x64\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x86\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx86\x64\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx86\x86\dumpbin.exe

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

How to read from a text file using VBScript?

Use first the method OpenTextFile, and then...

either read the file at once with the method ReadAll:

Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll

or line by line with the method ReadLine:

Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

'Loop over it
For Each line in dict.Items
  WScript.Echo line
Next

Launch custom android application from android browser

Look @JRuns answer in here. The idea is to create html with your custom scheme and upload it somewhere. Then if you click on your custom link on your html-file, you will be redirected to your app. I used this article for android. But dont forget to set full name Name = "MyApp.Mobile.Droid.MainActivity" attribute to your target activity.

Close Current Tab

Try this:

window.open('', '_self').close();

How do I combine two data-frames based on two columns?

See the documentation on ?merge, which states:

By default the data frames are merged on the columns with names they both have, 
 but separate specifications of the columns can be given by by.x and by.y.

This clearly implies that merge will merge data frames based on more than one column. From the final example given in the documentation:

x <- data.frame(k1=c(NA,NA,3,4,5), k2=c(1,NA,NA,4,5), data=1:5)
y <- data.frame(k1=c(NA,2,NA,4,5), k2=c(NA,NA,3,4,5), data=1:5)
merge(x, y, by=c("k1","k2")) # NA's match

This example was meant to demonstrate the use of incomparables, but it illustrates merging using multiple columns as well. You can also specify separate columns in each of x and y using by.x and by.y.

Best practice for Django project working directory structure

Here is what I follow on My system.

  1. All Projects: There is a projects directory in my home folder i.e. ~/projects. All the projects rest inside it.

  2. Individual Project: I follow a standardized structure template used by many developers called django-skel for individual projects. It basically takes care of all your static file and media files and all.

  3. Virtual environment: I have a virtualenvs folder inside my home to store all virtual environments in the system i.e. ~/virtualenvs . This gives me flexibility that I know what all virtual environments I have and can look use easily

The above 3 are the main partitions of My working environment.

All the other parts you mentioned are mostly dependent on project to project basis (i.e. you might use different databases for different projects). So they should reside in their individual projects.

Styling Password Fields in CSS

When I needed to create similar dots in input[password] I use a custom font in base64 (with 2 glyphs see above 25CF and 2022)

SCSS styles

@font-face {
  font-family: 'pass';
  font-style: normal;
  font-weight: 400;
  src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATsAA8AAAAAB2QAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABWAAAABwAAAAcg9+z70dERUYAAAF0AAAAHAAAAB4AJwANT1MvMgAAAZAAAAA/AAAAYH7AkBhjbWFwAAAB0AAAAFkAAAFqZowMx2N2dCAAAAIsAAAABAAAAAQAIgKIZ2FzcAAAAjAAAAAIAAAACAAAABBnbHlmAAACOAAAALkAAAE0MwNYJ2hlYWQAAAL0AAAAMAAAADYPA2KgaGhlYQAAAyQAAAAeAAAAJAU+ATJobXR4AAADRAAAABwAAAAcCPoA6mxvY2EAAANgAAAAEAAAABAA5gFMbWF4cAAAA3AAAAAaAAAAIAAKAE9uYW1lAAADjAAAARYAAAIgB4hZ03Bvc3QAAASkAAAAPgAAAE5Ojr8ld2ViZgAABOQAAAAGAAAABuK7WtIAAAABAAAAANXulPUAAAAA1viLwQAAAADW+JM4eNpjYGRgYOABYjEgZmJgBEI2IGYB8xgAA+AANXjaY2BifMg4gYGVgYVBAwOeYEAFjMgcp8yiFAYHBl7VP8wx/94wpDDHMIoo2DP8B8kx2TLHACkFBkYA8/IL3QB42mNgYGBmgGAZBkYGEEgB8hjBfBYGDyDNx8DBwMTABmTxMigoKKmeV/3z/z9YJTKf8f/X/4/vP7pldosLag4SYATqhgkyMgEJJnQFECcMOGChndEAfOwRuAAAAAAiAogAAQAB//8AD3jaY2BiUGJgYDRiWsXAzMDOoLeRkUHfZhM7C8Nbo41srHdsNjEzAZkMG5lBwqwg4U3sbIx/bDYxgsSNBRUF1Y0FlZUYBd6dOcO06m+YElMa0DiGJIZUxjuM9xjkGRhU2djZlJXU1UDQ1MTcDASNjcTFQFBUBGjYEkkVMJCU4gcCKRTeHCk+fn4+KSllsJiUJEhMUgrMUQbZk8bgz/iA8SRR9qzAY087FjEYD2QPDDAzMFgyAwC39TCRAAAAeNpjYGRgYADid/fqneL5bb4yyLMwgMC1H90HIfRkCxDN+IBpFZDiYGAC8QBbSwuceNpjYGRgYI7594aBgcmOAQgYHzAwMqACdgBbWQN0AAABdgAiAAAAAAAAAAABFAAAAj4AYgI+AGYB9AAAAAAAKgAqACoAKgBeAJIAmnjaY2BkYGBgZ1BgYGIAAUYGBNADEQAFQQBaAAB42o2PwUrDQBCGvzVV9GAQDx485exBY1CU3PQgVgIFI9prlVqDwcZNC/oSPoKP4HNUfQLfxYN/NytCe5GwO9/88+/MBAh5I8C0VoAtnYYNa8oaXpAn9RxIP/XcIqLreZENnjwvyfPieVVdXj2H7DHxPJH/2/M7sVn3/MGyOfb8SWjOGv4K2DRdctpkmtqhos+D6ISh4kiUUXDj1Fr3Bc/Oc0vPqec6A8aUyu1cdTaPZvyXyqz6Fm5axC7bxHOv/r/dnbSRXCk7+mpVrOqVtFqdp3NKxaHUgeod9cm40rtrzfrt2OyQa8fppCO9tk7d1x0rpiQcuDuRkjjtkHt16ctbuf/radZY52/PnEcphXpZOcofiEZNcQAAeNpjYGIAg///GBgZsAF2BgZGJkZmBmaGdkYWRla29JzKggxD9tK8TAMDAxc2D0MLU2NjENfI1M0ZACUXCrsAAAABWtLiugAA) format('woff');
}

input.password {
  font-family: 'pass', 'Roboto', Helvetica, Arial, sans-serif ;
  font-size: 18px;
  &::-webkit-input-placeholder {
    transform: scale(0.77);
    transform-origin: 0 50%;
  }
  &::-moz-placeholder {
    font-size: 14px;
    opacity: 1;
  }
  &:-ms-input-placeholder {
    font-size: 14px;
    font-family: 'Roboto', Helvetica, Arial, sans-serif;
  }

After that, I got identical display input[password]

How to fix Warning Illegal string offset in PHP

1.

 if(1 == @$manta_option['iso_format_recent_works']){
      $theme_img = 'recent_works_thumbnail';
 } else {
      $theme_img = 'recent_works_iso_thumbnail';
 }

2.

if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
    $theme_img = 'recent_works_thumbnail';
} else {
    $theme_img = 'recent_works_iso_thumbnail';
}

3.

if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}

Redirect output of mongo query to a csv file

When executing a script in a remote server. Mongo will add its own logging output, which we might want to omit from our file. --quiet option will only disable connection related logs. Not all mongo logs. In such case we might need to filter out unneeded lines manually. A Windows based example:

mongo dbname --username userName --password password --host replicaset/ip:port --quiet printDataToCsv.js | findstr /v "NETWORK" > data.csv

This will pipe the script output and use findstr to filter out any lines, which have NETWORK string in them. More information on findstr: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/findstr

A Linux version of this would use grep.

Run ssh and immediately execute command

This isn't quite what you're looking for, but I've found it useful in similar circumstances.

I recently added the following to my $HOME/.bashrc (something similar should be possible with shells other than bash):

if [ -f $HOME/.add-screen-to-history ] ; then
    history -s 'screen -dr'
fi

I keep a screen session running on one particular machine, and I've had problems with ssh connections to that machine being dropped, requiring me to re-run screen -dr every time I reconnect.

With that addition, and after creating that (empty) file in my home directory, I automatically have the screen -dr command in my history when my shell starts. After reconnecting, I can just type Control-P Enter and I'm back in my screen session -- or I can ignore it. It's flexible, but not quite automatic, and in your case it's easier than typing tmux list-sessions.

You might want to make the history -s command unconditional.

This does require updating your $HOME/.bashrc on each of the target systems, which might or might not make it unsuitable for your purposes.

DropDownList's SelectedIndexChanged event not firing

Set DropDownList AutoPostBack property to true.

Eg:

<asp:DropDownList ID="logList" runat="server" AutoPostBack="True" 
        onselectedindexchanged="itemSelected">
    </asp:DropDownList>

How do I get a string format of the current date time, in python?

#python3

import datetime
print(
    '1: test-{date:%Y-%m-%d_%H:%M:%S}.txt'.format( date=datetime.datetime.now() )
    )

d = datetime.datetime.now()
print( "2a: {:%B %d, %Y}".format(d))

# see the f" to tell python this is a f string, no .format
print(f"2b: {d:%B %d, %Y}")

print(f"3: Today is {datetime.datetime.now():%Y-%m-%d} yay")

1: test-2018-02-14_16:40:52.txt

2a: March 04, 2018

2b: March 04, 2018

3: Today is 2018-11-11 yay


Description:

Using the new string format to inject value into a string at placeholder {}, value is the current time.

Then rather than just displaying the raw value as {}, use formatting to obtain the correct date format.

https://docs.python.org/3/library/string.html#formatexamples

Getting permission denied (public key) on gitlab

Go to the terminal and regenerate the ssh key again. Type ssh-keygen. It will ask you where you want to save it, type the path.

Then copy the public key to gitlabs platform. It usually starts with ssh-rsa.

Spring MVC: how to create a default controller for index page?

It can be solved in more simple way: in web.xml

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.htm</welcome-file>
</welcome-file-list>

After that use any controllers that your want to process index.htm with @RequestMapping("index.htm"). Or just use index controller

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <props>
            <prop key="index.htm">indexController</prop>
        </props>
    </property>
<bean name="indexController" class="org.springframework.web.servlet.mvc.ParameterizableViewController"
      p:viewName="index" />
</bean>

PHP fopen() Error: failed to open stream: Permission denied

You may need to change the permissions as an administrator. Open up terminal on your Mac and then open the directory that markers.xml is located in. Then type:

sudo chmod 777 markers.xml

You may be prompted for a password. Also, it could be the directories that don't allow full access. I'm not familiar with WordPress, so you may have to change the permission of each directory moving upward to the mysite directory.

Working with Enums in android

There has been some debate around this point of contention, but even in the most recent documents android suggests that it's not such a good idea to use enums in an android application. The reason why is because they use up more memory than a static constants variable. Here is a document from a page of 2014 that advises against the use of enums in an android application. http://developer.android.com/training/articles/memory.html#Overhead

I quote:

Be aware of memory overhead

Be knowledgeable about the cost and overhead of the language and libraries you are using, and keep this information in mind when you design your app, from start to finish. Often, things on the surface that look innocuous may in fact have a large amount of overhead. Examples include:

  • Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.

  • Every class in Java (including anonymous inner classes) uses about 500 bytes of code.

  • Every class instance has 12-16 bytes of RAM overhead.

  • Putting a single entry into a HashMap requires the allocation of an additional entry object that takes 32 bytes (see the previous section about optimized data containers).

A few bytes here and there quickly add up—app designs that are class- or object-heavy will suffer from this overhead. That can leave you in the difficult position of looking at a heap analysis and realizing your problem is a lot of small objects using up your RAM.

There has been some places where they say that these tips are outdated and no longer valuable, but the reason they keep repeating it, must be there is some truth to it. Writing an android application is something you should keep as lightweight as possible for a smooth user experience. And every little inch of performance counts!

IIS7: Setup Integrated Windows Authentication like in IIS6

Two-stage authentication is not supported with IIS7 Integrated mode. Authentication is now modularized, so rather than IIS performing authentication followed by asp.net performing authentication, it all happens at the same time.

You can either:

  1. Change the app domain to be in IIS6 classic mode...
  2. Follow this example (old link) of how to fake two-stage authentication with IIS7 integrated mode.
  3. Use Helicon Ape and mod_auth to provide basic authentication

Format a Go string without printing?

We can custom A new String type via define new Type with Format support.

package main

import (
    "fmt"
    "text/template"
    "strings"
)

type String string
func (s String) Format(data map[string]interface{}) (out string, err error) {
    t := template.Must(template.New("").Parse(string(s)))
    builder := &strings.Builder{}
    if err = t.Execute(builder, data); err != nil {
        return
    }
    out = builder.String()
    return
}


func main() {
    const tmpl = `Hi {{.Name}}!  {{range $i, $r := .Roles}}{{if $i}}, {{end}}{{.}}{{end}}`
    data := map[string]interface{}{
        "Name":     "Bob",
        "Roles":    []string{"dbteam", "uiteam", "tester"},
    }

    s ,_:= String(tmpl).Format(data)
    fmt.Println(s)
}

how to wait for first command to finish?

Make sure that st_new.sh does something at the end what you can recognize (like touch /tmp/st_new.tmp when you remove the file first and always start one instance of st_new.sh).
Then make a polling loop. First sleep the normal time you think you should wait, and wait short time in every loop. This will result in something like

max_retry=20
retry=0
sleep 10 # Minimum time for st_new.sh to finish
while [ ${retry} -lt ${max_retry} ]; do
   if [ -f /tmp/st_new.tmp ]; then
      break # call results.sh outside loop
   else
      (( retry = retry + 1 ))
      sleep 1
   fi
done
if [ -f /tmp/st_new.tmp ]; then
   source ../../results.sh 
   rm -f /tmp/st_new.tmp
else
   echo Something wrong with st_new.sh
fi

MySQL - How to select rows where value is in array?

If the array element is not integer you can use something like below :

$skus  = array('LDRES10','LDRES12','LDRES11');   //sample data

if(!empty($skus)){     
    $sql = "SELECT * FROM `products` WHERE `prodCode` IN ('" . implode("','", $skus) . "') "      
}

Accessing Redux state in an action creator?

I wouldn't access state in the Action Creator. I would use mapStateToProps() and import the entire state object and import a combinedReducer file (or import * from './reducers';) in the component the Action Creator is eventually going to. Then use destructuring in the component to use whatever you need from the state prop. If the Action Creator is passing the state onto a Reducer for the given TYPE, you don't need to mention state because the reducer has access to everything that is currently set in state. Your example is not updating anything. I would only use the Action Creator to pass along state from its parameters.

In the reducer do something like:

const state = this.state;
const apple = this.state.apples;

If you need to perform an action on state for the TYPE you are referencing, please do it in the reducer.

Please correct me if I'm wrong!!!

Continue For loop

You can use a GoTo:

Do

    '... do stuff your loop will be doing

    ' skip to the end of the loop if necessary:
    If <condition-to-go-to-next-iteration> Then GoTo ContinueLoop 

    '... do other stuff if the condition is not met

ContinueLoop:
Loop

removing table border

This will do it with border-collapse

table{
    border-collapse:collapse;
}

Node.js - EJS - including a partial

In oficial documentation https://github.com/mde/ejs#includes show that includes works like that:

<%- include('../partials/head') %>

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

If you have completed all steps given by Surjeet and still not getting network connection icon then follow below steps:

  1. Unpair Device using right click on the device from the Connected section.

    enter image description here

  2. Reconnect the device.

  3. Click on "+" button from the end of the lefthand side of the popup.

enter image description here

  1. Select the device and click on next button

enter image description here

  1. Click on Trust and passcode(if available) from the device.

enter image description here

  1. Click on Done button.

enter image description here

  1. Now, click on connect via network.

enter image description here

Now you can see the network connection icon after the device name. Enjoy!

enter image description here

How do you handle multiple submit buttons in ASP.NET MVC Framework?

Here is what works best for me:

<input type="submit" value="Delete" name="onDelete" />
<input type="submit" value="Save" name="onSave" />


public ActionResult Practice(MyModel model, string onSave, string onDelete)
{
    if (onDelete != null)
    {
        // Delete the object
        ...
        return EmptyResult();
    }

    // Save the object
    ...
    return EmptyResult();
}

Batch File: ( was unexpected at this time

You are getting that error because when the param1 if statements are evaluated, param is always null due to being scoped variables without delayed expansion.

When parentheses are used, all the commands and variables within those parentheses are expanded. And at that time, param1 has no value making the if statements invalid. When using delayed expansion, the variables are only expanded when the command is actually called.

Also I recommend using if not defined command to determine if a variable is set.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.

set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if not defined a goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection

    ::param1
    set "param1=%globalparam2%"
    goto :param1Check
    :param1Prompt
    set /p "param1=Enter Choice: "
    :param1Check
    if not defined param1 goto :param1Prompt
    echo !param1!

    if "!param1!"=="1" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001 
        echo USB Write is Locked!
    )
    if "!param1!"=="2" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
        echo USB Write is Unlocked! 
    )
)
pause
endlocal

Adding blank spaces to layout

I strongly disagree with CaspNZ's approach.

First of all, this invisible view will be measured because it is "fill_parent". Android will try to calculate the right width of it. Instead, a small constant number (1dp) is recommended here.

Secondly, View should be replaced by a simpler class Space, a class dedicated to create empty spaces between UI component for fastest speed.

how to get the one entry from hashmap without iterating

import java.util.*;

public class Friday {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<String, Integer>();

        map.put("code", 10);
        map.put("to", 11);
        map.put("joy", 12);

        if (! map.isEmpty()) {
            Map.Entry<String, Integer> entry = map.entrySet().iterator().next();
            System.out.println(entry);
        }
    }
}

This approach doesn't work because you used HashMap. I assume using LinkedHashMap will be right solution in this case.

How to use SearchView in Toolbar Android

Integrating SearchView with RecyclerView

1) Add SearchView Item in Menu

SearchView can be added as actionView in menu using

app:useActionClass = "android.support.v7.widget.SearchView" .

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
    android:id="@+id/searchBar"
    app:showAsAction="always"
    app:actionViewClass="android.support.v7.widget.SearchView"
    />
</menu>

2) Implement SearchView.OnQueryTextListener in your Activity

SearchView.OnQueryTextListener has two abstract methods. So your activity skeleton would now look like this after implementing SearchView text listener.

YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{

   public boolean onQueryTextSubmit(String query)

   public boolean onQueryTextChange(String newText) 

}

3) Set up SerchView Hint text, listener etc

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    MenuItem searchItem = menu.findItem(R.id.searchBar);

    SearchView searchView = (SearchView) searchItem.getActionView();
    searchView.setQueryHint("Search People");
    searchView.setOnQueryTextListener(this);
    searchView.setIconified(false);

    return true;
}

4) Implement SearchView.OnQueryTextListener

This is how you can implement abstract methods of the listener.

@Override
public boolean onQueryTextSubmit(String query) {

    // This method can be used when a query is submitted eg. creating search history using SQLite DB

    Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
    return true;
}

@Override
public boolean onQueryTextChange(String newText) {

    adapter.filter(newText);
    return true;
}

5) Write a filter method in your RecyclerView Adapter.

You can come up with your own logic based on your requirement. Here is the sample code snippet to show the list of Name which contains the text typed in the SearchView.

public void filter(String queryText)
{
    list.clear();

    if(queryText.isEmpty())
    {
        list.addAll(copyList);
    }
    else
    {

        for(String name: copyList)
        {
            if(name.toLowerCase().contains(queryText.toLowerCase()))
            {
                list.add(name);
            }
        }

    }

    notifyDataSetChanged();
}

Full working code sample can be found > HERE
You can also check out the code on SearchView with an SQLite database in this Music App

View list of all JavaScript variables in Google Chrome Console

List the variable and their values

for(var b in window) { if(window.hasOwnProperty(b)) console.log(b+" = "+window[b]); }

enter image description here

Display the value of a particular variable object

console.log(JSON.stringify(content_of_some_variable_object))

enter image description here

Sources: comment from @northern-bradley and answer from @nick-craver

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

Quick answer: the FROM address must exactly match the account you are sending from, or you will get a error 5.7.1 Client does not have permissions to send as this sender.

My guess is that prevents email spoofing with your Office 365 account, otherwise you might be able to send as [email protected].

Another thing to try is in the authentication, fill in the third field with the domain, like

Dim smtpAuth = New System.Net.NetworkCredential(
    "TheDude", "hunter2password", "MicrosoftOffice365Domain.com")

If that doesn't work, double check that you can log into the account at: https://portal.microsoftonline.com

Yet another thing to note is your Antivirus solution may be blocking programmatic access to ports 25 and 587 as a anti-spamming solution. Norton and McAfee may silently block access to these ports. Only enabling Mail and Socket debugging will allow you to notice it (see below).

One last thing to note, the Send method is Asynchronous. If you call

Dispose
immediately after you call send, your are more than likely closing your connection before the mail is sent. Have your smtpClient instance listen for the OnSendCompleted event, and call dispose from there. You must use SendAsync method instead, the Send method does not raise this event.


Detailed Answer: With Visual Studio (VB.NET or C# doesn't matter), I made a simple form with a button that created the Mail Message, similar to that above. Then I added this to the application.exe.config (in the bin/debug directory of my project). This enables the Output tab to have detailed debug info.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>
        <sources>
            <source name="System.Net">
                <listeners>
                    <add name="System.Net" />
                </listeners>
            </source>
            <source name="System.Net.Sockets">
                <listeners>
                    <add name="System.Net" />
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="System.Net" value="Verbose" />
            <add name="System.Net.Sockets" value="Verbose" />
        </switches>
        <sharedListeners>
            <add name="System.Net"
              type="System.Diagnostics.TextWriterTraceListener"
              initializeData="System.Net.log"
            />
        </sharedListeners>
        <trace autoflush="true" />
    </system.diagnostics>
</configuration>

WordPress asking for my FTP credentials to install plugins

We had the same problem as part of a bigger problem. The suggested solution of

define('FS_METHOD', 'direct');

hides that window but then we still had problems with loading themes and upgrades etc. It is related to permissions however in our case we fixed the problem by moving from php OS vendor mod_php to the more secure php OS vendor FastCGI application.

Extracting Path from OpenFileDialog path/filename

how about this:

string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

creating logo

in folders "drawable-..." create in all of them logo.png . The location of the folders: [YOUR APP]\app\src\main\res

In AndroidManifest.xml add line: android:logo="@drawable/logo"

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:logo="@drawable/logo"
    ...

that's it.

Determining the current foreground application from a background task or service

For cases when we need to check from our own service/background-thread whether our app is in foreground or not. This is how I implemented it, and it works fine for me:

public class TestApplication extends Application implements Application.ActivityLifecycleCallbacks {

    public static WeakReference<Activity> foregroundActivityRef = null;

    @Override
    public void onActivityStarted(Activity activity) {
        foregroundActivityRef = new WeakReference<>(activity);
    }

    @Override
    public void onActivityStopped(Activity activity) {
        if (foregroundActivityRef != null && foregroundActivityRef.get() == activity) {
            foregroundActivityRef = null;
        }
    }

    // IMPLEMENT OTHER CALLBACK METHODS
}

Now to check from other classes, whether app is in foreground or not, simply call:

if(TestApplication.foregroundActivityRef!=null){
    // APP IS IN FOREGROUND!
    // We can also get the activity that is currently visible!
}

Update (as pointed out by SHS):

Do not forget to register for the callbacks in your Application class's onCreate method.

@Override
public void onCreate() {
    ...
    registerActivityLifecycleCallbacks(this);
}

C# removing items from listbox

You could try this method:

List<string> temp = new List<string>();

    foreach (string item in listBox1.Items)
    {
        string removelistitem = "OBJECT";
        if(item.Contains(removelistitem))
        {
            temp.Items.Add(item);
         }
     }

    foreach(string item in temp)
    {
       listBox1.Items.Remove(item);
    }

This should be correct as it simply copies the contents to a temporary list which is then used to delete it from the ListBox.

Everyone else please feel free to mention corrections as i'm not 100% sure it's completely correct, i used it a long time ago.

Array of strings in groovy

Most of the time you would create a list in groovy rather than an array. You could do it like this:

names = ["lucas", "Fred", "Mary"]

Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:

names = "lucas Fred Mary".split()

How do you redirect HTTPS to HTTP?

It is better to avoid using mod_rewrite when you can.

In your case I would replace the Rewrite with this:

    <If "%{HTTPS} == 'on'" >
            Redirect permanent / http://production_server/
    </If>

The <If> directive is only available in Apache 2.4+ as per this blog here.

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

How to use an arraylist as a prepared statement parameter

If you have ArrayList then convert into Array[Object]

ArrayList<String> list = new ArrayList<String>();
PreparedStatement pstmt = 
            conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", list.toArray());
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

You would expect that this is easily possible but that seems not be the case. The only way I see at the moment is to create a user defined JQL function. I never tried this but here is a plug-in:

http://confluence.atlassian.com/display/DEVNET/Plugin+Tutorial+-+Adding+a+JQL+Function+to+JIRA

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

Now on Android Studio 3 and above, you can try to sync project with gradle like:

File -> Sync Project with Gradle Files

enter image description here

How do I create a simple Qt console application in C++?

I managed to create a simple console "hello world" with QT Creator

used creator 2.4.1 and QT 4.8.0 on windows 7

two ways to do this

Plain C++

do the following

  1. File- new file project
  2. under projects select : other Project
  3. select "Plain C++ Project"
  4. enter project name 5.Targets select Desktop 'tick it'
  5. project managment just click next
  6. you can use c++ commands as normal c++

or

QT Console

  1. File- new file project
  2. under projects select : other Project
  3. select QT Console Application
  4. Targets select Desktop 'tick it'
  5. project managment just click next
  6. add the following lines (all the C++ includes you need)
  7. add "#include 'iostream' "
  8. add "using namespace std; "
  9. after QCoreApplication a(int argc, cghar *argv[]) 10 add variables, and your program code..

example: for QT console "hello world"

file - new file project 'project name '

other projects - QT Console Application

Targets select 'Desktop'

project management - next

code:

    #include <QtCore/QCoreApplication>
    #include <iostream>
    using namespace std;
    int main(int argc, char *argv[])
    {
     QCoreApplication a(argc, argv);
     cout<<" hello world";
     return a.exec();
     }

ctrl -R to run

compilers used for above MSVC 2010 (QT SDK) , and minGW(QT SDK)

hope this helps someone

As I have just started to use QT recently and also searched the Www for info and examples to get started with simple examples still searching...

How to download Google Play Services in an Android emulator?

I tried to develop google MAP API V2 application recently and tried to run it through emulator but I everytime it showed me error "Google Play Servcies is not installed in this phone". From my perpective even I think google MAP API V2 doesn't work on emulator.

Solution

Then I tried to run the same example on my Sony Experia you and again it showed me same error. Then I installed google play services on my mobile and amazingly it started working..:)))

how to find 2d array size in c++

#include <bits/stdc++.h>
using namespace std;


int main(int argc, char const *argv[])
{
    int arr[6][5] = {
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5}
    };
    int rows = sizeof(arr)/sizeof(arr[0]);
    int cols = sizeof(arr[0])/sizeof(arr[0][0]);
    cout<<rows<<" "<<cols<<endl;
    return 0;
}

Output: 6 5

Python: BeautifulSoup - get an attribute value based on the name attribute

It's pretty simple, use the following -

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<META NAME="City" content="Austin">')
>>> soup.find("meta", {"name":"City"})
<meta name="City" content="Austin" />
>>> soup.find("meta", {"name":"City"})['content']
u'Austin'

Leave a comment if anything is not clear.

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

Getting full URL of action in ASP.NET MVC

This may be just me being really, really picky, but I like to only define constants once. If you use any of the approaches defined above, your action constant will be defines multiple times.

To avoid this, you can do the following:

    public class Url
    {
        public string LocalUrl { get; }

        public Url(string localUrl)
        {
            LocalUrl = localUrl;
        }

        public override string ToString()
        {
            return LocalUrl;
        }
    }

    public abstract class Controller
    {
        public Url RootAction => new Url(GetUrl());

        protected abstract string Root { get; }

        public Url BuildAction(string actionName)
        {
            var localUrl = GetUrl() + "/" + actionName;
            return new Url(localUrl);
        }

        private string GetUrl()
        {
            if (Root == "")
            {
                return "";
            }

            return "/" + Root;
        }

        public override string ToString()
        {
            return GetUrl();
        }
    }

Then create your controllers, say for example the DataController:

    public static readonly DataController Data = new DataController();
    public class DataController : Controller
    {
        public const string DogAction = "dog";
        public const string CatAction = "cat";
        public const string TurtleAction = "turtle";

        protected override string Root => "data";

        public Url Dog => BuildAction(DogAction);
        public Url Cat => BuildAction(CatAction);
        public Url Turtle => BuildAction(TurtleAction);
    }

Then just use it like:

    // GET: Data/Cat
    [ActionName(ControllerRoutes.DataController.CatAction)]
    public ActionResult Etisys()
    {
        return View();
    }

And from your .cshtml (or any code)

<ul>
    <li><a href="@ControllerRoutes.Data.Dog">Dog</a></li>
    <li><a href="@ControllerRoutes.Data.Cat">Cat</a></li>
</ul>

This is definitely a lot more work, but I rest easy knowing compile time validation is on my side.

How to Select Every Row Where Column Value is NOT Distinct

This is significantly faster than the EXISTS way:

SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN
  (SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1)

How can I get the browser's scrollbar sizes?

This is a great answer: https://stackoverflow.com/a/986977/5914609

However in my case it did not work. And i spent hours searching for the solution.
Finally i've returned to above code and added !important to each style. And it worked.
I can not add comments below the original answer. So here is the fix:

function getScrollBarWidth () {
  var inner = document.createElement('p');
  inner.style.width = "100% !important";
  inner.style.height = "200px !important";

  var outer = document.createElement('div');
  outer.style.position = "absolute !important";
  outer.style.top = "0px !important";
  outer.style.left = "0px !important";
  outer.style.visibility = "hidden !important";
  outer.style.width = "200px !important";
  outer.style.height = "150px !important";
  outer.style.overflow = "hidden !important";
  outer.appendChild (inner);

  document.body.appendChild (outer);
  var w1 = inner.offsetWidth;
  outer.style.overflow = 'scroll !important';
  var w2 = inner.offsetWidth;
  if (w1 == w2) w2 = outer.clientWidth;

  document.body.removeChild (outer);

  return (w1 - w2);
};

What are the most-used vim commands/keypresses?

@Greg Hewgill's cheatsheet is very good. I started my switch from TextMate a few months ago. Now I'm as productive as I was with TM and constantly amazed by Vim's power.

Here is how I switched. Maybe it can be useful to you.

Grosso modo, I don't think it's a good idea to do a radical switch. Vim is very different and it's best to go progressively.

And to answer your subquestion, yes, I use all of iaIAoO everyday to enter insert mode. It certainly seems weird at first but you don't really think about it after a while.

Some commands incredibly useful for any programming related tasks:

  • r and R to replace characters
  • <C-a> and <C-x>to increase and decrease numbers
  • cit to change the content of an HTML tag, and its variants (cat, dit, dat, ci(, etc.)
  • <C-x><C-o> (mapped to ,,) for omnicompletion
  • visual block selection with <C-v>
  • and so on…

Once you are accustomed to the Vim way it becomes really hard to not hit o or x all the time when editing text in some other editor or textfield.

How do I remove carriage returns with Ruby?

Use String#strip

Returns a copy of str with leading and trailing whitespace removed.

e.g

"    hello    ".strip   #=> "hello"   
"\tgoodbye\r\n".strip   #=> "goodbye"

Using gsub

string = string.gsub(/\r/," ")
string = string.gsub(/\n/," ")

Change the spacing of tick marks on the axis of a plot?

With base graphics, the easiest way is to stop the plotting functions from drawing axes and then draw them yourself.

plot(1:10, 1:10, axes = FALSE)
axis(side = 1, at = c(1,5,10))
axis(side = 2, at = c(1,3,7,10))
box()

Multiple separate IF conditions in SQL Server

To avoid syntax errors, be sure to always put BEGIN and END after an IF clause, eg:

IF (@A!= @SA)
   BEGIN
   --do stuff
   END
IF (@C!= @SC)
   BEGIN
   --do stuff
   END

... and so on. This should work as expected. Imagine BEGIN and END keyword as the opening and closing bracket, respectively.

PHP class: Global variable as property in class

Simply use the global keyword.

e.g.:

class myClass() {
    private function foo() {
        global $MyNumber;
        ...

$MyNumber will then become accessible (and indeed modifyable) within that method.

However, the use of globals is often frowned upon (they can give off a bad code smell), so you might want to consider using a singleton class to store anything of this nature. (Then again, without knowing more about what you're trying to achieve this might be a very bad idea - a define could well be more useful.)

Maximum number of rows of CSV data in excel sheet

CSV files have no limit of rows you can add to them. Excel won't hold more that the 1 million lines of data if you import a CSV file having more lines.

Excel will actually ask you whether you want to proceed when importing more than 1 million data rows. It suggests to import the remaining data by using the text import wizard again - you will need to set the appropriate line offset.

Jquery open popup on button click for bootstrap

The answer is on the example link you provided:

http://getbootstrap.com/javascript/#modals-usage

i.e.

Call a modal with id myModal with a single line of JavaScript:

$('#myModal').modal('show');

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

In response to some comments asking questions about the behaviour of Arrays.asList() since Java 8:

    int[] arr1 = {1,2,3};
    /* 
       Arrays are objects in Java, internally int[] will be represented by 
       an Integer Array object which when printed on console shall output
       a pattern such as 
       [I@address for 1-dim int array,
       [[I@address for 2-dim int array, 
       [[F@address for 2-dim float array etc. 
   */
    System.out.println(Arrays.asList(arr1)); 

    /* 
       The line below results in Compile time error as Arrays.asList(int[] array)
       returns List<int[]>. The returned list contains only one element 
       and that is the int[] {1,2,3} 
    */
    // List<Integer> list1 = Arrays.asList(arr1);

    /* 
       Arrays.asList(arr1) is  Arrays$ArrayList object whose only element is int[] array
       so the line below prints [[I@...], where [I@... is the array object.
    */
    System.out.println(Arrays.asList(arr1)); 

    /* 
     This prints [I@..., the actual array object stored as single element 
     in the Arrays$ArrayList object. 
    */
    System.out.println(Arrays.asList(arr1).get(0));

    // prints the contents of array [1,2,3]
    System.out.println(Arrays.toString(Arrays.asList(arr1).get(0)));

    Integer[] arr2 = {1,2,3};
    /* 
     Arrays.asList(arr) is  Arrays$ArrayList object which is 
     a wrapper list object containing three elements 1,2,3.
     Technically, it is pointing to the original Integer[] array 
    */
    List<Integer> list2 = Arrays.asList(arr2);

    // prints the contents of list [1,2,3]
    System.out.println(list2);

pypi UserWarning: Unknown distribution option: 'install_requires'

This is a warning from distutils, and is a sign that you do not have setuptools installed. Installing it from http://pypi.python.org/pypi/setuptools will remove the warning.

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

Some times appeared if you declare a constant in the header file without static notation. like this

const int k = 10;

it should be:

static const int k = 10;

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

If anyone got an error while signing in to Google and this message appear:

Couldn't Sign In
can't establish a reliable connection to the server...

then try to sign in from the browser - in YouTube, Gmail, Google sites, etc.

This helped me. After signing in in the browser I was able to sign in the Google Play app...

how to pass data in an hidden field from one jsp page to another?

The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher

//Pass results back to the client
RequestDispatcher dispatcher =   getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);

How can I make a countdown with NSTimer?

Swift 5 with Closure:

class ViewController: UIViewController {
    
var secondsRemaining = 30
    
@IBAction func startTimer(_ sender: UIButton) {
        
    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
        if self.secondsRemaining > 0 {
            print ("\(self.secondsRemaining) seconds")
            self.secondsRemaining -= 1
        } else {
            Timer.invalidate()
        }
    }
            
}

npm install error - unable to get local issuer certificate

This worked for me:

export NODE_TLS_REJECT_UNAUTHORIZED=0

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

We hit a heap space issue with Ant while trying to build a very large Flex project which could not be solved by increasing the memory allocated to Ant or by adding the fork=true param. It ended up being a bug in Flex 3.4.0 sdk. I finally figured this out after polling the devs for their sdk version and reverting to 3.3.0.

For the curious.

I tracked the bug down to an Interface file that had an additional accessor pair added "get/set maskTrackSkin". The heap space error hit if any additional functions were added to the interface and to make things worse the interface was not in the project that was getting the heap space error. Hope this helps someone.

What is the difference between a mutable and immutable string in C#?

The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

What's the quickest way to multiply multiple cells by another number?

To multiply a column of numbers with a constant(same number), I have done like this.

Let C2 to C12 be different numbers which need to be multiplied by a single number (constant). Then type the numbers from C2 to C12.

In D2 type 1 (unity) and in E2 type formula =PRODUCT(C2:C12,CONSTANT). SELECT RIGHT ICON TO APPLY. NOW DRAG E2 THROUGH E12. YOU HAVE DONE IT.

C       D       E=PRODUCT(C2:C12,20)

25  1   500
30      600
35      700
40      800
45      900
50      1000
55      1100
60      1200
65      1300
70      1400
75      1500

Iterate through a HashMap

for (Map.Entry<String, String> item : hashMap.entrySet()) {
    String key = item.getKey();
    String value = item.getValue();
}

Difference between static and shared libraries?

The most significant advantage of shared libraries is that there is only one copy of code loaded in memory, no matter how many processes are using the library. For static libraries each process gets its own copy of the code. This can lead to significant memory wastage.

OTOH, a advantage of static libraries is that everything is bundled into your application. So you don't have to worry that the client will have the right library (and version) available on their system.

Multi-key dictionary in c#?

I wrote and have used this with success.

public class MultiKeyDictionary<K1, K2, V> : Dictionary<K1, Dictionary<K2, V>>  {

    public V this[K1 key1, K2 key2] {
        get {
            if (!ContainsKey(key1) || !this[key1].ContainsKey(key2))
                throw new ArgumentOutOfRangeException();
            return base[key1][key2];
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new Dictionary<K2, V>();
            this[key1][key2] = value;
        }
    }

    public void Add(K1 key1, K2 key2, V value) {
            if (!ContainsKey(key1))
                this[key1] = new Dictionary<K2, V>();
            this[key1][key2] = value;
    }

    public bool ContainsKey(K1 key1, K2 key2) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2);
    }

    public new IEnumerable<V> Values {
        get {
            return from baseDict in base.Values
                   from baseKey in baseDict.Keys
                   select baseDict[baseKey];
        }
    } 

}


public class MultiKeyDictionary<K1, K2, K3, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, V>> {
    public V this[K1 key1, K2 key2, K3 key3] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, V>();
            this[key1][key2, key3] = value;
        }
    }

    public bool ContainsKey(K1 key1, K2 key2, K3 key3) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, V>();
            this[key1][key2, key3, key4] = value;
        }
    }

    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, V>();
            this[key1][key2, key3, key4, key5] = value;
        }
    }

    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, V>();
            this[key1][key2, key3, key4, key5, key6] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, V>();
            this[key1][key2, key3, key4, key5, key6, key7] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, K8, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7, key8] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, V>();
            this[key1][key2, key3, key4, key5, key6, key7, key8] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7, key8);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, K8, K9, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7, key8, key9] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, V>();
            this[key1][key2, key3, key4, key5, key6, key7, key8, key9] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7, key8, key9);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, K10, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9, K10 key10] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7, key8, key9, key10] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, K10, V>();
            this[key1][key2, key3, key4, key5, key6, key7, key8, key9, key10] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9, K10 key10) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7, key8, key9, key10);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9, K10 key10, K11 key11] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7, key8, key9, key10, key11] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, V>();
            this[key1][key2, key3, key4, key5, key6, key7, key8, key9, key10, key11] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9, K10 key10, K11 key11) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7, key8, key9, key10, key11);
    }
}

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

No need for cut or magic, in bash you can cut a string like so:

  ORGSTRING="123456"
  CUTSTRING=${ORGSTRING:0:-3}
  echo "The original string: $ORGSTRING"
  echo "The new, shorter and faster string: $CUTSTRING"

See http://tldp.org/LDP/abs/html/string-manipulation.html

org.apache.jasper.JasperException: Unable to compile class for JSP:

This maybe caused by jar conflict. Remove the servlet-api.jar in your servlet/WEB-INF/ directory, %Tomcat home%/lib already have this lib.

How to find longest string in the table column data

For Postgres:

SELECT column
FROM table
WHERE char_length(column) = (SELECT max(char_length(column)) FROM table )

This will give you the string itself,modified for postgres from @Thorsten Kettner answer

JBoss default password

The default credentials are:

login: admin
password: admin

But if you use EAP these credentials are turned off by default and there is no active user (security reasons :)). If you want to turn on these users, you have to edit the following file in your current profile: ./deploy/management/console-mgr.sar/web-console.war/WEB-INF/classes/web-console-users.properties. It should be enough to remove the # sign from the line with the user.

If you want to create a new user, don't forget to set up the correct groups in web-console-roles.properties file.

You can easily find information where these information are stored: just open the ./conf/login-config.xml file and find the proper security domain definition. In the case of the Web Console application, it will be web-console policy.

Also if you want to have access to JMX, you have unlock JMX Console. Just check the following files in the conf/props/ directory (in your profile): jmx-console-users.properties and jmx-console-roles.properties.

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

You don't have permission to the Python folder.

sudo chown -R $USER /usr/local/lib/python2.7

Remove ALL styling/formatting from hyperlinks

You can simply define a style for links, which would override a:hover, a:visited etc.:

a {
  color: blue;
  text-decoration: none; /* no underline */
}

You can also use the inherit value if you want to use attributes from parent styles instead:

body {
  color: blue;
}
a {
  color: inherit; /* blue colors for links too */
  text-decoration: inherit; /* no underline */
}

error: pathspec 'test-branch' did not match any file(s) known to git

You can also get this error with any version of git if the remote branch was created after your last clone/fetch and your local repo doesn't know about it yet. I solved it by doing a git fetch first which "tells" your local repo about all the remote branches.

git fetch
git checkout test-branch

Calculating percentile of dataset column

Using {dplyr}:

library(dplyr)

# percentiles
infert %>% 
  mutate(PCT = ntile(age, 100))

# quartiles
infert %>% 
  mutate(PCT = ntile(age, 4))

# deciles
infert %>% 
  mutate(PCT = ntile(age, 10))

Colouring plot by factor in R

The lattice library is another good option. Here I've added a legend on the right side and jittered the points because some of them overlapped.

xyplot(Sepal.Width ~ Sepal.Length, group=Species, data=iris, 
       auto.key=list(space="right"), 
       jitter.x=TRUE, jitter.y=TRUE)

example plot

MVC pattern on Android

The best resource I found to implement MVC on Android is this post:

I followed the same design for one of my projects, and it worked great. I am a beginner on Android, so I can't say that this is the best solution.

I made one modification: I instantiated the model and the controller for each activity in the application class so that these are not recreated when the landscape-portrait mode changes.

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

Initialise a list to a specific length in Python

If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10, is good enough.

But if you want, say, a list of ten dicts, do not use [{}]*10 -- that would give you a list with the same initially-empty dict ten times, not ten distinct ones. Rather, use [{} for i in range(10)] or similar constructs, to construct ten separate dicts to make up your list.

Detecting when Iframe content has loaded (Cross browser)

See this blog post. It uses jQuery, but it should help you even if you are not using it.

Basically you add this to your document.ready()

$('iframe').load(function() {
    RunAfterIFrameLoaded();
});

How to remove foreign key constraint in sql server?

ALTER TABLE [TableName] DROP CONSTRAINT [CONSTRAINT_NAME]

But, be careful man, once you do that, you may never get a chance back, and you should read some basic database book see why we need foreign key

What is the C# version of VB.net's InputDialog?

Add reference to Microsoft.VisualBasic and use this function:

string response =  Microsoft.VisualBasic.Interaction.InputBox("What's 1+1?", "Title", "2", 0, 0);

The last 2 number is an X/Y position to display the input dialog.

How to catch exception correctly from http.request()?

Perhaps you can try adding this in your imports:

import 'rxjs/add/operator/catch';

You can also do:

return this.http.request(request)
  .map(res => res.json())
  .subscribe(
    data => console.log(data),
    err => console.log(err),
    () => console.log('yay')
  );

Per comments:

EXCEPTION: TypeError: Observable_1.Observable.throw is not a function

Similarly, for that, you can use:

import 'rxjs/add/observable/throw';

Parsing arguments to a Java command line program

Use the Apache Commons CLI library commandline.getArgs() to get arg1, arg2, arg3, and arg4. Here is some code:



    import org.apache.commons.cli.CommandLine;
    import org.apache.commons.cli.Option;
    import org.apache.commons.cli.Options;
    import org.apache.commons.cli.Option.Builder;
    import org.apache.commons.cli.CommandLineParser;
    import org.apache.commons.cli.DefaultParser;
    import org.apache.commons.cli.ParseException;

    public static void main(String[] parameters)
    {
        CommandLine commandLine;
        Option option_A = Option.builder("A")
            .required(true)
            .desc("The A option")
            .longOpt("opt3")
            .build();
        Option option_r = Option.builder("r")
            .required(true)
            .desc("The r option")
            .longOpt("opt1")
            .build();
        Option option_S = Option.builder("S")
            .required(true)
            .desc("The S option")
            .longOpt("opt2")
            .build();
        Option option_test = Option.builder()
            .required(true)
            .desc("The test option")
            .longOpt("test")
            .build();
        Options options = new Options();
        CommandLineParser parser = new DefaultParser();

        String[] testArgs =
        { "-r", "opt1", "-S", "opt2", "arg1", "arg2",
          "arg3", "arg4", "--test", "-A", "opt3", };

        options.addOption(option_A);
        options.addOption(option_r);
        options.addOption(option_S);
        options.addOption(option_test);

        try
        {
            commandLine = parser.parse(options, testArgs);

            if (commandLine.hasOption("A"))
            {
                System.out.print("Option A is present.  The value is: ");
                System.out.println(commandLine.getOptionValue("A"));
            }

            if (commandLine.hasOption("r"))
            {
                System.out.print("Option r is present.  The value is: ");
                System.out.println(commandLine.getOptionValue("r"));
            }

            if (commandLine.hasOption("S"))
            {
                System.out.print("Option S is present.  The value is: ");
                System.out.println(commandLine.getOptionValue("S"));
            }

            if (commandLine.hasOption("test"))
            {
                System.out.println("Option test is present.  This is a flag option.");
            }

            {
                String[] remainder = commandLine.getArgs();
                System.out.print("Remaining arguments: ");
                for (String argument : remainder)
                {
                    System.out.print(argument);
                    System.out.print(" ");
                }

                System.out.println();
            }

        }
        catch (ParseException exception)
        {
            System.out.print("Parse error: ");
            System.out.println(exception.getMessage());
        }
    }

iOS: Convert UTC NSDate to local Timezone

NSTimeInterval seconds; // assume this exists
NSDate* ts_utc = [NSDate dateWithTimeIntervalSince1970:seconds];

NSDateFormatter* df_utc = [[[NSDateFormatter alloc] init] autorelease];
[df_utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[df_utc setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];

NSDateFormatter* df_local = [[[NSDateFormatter alloc] init] autorelease];
[df_local setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
[df_local setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];

NSString* ts_utc_string = [df_utc stringFromDate:ts_utc];
NSString* ts_local_string = [df_local stringFromDate:ts_utc];

// you can also use NSDateFormatter dateFromString to go the opposite way

Table of formatting string parameters:

https://waracle.com/iphone-nsdateformatter-date-formatting-table/

If performance is a priority, you may want to consider using strftime

https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/strftime.3.html

Java generics - ArrayList initialization

You have strange expectations. If you gave the chain of arguments that led you to them, we might spot the flaw in them. As it is, I can only give a short primer on generics, hoping to touch on the points you might have misunderstood.

ArrayList<? extends Object> is an ArrayList whose type parameter is known to be Object or a subtype thereof. (Yes, extends in type bounds has a meaning other than direct subclass). Since only reference types can be type parameters, this is actually equivalent to ArrayList<?>.

That is, you can put an ArrayList<String> into a variable declared with ArrayList<?>. That's why a1.add(3) is a compile time error. a1's declared type permits a1 to be an ArrayList<String>, to which no Integer can be added.

Clearly, an ArrayList<?> is not very useful, as you can only insert null into it. That might be why the Java Spec forbids it:

It is a compile-time error if any of the type arguments used in a class instance creation expression are wildcard type arguments

ArrayList<ArrayList<?>> in contrast is a functional data type. You can add all kinds of ArrayLists into it, and retrieve them. And since ArrayList<?> only contains but is not a wildcard type, the above rule does not apply.

How to sort ArrayList<Long> in decreasing order?

Here's one way for your list:

list.sort(null);
Collections.reverse(list);

Or you could implement your own Comparator to sort on and eliminate the reverse step:

list.sort((o1, o2) -> o2.compareTo(o1));

Or even more simply use Collections.reverseOrder() since you're only reversing:

list.sort(Collections.reverseOrder());

How to convert from java.sql.Timestamp to java.util.Date?

java.sql.ResultSet rs;
//fill rs somehow
java.sql.Timestamp timestamp = rs.getTimestamp(1); //get first column
long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
java.util.Date date = return new java.util.Date(milliseconds);

Open button in new window?

You can acheive this using window.open() method, passing _blank as one of the parameter. You can refer the below links which has more information on this.

http://www.w3schools.com/jsref/met_win_open.asp

http://msdn.microsoft.com/en-us/library/ms536651(v=vs.85).aspx

Hope this will help you.

ERROR: Google Maps API error: MissingKeyMapError

you must create a project and collect the key in this way:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;language=en&key=()"></script>

How can I pad a value with leading zeros?

With ES6+ JavaScript:

You can "zerofill a number" with something like the following function:

/**
 * @param number The number
 * @param minLength Minimal length for your string with leading zeroes
 * @return Your formatted string
 */
function zerofill(nb, minLength) {
    // Convert your number to string.
    let nb2Str = nb.toString()

    // Guess the number of zeroes you will have to write.
    let nbZeroes = Math.max(0, minLength - nb2Str.length)

    // Compute your result.
    return `${ '0'.repeat(nbZeroes) }${ nb2Str }`
}

console.log(zerofill(5, 6))    // Displays "000005"

With ES2017+:

/**
 * @param number The number
 * @param minLength Minimal length for your string with leading zeroes
 * @return Your formatted string
 */
const zerofill = (nb, minLength) => nb.toString().padStart(minLength, '0')

console.log(zerofill(5, 6))    // Displays "000005"

Javascript to stop HTML5 video playback on modal window close

None of these worked for me using 4.1 video.js CDN. This code kills the video playing in a modal when the (.closemodal) is clicked. I had 3 videos. Someone else can refactor.


var myPlayer = videojs("my_video_1");
var myPlayer2 = videojs("my_video_2");
var myPlayer3 = videojs("my_video_3");
$(".closemodal").click(function(){
   myPlayer.pause();
myPlayer2.pause();
myPlayer3.pause();
});
});

as per their Api docs.

How do I line up 3 divs on the same row?

See my code

_x000D_
_x000D_
.float-left {_x000D_
    float:left;_x000D_
    width:300px; // or 33% for equal width independent of parent width_x000D_
}
_x000D_
<div>_x000D_
    <h2 align="center">San Andreas: Multiplayer</h2>_x000D_
    <div align="center" class="float-left">CONTENT OF COLUMN ONE GOES HERE</div>_x000D_
    <div align="center" class="float-left">CONTENT OF COLUMN TWO GOES HERE</div>_x000D_
    <div align="center" class="float-left">CONTENT OF COLUMN THREE GOES HERE</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Tomcat starts but home page cannot open with url http://localhost:8080

In my case, the port that tomcat was running on was defined in an application.properties file for 8000, not 8080. In my case, it looked like the same problem described here. Just leaving this here in case anyone has a similar setup and issue! :)

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

I needed an example using React.Component so I am posting it:

import React from 'react';
import * as Redux from 'react-redux';

class NavigationHeader extends React.Component {

}

const mapStateToProps = function (store) {
    console.log(`mapStateToProps ${store}`);
    return {
        navigation: store.navigation
    };
};

export default Redux.connect(mapStateToProps)(NavigationHeader);

WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server

Just edit the file "c:\wamp\alias\phpmyadmin.conf"

like this

<Directory "C:/wamp64/apps/phpmyadmin4.5.5.1/">
    Options Indexes FollowSymLinks MultiViews

    AllowOverride All
    Require all granted
</Directory>

Disable Buttons in jQuery Mobile

Try one of the statements below:

$('input[type=submit]').attr('disabled','disabled');

or

$('input[type=button]').attr('disabled','disabled');

UPDATE

To target a particular button, given the HTML you provided:

$('div#DT1S input[type=button]').attr('disabled','disabled');

http://jsfiddle.net/kZcd8/

Python: fastest way to create a list of n lists

Here are two methods, one sweet and simple(and conceptual), the other more formal and can be extended in a variety of situations, after having read a dataset.

Method 1: Conceptual

X2=[]
X1=[1,2,3]
X2.append(X1)
X3=[4,5,6]
X2.append(X3)
X2 thus has [[1,2,3],[4,5,6]] ie a list of lists. 

Method 2 : Formal and extensible

Another elegant way to store a list as a list of lists of different numbers - which it reads from a file. (The file here has the dataset train) Train is a data-set with say 50 rows and 20 columns. ie. Train[0] gives me the 1st row of a csv file, train[1] gives me the 2nd row and so on. I am interested in separating the dataset with 50 rows as one list, except the column 0 , which is my explained variable here, so must be removed from the orignal train dataset, and then scaling up list after list- ie a list of a list. Here's the code that does that.

Note that I am reading from "1" in the inner loop since I am interested in explanatory variables only. And I re-initialize X1=[] in the other loop, else the X2.append([0:(len(train[0])-1)]) will rewrite X1 over and over again - besides it more memory efficient.

X2=[]
for j in range(0,len(train)):
    X1=[]
    for k in range(1,len(train[0])):
        txt2=train[j][k]
        X1.append(txt2)
    X2.append(X1[0:(len(train[0])-1)])

How do I convert a list into a string with spaces in Python?

you can iterate through it to do it

my_list = ['how', 'are', 'you']
my_string = " "
for a in my_list:
    my_string = my_string + ' ' + a
print(my_string)

output is

 how are you

you can strip it to get

how are you

like this

my_list = ['how', 'are', 'you']
my_string = " "
for a in my_list:
    my_string = my_string + ' ' + a
print(my_string.strip())

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

What's the difference between ViewData and ViewBag?

Although you might not have a technical advantage to choosing one format over the other, you should be aware of some important differences between the two syntaxes. One obvious difference is that ViewBag works only when the key you’re accessing is a valid C# identifi er. For example, if you place a value in ViewData["Key With Spaces"], you can’t access that value using ViewBag because the code won’t compile. Another key issue to consider is that you cannot pass in dynamic values as parameters to extension methods. The C# compiler must know the real type of every parameter at compile time in order to choose the correct extension method. If any parameter is dynamic, compilation will fail. For example, this code will always fail: @Html.TextBox("name", ViewBag.Name). To work around this, either use ViewData["Name"] or cast the va

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

(Note: although the cloning version is potentially useful, for a simple shallow copy the constructor I mention in the other post is a better option.)

How deep do you want the copy to be, and what version of .NET are you using? I suspect that a LINQ call to ToDictionary, specifying both the key and element selector, will be the easiest way to go if you're using .NET 3.5.

For instance, if you don't mind the value being a shallow clone:

var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
                                               entry => entry.Value);

If you've already constrained T to implement ICloneable:

var newDictionary = oldDictionary.ToDictionary(entry => entry.Key, 
                                               entry => (T) entry.Value.Clone());

(Those are untested, but should work.)

Paste in insert mode?

You can also use the mouse middle button to paste in insert mode (Linux only).

Commit only part of a file in Git

For Atom users, the package github includes interactive staging, in the style of git gui. For shortcuts see the package's documentation.

Using Atom allows working with a theme that has dark background (by default, git gui has a white background).

Ripple effect on Android Lollipop CardView

Add these two like of code work like a charm for any view like Button, Linear Layout, or CardView Just put these two lines and see the magic...

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

Determine if variable is defined in Python

One possible situation where this might be needed:

If you are using finally block to close connections but in the try block, the program exits with sys.exit() before the connection is defined. In this case, the finally block will be called and the connection closing statement will fail since no connection was created.

Alternate table row color using CSS?

<script type="text/javascript">
$(function(){
  $("table.alternate_color tr:even").addClass("d0");
   $("table.alternate_color tr:odd").addClass("d1");
});
</script>

How to construct a set out of list items in python?

You can do

my_set = set(my_list)

or, in Python 3,

my_set = {*my_list}

to create a set from a list. Conversely, you can also do

my_list = list(my_set)

or, in Python 3,

my_list = [*my_set]

to create a list from a set.

Just note that the order of the elements in a list is generally lost when converting the list to a set since a set is inherently unordered. (One exception in CPython, though, seems to be if the list consists only of non-negative integers, but I assume this is a consequence of the implementation of sets in CPython and that this behavior can vary between different Python implementations.)

How can I tell gcc not to inline a function?

static __attribute__ ((noinline))  void foo()
{

}

This is what worked for me.

WAMP won't turn green. And the VCRUNTIME140.dll error

WAMP is not turning GREEN? Don`t panic

First of all check your windows update by searching "Windows Update"

or

Download updates from microsoft windows site (i had windows 7 x64 updated to service pack 1 full) windows 7 Service pack 1 download

Now there are some more downloads that support WAMP for installing time

From the readme.txt

BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing.

Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 and VC14 Even if you think you are up to date, install each package as administrator and if message "Already installed", validate Repair.

The following packages (VC9, VC10, VC11) are imperatively required to Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions VC11 and VC14 is required for PHP 7 and Apache 2.4.17

VC9 Packages (Visual C++ 2008 SP1) https://www.microsoft.com/en-us/download/details.aspx?id=5582 https://www.microsoft.com/en-us/download/details.aspx?id=2092

VC10 Packages (Visual C++ 2010 SP1) https://www.microsoft.com/en-us/download/details.aspx?id=8328 https://www.microsoft.com/en-us/download/details.aspx?id=13523

VC11 Packages (Visual C++ 2012 Update 4) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=30679

VC13 Packages[/b] (Visual C++ 2013) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe

VC14 Packages (Visual C++ 2015) The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page: https://www.microsoft.com/en-us/download/details.aspx?id=52685

VC Packages x64 (Visual C++ 2017)

https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads

Determine project root from a running node.js application

Actually, i find the perhaps trivial solution also to most robust: you simply place the following file at the root directory of your project: root-path.js which has the following code:

import * as path from 'path'
const projectRootPath = path.resolve(__dirname)
export const rootPath = projectRootPath

Difference between Big-O and Little-O Notation

Big-O is to little-o as = is to <. Big-O is an inclusive upper bound, while little-o is a strict upper bound.

For example, the function f(n) = 3n is:

  • in O(n²), o(n²), and O(n)
  • not in O(lg n), o(lg n), or o(n)

Analogously, the number 1 is:

  • = 2, < 2, and = 1
  • not = 0, < 0, or < 1

Here's a table, showing the general idea:

Big o table

(Note: the table is a good guide but its limit definition should be in terms of the superior limit instead of the normal limit. For example, 3 + (n mod 2) oscillates between 3 and 4 forever. It's in O(1) despite not having a normal limit, because it still has a lim sup: 4.)

I recommend memorizing how the Big-O notation converts to asymptotic comparisons. The comparisons are easier to remember, but less flexible because you can't say things like nO(1) = P.

Creating NSData from NSString in Swift

Swift 4.2

let data = yourString.data(using: .utf8, allowLossyConversion: true)

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

Just a small hack. Update the URL in the file "hudson.model.UpdateCenter.xml" from https to http

<?xml version='1.1' encoding='UTF-8'?>
<sites>
  <site>
    <id>default</id>
    <url>http://updates.jenkins.io/update-center.json</url>
  </site>
</sites>

How to skip "are you sure Y/N" when deleting files in batch files

Use del /F /Q to force deletion of read-only files (/F) and directories and not ask to confirm (/Q) when deleting via wildcard.

String to list in Python

>>> 'QH QD JC KD JS'.split()
['QH', 'QD', 'JC', 'KD', 'JS']

split:

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made).

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

For example, ' 1 2 3 '.split() returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 '].

Java: getMinutes and getHours

One more way of getting minutes and hours is by using SimpleDateFormat.

SimpleDateFormat formatMinutes = new SimpleDateFormat("mm")
String getMinutes = formatMinutes.format(new Date())

SimpleDateFormat formatHours = new SimpleDateFormat("HH")
String getHours = formatHours.format(new Date())

Docker - Container is not running

By default, docker container will exit immediately if you do not have any task running on the container.

To keep the container running in the background, try to run it with --detach (or -d) argument.

For examples:

docker pull debian

docker run -t -d --name my_debian debian
e7672d54b0c2

docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
e7672d54b0c2        debian              "bash"              3 minutes ago       Up 3 minutes                            my_debian

#now you can execute command on the container
docker exec -it my_debian bash
root@e7672d54b0c2:/# 

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.1'

defaultConfig {
    applicationId ""
    minSdkVersion 14
    targetSdkVersion 22
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.android.support:recyclerview-v7:23.0.0'
compile 'com.android.support:appcompat-v7:23.0.1'
}

afxwin.h file is missing in VC++ Express Edition

Including the header afxwin.h signalizes use of MFC. The following instructions (based on those on CodeProject.com) could help to get MFC code compiling:

  1. Download and install the Windows Driver Kit.

  2. Select menu Tools > Options… > Projects and Solutions > VC++ Directories.

  3. In the drop-down menu Show directories for select Include files.

  4. Add the following paths (replace $(WDK_directory) with the directory where you installed Windows Driver Kit in the first step):

    $(WDK_directory)\inc\mfc42
    $(WDK_directory)\inc\atl30
    

  5. In the drop-down menu Show directories for select Library files and add (replace $(WDK_directory) like before):

    $(WDK_directory)\lib\mfc\i386
    $(WDK_directory)\lib\atl\i386
    

  6. In the $(WDK_directory)\inc\mfc42\afxwin.inl file, edit the following lines (starting from 1033):

    _AFXWIN_INLINE CMenu::operator==(const CMenu& menu) const
        { return ((HMENU) menu) == m_hMenu; }
    _AFXWIN_INLINE CMenu::operator!=(const CMenu& menu) const
        { return ((HMENU) menu) != m_hMenu; }
    

    to

    _AFXWIN_INLINE BOOL CMenu::operator==(const CMenu& menu) const
        { return ((HMENU) menu) == m_hMenu; }
    _AFXWIN_INLINE BOOL CMenu::operator!=(const CMenu& menu) const
        { return ((HMENU) menu) != m_hMenu; }
    

    In other words, add BOOL after _AFXWIN_INLINE.

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

If you can't/won't use iterators and if you can't/won't use std::size_t for the loop index, make a .size() to int conversion function that documents the assumption and does the conversion explicitly to silence the compiler warning.

#include <cassert>
#include <cstddef>
#include <limits>

// When using int loop indexes, use size_as_int(container) instead of
// container.size() in order to document the inherent assumption that the size
// of the container can be represented by an int.
template <typename ContainerType>
/* constexpr */ int size_as_int(const ContainerType &c) {
    const auto size = c.size();  // if no auto, use `typename ContainerType::size_type`
    assert(size <= static_cast<std::size_t>(std::numeric_limits<int>::max()));
    return static_cast<int>(size);
}

Then you write your loops like this:

for (int i = 0; i < size_as_int(things); ++i) { ... }

The instantiation of this function template will almost certainly be inlined. In debug builds, the assumption will be checked. In release builds, it won't be and the code will be as fast as if you called size() directly. Neither version will produce a compiler warning, and it's only a slight modification to the idiomatic loop.

If you want to catch assumption failures in the release version as well, you can replace the assertion with an if statement that throws something like std::out_of_range("container size exceeds range of int").

Note that this solves both the signed/unsigned comparison as well as the potential sizeof(int) != sizeof(Container::size_type) problem. You can leave all your warnings enabled and use them to catch real bugs in other parts of your code.

Initialization of an ArrayList in one line

The simple answer

In Java 9 or later, after List.of() was added:

List<String> strings = List.of("foo", "bar", "baz");

With Java 10 or later, this can be shortened with the var keyword.

var strings = List.of("foo", "bar", "baz");

This will give you an immutable List, so it cannot be changed.
Which is what you want in most cases where you're prepopulating it.


Java 8 or earlier:

List<String> strings = Arrays.asList("foo", "bar", "baz");

This will give you a List backed by an array, so it cannot change length.
But you can call List.set, so it's still mutable.


You can make Arrays.asList even shorter with a static import:

List<String> strings = asList("foo", "bar", "baz");

The static import:

import static java.util.Arrays.asList;  

Which any modern IDE will suggest and automatically do for you.
For example in IntelliJ IDEA you press Alt+Enter and select Static import method....


However, i don't recommend shortening the List.of method to of, because that becomes confusing.
List.of is already short enough and reads well.


Using Streams

Why does it have to be a List?
With Java 8 or later you can use a Stream which is more flexible:

Stream<String> strings = Stream.of("foo", "bar", "baz");

You can concatenate Streams:

Stream<String> strings = Stream.concat(Stream.of("foo", "bar"),
                                       Stream.of("baz", "qux"));

Or you can go from a Stream to a List:

import static java.util.stream.Collectors.toList;

List<String> strings = Stream.of("foo", "bar", "baz").collect(toList());

But preferably, just use the Stream without collecting it to a List.


If you really specifically need a java.util.ArrayList

(You probably don't.)
To quote JEP 269 (emphasis mine):

There is a small set of use cases for initializing a mutable collection instance with a predefined set of values. It's usually preferable to have those predefined values be in an immutable collection, and then to initialize the mutable collection via a copy constructor.


If you want to both prepopulate an ArrayList and add to it afterwards (why?), use

ArrayList<String> strings = new ArrayList<>(List.of("foo", "bar"));
strings.add("baz");

or in Java 8 or earlier:

ArrayList<String> strings = new ArrayList<>(asList("foo", "bar"));
strings.add("baz");

or using Stream:

import static java.util.stream.Collectors.toCollection;

ArrayList<String> strings = Stream.of("foo", "bar")
                             .collect(toCollection(ArrayList::new));
strings.add("baz");

But again, it's better to just use the Stream directly instead of collecting it to a List.


Program to interfaces, not to implementations

You said you've declared the list as an ArrayList in your code, but you should only do that if you're using some member of ArrayList that's not in List.

Which you are most likely not doing.

Usually you should just declare variables by the most general interface that you are going to use (e.g. Iterable, Collection, or List), and initialize them with the specific implementation (e.g. ArrayList, LinkedList or Arrays.asList()).

Otherwise you're limiting your code to that specific type, and it'll be harder to change when you want to.

For example, if you're passing an ArrayList to a void method(...):

// Iterable if you just need iteration, for (String s : strings):
void method(Iterable<String> strings) { 
    for (String s : strings) { ... } 
}

// Collection if you also need .size(), .isEmpty(), or .stream():
void method(Collection<String> strings) {
    if (!strings.isEmpty()) { strings.stream()... }
}

// List if you also need .get(index):
void method(List<String> strings) {
    strings.get(...)
}

// Don't declare a specific list implementation
// unless you're sure you need it:
void method(ArrayList<String> strings) {
    ??? // You don't want to limit yourself to just ArrayList
}

Another example would be always declaring variable an InputStream even though it is usually a FileInputStream or a BufferedInputStream, because one day soon you or somebody else will want to use some other kind of InputStream.

Why can templates only be implemented in the header file?

If the concern is the extra compilation time and binary size bloat produced by compiling the .h as part of all the .cpp modules using it, in many cases what you can do is make the template class descend from a non-templatized base class for non type-dependent parts of the interface, and that base class can have its implementation in the .cpp file.

Reference to non-static member function must be called

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

Not receiving Google OAuth refresh token

In order to get the refresh_token you need to include access_type=offline in the OAuth request URL. When a user authenticates for the first time you will get back a non-nil refresh_token as well as an access_token that expires.

If you have a situation where a user might re-authenticate an account you already have an authentication token for (like @SsjCosty mentions above), you need to get back information from Google on which account the token is for. To do that, add profile to your scopes. Using the OAuth2 Ruby gem, your final request might look something like this:

client = OAuth2::Client.new(
  ENV["GOOGLE_CLIENT_ID"],
  ENV["GOOGLE_CLIENT_SECRET"],
  authorize_url: "https://accounts.google.com/o/oauth2/auth",
  token_url: "https://accounts.google.com/o/oauth2/token"
)

# Configure authorization url
client.authorize_url(
  scope: "https://www.googleapis.com/auth/analytics.readonly profile",
  redirect_uri: callback_url,
  access_type: "offline",
  prompt: "select_account"
)

Note the scope has two space-delimited entries, one for read-only access to Google Analytics, and the other is just profile, which is an OpenID Connect standard.

This will result in Google providing an additional attribute called id_token in the get_token response. To get information out of the id_token, check out this page in the Google docs. There are a handful of Google-provided libraries that will validate and “decode” this for you (I used the Ruby google-id-token gem). Once you get it parsed, the sub parameter is effectively the unique Google account ID.

Worth noting, if you change the scope, you'll get back a refresh token again for users that have already authenticated with the original scope. This is useful if, say, you have a bunch of users already and don't want to make them all un-auth the app in Google.

Oh, and one final note: you don't need prompt=select_account, but it's useful if you have a situation where your users might want to authenticate with more than one Google account (i.e., you're not using this for sign-in / authentication).

restrict edittext to single line

android:singleLine is now deprecated. From the documentation:

This constant was deprecated in API level 3.

This attribute is deprecated. Use maxLines instead to change the layout of a static text, and use the textMultiLine flag in the inputType attribute instead for editable text views (if both singleLine and inputType are supplied, the inputType flags will override the value of singleLine).

So you could just set android:inputType="textEmailSubject" or any other value that matches the content of the field.

Check if value is zero or not null in python

Zero and None both treated as same for if block, below code should work fine.

if number or number==0:
    return True

How can I find out what version of git I'm running?

If you're using the command-line tools, running git --version should give you the version number.

Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

or

case 
    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

What is the point of WORKDIR on Dockerfile?

You dont have to

RUN mkdir -p /usr/src/app

This will be created automatically when you specifiy your WORKDIR

FROM node:latest
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY . ./
EXPOSE 3000
CMD [ “npm”, “start” ] 

YouTube: How to present embed video with sound muted

The accepted answer was not working for me, I followed this tutorial instead with success.

Basically:

<div id="muteYouTubeVideoPlayer"></div>
<script async src="https://www.youtube.com/iframe_api"></script>
<script>
 function onYouTubeIframeAPIReady() {
  var player;
  player = new YT.Player('muteYouTubeVideoPlayer', {
    videoId: 'YOUR_VIDEO_ID', // YouTube Video ID
    width: 560,               // Player width (in px)
    height: 316,              // Player height (in px)
    playerVars: {
      autoplay: 1,        // Auto-play the video on load
      controls: 1,        // Show pause/play buttons in player
      showinfo: 0,        // Hide the video title
      modestbranding: 1,  // Hide the Youtube Logo
      loop: 1,            // Run the video in a loop
      fs: 0,              // Hide the full screen button
      cc_load_policy: 0, // Hide closed captions
      iv_load_policy: 3,  // Hide the Video Annotations
      autohide: 0         // Hide video controls when playing
    },
    events: {
      onReady: function(e) {
        e.target.mute();
      }
    }
  });
 }

 // Written by @labnol 
</script>

jQuery: Wait/Delay 1 second without executing code

function sleep(num) {
    var now = new Date();
    var stop = now.getTime() + num;
    while(true) {
        now = new Date();
        if(now.getTime() > stop) return;
    }
}

sleep(1000);   // 1 second 
alert('here');

this code work well for me.

Trust Store vs Key Store - creating with keytool

keystore simply stores private keys, wheras truststore stores public keys. You will want to generate a java certificate for SSL communication. You can use a keygen command in windows, this will probably be the most easy solution.

How to round up integer division and have int result in Java?

long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();

How to open a new window on form submit

In a web-based database application that uses a pop-up window to display print-outs of database data, this worked well enough for our needs (tested in Chrome 48):

<form method="post" 
      target="print_popup" 
      action="/myFormProcessorInNewWindow.aspx"
      onsubmit="window.open('about:blank','print_popup','width=1000,height=800');">

The trick is to match the target attribute on the <form> tag with the second argument in the window.open call in the onsubmit handler.

How do I select an entire row which has the largest ID in the table?

You can not give order by because order by does a "full scan" on a table.

The following query is better:

SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table);

HTML 5 input type="number" element for floating point numbers on Chrome

Try <input type="number" step="0.01" /> if you are targeting 2 decimal places :-).

how to set default culture info for entire c# application

With 4.0, you will need to manage this yourself by setting the culture for each thread as Alexei describes. But with 4.5, you can define a culture for the appdomain and that is the preferred way to handle this. The relevant apis are CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture.

How do I set default terminal to terminator?

Copy-paste the following into your current terminal:

gsettings set org.gnome.desktop.default-applications.terminal exec /usr/bin/terminator
gsettings set org.gnome.desktop.default-applications.terminal exec-arg "-x"

This modifies the dconf to make terminator the default program. You could also use dconf-editor (a GUI-based tool) to make changes to the dconf, as another answer has suggested. If you would like to learn and understand more about this topic, this may help you.

Line break in HTML with '\n'

you can use <pre> tag :

_x000D_
_x000D_
<div class="text">_x000D_
<pre>_x000D_
abc_x000D_
def_x000D_
ghi_x000D_
</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

How to compare types

You can compare for exactly the same type using:

class A {
}
var a = new A();
var typeOfa = a.GetType();
if (typeOfa == typeof(A)) {
}

typeof returns the Type object from a given class.

But if you have a type B, that inherits from A, then this comparison is false. And you are looking for IsAssignableFrom.

class B : A {
}
var b = new B();
var typeOfb = b.GetType();

if (typeOfb == typeof(A)) { // false
}

if (typeof(A).IsAssignableFrom(typeOfb)) { // true
}

Get current NSDate in timestamp format

- (void)GetCurrentTimeStamp
    {
        NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
        [objDateformat setDateFormat:@"yyyy-MM-dd"];
        NSString    *strTime = [objDateformat stringFromDate:[NSDate date]];
        NSString    *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter.
        NSDate *objUTCDate  = [objDateformat dateFromString:strUTCTime];
        long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);

        NSString *strTimeStamp = [NSString stringWithFormat:@"%lld",milliseconds];
NSLog(@"The Timestamp is = %@",strTimeStamp);
    }

 - (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate  *objDate    = [dateFormatter dateFromString:IN_strLocalTime];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSString *strDateTime   = [dateFormatter stringFromDate:objDate];
        return strDateTime;
    }

NOTE :- The Timestamp must be in UTC Zone, So I convert our local Time to UTC Time.

How to copy a file from one directory to another using PHP?

<?php  
  
// Copy the file from /user/desktop/geek.txt  
// to user/Downloads/geeksforgeeks.txt' 
// directory 
  
// Store the path of source file 
$source = '/user/Desktop/geek.txt';  
  
// Store the path of destination file 
$destination = 'user/Downloads/geeksforgeeks.txt';  
  
// Copy the file from /user/desktop/geek.txt  
// to user/Downloads/geeksforgeeks.txt' 
// directory 
if( !copy($source, $destination) ) {  
    echo "File can't be copied! \n";  
}  
else {  
    echo "File has been copied! \n";  
}  
  
?>  

Change DataGrid cell colour based on values

If you need to do it with a set number of columns, H.B.'s way is best. But if you don't know how many columns you are dealing with until runtime, then the below code [read: hack] will work. I am not sure if there is a better solution with an unknown number of columns. It took me two days working at it off and on to get it, so I'm sticking with it regardless.

C#

public class ValueToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int input;
        try
        {
            DataGridCell dgc = (DataGridCell)value;
            System.Data.DataRowView rowView = (System.Data.DataRowView)dgc.DataContext;
            input = (int)rowView.Row.ItemArray[dgc.Column.DisplayIndex];
        }
        catch (InvalidCastException e)
        {
            return DependencyProperty.UnsetValue;
        }
        switch (input)
        {
            case 1: return Brushes.Red;
            case 2: return Brushes.White;
            case 3: return Brushes.Blue;
            default: return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

XAML

<UserControl.Resources>
    <conv:ValueToBrushConverter x:Key="ValueToBrushConverter"/>
    <Style x:Key="CellStyle" TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
    </Style>
</UserControl.Resources>
<DataGrid x:Name="dataGrid" CellStyle="{StaticResource CellStyle}">
</DataGrid>

click command in selenium webdriver does not work

If you know for sure that the element is present, you could try this to simulate the click - if .Click() isn't working

driver.findElement(By.name("submit")).sendKeys(Keys.RETURN);

or

driver.findElement(By.name("submit")).sendKeys(Keys.ENTER);

Why does the order in which libraries are linked sometimes cause errors in GCC?

You may can use -Xlinker option.

g++ -o foobar  -Xlinker -start-group  -Xlinker libA.a -Xlinker libB.a -Xlinker libC.a  -Xlinker -end-group 

is ALMOST equal to

g++ -o foobar  -Xlinker -start-group  -Xlinker libC.a -Xlinker libB.a -Xlinker libA.a  -Xlinker -end-group 

Careful !

  1. The order within a group is important ! Here's an example: a debug library has a debug routine, but the non-debug library has a weak version of the same. You must put the debug library FIRST in the group or you will resolve to the non-debug version.
  2. You need to precede each library in the group list with -Xlinker

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

When I had this problem it was because I was trying to use an actual function in place of an anonymous function.

Incorrect:

$(document).on('change', "#MyId", MyFunction());

Correct

$(document).on('change', "#MyId", MyFunction);

or also correct and if you need to pass event object or other params.

$(document).on('change', "#MyId", function(e) { MyFunction(e); });

Check if passed argument is file or directory in Bash

This should work:

#!/bin/bash

echo "Enter your Path:"
read a

if [[ -d $a ]]; then 
    echo "$a is a Dir" 
elif [[ -f $a ]]; then 
    echo "$a is the File" 
else 
    echo "Invalid path" 
fi

Tracing XML request/responses with JAX-WS

Following options enable logging of all communication to the console (technically, you only need one of these, but that depends on the libraries you use, so setting all four is safer option). You can set it in the code like in example, or as command line parameter using -D or as environment variable as Upendra wrote.

System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dumpTreshold", "999999");

See question Tracing XML request/responses with JAX-WS when error occurs for details.

How to set a Timer in Java?

    new java.util.Timer().schedule(new TimerTask(){
        @Override
        public void run() {
            System.out.println("Executed...");
           //your code here 
           //1000*5=5000 mlsec. i.e. 5 seconds. u can change accordngly 
        }
    },1000*5,1000*5); 

Writing Python lists to columns in csv

The following code writes python lists into columns in csv

import csv
from itertools import zip_longest
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j']
d = [list1, list2]
export_data = zip_longest(*d, fillvalue = '')
with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
      wr = csv.writer(myfile)
      wr.writerow(("List1", "List2"))
      wr.writerows(export_data)
myfile.close()

The output looks like this

enter image description here

C# "internal" access modifier when doing unit testing

If you want to test private methods, have a look at PrivateObject and PrivateType in the Microsoft.VisualStudio.TestTools.UnitTesting namespace. They offer easy to use wrappers around the necessary reflection code.

Docs: PrivateType, PrivateObject

For VS2017 & 2019, you can find these by downloading the MSTest.TestFramework nuget

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

If anyone is having this exception and is building the query using Scala multi-line strings:

Looks like there is a problem with some JPA drivers in this situation. I'm not sure what is the character Scala uses for LINE END, but when you have a parameter right at the end of the line, the LINE END character seems to be attached to the parameter and so when the driver parses the query, this error comes up. A simple work around is to leave an empty space right after the param at the end:

SELECT * FROM some_table a
WHERE a.col = ?param
AND a.col2 = ?param2

So, just make sure to leave an empty space after param (and param2, if you have a line break there).

How do I create a link using javascript?

_x000D_
_x000D_
    <script>_x000D_
      _$ = document.querySelector  .bind(document) ;_x000D_
_x000D_
        var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs_x000D_
        var a   =  document.createElement( 'a' )_x000D_
        a.text  = "Download example" _x000D_
        a.href  = "//bit\.do/DeezerDL"_x000D_
_x000D_
        AppendLinkHere.appendChild( a )_x000D_
        _x000D_
_x000D_
     // a.title = 'Well well ... _x000D_
        a.setAttribute( 'title', _x000D_
                         'Well well that\'s a link'_x000D_
                      );_x000D_
    </script>
_x000D_
_x000D_
_x000D_

  1. The 'Anchor Object' has its own*(inherited)* properties for setting the link, its text. So just use them. .setAttribute is more general but you normally don't need it. a.title ="Blah" will do the same and is more clear! Well a situation that'll demand .setAttribute is this: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")

  2. Leave the protocol open. Instead of http://example.com/path consider to just use //example.com/path. Check if example.com can be accessed by http: as well as https: but 95 % of sites will work on both.

  3. OffTopic: That's not really relevant about creating links in JS but maybe good to know: Well sometimes like in the chromes dev-console you can use $("body") instead of document.querySelector("body") A _$ = document.querySelectorwill 'honor' your efforts with an Illegal invocation error the first time you use it. That's because the assignment just 'grabs' .querySelector (a ref to the class method). With .bind(... you'll also involve the context (here it's document) and you get an object method that'll work as you might expect it.

Find and Replace Inside a Text File from a Bash Command

You can use sed:

sed -i 's/abc/XYZ/gi' /tmp/file.txt

You can use find and sed if you don't know your filename:

find ./ -type f -exec sed -i 's/abc/XYZ/gi' {} \;

Find and replace in all Python files:

find ./ -iname "*.py" -type f -exec sed -i 's/abc/XYZ/gi' {} \;

Maximum and Minimum values for ints

If you want the max for array or list indices (equivalent to size_t in C/C++), you can use numpy:

np.iinfo(np.intp).max

This is same as sys.maxsize however advantage is that you don't need import sys just for this.

If you want max for native int on the machine:

np.iinfo(np.intc).max

You can look at other available types in doc.

For floats you can also use sys.float_info.max.