Programs & Examples On #Irix

IRIX is the UNIX System V operating system produced by Silicon Graphics Inc.

in_array() and multidimensional array

Please try:

in_array("irix",array_keys($b))
in_array("Linux",array_keys($b["irix"])

Im not sure about the need, but this might work for your requirement

what's data-reactid attribute in html?

data attributes are commonly used for a variety of interactions. Typically via javascript. They do not affect anything regarding site behavior and stand as a convenient method to pass data for whatever purpose needed. Here is an article that may clear things up:

http://ejohn.org/blog/html-5-data-attributes/

You can create a data attribute by prefixing data- to any standard attribute safe string (alphanumeric with no spaces or special characters). For example, data-id or in this case data-reactid

How to convert a const char * to std::string

What you want is this constructor: std::string ( const string& str, size_t pos, size_t n = npos ), passing pos as 0. Your const char* c-style string will get implicitly cast to const string for the first parameter.

const char *c_style = "012abd";
std::string cpp_style = new std::string(c_style, 0, 10);

How to have a default option in Angular.js select box

Try this:

HTML

<select 
    ng-model="selectedOption" 
    ng-options="option.name for option in options">
</select>

Javascript

function Ctrl($scope) {
    $scope.options = [
        {
          name: 'Something Cool',
          value: 'something-cool-value'
        }, 
        {
          name: 'Something Else',
          value: 'something-else-value'
        }
    ];

    $scope.selectedOption = $scope.options[0];
}

Plunker here.

If you really want to set the value that will be bound to the model, then change the ng-options attribute to

ng-options="option.value as option.name for option in options"

and the Javascript to

...
$scope.selectedOption = $scope.options[0].value;

Another Plunker here considering the above.

How to escape the equals sign in properties files

This method should help to programmatically generate values guaranteed to be 100% compatible with .properties files:

public static String escapePropertyValue(final String value) {
    if (value == null) {
        return null;
    }

    try (final StringWriter writer = new StringWriter()) {
        final Properties properties = new Properties();
        properties.put("escaped", value);
        properties.store(writer, null);
        writer.flush();

        final String stringifiedProperties = writer.toString();
        final Pattern pattern = Pattern.compile("(.*?)escaped=(.*?)" + Pattern.quote(System.lineSeparator()) + "*");
        final Matcher matcher = pattern.matcher(stringifiedProperties);

        if (matcher.find() && matcher.groupCount() <= 2) {
            return matcher.group(matcher.groupCount());
        }

        // This should never happen unless the internal implementation of Properties::store changed
        throw new IllegalStateException("Could not escape property value");
    } catch (final IOException ex) {
        // This should never happen. IOException is only because the interface demands it
        throw new IllegalStateException("Could not escape property value", ex);
    }
}

You can call it like this:

final String escapedPath = escapePropertyValue("C:\\Users\\X");
writeToFile(escapedPath); // will pass "C\\:\\\\Users\\\\X"

This method a little bit expensive but, writing properties to a file is typically an sporadic operation anyway.

How to print a dictionary line by line in Python?

pprint.pprint() is a good tool for this job:

>>> import pprint
>>> cars = {'A':{'speed':70,
...         'color':2},
...         'B':{'speed':60,
...         'color':3}}
>>> pprint.pprint(cars, width=1)
{'A': {'color': 2,
       'speed': 70},
 'B': {'color': 3,
       'speed': 60}}

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

Old thread, but the question is still relevant, so...

(1) The example in your question now DOES work in Firefox. However in addition to calling the event handler (which displays an alert), it ALSO clicks on the link, causing navigation (once the alert is dismissed).

(2) To JUST call the event handler (without triggering navigation) merely replace:

document.getElementById('linkid').click();

with

document.getElementById('linkid').onclick();

jQuery ajax success callback function definition

I do not know why you are defining the parameter outside the script. That is unnecessary. Your callback function will be called with the return data as a parameter automatically. It is very possible to define your callback outside the sucess: i.e.

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

function handleData(data) {
    alert(data);
    //do some stuff
}

the handleData function will be called and the parameter passed to it by the ajax function.

How to parse a JSON object to a TypeScript Object

First of all you need to be sure that all attributes of that comes from the service are named the same in your class. Then you can parse the object and after that assign it to your new variable, something like this:

const parsedJSON = JSON.parse(serverResponse);
const employeeObj: Employee = parsedJSON as Employee;

Try that!

How does System.out.print() work?

The scenarios that you have mentioned are not of overloading, you are just concatenating different variables with a String.

System.out.print("Hello World");

System.out.print("My name is" + foo);

System.out.print("Sum of " + a + "and " + b + "is " + c); 

System.out.print("Total USD is " + usd);

in all of these cases, you are only calling print(String s) because when something is concatenated with a string it gets converted to a String by calling the toString() of that object, and primitives are directly concatenated. However if you want to know of different signatures then yes print() is overloaded for various arguments.

How to save a figure in MATLAB from the command line?

try plot(var); saveFigure('title'); it will save as a jpeg automatically

What is bootstrapping?

For completeness, it is also a rather important (and relatively new) method in statistics that uses resampling / simulation to infer population properties from a sample. It has its own lengthy Wikipedia article on bootstrapping (statistics).

Force drop mysql bypassing foreign key constraint

Simple solution to drop all the table at once from terminal.

This involved few steps inside your mysql shell (not a one step solution though), this worked me and saved my day.

Worked for Server version: 5.6.38 MySQL Community Server (GPL)

Steps I followed:

 1. generate drop query using concat and group_concat.
 2. use database
 3. turn off / disable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 0;), 
 4. copy the query generated from step 1
 5. re enable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 1;)
 6. run show table

MySQL shell

$ mysql -u root -p
Enter password: ****** (your mysql root password)
mysql> SYSTEM CLEAR;
mysql> SELECT CONCAT('DROP TABLE IF EXISTS `', GROUP_CONCAT(table_name SEPARATOR '`, `'), '`;') AS dropquery FROM information_schema.tables WHERE table_schema = 'emall_duplicate';
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| dropquery                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`; |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> USE emall_duplicate;
Database changed
mysql> SET FOREIGN_KEY_CHECKS = 0;                                                                                                                                                   Query OK, 0 rows affected (0.00 sec)

// copy and paste generated query from step 1
mysql> DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`;
Query OK, 0 rows affected (0.18 sec)

mysql> SET FOREIGN_KEY_CHECKS = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW tables;
Empty set (0.01 sec)

mysql> 

Android ListView selected item stay highlighted

*please be sure there is no Ripple at your root layout of list view container

add this line to your list view

android:listSelector="@drawable/background_listview"

here is the "background_listview.xml" file

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/white_background" android:state_pressed="true" />
<item android:drawable="@color/primary_color" android:state_focused="false" /></selector>

the colors that used in the background_listview.xml file :

<color name="primary_color">#cc7e00</color>
<color name="white_background">#ffffffff</color>

after these

(clicked item contain orange color until you click another item)

How can I use Bash syntax in Makefile targets?

One way that also works is putting it this way in the first line of the your target:

your-target: $(eval SHELL:=/bin/bash)
    @echo "here shell is $$0"

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

RookieRick is right, using DataGridTemplateColumn instead of DataGridComboBoxColumn gives a much simpler XAML.

Moreover, putting the CompanyItem list directly accessible from the GridItem allows you to get rid of the RelativeSource.

IMHO, this give you a very clean solution.

XAML:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding GridItems}" >
    <DataGrid.Resources>
        <DataTemplate x:Key="CompanyDisplayTemplate" DataType="vm:GridItem">
            <TextBlock Text="{Binding Company}" />
        </DataTemplate>
        <DataTemplate x:Key="CompanyEditingTemplate" DataType="vm:GridItem">
            <ComboBox SelectedItem="{Binding Company}" ItemsSource="{Binding CompanyList}" />
        </DataTemplate>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}" />
        <DataGridTemplateColumn CellTemplate="{StaticResource CompanyDisplayTemplate}"
                                CellEditingTemplate="{StaticResource CompanyEditingTemplate}" />
    </DataGrid.Columns>
</DataGrid>

View model:

public class GridItem
{
    public string Name { get; set; }
    public CompanyItem Company { get; set; }
    public IEnumerable<CompanyItem> CompanyList { get; set; }
}

public class CompanyItem
{
    public int ID { get; set; }
    public string Name { get; set; }

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

public class ViewModel
{
    readonly ObservableCollection<CompanyItem> companies;

    public ViewModel()
    {
        companies = new ObservableCollection<CompanyItem>{
            new CompanyItem { ID = 1, Name = "Company 1" },
            new CompanyItem { ID = 2, Name = "Company 2" }
        };

        GridItems = new ObservableCollection<GridItem> {
            new GridItem { Name = "Jim", Company = companies[0], CompanyList = companies}
        };
    }

    public ObservableCollection<GridItem> GridItems { get; set; }
}

MySQL: is a SELECT statement case sensitive?

The collation you pick sets whether you are case sensitive or not.

Convert np.array of type float64 to type uint8 scaling values

Considering that you are using OpenCV, the best way to convert between data types is to use normalize function.

img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

However, if you don't want to use OpenCV, you can do this in numpy

def convert(img, target_type_min, target_type_max, target_type):
    imin = img.min()
    imax = img.max()

    a = (target_type_max - target_type_min) / (imax - imin)
    b = target_type_max - a * imax
    new_img = (a * img + b).astype(target_type)
    return new_img

And then use it like this

imgu8 = convert(img16u, 0, 255, np.uint8)

This is based on the answer that I found on crossvalidated board in comments under this solution https://stats.stackexchange.com/a/70808/277040

Do AJAX requests retain PHP Session info?

What you're really getting at is: are cookies sent to with the AJAX request? Assuming the AJAX request is to the same domain (or within the domain constraints of the cookie), the answer is yes. So AJAX requests back to the same server do retain the same session info (assuming the called scripts issue a session_start() as per any other PHP script wanting access to session information).

jQuery, checkboxes and .is(":checked")

I'm still experiencing this behavior with jQuery 1.7.2. A simple workaround is to defer the execution of the click handler with setTimeout and let the browser do its magic in the meantime:

$("#myCheckbox").click( function() {
    var that = this;
    setTimeout(function(){
        alert($(that).is(":checked"));
    });
});

How to declare and add items to an array in Python?

You can also do:

array = numpy.append(array, value)

Note that the numpy.append() method returns a new object, so if you want to modify your initial array, you have to write: array = ...

how to start the tomcat server in linux?

Use ./catalina.sh start to start Tomcat. Do ./catalina.sh to get the usage.

I am using apache-tomcat-6.0.36.

How can I solve the error 'TS2532: Object is possibly 'undefined'?

Edit / Update:

If you are using Typescript 3.7 or newer you can now also do:

    const data = change?.after?.data();

    if(!data) {
      console.error('No data here!');
       return null
    }

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }

Original Response

Typescript is saying that change or data is possibly undefined (depending on what onUpdate returns).

So you should wrap it in a null/undefined check:

if(change && change.after && change.after.data){
    const data = change.after.data();

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }
}

If you are 100% sure that your object is always defined then you can put this:

const data = change.after!.data();

What HTTP traffic monitor would you recommend for Windows?

I now use CharlesProxy for development, but previously I have used Fiddler

How to check if that data already exist in the database during update (Mongoose And Express)

check with one query if email or phoneNumber already exists in DB

let userDB = await UserS.findOne({ $or: [
  { email: payload.email },
  { phoneNumber: payload.phoneNumber }
] })

if (userDB) {
  if (payload.email == userDB.email) {
    throw new BadRequest({ message: 'E-mail already exists' })
  } else if (payload.phoneNumber == userDB.phoneNumber) {
    throw new BadRequest({ message: 'phoneNumber already exists' })
  }
}

jQuery - find child with a specific class

I'm not sure if I understand your question properly, but it shouldn't matter if this div is a child of some other div. You can simply get text from all divs with class bgHeaderH2 by using following code:

$(".bgHeaderH2").text();

How to update (append to) an href in jquery?

var _href = $("a.directions-link").attr("href");
$("a.directions-link").attr("href", _href + '&saddr=50.1234567,-50.03452');

To loop with each()

$("a.directions-link").each(function() {
   var $this = $(this);       
   var _href = $this.attr("href"); 
   $this.attr("href", _href + '&saddr=50.1234567,-50.03452');
});

What is the difference between new/delete and malloc/free?

1.new syntex is simpler than malloc()

2.new/delete is a operator where malloc()/free() is a function.

3.new/delete execute faster than malloc()/free() because new assemly code directly pasted by the compiler.

4.we can change new/delete meaning in program with the help of operator overlading.

How do you get the file size in C#?

It returns the file contents length

Kubernetes Pod fails with CrashLoopBackOff

Pod is not started due to problem coming after initialization of POD.

Check and use command to get docker container of pod

docker ps -a | grep private-reg

Output will be information of docker container with id.

See docker logs:

docker logs -f <container id>

How to correctly close a feature branch in Mercurial?

imho there are two cases for branches that were forgot to close

Case 1: branch was not merged into default

in this case I update to the branch and do another commit with --close-branch, unfortunatly this elects the branch to become the new tip and hence before pushing it to other clones I make sure that the real tip receives some more changes and others don't get confused about that strange tip.

hg up myBranch
hg commit --close-branch

Case 2: branch was merged into default

This case is not that much different from case 1 and it can be solved by reproducing the steps for case 1 and two additional ones.

in this case I update to the branch changeset, do another commit with --close-branch and merge the new changeset that became the tip into default. the last operation creates a new tip that is in the default branch - HOORAY!

hg up myBranch
hg commit --close-branch
hg up default
hg merge myBranch

Hope this helps future readers.

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7

To fix this problem, you have to install OpenSSL development package, which is available in standard repositories of all modern Linux distributions.

To install OpenSSL development package on Debian, Ubuntu or their derivatives:

$ sudo apt-get install libssl-dev

To install OpenSSL development package on Fedora, CentOS or RHEL:

$ sudo yum install openssl-devel 

Edit : As @isapir has pointed out, for Fedora version>=22 use the DNF package manager :

dnf install openssl-devel

Select element based on multiple classes

You can use these solutions :

CSS rules applies to all tags that have following two classes :

.left.ui-class-selector {
    /*style here*/
}

CSS rules applies to all tags that have <li> with following two classes :

li.left.ui-class-selector {
   /*style here*/
}

jQuery solution :

$("li.left.ui-class-selector").css("color", "red");

Javascript solution :

document.querySelector("li.left.ui-class-selector").style.color = "red";

How to Run Terminal as Administrator on Mac Pro

To switch to root so that all subsequent commands are executed with high privileges instead of using sudo before each command use following command and then provide the password when prompted.

sudo -i

User will change and remain root until you close the terminal. Execute exit commmand which will change the user back to original user without closing terminal.

What is the C# equivalent of NaN or IsNumeric?

Yeah, IsNumeric is VB. Usually people use the TryParse() method, though it is a bit clunky. As you suggested, you can always write your own.

int i;
if (int.TryParse(string, out i))
{

}

What exactly is Spring Framework for?

Very short summarized, I will say that Spring is the "glue" in your application. It's used to integrate different frameworks and your own code.

How to check whether a variable is a class or not?

There are some working solutions here already, but here's another one:

>>> import types
>>> class Dummy: pass
>>> type(Dummy) is types.ClassType
True

HTML radio buttons allowing multiple selections

All radio buttons must have the same name attribute added.

Google Play Services Missing in Emulator (Android 4.4.2)

google play service is just a library to create application but in order to use application that use google play service library , you need to install google play in your emulator.and for that it need the unique device id. and device id is only on the real device not have on emulator. so for testing it , you need real android device.

How to create a list of objects?

In Python, the name of the class refers to the class instance. Consider:

class A: pass
class B: pass
class C: pass

lst = [A, B, C]

# instantiate second class
b_instance = lst[1]()
print b_instance

addEventListener, "change" and option selection

You need a click listener which calls addActivityItem if less than 2 options exist:

var activities = document.getElementById("activitySelector");

activities.addEventListener("click", function() {
    var options = activities.querySelectorAll("option");
    var count = options.length;
    if(typeof(count) === "undefined" || count < 2)
    {
        addActivityItem();
    }
});

activities.addEventListener("change", function() {
    if(activities.value == "addNew")
    {
        addActivityItem();
    }
});

function addActivityItem() {
    // ... Code to add item here
}

A live demo is here on JSfiddle.

Stopping fixed position scrolling at a certain point?

Just improvised mVChr code

$(".sidebar").css('position', 'fixed')

    var windw = this;

    $.fn.followTo = function(pos) {
        var $this = this,
                $window = $(windw);

        $window.scroll(function(e) {
            if ($window.scrollTop() > pos) {
                topPos = pos + $($this).height();
                $this.css({
                    position: 'absolute',
                    top: topPos
                });
            } else {
                $this.css({
                    position: 'fixed',
                    top: 250 //set your value
                });
            }
        });
    };

    var height = $("body").height() - $("#footer").height() ;
    $('.sidebar').followTo(height);
    $('.sidebar').scrollTo($('html').offset().top);

How to configure Fiddler to listen to localhost?

tools => fiddler options => connections there is a textarea with stuff to jump, delete LH from there

How to extract IP Address in Spring MVC Controller get call?

The solution is

@RequestMapping(value = "processing", method = RequestMethod.GET)
public @ResponseBody ProcessResponse processData(@RequestParam("workflow") final String workflow,
    @RequestParam("conf") final String value, @RequestParam("dc") final String dc, HttpServletRequest request) {

        System.out.println(workflow);
        System.out.println(value);
        System.out.println(dc);
        System.out.println(request.getRemoteAddr());
        // some other code
    }

Add HttpServletRequest request to your method definition and then use the Servlet API

Spring Documentation here said in

15.3.2.3 Supported handler method arguments and return types

Handler methods that are annotated with @RequestMapping can have very flexible signatures.
Most of them can be used in arbitrary order (see below for more details).

Request or response objects (Servlet API). Choose any specific request or response type,
for example ServletRequest or HttpServletRequest

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

The code you have for the two columns looks ok. Look for any other datetime columns on that mapping class. Also, enable logging on the datacontext to see the query and parameters.

dc.Log = Console.Out;

DateTime is initialized to c#'s 0 - which is 0001-01-01. This is transmitted by linqtosql to the database via sql string literal : '0001-01-01'. Sql cannot parse a T-Sql datetime from this date.

There's a couple ways to deal with this:

  • Make sure you initialize all date times with a value that SQL can handle (such as Sql's 0 : 1900-01-01 )
  • Make sure any date times that may occasionally be omitted are nullable datetimes

Does bootstrap have builtin padding and margin classes?

I'm adding this code to my Bootstrap3.3 project with the same grid columns breakpoints, based with the @guest answer. Before I have used the Bootstrap 4 padding and margins helper it seens to be a good choice.

/*Margin and Padding helpers*/
/*xs*/
.p-xs { padding: .25em; }
.p-x-xs { padding: 0 .25em; }
.p-y-xs { padding: .25em 0 ; }
.p-t-xs { padding-top: .25em; }
.p-r-xs { padding-right: .25em; }
.p-b-xs { padding-bottom: .25em; }
.p-l-xs { padding-left: .25em; }
.m-xs { margin: .25em; }
.m-x-xs { margin: 0 .25em; }
.m-y-xs { margin: .25em 0 ; }
.m-r-xs { margin-right: .25em; }
.m-l-xs { margin-left: .25em; }
.m-t-xs { margin-top: .25em; }
.m-b-xs { margin-bottom: .25em; }
/*sm*/
@media (min-width:768px){
/*sm*/
.p-sm { padding: .5em; }
.p-x-sm { padding: 0 .5em; }
.p-y-sm { padding: .5em 0 ; }
.p-t-sm { padding-top: .5em; }
.p-r-sm { padding-right: .5em; }
.p-b-sm { padding-bottom: .5em; }
.p-l-sm { padding-left: .5em; }
.m-sm { margin: .5em; }
.m-x-sm { margin: 0 .5em; }
.m-y-sm { margin: .5em 0 ; }
.m-t-sm { margin-top: .5em; }
.m-r-sm { margin-right: .5em; }
.m-b-sm { margin-bottom: .5em; }
.m-l-sm { margin-left: .5em; }
}

/*md*/
@media (min-width: 992px){
.p-md { padding: 1em; }
.p-x-md { padding: 0 1em; }
.p-y-md { padding: 1em 0; }
.p-t-md { padding-top: 1em; }
.p-r-md { padding-right: 1em; }
.p-b-md { padding-bottom: 1em; }
.p-l-md { padding-left: 1em; }
.m-md { margin: 1em; }
.m-x-md { margin: 0 1em; }
.m-y-md { margin: 1em 0 ; }
.m-t-md { margin-top: 1em; }
.m-r-md { margin-right: 1em; }
.m-b-md { margin-bottom: 1em; }
.m-l-md { margin-left: 1em; }
}

/*lg*/
@media (min-width: 1200px){
.p-lg { padding: 1.5em; }
.p-x-lg { padding: 0 1.5em; }
.p-y-lg { padding: 1.5em 0; }
.p-t-lg { padding-top: 1.5em; }
.p-r-lg { padding-right: 1.5em; }
.p-b-lg { padding-bottom: 1.5em; }
.p-l-lg { padding-left: 1.5em; }
.m-lg { margin: 1.5em; }
.m-x-lg { margin: 0 1.5em; }
.m-y-lg { margin: 1.5em 0; }
.m-t-lg { margin-top: 1.5em; }
.m-r-lg { margin-right: 1.5em; }
.m-b-lg { margin-bottom: 1.5em; }
.m-l-lg { margin-left: 1.5em; }
}
/*xl*/
.p-xl { padding: 3em; }
.p-x-xl { padding: 0 3em; }
.p-y-xl { padding: 3em 0 ; }
.p-t-xl { padding-top: 3em; }
.p-r-xl { padding-right: 3em; }
.p-b-xl { padding-bottom: 3em; }
.p-l-xl { padding-left: 3em; }
.m-xl { margin: 3em; }
.m-x-xl { margin: 0 3em; }
.m-y-xl { margin: 3em 0; }
.m-t-xl { margin-top: 3em; }
.m-r-xl { margin-right: 3em; }
.m-b-xl { margin-bottom: 3em; }
.m-l-xl { margin-left: 3em; }``

Chrome ignores autocomplete="off"

TL;DR: Tell Chrome that this is a new password input and it won't provide old ones as autocomplete suggestions:

<input type="password" name="password" autocomplete="new-password">

autocomplete="off" doesn't work due to a design decision - lots of research shows that users have much longer and harder to hack passwords if they can store them in a browser or password manager.

The specification for autocomplete has changed, and now supports various values to make login forms easy to auto complete:

<!-- Auto fills with the username for the site, even though it's email format -->
<input type="email" name="email" autocomplete="username">

<!-- current-password will populate for the matched username input  -->
<input type="password" autocomplete="current-password" />

If you don't provide these Chrome still tries to guess, and when it does it ignores autocomplete="off".

The solution is that autocomplete values also exist for password reset forms:

<label>Enter your old password:
    <input type="password" autocomplete="current-password" name="pass-old" />
</label>
<label>Enter your new password:
    <input type="password" autocomplete="new-password" name="pass-new" />
</label>
<label>Please repeat it to be sure:
    <input type="password" autocomplete="new-password" name="pass-repeat" />
</label>

You can use this autocomplete="new-password" flag to tell Chrome not to guess the password, even if it has one stored for this site.

Chrome can also manage passwords for sites directly using the credentials API, which is a standard and will probably have universal support eventually.

Print text in Oracle SQL Developer SQL Worksheet window

enter image description here

for simple comments:

set serveroutput on format wrapped;
begin
    DBMS_OUTPUT.put_line('simple comment');
end;
/

-- do something

begin
    DBMS_OUTPUT.put_line('second simple comment');
end;
/

you should get:

anonymous block completed
simple comment

anonymous block completed
second simple comment

if you want to print out the results of variables, here's another example:

set serveroutput on format wrapped;
declare
a_comment VARCHAR2(200) :='first comment';
begin
    DBMS_OUTPUT.put_line(a_comment);
end;

/

-- do something


declare
a_comment VARCHAR2(200) :='comment';
begin
    DBMS_OUTPUT.put_line(a_comment || 2);
end;

your output should be:

anonymous block completed
first comment

anonymous block completed
comment2

Get current AUTO_INCREMENT value for any table

If you just want to know the number, rather than get it in a query then you can use:

SHOW CREATE TABLE tablename;

You should see the auto_increment at the bottom

What is declarative programming?

I have refined my understanding of declarative programming, since Dec 2011 when I provided an answer to this question. Here follows my current understanding.

The long version of my understanding (research) is detailed at this link, which you should read to gain a deep understanding of the summary I will provide below.

Imperative programming is where mutable state is stored and read, thus the ordering and/or duplication of program instructions can alter the behavior (semantics) of the program (and even cause a bug, i.e. unintended behavior).

In the most naive and extreme sense (which I asserted in my prior answer), declarative programming (DP) is avoiding all stored mutable state, thus the ordering and/or duplication of program instructions can NOT alter the behavior (semantics) of the program.

However, such an extreme definition would not be very useful in the real world, since nearly every program involves stored mutable state. The spreadsheet example conforms to this extreme definition of DP, because the entire program code is run to completion with one static copy of the input state, before the new states are stored. Then if any state is changed, this is repeated. But most real world programs can't be limited to such a monolithic model of state changes.

A more useful definition of DP is that the ordering and/or duplication of programming instructions do not alter any opaque semantics. In other words, there are not hidden random changes in semantics occurring-- any changes in program instruction order and/or duplication cause only intended and transparent changes to the program's behavior.

The next step would be to talk about which programming models or paradigms aid in DP, but that is not the question here.

Git: How to update/checkout a single file from remote origin master?

Or git stash (if you have changes) on the branch you're on, checkout master, pull for the latest changes, grab that file to your desktop (or the entire app). Checkout the branch you were on. Git stash apply back to the state you were at, then fix the changes manually or drag it replacing the file.

This way is not sooooo cool but it def works if you guys can't figure anything else out.

Codeigniter: does $this->db->last_query(); execute a query?

For me save_queries option was turned off so,

$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;

Ref: Can't get result from $this->db->last_query(); codeigniter

HTML5 record audio to file

Update now Chrome also supports MediaRecorder API from v47. The same thing to do would be to use it( guessing native recording method is bound to be faster than work arounds), the API is really easy to use, and you would find tons of answers as to how to upload a blob for the server.

Demo - would work in Chrome and Firefox, intentionally left out pushing blob to server...

Code Source


Currently, there are three ways to do it:

  1. as wav[ all code client-side, uncompressed recording], you can check out --> Recorderjs. Problem: file size is quite big, more upload bandwidth required.
  2. as mp3[ all code client-side, compressed recording], you can check out --> mp3Recorder. Problem: personally, I find the quality bad, also there is this licensing issue.
  3. as ogg [ client+ server(node.js) code, compressed recording, infinite hours of recording without browser crash ], you can check out --> recordOpus, either only client-side recording, or client-server bundling, the choice is yours.

    ogg recording example( only firefox):

    var mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.start();  // to start recording.    
    ...
    mediaRecorder.stop();   // to stop recording.
    mediaRecorder.ondataavailable = function(e) {
        // do something with the data.
    }
    

    Fiddle Demo for ogg recording.

What are naming conventions for MongoDB?

  1. Keep'em short: Optimizing Storage of Small Objects, SERVER-863. Silly but true.

  2. I guess pretty much the same rules that apply to relation databases should apply here. And after so many decades there is still no agreement whether RDBMS tables should be named singular or plural...

  3. MongoDB speaks JavaScript, so utilize JS naming conventions of camelCase.

  4. MongoDB official documentation mentions you may use underscores, also built-in identifier is named _id (but this may be be to indicate that _id is intended to be private, internal, never displayed or edited.

How do I send a POST request with PHP?

I recommend you to use the open-source package guzzle that is fully unit tested and uses the latest coding practices.

Installing Guzzle

Go to the command line in your project folder and type in the following command (assuming you already have the package manager composer installed). If you need help how to install Composer, you should have a look here.

php composer.phar require guzzlehttp/guzzle

Using Guzzle to send a POST request

The usage of Guzzle is very straight forward as it uses a light-weight object-oriented API:

// Initialize Guzzle client
$client = new GuzzleHttp\Client();

// Create a POST request
$response = $client->request(
    'POST',
    'http://example.org/',
    [
        'form_params' => [
            'key1' => 'value1',
            'key2' => 'value2'
        ]
    ]
);

// Parse the response object, e.g. read the headers, body, etc.
$headers = $response->getHeaders();
$body = $response->getBody();

// Output headers and body for debugging purposes
var_dump($headers, $body);

npm install hangs

The registry(https://registry.npmjs.org/cordova) was blocked by our firewall. Unblocking it fixed the issue.

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

you need /q at the end

MsiExec.exe /x {2F808931-D235-4FC7-90CD-F8A890C97B2F} /q

Scroll Automatically to the Bottom of the Page

window.scrollTo(0,1e10);

always works.

1e10 is a big number. so its always the end of the page.

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

You may go with Plotly library. It can render interactive 3D plots directly in Jupyter Notebooks.

To do so you first need to install Plotly by running:

pip install plotly

You might also want to upgrade the library by running:

pip install plotly --upgrade

After that in you Jupyter Notebook you may write something like:

# Import dependencies
import plotly
import plotly.graph_objs as go

# Configure Plotly to be rendered inline in the notebook.
plotly.offline.init_notebook_mode()

# Configure the trace.
trace = go.Scatter3d(
    x=[1, 2, 3],  # <-- Put your data instead
    y=[4, 5, 6],  # <-- Put your data instead
    z=[7, 8, 9],  # <-- Put your data instead
    mode='markers',
    marker={
        'size': 10,
        'opacity': 0.8,
    }
)

# Configure the layout.
layout = go.Layout(
    margin={'l': 0, 'r': 0, 'b': 0, 't': 0}
)

data = [trace]

plot_figure = go.Figure(data=data, layout=layout)

# Render the plot.
plotly.offline.iplot(plot_figure)

As a result the following chart will be plotted for you in Jupyter Notebook and you'll be able to interact with it. Of course you will need to provide your specific data instead of suggeseted one.

enter image description here

How to position absolute inside a div?

One of #a or #b needs to be not position:absolute, so that #box will grow to accommodate it.

So you can stop #a from being position:absolute, and still position #b over the top of it, like this:

_x000D_
_x000D_
 #box {_x000D_
        background-color: #000;_x000D_
        position: relative;     _x000D_
        padding: 10px;_x000D_
        width: 220px;_x000D_
    }_x000D_
    _x000D_
    .a {_x000D_
        width: 210px;_x000D_
        background-color: #fff;_x000D_
        padding: 5px;_x000D_
    }_x000D_
    _x000D_
    .b {_x000D_
        width: 100px; /* So you can see the other one */_x000D_
        position: absolute;_x000D_
        top: 10px; left: 10px;_x000D_
        background-color: red;_x000D_
        padding: 5px;_x000D_
    }_x000D_
    _x000D_
    #after {_x000D_
        background-color: yellow;_x000D_
        padding: 10px;_x000D_
        width: 220px;_x000D_
    }
_x000D_
    <div id="box">_x000D_
        <div class="a">Lorem</div>_x000D_
        <div class="b">Lorem</div>_x000D_
    </div>_x000D_
    <div id="after">Hello world</div>
_x000D_
_x000D_
_x000D_

(Note that I've made the widths different, so you can see one behind the other.)

Edit after Justine's comment: Then your only option is to specify the height of #box. This:

#box {
    /* ... */
    height: 30px;
}

works perfectly, assuming the heights of a and b are fixed. Note that you'll need to put IE into standards mode by adding a doctype at the top of your HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
          "http://www.w3.org/TR/html4/strict.dtd">

before that works properly.

Can I create a One-Time-Use Function in a Script or Stored Procedure?

I know I might get criticized for suggesting dynamic SQL, but sometimes it's a good solution. Just make sure you understand the security implications before you consider this.

DECLARE @add_a_b_func nvarchar(4000) = N'SELECT @c = @a + @b;';
DECLARE @add_a_b_parm nvarchar(500) = N'@a int, @b int, @c int OUTPUT';

DECLARE @result int;
EXEC sp_executesql @add_a_b_func, @add_a_b_parm, 2, 3, @c = @result OUTPUT;
PRINT CONVERT(varchar, @result); -- prints '5'

Pod install is staying on "Setting up CocoaPods Master repo"

Just setup the master repo, was excited to see that we have a download progress, see screenshot ;)

CocoaPods release 1.2.0 (Jan 28) fixes this issue, thanks to all contributors and Danielle Tomlinson for this release.


enter image description here

Changing text of UIButton programmatically swift

Just a clarification for those new to Swift and iOS programming. Below line of code:

button.setTitle("myTitle", forState: UIControlState.Normal)

only applies to IBOutlets, not IBActions.

So, if your app is using a button as a function to execute some code, say playing music, and you want to change the title from Play to Pause based on a toggle variable, you need to also create an IBOutlet for that button.

If you try to use button.setTitle against an IBAction you will get an error. Its obvious once you know it, but for the noobs (we all were) this is a helpful tip.

How do I change JPanel inside a JFrame on the fly?

1) Setting the first Panel:

JFrame frame=new JFrame();
frame.getContentPane().add(new JPanel());

2)Replacing the panel:

frame.getContentPane().removeAll();
frame.getContentPane().add(new JPanel());

Also notice that you must do this in the Event's Thread, to ensure this use the SwingUtilities.invokeLater or the SwingWorker

How do I specify the JDK for a GlassFish domain?

In Linux file system , Edit below file as this steps

Path - /opt/glassfish3/glassfish/config

File Name - asenv.conf

Add the JAVA HOME path as below to the end of file.

AS_JAVA=/opt/jdk1.8.0_201

Now start the glassfish server.

Check if a Class Object is subclass of another Class Object in Java

Another option is instanceof:

Object o =...
if (o instanceof Number) {
  double d = ((Number)o).doubleValue(); //this cast is safe
}

How to start debug mode from command prompt for apache tomcat server?

First, Navigate to the TOMCAT-HOME/bin directory.

Then, Execute the following in the command-line:

catalina.bat jpda start

If the Tomcat server is running under Linux, just invoke the catalina.sh program

catalina.sh jpda start

It's the same for Tomcat 5.5 and Tomcat 6

How to determine the screen width in terms of dp or dip at runtime in Android?

I stumbled upon this question from Google, and later on I found an easy solution valid for API >= 13.

For future references:

Configuration configuration = yourActivity.getResources().getConfiguration();
int screenWidthDp = configuration.screenWidthDp; //The current width of the available screen space, in dp units, corresponding to screen width resource qualifier.
int smallestScreenWidthDp = configuration.smallestScreenWidthDp; //The smallest screen size an application will see in normal operation, corresponding to smallest screen width resource qualifier.

See Configuration class reference

Edit: As noted by Nick Baicoianu, this returns the usable width/height of the screen (which should be the interesting ones in most uses). If you need the actual display dimensions stick to the top answer.

JavaScript TypeError: Cannot read property 'style' of null

This happens because document.write would overwrite your existing code therefore place your div before your javascript code. e.g.:

CSS:

#mydiv { 
  visibility:hidden;
 }

Inside your html file

<div id="mydiv">
   <p>Hello world</p>
</div>
<script type="text/javascript">
   document.getElementById('mydiv').style.visibility='visible';
</script>

Hope this was helpful

Convert date formats in bash

If you would like a bash function that works both on Mac OS X and Linux:

#
# Convert one date format to another
# 
# Usage: convert_date_format <input_format> <date> <output_format>
#
# Example: convert_date_format '%b %d %T %Y %Z' 'Dec 10 17:30:05 2017 GMT' '%Y-%m-%d'
convert_date_format() {
  local INPUT_FORMAT="$1"
  local INPUT_DATE="$2"
  local OUTPUT_FORMAT="$3"
  local UNAME=$(uname)

  if [[ "$UNAME" == "Darwin" ]]; then
    # Mac OS X
    date -j -f "$INPUT_FORMAT" "$INPUT_DATE" +"$OUTPUT_FORMAT"
  elif [[ "$UNAME" == "Linux" ]]; then
    # Linux
    date -d "$INPUT_DATE" +"$OUTPUT_FORMAT"
  else
    # Unsupported system
    echo "Unsupported system"
  fi
}

# Example: 'Dec 10 17:30:05 2017 GMT' => '2017-12-10'
convert_date_format '%b %d %T %Y %Z' 'Dec 10 17:30:05 2017 GMT' '%Y-%m-%d'

CSS how to make scrollable list

Another solution would be as below where the list is placed under a drop-down button.

  <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
    >Markets<span class="caret"></span></button>

    <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
      {{ form.markets }}
    </ul>

How to compute the sum and average of elements in an array?

var sum = 0;
for( var i = 0; i < elmt.length; i++ ){
    sum += parseInt( elmt[i], 10 ); //don't forget to add the base
}

var avg = sum/elmt.length;

document.write( "The sum of all the elements is: " + sum + " The average is: " + avg );

Just iterate through the array, since your values are strings, they have to be converted to an integer first. And average is just the sum of values divided by the number of values.

Local dependency in package.json

Actually, as of npm 2.0, there is support now local paths (see here).

How to check if a file exists before creating a new file

Assuming it is OK that the operation is not atomic, you can do:

if (std::ifstream(name))
{
     std::cout << "File already exists" << std::endl;
     return false;
}
std::ofstream file(name);
if (!file)
{
     std::cout << "File could not be created" << std::endl;
     return false;
}
... 

Note that this doesn't work if you run multiple threads trying to create the same file, and certainly will not prevent a second process from "interfering" with the file creation because you have TOCTUI problems. [We first check if the file exists, and then create it - but someone else could have created it in between the check and the creation - if that's critical, you will need to do something else, which isn't portable].

A further problem is if you have permissions such as the file is not readable (so we can't open it for read) but is writeable, it will overwrite the file.

In MOST cases, neither of these things matter, because all you care about is telling someone that "you already have a file like that" (or something like that) in a "best effort" approach.

How do I find the difference between two values without knowing which is larger?

If you have an array, you can also use numpy.diff:

import numpy as np
a = [1,5,6,8]
np.diff(a)
Out: array([4, 1, 2])

Path to MSBuild

The Registry locations

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\2.0
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\3.5

give the location for the executable.

But if you need the location where to save the Task extensions, it's on

%ProgramFiles%\MSBuild

Local variable referenced before assignment?

You have to specify that test1 is global:

test1 = 0
def testFunc():
    global test1
    test1 += 1
testFunc()

How to save .xlsx data to file as a blob

I've found a solution worked for me:

const handleDownload = async () => {
   const req = await axios({
     method: "get",
     url: `/companies/${company.id}/data`,
     responseType: "blob",
   });
   var blob = new Blob([req.data], {
     type: req.headers["content-type"],
   });
   const link = document.createElement("a");
   link.href = window.URL.createObjectURL(blob);
   link.download = `report_${new Date().getTime()}.xlsx`;
   link.click();
 };

I just point a responseType: "blob"

Escaping regex string

You can use re.escape():

re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'

If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.

If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_).

Sorting an array in C?

I'd like to make some changes: In C, you can use the built in qsort command:

int compare( const void* a, const void* b)
{
   int int_a = * ( (int*) a );
   int int_b = * ( (int*) b );

   // an easy expression for comparing
   return (int_a > int_b) - (int_a < int_b);
}

qsort( a, 6, sizeof(int), compare )

Wait .5 seconds before continuing code VB.net

VB.net 4.0 framework Code :

Threading.Thread.Sleep(5000)

The integer is in miliseconds ( 1 sec = 1000 miliseconds)

I did test it and it works

Calculate execution time of a SQL query?

Please use

-- turn on statistics IO for IO related 
SET STATISTICS IO ON 
GO

and for time calculation use

SET STATISTICS TIME ON
GO

then It will give result for every query . In messages window near query input window.

Git pull till a particular commit

This works for me:

git pull origin <sha>

e.g.

[dbn src]$ git fetch
[dbn src]$ git status
On branch current_feature
Your branch and 'origin/master' have diverged,
and have 2 and 7 different commits each, respectively.
...
[dbn src]$ git log -3 --pretty=oneline origin/master
f4d10ad2a5eda447bea53fed0b421106dbecea66 CASE-ID1: some descriptive msg
28eb00a42e682e32bdc92e5753a4a9c315f62b42 CASE-ID2: I'm so good at writing commit titles
ff39e46b18a66b21bc1eed81a0974e5c7de6a3e5 CASE-ID2: woooooo
[dbn src]$ git pull origin 28eb00a42e682e32bdc92e5753a4a9c315f62b42
[dbn src]$ git status
On branch current_feature
Your branch and 'origin/master' have diverged,
and have 2 and 1 different commits each, respectively.
...

This pulls 28eb00, ff39e4, and everything before, but doesn't pull f4d10ad. It allows the use of pull --rebase, and honors pull settings in your gitconfig. This works because you're basically treating 28eb00 as a branch.

For the version of git that I'm using, this method requires a full commit hash - no abbreviations or aliases are allowed. You could do something like:

[dbn src]$ git pull origin `git rev-parse origin/master^`

Fastest way to remove first char in a String

I know this is hyper-optimization land, but it seemed like a good excuse to kick the wheels of BenchmarkDotNet. The result of this test (on .NET Core even) is that Substring is ever so slightly faster than Remove, in this sample test: 19.37ns vs 22.52ns for Remove. So some ~16% faster.

using System;
using BenchmarkDotNet.Attributes;

namespace BenchmarkFun
{
    public class StringSubstringVsRemove
    {
        public readonly string SampleString = " My name is Daffy Duck.";

        [Benchmark]
        public string StringSubstring() => SampleString.Substring(1);

        [Benchmark]
        public string StringRemove() => SampleString.Remove(0, 1);

        public void AssertTestIsValid()
        {
            string subsRes = StringSubstring();
            string remvRes = StringRemove();

            if (subsRes == null
                || subsRes.Length != SampleString.Length - 1
                || subsRes != remvRes) {
                throw new Exception("INVALID TEST!");
            }
        }
    }

    class Program
    {
        static void Main()
        {
            // let's make sure test results are really equal / valid
            new StringSubstringVsRemove().AssertTestIsValid();

            var summary = BenchmarkRunner.Run<StringSubstringVsRemove>();
        }
    }
}

Results:

BenchmarkDotNet=v0.11.4, OS=Windows 10.0.17763.253 (1809/October2018Update/Redstone5)
Intel Core i7-6700HQ CPU 2.60GHz (Skylake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.0.100-preview-010184
  [Host]     : .NET Core 3.0.0-preview-27324-5 (CoreCLR 4.6.27322.0, CoreFX 4.7.19.7311), 64bit RyuJIT
  DefaultJob : .NET Core 3.0.0-preview-27324-5 (CoreCLR 4.6.27322.0, CoreFX 4.7.19.7311), 64bit RyuJIT

|          Method |     Mean |     Error |    StdDev |
|---------------- |---------:|----------:|----------:|
| StringSubstring | 19.37 ns | 0.3940 ns | 0.3493 ns |
|    StringRemove | 22.52 ns | 0.4062 ns | 0.3601 ns |

How to search and replace text in a file?

Besides the answers already mentioned, here is an explanation of why you have some random characters at the end:
You are opening the file in r+ mode, not w mode. The key difference is that w mode clears the contents of the file as soon as you open it, whereas r+ doesn't.
This means that if your file content is "123456789" and you write "www" to it, you get "www456789". It overwrites the characters with the new input, but leaves any remaining input untouched.
You can clear a section of the file contents by using truncate(<startPosition>), but you are probably best off saving the updated file content to a string first, then doing truncate(0) and writing it all at once.
Or you can use my library :D

Get output parameter value in ADO.NET

You can get your result by below code::

using (SqlConnection conn = new SqlConnection(...))
{
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add other parameters parameters

    //Add the output parameter to the command object
    SqlParameter outPutParameter = new SqlParameter();
    outPutParameter.ParameterName = "@Id";
    outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
    outPutParameter.Direction = System.Data.ParameterDirection.Output;
    cmd.Parameters.Add(outPutParameter);

    conn.Open();
    cmd.ExecuteNonQuery();

    //Retrieve the value of the output parameter
    string Id = outPutParameter.Value.ToString();

    // *** read output parameter here, how?
    conn.Close();
}

What does this format means T00:00:00.000Z?

i suggest you use moment.js for this. In moment.js you can:

var localTime = moment().format('YYYY-MM-DD'); // store localTime
var proposedDate = localTime + "T00:00:00.000Z";

now that you have the right format for a time, parse it if it's valid:

var isValidDate = moment(proposedDate).isValid();
// returns true if valid and false if it is not.

and to get time parts you can do something like:

var momentDate = moment(proposedDate)
var hour = momentDate.hours();
var minutes = momentDate.minutes();
var seconds = momentDate.seconds();

// or you can use `.format`:
console.log(momentDate.format("YYYY-MM-DD hh:mm:ss A Z"));

More info about momentjs http://momentjs.com/

Text File Parsing in Java

It sounds like you're doing something wrong to me - a whole lotta object creation going on.

How representative is that "test" file? What are you really doing with that data? If that's typical of what you really have, I'd say there's lots of repetition in that data.

If it's all going to be in Strings anyway, start with a BufferedReader to read each line. Pre-allocate that List to a size that's close to what you need so you don't waste resources adding to it each time. Split each of those lines at the comma; be sure to strip off the double quotes.

You might want to ask yourself: "Why do I need this whole file in memory all at once?" Can you read a little, process a little, and never have the whole thing in memory at once? Only you know your problem well enough to answer.

Maybe you can fire up jvisualvm if you have JDK 6 and see what's going on with memory. That would be a great clue.

I get conflicting provisioning settings error when I try to archive to submit an iOS app

The problem is in the Cordova settings.

Note this:

iPhone Distribution has been manually specified

This didn’t make any sense to me, since I had set the project to auto sign in xcode. Like you, the check and uncheck didn’t work. But then I read the last file path given and followed it. The file path is APP > Platforms > ios > Cordova > build-release.xconfig

And in the file, iPhone Distribution is explicitly set for CODE_SIGN_IDENTITY.

Change:

CODE_SIGN_IDENTITY = iPhone Distribution
CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Distribution

To:

CODE_SIGN_IDENTITY = iPhone Developer
CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Developer

It a simple thing, and the error message does make it clear that iPhone Distribution has been manually specified, but it doesn’t really say where unless you follow the path. I looked and fiddled with xcode for about three hours trying to figure this out. Hopes this helps anyone in the future.

How and when to use ‘async’ and ‘await’

For fastest learning..

  • Understand method execution flow(with a diagram): 3 mins

  • Question introspection (learning sake): 1 min

  • Quickly get through syntax sugar: 5 mins

  • Share the confusion of a developer : 5 mins

  • Problem: Quickly change a real-world implementation of normal code to Async code: 2 mins

  • Where to Next?

Understand method execution flow(with a diagram): 3 mins

In this image, just focus on #6 (nothing more) enter image description here

At #6 step, execution ran out of work and stopped. To continue it needs a result from getStringTask(kind of a function). Therefore, it uses an await operator to suspend its progress and give control back(yield) to the caller(of this method we are in). The actual call to getStringTask was made earlier in #2. At #2 a promise was made to return a string result. But when will it return the result? Should we(#1:AccessTheWebAsync) make a 2nd call again? Who gets the result, #2(calling statement) or #6(awaiting statement)?

The external caller of AccessTheWebAsync() also is waiting now. So caller waiting for AccessTheWebAsync, and AccessTheWebAsync is waiting for GetStringAsync at the moment. Interesting thing is AccessTheWebAsync did some work(#4) before waiting perhaps to save time from waiting. The same freedom to multitask is also available for the external caller(and all callers in the chain) and this is the biggest plus of this 'async' thingy! You feel like it is synchronous..or normal but it is not.

#2 and #6 is split so we have the advantage of #4(work while waiting). But we can also do it without splitting. string urlContents = await client.GetStringAsync("...");. Here we see no advantage but somewhere in the chain one function will be splitting while rest of them call it without splitting. It depends which function/class in the chain you use. This change in behavior from function to function is the most confusing part.

Remember, the method was already returned(#2), it cannot return again(no second time). So how will the caller know? It is all about Tasks! Task was returned. Task status was waited for (not method, not value). Value will be set in Task. Task status will be set to complete. Caller just monitors Task(#6). So 6# is the answer to where/who gets the result. Further reads for later here.

Question introspection for learning sake: 1 min

Let us adjust the question a bit:

How and When to use async and await Tasks?

Because learning Task automatically covers the other two(and answers your question)

Quickly get through syntax sugar: 5 mins

  • Original non-async method
internal static int Method(int arg0, int arg1)
        {
            int result = arg0 + arg1;
            IO(); // Do some long running IO.
            return result;
        }
  • a brand new Task-ified method to call the above method
internal static Task<int> MethodTask(int arg0, int arg1)
    {
        Task<int> task = new Task<int>(() => Method(arg0, arg1));
        task.Start(); // Hot task (started task) should always be returned.
        return task;
    }

Did we mention await or async? No. Call the above method and you get a task which you can monitor. You already know what the task returns.. an integer.

  • Calling a Task is slightly tricky and that is when the keywords starts to appear. If there was a method calling the original method(non-async) then we need to edit it as given below. Let us call MethodTask()
internal static async Task<int> MethodAsync(int arg0, int arg1)
    {
        int result = await HelperMethods.MethodTask(arg0, arg1);
        return result;
    }

Same code above added as image below: enter image description here

  1. We are 'awaiting' task to be finished. Hence the await(mandatory syntax)
  2. Since we use await, we must use async(mandatory syntax)
  3. MethodAsync with Async as the prefix (coding standard)

await is easy to understand but the remaining two (async,Async) may not be :). Well, it should make a lot more sense to the compiler though.Further reads for later here

So there are 2 parts.

  1. Create 'Task' (only one task and it will be an additional method)

  2. Create syntactic sugar to call the task with await+async(this involves changing existing code if you are converting a non-async method)

Remember, we had an external caller to AccessTheWebAsync() and that caller is not spared either... i.e it needs the same await+async too. And the chain continues(hence this is a breaking change which could affect many classes). It can also be considered a non-breaking change because the original method is still there to be called. Change it's access if you want to impose a breaking change and then the classes will be forced to use Task-method. Or just delete the method and move it to task-method. Anyways, in an async call there will always be a Task at one end and only one.

All okay, but one developer was surprised to see Task missing...

Share the confusion of a developer: 5 mins

A developer has made a mistake of not implementing Task but it still works! Try to understand the question and just the accepted answer provided here. Hope you have read and fully understood. The summary is that we may not see/implement 'Task' but it is implemented somewhere in a parent/associated class. Likewise in our example calling an already built MethodAsync() is way easier than implementing that method with a Task (MethodTask()) ourself. Most developers find it difficult to get their head around Tasks while converting a code to Asynchronous one.

Tip: Try to find an existing Async implementation (like MethodAsync or ToListAsync) to outsource the difficulty. So we only need to deal with Async and await (which is easy and pretty similar to normal code)

Problem: Quickly change a real-world implementation of normal code to Async operation: 2 mins

Code line shown below in Data Layer started to break(many places). Because we updated some of our code from .Net framework 4.2.* to .Net core. We had to fix this in 1 hour all over the application!

var myContract = query.Where(c => c.ContractID == _contractID).First();

easypeasy!

  1. We installed EntityFramework nuget package because it has QueryableExtensions. Or in other words it does the Async implementation(task), so we could survive with simple Async and await in code.
  2. namespace = Microsoft.EntityFrameworkCore

calling code line got changed like this

var myContract = await query.Where(c => c.ContractID == _contractID).FirstAsync();
  1. Method signature changed from

Contract GetContract(int contractnumber)

to

async Task<Contract> GetContractAsync(int contractnumber)

  1. calling method also got affected: GetContractAsync(123456); was called as GetContractAsync(123456).Result;

  2. We changed it everywhere in 30 minutes!

But the architect told us not to use EntityFramework library just for this! oops! drama! Then we made a custom Task implementation(yuk). Which you know how. Still easy! ..still yuk..

Where to Next? There is a wonderful quick video we could watch about Converting Synchronous Calls to Asynchronous in ASP.Net Core, perhaps that is likely the direction one would go after reading this. Or have I explained enough? ;)

How to print to console when using Qt

If you are printing to stderr using the stdio library, a call to fflush(stderr) should flush the buffer and get you real-time logging.

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

Add a label= to each of your plot() calls, and then call legend(loc='upper left').

Consider this sample (tested with Python 3.8.0):

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, "-b", label="sine")
plt.plot(x, y2, "-r", label="cosine")
plt.legend(loc="upper left")
plt.ylim(-1.5, 2.0)
plt.show()

enter image description here Slightly modified from this tutorial: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html

What is the default initialization of an array in Java?

JLS clearly says

An array initializer creates an array and provides initial values for all its components.

and this is irrespective of whether the array is an instance variable or local variable or class variable.

Default values for primitive types : docs

For objects default values is null.

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

LINQ query to find if items in a list are contained in another list

List<string> l = new List<string> { "@bob.com", "@tom.com" };
List<string> l2 = new List<string> { "[email protected]", "[email protected]" };
List<string> myboblist= (l2.Where (i=>i.Contains("bob")).ToList<string>());
foreach (var bob in myboblist)
    Console.WriteLine(bob.ToString());

LD_LIBRARY_PATH vs LIBRARY_PATH

Since I link with gcc why ld is being called, as the error message suggests?

gcc calls ld internally when it is in linking mode.

How to delete a file via PHP?

AIO solution, handles everything, It's not my work but I just improved myself. Enjoy!

/**
 * Unlink a file, which handles symlinks.
 * @see https://github.com/luyadev/luya/blob/master/core/helpers/FileHelper.php
 * @param string $filename The file path to the file to delete.
 * @return boolean Whether the file has been removed or not.
 */
function unlinkFile ( $filename ) {
    // try to force symlinks
    if ( is_link ($filename) ) {
        $sym = @readlink ($filename);
        if ( $sym ) {
            return is_writable ($filename) && @unlink ($filename);
        }
    }

    // try to use real path
    if ( realpath ($filename) && realpath ($filename) !== $filename ) {
        return is_writable ($filename) && @unlink (realpath ($filename));
    }

    // default unlink
    return is_writable ($filename) && @unlink ($filename);
}

How to add a title to a html select tag

<select>
    <option selected disabled>Choose one</option>
    <option value="sydney">Sydney</option>
    <option value="melbourne">Melbourne</option>
    <option value="cromwell">Cromwell</option>
    <option value="queenstown">Queenstown</option>
</select>

Using selected and disabled will make "Choose one" be the default selected value, but also make it impossible for the user to actually select the item, like so:

Dropdown menu

How to get complete current url for Cakephp

for CakePHP 3.x You can use UrlHelper:

$this->Url->build(null, true) // output http://somedomain.com/app-name/controller/action/params

$this->Url->build() // output /controller/action/params

Or you can use PaginatorHelper (in case you want to use it in javascript or ...):

$this->Paginator->generateUrl() // returns a full pagination URL without hostname

$this->Paginator->generateUrl([],null,true) // returns a full pagination URL with hostname

How can I generate a random number in a certain range?

private int getRandomNumber(int min,int max) {
    return (new Random()).nextInt((max - min) + 1) + min;
}

Compare two folders which has many files inside contents

diff -r will do this, telling you both if any files have been added or deleted, and what's changed in the files that have been modified.

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

Fast way to upgrade ruby to v2.4+

brew upgrade ruby

or

sudo gem update --system 

How to use PHP's password_hash to hash and verify passwords

Never use md5() for securing your password, even with salt, it is always dangerous!!

Make your password secured with latest hashing algorithms as below.

<?php

// Your original Password
$password = '121@121';

//PASSWORD_BCRYPT or PASSWORD_DEFAULT use any in the 2nd parameter
/*
PASSWORD_BCRYPT always results 60 characters long string.
PASSWORD_DEFAULT capacity is beyond 60 characters
*/
$password_encrypted = password_hash($password, PASSWORD_BCRYPT);

For matching with database's encrypted password and user inputted password use the below function.

<?php 

if (password_verify($password_inputted_by_user, $password_encrypted)) {
    // Success!
    echo 'Password Matches';
}else {
    // Invalid credentials
    echo 'Password Mismatch';
}

If you want to use your own salt, use your custom generated function for the same, just follow below, but I not recommend this as It is found deprecated in latest versions of PHP.

Read about password_hash() before using below code.

<?php

$options = [
    'salt' => your_custom_function_for_salt(), 
    //write your own code to generate a suitable & secured salt
    'cost' => 12 // the default cost is 10
];

$hash = password_hash($your_password, PASSWORD_DEFAULT, $options);

Programmatically shut down Spring Boot application

This works, even done is printed.

  SpringApplication.run(MyApplication.class, args).close();
  System.out.println("done");

So adding .close() after run()

Explanation:

public ConfigurableApplicationContext run(String... args)

Run the Spring application, creating and refreshing a new ApplicationContext. Parameters:

args - the application arguments (usually passed from a Java main method)

Returns: a running ApplicationContext

and:

void close() Close this application context, releasing all resources and locks that the implementation might hold. This includes destroying all cached singleton beans. Note: Does not invoke close on a parent context; parent contexts have their own, independent lifecycle.

This method can be called multiple times without side effects: Subsequent close calls on an already closed context will be ignored.

So basically, it will not close the parent context, that's why the VM doesn't quit.

Gridview with two columns and auto resized images

Here's a relatively easy method to do this. Throw a GridView into your layout, setting the stretch mode to stretch the column widths, set the spacing to 0 (or whatever you want), and set the number of columns to 2:

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:stretchMode="columnWidth"
        android:numColumns="2"/>

</FrameLayout>

Make a custom ImageView that maintains its aspect ratio:

src/com/example/graphicstest/SquareImageView.java

public class SquareImageView extends ImageView {
    public SquareImageView(Context context) {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
    }
}

Make a layout for a grid item using this SquareImageView and set the scaleType to centerCrop:

res/layout/grid_item.xml

<?xml version="1.0" encoding="utf-8"?>

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

    <com.example.graphicstest.SquareImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:layout_gravity="bottom"
        android:textColor="@android:color/white"
        android:background="#55000000"/>

</FrameLayout>

Now make some sort of adapter for your GridView:

src/com/example/graphicstest/MyAdapter.java

private final class MyAdapter extends BaseAdapter {
    private final List<Item> mItems = new ArrayList<Item>();
    private final LayoutInflater mInflater;

    public MyAdapter(Context context) {
        mInflater = LayoutInflater.from(context);

        mItems.add(new Item("Red",       R.drawable.red));
        mItems.add(new Item("Magenta",   R.drawable.magenta));
        mItems.add(new Item("Dark Gray", R.drawable.dark_gray));
        mItems.add(new Item("Gray",      R.drawable.gray));
        mItems.add(new Item("Green",     R.drawable.green));
        mItems.add(new Item("Cyan",      R.drawable.cyan));
    }

    @Override
    public int getCount() {
        return mItems.size();
    }

    @Override
    public Item getItem(int i) {
        return mItems.get(i);
    }

    @Override
    public long getItemId(int i) {
        return mItems.get(i).drawableId;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = view;
        ImageView picture;
        TextView name;

        if (v == null) {
            v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
            v.setTag(R.id.picture, v.findViewById(R.id.picture));
            v.setTag(R.id.text, v.findViewById(R.id.text));
        }

        picture = (ImageView) v.getTag(R.id.picture);
        name = (TextView) v.getTag(R.id.text);

        Item item = getItem(i);

        picture.setImageResource(item.drawableId);
        name.setText(item.name);

        return v;
    }

    private static class Item {
        public final String name;
        public final int drawableId;

        Item(String name, int drawableId) {
            this.name = name;
            this.drawableId = drawableId;
        }
    }
}

Set that adapter to your GridView:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GridView gridView = (GridView)findViewById(R.id.gridview);
    gridView.setAdapter(new MyAdapter(this));
}

And enjoy the results:

Example GridView

keyword not supported data source

What you have is a valid ADO.NET connection string - but it's NOT a valid Entity Framework connection string.

The EF connection string would look something like this:

<connectionStrings> 
  <add name="NorthwindEntities" connectionString=
     "metadata=.\Northwind.csdl|.\Northwind.ssdl|.\Northwind.msl;
      provider=System.Data.SqlClient;
      provider connection string=&quot;Data Source=SERVER\SQL2000;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=False&quot;" 
      providerName="System.Data.EntityClient" /> 
</connectionStrings>

You're missing all the metadata= and providerName= elements in your EF connection string...... you basically only have what's contained in the provider connection string part.

Using the EDMX designer should create a valid EF connection string for you, in your web.config or app.config.

Marc

UPDATE: OK, I understand what you're trying to do: you need a second "ADO.NET" connection string just for ASP.NET user / membership database. Your string is OK, but the providerName is wrong - it would have to be "System.Data.SqlClient" - this connection doesn't use ENtity Framework - don't specify the "EntityClient" for it then!

<add name="ASPNETMembership" 
     connectionString="Data Source=MONTGOMERY-DEV\SQLEXPRESS;Initial Catalog=ASPNETDB;Integrated Security=True;" 
     providerName="System.Data.SqlClient" />

If you specify providerName=System.Data.EntityClient ==> Entity Framework connection string (with the metadata= and everything).

If you need and specify providerName=System.Data.SqlClient ==> straight ADO.NET SQL Server connection string without all the EF additions

SVN remains in conflict?

Give the following command:

svn resolved <filename or directory that gives trouble>

(Thanks to @Jeremy Leipzig for this answer in a comment)

How to encode text to base64 in python

Remember to import base64 and that b64encode takes bytes as an argument.

import base64
base64.b64encode(bytes('your string', 'utf-8'))

Proper way to wait for one function to finish before continuing?

I wonder why no one have mentioned this simple pattern? :

(function(next) {
  //do something
  next()
}(function() {
  //do some more
}))

Using timeouts just for blindly waiting is bad practice; and involving promises just adds more complexity to the code. In OP's case:

(function(next) {
  for(i=0;i<x;i++){
    // do something
    if (i==x-1) next()
  }
}(function() {
  // now wait for firstFunction to finish...
  // do something else
}))

a small demo -> http://jsfiddle.net/5jdeb93r/

What is the mouse down selector in CSS?

I figured out that this behaves like a mousedown event:

button:active:hover {}

How to convert an integer to a string in any base?

Well I personally use this function, written by me

import string

def to_base(value, base, digits=string.digits+string.ascii_letters):    # converts decimal to base n

    digits_slice = digits[0:base]

    temporary_var = value
    data = [temporary_var]

    while True:
        temporary_var = temporary_var // base
        data.append(temporary_var)
        if temporary_var < base:
            break

    result = ''
    for each_data in data:
        result += digits_slice[each_data % base]
    result = result[::-1]

    return result

This is how you can use it

print(to_base(7, base=2))

Output: "111"

print(to_base(23, base=3))

Output: "212"

Please feel free to suggest improvements in my code.

How do I check for vowels in JavaScript?

benchmark

I think you can safely say a for loop is faster.

I do admit that a regexp looks cleaner in terms of code. If it's a real bottleneck then use a for loop, otherwise stick with the regular expression for reasons of "elegance"

If you want to go for simplicity then just use

function isVowel(c) {
    return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1
}

CSS text-decoration underline color

(for fellow googlers, copied from duplicate question) This answer is outdated since text-decoration-color is now supported by most modern browsers.

You can do this via the following CSS rule as an example:

text-decoration-color:green


If this rule isn't supported by an older browser, you can use the following solution:

Setting your word with a border-bottom:

a:link {
  color: red;
  text-decoration: none;
  border-bottom: 1px solid blue;
}
a:hover {
 border-bottom-color: green;
}

Get average color of image via Javascript

All-In-One Solution

I would personally combine Color Thief along with this modified version of Name that Color to obtain a more-than-sufficient array of dominant color results for images.

Example:

Consider the following image:

enter image description here

You can use the following code to extract image data relating to the dominant color:

let color_thief = new ColorThief();
let sample_image = new Image();

sample_image.onload = () => {
  let result = ntc.name('#' + color_thief.getColor(sample_image).map(x => {
    const hex = x.toString(16);
    return hex.length === 1 ? '0' + hex : hex;
    
  }).join(''));
  
  console.log(result[0]); // #f0c420     : Dominant HEX/RGB value of closest match
  console.log(result[1]); // Moon Yellow : Dominant specific color name of closest match
  console.log(result[2]); // #ffff00     : Dominant HEX/RGB value of shade of closest match
  console.log(result[3]); // Yellow      : Dominant color name of shade of closest match
  console.log(result[4]); // false       : True if exact color match
};

sample_image.crossOrigin = 'anonymous';
sample_image.src = document.getElementById('sample-image').src;

How to test if list element exists?

This is actually a bit trickier than you'd think. Since a list can actually (with some effort) contain NULL elements, it might not be enough to check is.null(foo$a). A more stringent test might be to check that the name is actually defined in the list:

foo <- list(a=42, b=NULL)
foo

is.null(foo[["a"]]) # FALSE
is.null(foo[["b"]]) # TRUE, but the element "exists"...
is.null(foo[["c"]]) # TRUE

"a" %in% names(foo) # TRUE
"b" %in% names(foo) # TRUE
"c" %in% names(foo) # FALSE

...and foo[["a"]] is safer than foo$a, since the latter uses partial matching and thus might also match a longer name:

x <- list(abc=4)
x$a  # 4, since it partially matches abc
x[["a"]] # NULL, no match

[UPDATE] So, back to the question why exists('foo$a') doesn't work. The exists function only checks if a variable exists in an environment, not if parts of a object exist. The string "foo$a" is interpreted literary: Is there a variable called "foo$a"? ...and the answer is FALSE...

foo <- list(a=42, b=NULL) # variable "foo" with element "a"
"bar$a" <- 42   # A variable actually called "bar$a"...
ls() # will include "foo" and "bar$a" 
exists("foo$a") # FALSE 
exists("bar$a") # TRUE

Root user/sudo equivalent in Cygwin?

A very simple way to have a cygwin shell and corresponding subshells to operate with administrator privileges is to change the properties of the link which opens the initial shell.

The following is valid for Windows 7+ (perhaps for previous versions too, but I've not checked)

I usually start the cygwin shell from a cygwin-link in the start button (or desktop). Then, I changed the properties of the cygwin-link in the tabs

/Compatibility/Privilege Level/

and checked the box,

"Run this program as an administrator"

This allows the cygwin shell to open with administrator privileges and the corresponding subshells too.

Determine a user's timezone

Getting a valid TZ Database timezone name in PHP is a two-step process:

  1. With JavaScript, get timezone offset in minutes through getTimezoneOffset. This offset will be positive if the local timezone is behind UTC and negative if it is ahead. So you must add an opposite sign to the offset.

    var timezone_offset_minutes = new Date().getTimezoneOffset();
    timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;
    

    Pass this offset to PHP.

  2. In PHP convert this offset into a valid timezone name with timezone_name_from_abbr function.

    // Just an example.
    $timezone_offset_minutes = -360;  // $_GET['timezone_offset_minutes']
    
    // Convert minutes to seconds
    $timezone_name = timezone_name_from_abbr("", $timezone_offset_minutes*60, false);
    
    // America/Chicago
    echo $timezone_name;</code></pre>
    

I've written a blog post on it: How to Detect User Timezone in PHP. It also contains a demo.

cell format round and display 2 decimal places

I use format, Number, 2 decimal places & tick ' use 1000 separater ', then go to 'File', 'Options', 'Advanced', scroll down to 'When calculating this workbook' and tick 'set precision as displayed'. You get an error message about losing accuracy, that's good as it means it is rounding to 2 decimal places. So much better than bothering with adding a needless ROUND function.

Android Studio: Where is the Compiler Error Output Window?

If you are in android studio 3.1, Verify if file->Project Structure -> Source compatibility is empty. it should not have 1.8 set.

then press ok, the project will sync and error will disappear.

WHERE clause on SQL Server "Text" data type

If you can't change the datatype on the table itself to use varchar(max), then change your query to this:

SELECT *
FROM   [Village]
WHERE  CONVERT(VARCHAR(MAX), [CastleType]) = 'foo'

How do I convert strings between uppercase and lowercase in Java?

Assuming that all characters are alphabetic, you can do this:

From lowercase to uppercase:

// Uppercase letters. 
class UpperCase {  
  public static void main(String args[]) { 
    char ch;
    for(int i=0; i < 10; i++) { 
      ch = (char) ('a' + i);
      System.out.print(ch); 

      // This statement turns off the 6th bit.   
      ch = (char) ((int) ch & 65503); // ch is now uppercase
      System.out.print(ch + " ");  
    } 
  } 
}

From uppercase to lowercase:

// Lowercase letters. 
class LowerCase {  
  public static void main(String args[]) { 
    char ch;
    for(int i=0; i < 10; i++) { 
      ch = (char) ('A' + i);
      System.out.print(ch);
      ch = (char) ((int) ch | 32); // ch is now uppercase
      System.out.print(ch + " ");  
    } 
  } 
}

How permission can be checked at runtime without throwing SecurityException?

You should check for permissions in the following way (as described here Android permissions):

int result = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_PHONE_STATE);

then, compare your result to either:

result == PackageManager.PERMISSION_DENIED

or:

result == PackageManager.PERMISSION_GRANTED

How to run a Powershell script from the command line and pass a directory as a parameter

try this:

powershell "C:\Dummy Directory 1\Foo.ps1 'C:\Dummy Directory 2\File.txt'"

No assembly found containing an OwinStartupAttribute Error

Add below code to your web.config file then run the project...

    <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    </runtime>

how to show progress bar(circle) in an activity having a listview before loading the listview with data

Use This Within button on Click option or your needs:

final ProgressDialog progressDialog;
progressDialog = new ProgressDialog(getApplicationContext());
progressDialog.setMessage("Loading..."); // Setting Message
progressDialog.setTitle("ProgressDialog"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
    public void run() {
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        progressDialog.dismiss();
    }
}).start();

Get column from a two dimensional array

This function works to arrays and objects. obs: it works like array_column php function. It means that an optional third parameter can be passed to define what column will correspond to the indices of return.

function array_column(list, column, indice){
    var result;

    if(typeof indice != "undefined"){
        result = {};

        for(key in list)
            result[list[key][indice]] = list[key][column];
    }else{
        result = [];

        for(key in list)
            result.push( list[key][column] );
    }

    return result;
}

This is a conditional version:

function array_column_conditional(list, column, indice){
    var result;

    if(typeof indice != "undefined"){
        result = {};

        for(key in list)
            if(typeof list[key][column] !== 'undefined' && typeof list[key][indice] !== 'undefined')
                result[list[key][indice]] = list[key][column];
    }else{
        result = [];

        for(key in list)
            if(typeof list[key][column] !== 'undefined')
                result.push( list[key][column] );
    }

    return result;
}

usability:

var lista = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

var obj_list = [
  {a: 1, b: 2, c: 3},
  {a: 4, b: 5, c: 6},
  {a: 8, c: 9}
];

var objeto = {
  d: {a: 1, b: 3},
  e: {a: 4, b: 5, c: 6},
  f: {a: 7, b: 8, c: 9}
};

var list_obj = {
  d: [1, 2, 3],
  e: [4, 5],
  f: [7, 8, 9]
};

console.log( "column list: ", array_column(lista, 1) );
console.log( "column obj_list: ", array_column(obj_list, 'b', 'c') );
console.log( "column objeto: ", array_column(objeto, 'c') );
console.log( "column list_obj: ", array_column(list_obj, 0, 0) );

console.log( "column list conditional: ", array_column_conditional(lista, 1) );
console.log( "column obj_list conditional: ", array_column_conditional(obj_list, 'b', 'c') );
console.log( "column objeto conditional: ", array_column_conditional(objeto, 'c') );
console.log( "column list_obj conditional: ", array_column_conditional(list_obj, 0, 0) );

Output:

/*
column list:  Array [ 2, 5, 8 ]
column obj_list:  Object { 3: 2, 6: 5, 9: undefined }
column objeto:  Array [ undefined, 6, 9 ]
column list_obj:  Object { 1: 1, 4: 4, 7: 7 }

column list conditional:  Array [ 2, 5, 8 ]
column obj_list conditional:  Object { 3: 2, 6: 5 }
column objeto conditional:  Array [ 6, 9 ]
column list_obj conditional:  Object { 1: 1, 4: 4, 7: 7 }
*/

How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView

You can use general compound drawable implementation, but if you need to define a size of drawable use this library:

https://github.com/a-tolstykh/textview-rich-drawable

Here is a small example of usage:

<com.tolstykh.textviewrichdrawable.TextViewRichDrawable
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some text"
        app:compoundDrawableHeight="24dp"
        app:compoundDrawableWidth="24dp" />

Cannot find R.layout.activity_main

This is happening due to resources are not loading properly and the similar issue can occur any view also so Below are some technics which you can use to remove this error:-

  • Clean your project, Build -> clean Project
  • Rebuild project, Build -> Rebuild Project
  • Open manifest and check if there's any resource missing
  • Check-in layout to particular id if missing add it
  • If the above steps did not work then restart android studio with invalidating the cache.

Note: In the above-mentioned steps, the last step will work for this issue for sure.

Jquery click not working with ipad

I know this was asked a long time ago but I found an answer while searching for this exact question.

There are two solutions.

You can either set an empty onlick attribute on the html element:

<div class="clickElement" onclick=""></div>

Or you can add it in css by setting the pointer cursor:

.clickElement { cursor:pointer }

The problem is that on ipad, the first click on a non-anchor element registers as a hover. This is not really a bug, because it helps with sites that have hover-menus that haven't been tablet/mobile optimised. Setting the cursor or adding an empty onclick attribute tells the browser that the element is indeed a clickable area.

(via http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working)

Google Text-To-Speech API

Allright, so Google has introduces tokens (see the tk parameter in the new url) and the old solution doesn't seem to work. I've found an alternative - which I even think is better-sounding, and has more voices! The command isn't pretty, but it works. Please note that this is for testing purposes only (I use it for a little domotica project) and use the real version from acapella-group if you're planning on using this commercially.

curl $(curl --data 'MyLanguages=sonid10&MySelectedVoice=Sharon&MyTextForTTS=Hello%20World&t=1&SendToVaaS=' 'http://www.acapela-group.com/demo-tts/DemoHTML5Form_V2.php' | grep -o "http.*mp3") > tts_output.mp3

Some of the supported voices are;

  • Sharon
  • Ella (genuine child voice)
  • EmilioEnglish (genuine child voice)
  • Josh (genuine child voice)
  • Karen
  • Kenny (artificial child voice)
  • Laura
  • Micah
  • Nelly (artificial child voice)
  • Rod
  • Ryan
  • Saul
  • Scott (genuine teenager voice)
  • Tracy
  • ValeriaEnglish (genuine child voice)
  • Will
  • WillBadGuy (emotive voice)
  • WillFromAfar (emotive voice)
  • WillHappy (emotive voice)
  • WillLittleCreature (emotive voice)
  • WillOldMan (emotive voice)
  • WillSad (emotive voice)
  • WillUpClose (emotive voice)

It also supports multiple languages and more voices - for that I refer you to their website; http://www.acapela-group.com/

How to enable remote access of mysql in centos?

so do the following edit my.cnf:

[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/English
bind-address = xxx.xxx.xxx.xxx
# skip-networking

after edit hit service mysqld restart

login into mysql and hit this query:

GRANT ALL ON foo.* TO bar@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'PASSWORD';

thats it make sure your iptables allow connection from 3306 if not put the following:

iptables -A INPUT -i lo -p tcp --dport 3306 -j ACCEPT

iptables -A OUTPUT -p tcp --sport 3306 -j ACCEPT

How can I get the named parameters from a URL using Flask?

Use request.args to get parsed contents of query string:

from flask import request

@app.route(...)
def login():
    username = request.args.get('username')
    password = request.args.get('password')

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

What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.

var val = '@ViewBag.ForSection';

If it's an integer you need to parse it as one i.e.

var val = parseInt(@ViewBag.ForSection);

Can I have H2 autocreate a schema in an in-memory database?

If you are using spring with application.yml the following will work for you

spring: datasource: url: jdbc:h2:mem:mydb;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;INIT=CREATE SCHEMA IF NOT EXISTS calendar

How to split a string after specific character in SQL Server and update this value to specific column

Maybe something like this:

First some test data:

DECLARE @tbl TABLE(Column1 VARCHAR(100))

INSERT INTO @tbl
SELECT '1/1' UNION ALL
SELECT '1/20' UNION ALL
SELECT '1/2'

Then like this:

SELECT
    SUBSTRING(tbl.Column1,CHARINDEX('/',tbl.Column1)+1,LEN(tbl.Column1))
FROM
    @tbl AS tbl

Left function in c#

It sounds like you're asking about a function

string Left(string s, int left)

that will return the leftmost left characters of the string s. In that case you can just use String.Substring. You can write this as an extension method:

public static class StringExtensions
{
    public static string Left(this string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value)) return value;
        maxLength = Math.Abs(maxLength);

        return ( value.Length <= maxLength 
               ? value 
               : value.Substring(0, maxLength)
               );
    }
}

and use it like so:

string left = s.Left(number);

For your specific example:

string s = fac.GetCachedValue("Auto Print Clinical Warnings").ToLower() + " ";
string left = s.Substring(0, 1);

Jquery check if element is visible in viewport

var visible = $(".media").visible();

C# - Create SQL Server table programmatically

For managing DataBase Objects in SQL Server i would suggest using Server Management Objects

How to use class from other files in C# with visual studio?

It would be more beneficial for us if we could see the actual project structure, as the classes alone do not say that much.

Assuming that both .cs files are in the same project (if they are in different projects inside the same solution, you'd have to add a reference to the project containing Class2.cs), you can click on the Class2 occurrence in your code that is underlined in red and press CTRL + . (period) or click on the blue bar that should be there. The first option appearing will then add the appropriate using statement automatically. If there is no such menu, it may indicate that there is something wrong with the project structure or a reference missing.

You could try making Class2 public, but it sounds like this can't be a problem here, since by default what you did is internal class Class2 and thus Class2 should be accessible if both are living in the same project/assembly. If you are referencing a different assembly or project wherein Class2 is contained, you have to make it public in order to access it, as internal classes can't be accessed from outside their assembly.

As for renaming: You can click Program.cs in the Solution Explorer and press F2 to rename it. It will then open up a dialog window asking you if the class Program itself and all references thereof should be renamed as well, which is usually what you want. Or you could just rename the class Program in the declaration and again open up the menu with the small blue bar (or, again, CTRL+.) and do the same, but it won't automatically rename the actual file accordingly.

Edit after your question edit: I have never used this option you used, but from quick checking I think that it's really not inside the same project then. Do the following when adding new classes to a project: In the Solution Explorer, right click the project you created and select [Add] -> [Class] or [Add] -> [New Item...] and then select 'Class'. This will automatically make the new class part of the project and thus the assembly (the assembly is basically the 'end product' after building the project). For me, there is also the shortcut Alt+Shift+C working to create a new class.

Sorting arrays in javascript by object key value

This worked for me

var files=data.Contents;
          files = files.sort(function(a,b){
        return a.LastModified - b. LastModified;
      });

OR use Lodash to sort the array

files = _.orderBy(files,'LastModified','asc');

How to skip a iteration/loop in while-loop

Try to add continue; where you want to skip 1 iteration.

Unlike the break keyword, continue does not terminate a loop. Rather, it skips to the next iteration of the loop, and stops executing any further statements in this iteration. This allows us to bypass the rest of the statements in the current sequence, without stopping the next iteration through the loop.

http://www.javacoffeebreak.com/articles/loopyjava/index.html

What is the proper way to URL encode Unicode characters?

IRIs do not replace URIs, because only URIs (effectively, ASCII) are permissible in some contexts -- including HTTP.

Instead, you specify an IRI and it gets transformed into a URI when going out on the wire.

Sort array of objects by single key with date value

Use underscore js or lodash,

var arrObj = [
    {
        "updated_at" : "2012-01-01T06:25:24Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-09T11:25:13Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-05T04:13:24Z",
        "foo" : "bar"
    }
];

arrObj = _.sortBy(arrObj,"updated_at");

_.sortBy() returns a new array

refer http://underscorejs.org/#sortBy and lodash docs https://lodash.com/docs#sortBy

Not able to access adb in OS X through Terminal, "command not found"

The problem is: adb is not in your PATH. This is where the shell looks for executables. You can check your current PATH with echo $PATH.

Bash will first try to look for a binary called adb in your Path, and not in the current directory. Therefore, if you are currently in the platform-tools directory, just call

./adb --help

The dot is your current directory, and this tells Bash to use adb from there.

But actually, you should add platform-tools to your PATH, as well as some other tools that the Android SDK comes with. This is how you do it:

  1. Find out where you installed the Android SDK. This might be (where $HOME is your user's home directory) one of the following (or verify via Configure > SDK Manager in the Android Studio startup screen):

    • Linux: $HOME/Android/Sdk
    • macOS: $HOME/Library/Android/sdk
  2. Find out which shell profile to edit, depending on which file is used:

    • Linux: typically $HOME/.bashrc
    • macOS: typically $HOME/.bash_profile
    • With Zsh: $HOME/.zshrc
  3. Open the shell profile from step two, and at the bottom of the file, add the following lines. Make sure to replace the path with the one where you installed platform-tools if it differs:

    export ANDROID_HOME="$HOME/Android/Sdk"
    export PATH="$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$ANDROID_HOME/platform-tools:$PATH"
    
  4. Save the profile file, then, re-start the terminal or run source ~/.bashrc (or whatever you just modified).

Note that setting ANDROID_HOME is required for some third party frameworks, so it does not hurt to add it.

How to install Guest addition in Mac OS as guest and Windows machine as host

Before you start, close VirtualBox! After those manipulations start VB as Administrator!


  1. Run CMD as Administrator
  2. Use lines below one by one:
  • cd "C:\Program Files\Oracle\Virtualbox"
  • VBoxManage setextradata “macOS_Catalina” VBoxInternal2/EfiGraphicsResolution 1920x1080

Screen Resolutions: 1280x720, 1920x1080, 2048x1080, 2560x1440, 3840x2160, 1280x800, 1280x1024, 1440x900, 1600x900

Description:

  • macOS_Catalina - insert your VB machine name.

  • 1920x1080 - put here your Screen Resolution.

Cheers!

Java - Change int to ascii

You can convert a number to ASCII in java. example converting a number 1 (base is 10) to ASCII.

char k = Character.forDigit(1, 10);
System.out.println("Character: " + k);
System.out.println("Character: " + ((int) k));

Output:

Character: 1
Character: 49

jquery data selector

If you also use jQueryUI, you get a (simple) version of the :data selector with it that checks for the presence of a data item, so you can do something like $("div:data(view)"), or $( this ).closest(":data(view)").

See http://api.jqueryui.com/data-selector/ . I don't know for how long they've had it, but it's there now!

Windows 7: unable to register DLL - Error Code:0X80004005

Open the start menu and type cmd into the search box Hold Ctrl + Shift and press Enter

This runs the Command Prompt in Administrator mode.

Now type regsvr32 MyComobject.dll

Should functions return null or an empty object?

The best in this case return "null" in a case there no a such user. Also make your method static.

Edit:

Usually methods like this are members of some "User" class and don't have an access to its instance members. In this case the method should be static, otherwise you must create an instance of "User" and then call GetUserById method which will return another "User" instance. Agree this is confusing. But if GetUserById method is member of some "DatabaseFactory" class - no problem to leave it as an instance member.

How do you change the launcher logo of an app in Android Studio?

Click app/manifests/AndroidManifest.xml You see android:icon="@mipmap/your image name"

Also change android:roundicon="@mipmap/your image name" Example: android:icon="@mipmap/image" that's all

How do I clear all options in a dropdown box?

var select = document.getElementById('/*id attribute of your select here*/');
for (var option in select){
    select.remove(option);
}

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

How to scroll to bottom in a ScrollView on activity startup

Try this

    final ScrollView scrollview = ((ScrollView) findViewById(R.id.scrollview));
    scrollview.post(new Runnable() {
       @Override
       public void run() {
         scrollview.fullScroll(ScrollView.FOCUS_DOWN);
       }
    });

Print a list in reverse order with range()?

I thought that many (as myself) could be more interested in a common case of traversing an existing list in reversed order instead, as it's stated in the title, rather than just generating indices for such traversal.

Even though, all the right answers are still perfectly fine for this case, I want to point out that the performance comparison done in Wolf's answer is for generating indices only. So I've made similar benchmark for traversing an existing list in reversed order.

TL;DR a[::-1] is the fastest.

NB: If you want more detailed analysis of different reversal alternatives and their performance, check out this great answer.

Prerequisites:

a = list(range(10))

Jason's answer:

%timeit [a[9-i] for i in range(10)]
1.27 µs ± 61.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

martineau's answer:

%timeit a[::-1]
135 ns ± 4.07 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Michal Šrajer's answer:

%timeit list(reversed(a))
374 ns ± 9.87 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

bene's answer:

%timeit [a[i] for i in range(9, -1, -1)]
1.09 µs ± 11.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

As you see, in this case there's no need to explicitly generate indices, so the fastest method is the one that makes less extra actions.

NB: I tested in JupyterLab which has handy "magic command" %timeit. It uses standard timeit.timeit under the hood. Tested for Python 3.7.3

Changing image size in Markdown

For future reference:

Markdown implementation for Joplin allows controlling the size of imported images in the following manner:

<img src=":/7653a812439451eb1803236687a70ca" width="450"/>

This feature was requested here and as promised by Laurent this has been implemented.


It took me a while to figure the Joplin specific answer.

angular.element vs document.getElementById or jQuery selector with spin (busy) control

You should read the angular element docs if you haven't yet, so you can understand what is supported by jqLite and what not -jqlite is a subset of jquery built into angular.

Those selectors won't work with jqLite alone, since selectors by id are not supported.

  var target = angular.element('#appBusyIndicator');
  var target = angular.element('appBusyIndicator');

So, either :

  • you use jqLite alone, more limited than jquery, but enough in most of the situations.
  • or you include the full jQuery lib in your app, and use it like normal jquery, in the places that you really need jquery.

Edit: Note that jQuery should be loaded before angularJS in order to take precedence over jqLite:

Real jQuery always takes precedence over jqLite, provided it was loaded before DOMContentLoaded event fired.

Edit2: I missed the second part of the question before:

The issue with <input type="number"> , I think it is not an angular issue, it is the intended behaviour of the native html5 number element.

It won't return a non-numeric value even if you try to retrieve it with jquery's .val() or with the raw .value attribute.

replacing text in a file with Python

This is a short and simple example I just used:

If:

fp = open("file.txt", "w")

Then:

fp.write(line.replace('is', 'now'))
// "This is me" becomes "This now me"

Not:

line.replace('is', 'now')
fp.write(line)
// "This is me" not changed while writing

Plot width settings in ipython notebook

This is way I did it:

%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (12, 9) # (w, h)

You can define your own sizes.

Get JSONArray without array name?

Here is a solution under 19API lvl:

  • First of all. Make a Gson obj. --> Gson gson = new Gson();

  • Second step is get your jsonObj as String with StringRequest(instead of JsonObjectRequest)

  • The last step to get JsonArray...

YoursObjArray[] yoursObjArray = gson.fromJson(response, YoursObjArray[].class);

background-size in shorthand background property (CSS3)

Just a note for reference: I was trying to do shorthand like so:

background: url('../images/sprite.png') -312px -234px / 355px auto no-repeat;

but iPhone Safari browsers weren't showing the image properly with a fixed position element. I didn't check with a non-fixed, because I'm lazy. I had to switch the css to what's below, being careful to put background-size after the background property. If you do them in reverse, the background reverts the background-size to the original size of the image. So generally I would avoid using the shorthand to set background-size.

background: url('../images/sprite.png') -312px -234px no-repeat;
background-size: 355px auto;

Visual studio equivalent of java System.out

Use Either Debug.WriteLine() or Trace.WriteLine(). If in release mode, only the latter will appear in the output window, in debug mode, both will.

Bash if statement with multiple conditions throws an error

You can use either [[ or (( keyword. When you use [[ keyword, you have to use string operators such as -eq, -lt. I think, (( is most preferred for arithmetic, because you can directly use operators such as ==, < and >.

Using [[ operator

a=$1
b=$2
if [[ a -eq 1 || b -eq 2 ]] || [[ a -eq 3 && b -eq 4 ]]
then
     echo "Error"
else
     echo "No Error"
fi

Using (( operator

a=$1
b=$2
if (( a == 1 || b == 2 )) || (( a == 3 && b == 4 ))
then
     echo "Error"
else
     echo "No Error"
fi

Do not use -a or -o operators Since it is not Portable.

Difference between Static methods and Instance methods

Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name using period sign which is in (.)

for example:

Person.staticMethod();           //accessing static method.

for non-static method you must instantiate the class.

Person person1 = new Person();   //instantiating
person1.nonStaticMethod();       //accessing non-static method.

how to get the base url in javascript

This is done simply by doing this variable.

var base_url = '<?php echo base_url();?>'

This will have base url now. And now make a javascript function that will use this variable

function base_url(string){
    return base_url + string;
}

And now this will always use the correct path.

var path    =   "assets/css/themes/" + color_ + ".css"
$('#style_color').attr("href", base_url(path) );

Jmeter - get current date and time

Use ${__time(yyyy-MM-dd'T'hh:mm:ss)} to convert time into a particular timeformat. Here are other formats that you can use:

yyyy/MM/dd HH:mm:ss.SSS
yyyy/MM/dd HH:mm:ss
yyyy-MM-dd HH:mm:ss.SSS
yyyy-MM-dd HH:mm:ss
MM/dd/yy HH:mm:ss

You can use Z character to get milliseconds too. For example:

yyyy/MM/dd HH:mm:ssZ => 2017-01-25T10:29:00-0700
yyyy/MM/dd HH:mm:ss.SSS'Z' => 2017-01-25T10:28:49.549Z

Most of the time yyyy/MM/dd HH:mm:ss.SSS'Z' is required in some APIs. It is better to know how to convert time into this format.

Linux/Unix command to determine if process is running?

You should know the PID of your process.

When you launch it, its PID will be recorded in the $! variable. Save this PID into a file.

Then you will need to check if this PID corresponds to a running process. Here's a complete skeleton script:

FILE="/tmp/myapp.pid"

if [ -f $FILE ];
then
   PID=$(cat $FILE)
else
   PID=1
fi

ps -o pid= -p $PID
if [ $? -eq 0 ]; then
  echo "Process already running."  
else
  echo "Starting process."
  run_my_app &
  echo $! > $FILE
fi

Based on the answer of peterh. The trick for knowing if a given PID is running is in the ps -o pid= -p $PID instruction.

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

How do I increase modal width in Angular UI Bootstrap?

You can do this in very simple way using size property of angular modal.

var modal = $modal.open({
                    templateUrl: "/partials/welcome",
                    controller: "welcomeCtrl",
                    backdrop: "static",
                    scope: $scope,
                    size:'lg' // you can try different width like 'sm', 'md'
                });

PHP save image file

Note: you should use the accepted answer if possible. It's better than mine.

It's quite easy with the GD library.

It's built in usually, you probably have it (use phpinfo() to check)

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");

imagejpeg($image, "folder/file.jpg");

The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");

This only works if allow_url_fopen is true (it is by default)

Usage of the backtick character (`) in JavaScript

It's a pretty useful functionality, for example here is a Node.js code snippet to test the set up of a 3 second timing function.

const waitTime = 3000;
console.log(`setting a ${waitTime/1000} second delay`);

Explanation

  1. Declare wait time as 3000
  2. Using the backtick you can embed the result of the calculation of 'wait time' divided by 1000 in the same line with your chosen text.
  3. Further calling a timer function using the 'waitTime' constant will result in a 3 second delay, as calculated in the console.log argument.

Best way to create a temp table with same columns and type as a permanent table

Sortest one...

select top 0 * into #temptable from mytable

Note : This creates an empty copy of temp, But it doesn't create a primary key

__init__() got an unexpected keyword argument 'user'

I got the same error.

On my view I was overriding get_form_kwargs() like this:

class UserAccountView(FormView):
    form_class = UserAccountForm
    success_url = '/'
    template_name = 'user_account/user-account.html'

def get_form_kwargs(self):
    kwargs = super(UserAccountView, self).get_form_kwargs()
    kwargs.update({'user': self.request.user})
    return kwargs

But on my form I failed to override the init() method. Once I did it. Problem solved

class UserAccountForm(forms.Form):
    first_name = forms.CharField(label='Your first name', max_length=30)
    last_name = forms.CharField(label='Your last name', max_length=30)
    email = forms.EmailField(max_length=75)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(UserAccountForm, self).__init__(*args, **kwargs)

How to get file path in iPhone app

Since it is your files in your app bundle, I think you can use pathForResource:ofType: to get the full pathname of your file.

Here is an example:

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"your_file_name" 
                                            ofType:@"the_file_extension"];

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

How to solve the memory error in Python

Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75

Doing some rough math:

75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

How to Find And Replace Text In A File With C#

Read all file content. Make a replacement with String.Replace. Write content back to file.

string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);

What do these operators mean (** , ^ , %, //)?

You are correct that ** is the power function.

^ is bitwise XOR.

% is indeed the modulus operation, but note that for positive numbers, x % m = x whenever m > x. This follows from the definition of modulus. (Additionally, Python specifies x % m to have the sign of m.)

// is a division operation that returns an integer by discarding the remainder. This is the standard form of division using the / in most programming languages. However, Python 3 changed the behavior of / to perform floating-point division even if the arguments are integers. The // operator was introduced in Python 2.6 and Python 3 to provide an integer-division operator that would behave consistently between Python 2 and Python 3. This means:

| context                                | `/` behavior   | `//` behavior |
---------------------------------------------------------------------------
| floating-point arguments, Python 2 & 3 | float division | int divison   |
---------------------------------------------------------------------------
| integer arguments, python 2            | int division   | int division  |
---------------------------------------------------------------------------
| integer arguments, python 3            | float division | int division  |

For more details, see this question: Division in Python 2.7. and 3.3

How to call a shell script from python code?

There are some ways using os.popen() (deprecated) or the whole subprocess module, but this approach

import os
os.system(command)

is one of the easiest.

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

On groupby object, the agg function can take a list to apply several aggregation methods at once. This should give you the result you need:

df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).agg(['mean', 'count'])

Resize image in PHP

I found a mathematical way to get this job done

Github repo - https://github.com/gayanSandamal/easy-php-image-resizer

Live example - https://plugins.nayague.com/easy-php-image-resizer/

<?php
//path for the image
$source_url = '2018-04-01-1522613288.PNG';

//separate the file name and the extention
$source_url_parts = pathinfo($source_url);
$filename = $source_url_parts['filename'];
$extension = $source_url_parts['extension'];

//define the quality from 1 to 100
$quality = 10;

//detect the width and the height of original image
list($width, $height) = getimagesize($source_url);
$width;
$height;

//define any width that you want as the output. mine is 200px.
$after_width = 200;

//resize only when the original image is larger than expected with.
//this helps you to avoid from unwanted resizing.
if ($width > $after_width) {

    //get the reduced width
    $reduced_width = ($width - $after_width);
    //now convert the reduced width to a percentage and round it to 2 decimal places
    $reduced_radio = round(($reduced_width / $width) * 100, 2);

    //ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places
    $reduced_height = round(($height / 100) * $reduced_radio, 2);
    //reduce the calculated height from the original height
    $after_height = $height - $reduced_height;

    //Now detect the file extension
    //if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG'
    if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG') {
        //then return the image as a jpeg image for the next step
        $img = imagecreatefromjpeg($source_url);
    } elseif ($extension == 'png' || $extension == 'PNG') {
        //then return the image as a png image for the next step
        $img = imagecreatefrompng($source_url);
    } else {
        //show an error message if the file extension is not available
        echo 'image extension is not supporting';
    }

    //HERE YOU GO :)
    //Let's do the resize thing
    //imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]);
    $imgResized = imagescale($img, $after_width, $after_height, $quality);

    //now save the resized image with a suffix called "-resized" and with its extension. 
    imagejpeg($imgResized, $filename . '-resized.'.$extension);

    //Finally frees any memory associated with image
    //**NOTE THAT THIS WONT DELETE THE IMAGE
    imagedestroy($img);
    imagedestroy($imgResized);
}
?>

Export javascript data to CSV file without server interaction

See adeneo's answer, but to make this work in Excel in all countries you should add "SEP=," to the first line of the file. This will set the standard separator in Excel and will not show up in the actual document

var csvString = "SEP=, \n" + csvRows.join("\r\n");

Using underscores in Java variables and method names

The reason people do it (in my experience) is to differentiate between member variables and function parameters. In Java you can have a class like this:

public class TestClass {
  int var1;

  public void func1(int var1) {
     System.out.println("Which one is it?: " + var1);
  }
}

If you made the member variable _var1 or m_var1, you wouldn't have the ambiguity in the function.

So it's a style, and I wouldn't call it bad.

Determine number of pages in a PDF file

You'll need a PDF API for C#. iTextSharp is one possible API, though better ones might exist.

iTextSharp Example

You must install iTextSharp.dll as a reference. Download iTextsharp from SourceForge.net This is a complete working program using a console application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
namespace GetPages_PDF
{
  class Program
{
    static void Main(string[] args)
      {
       // Right side of equation is location of YOUR pdf file
        string ppath = "C:\\aworking\\Hawkins.pdf";
        PdfReader pdfReader = new PdfReader(ppath);
        int numberOfPages = pdfReader.NumberOfPages;
        Console.WriteLine(numberOfPages);
        Console.ReadLine();
      }
   }
}

SpringMVC RequestMapping for GET parameters

You can add @RequestMapping like so:

@RequestMapping("/userGrid")
public @ResponseBody GridModel getUsersForGrid(
   @RequestParam("_search") String search,
   @RequestParam String nd,
   @RequestParam int rows,
   @RequestParam int page,
   @RequestParam String sidx) 
   @RequestParam String sord) {

window.location (JS) vs header() (PHP) for redirection

The first case will fail when JS is off. It's also a little bit slower since JS must be parsed first (DOM must be loaded). However JS is safer since the destination doesn't know the referer and your redirect might be tracked (referers aren't reliable in general yet this is something).

You can also use meta refresh tag. It also requires DOM to be loaded.

How to run a task when variable is undefined in ansible?

As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined keyword.

tasks:
    - shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
      when: foo is defined

    - fail: msg="Bailing out. this play requires 'bar'"
      when: bar is undefined

Ansible Documentation

What is the difference between res.end() and res.send()?

In addition to the excellent answers, I would like to emphasize here when to use res.end() and when to use res.send() this was why I originally landed here and I didn't found a solution.

The answer is really simple

res.end() is used to quickly end the response without sending any data.

An example for this would be starting a process on a server

app.get(/start-service, (req, res) => {
   // Some logic here
   exec('./application'); // dummy code
   res.end();
});

If you would like to send data in your response then you should use res.send() instead

app.get(/start-service, (req, res) => {
   res.send('{"age":22}');
});

Here you can read more

Java Error: illegal start of expression

Remove the public keyword from int[] locations={1,2,3};. An access modifier isn't allowed inside a method, as its accessbility is defined by its method scope.

If your goal is to use this reference in many a method, you might want to move the declaration outside the method.

What's the difference between Cache-Control: max-age=0 and no-cache?

By the way, it's worth noting that some mobile devices, particularly Apple products like iPhone/iPad completely ignore headers like no-cache, no-store, Expires: 0, or whatever else you may try to force them to not re-use expired form pages.

This has caused us no end of headaches as we try to get the issue of a user's iPad say, being left asleep on a page they have reached through a form process, say step 2 of 3, and then the device totally ignores the store/cache directives, and as far as I can tell, simply takes what is a virtual snapshot of the page from its last state, that is, ignoring what it was told explicitly, and, not only that, taking a page that should not be stored, and storing it without actually checking it again, which leads to all kinds of strange Session issues, among other things.

I'm just adding this in case someone comes along and can't figure out why they are getting session errors with particularly iphones and ipads, which seem by far to be the worst offenders in this area.

I've done fairly extensive debugger testing with this issue, and this is my conclusion, the devices ignore these directives completely.

Even in regular use, I've found that some mobiles also totally fail to check for new versions via say, Expires: 0 then checking last modified dates to determine if it should get a new one.

It simply doesn't happen, so what I was forced to do was add query strings to the css/js files I needed to force updates on, which tricks the stupid mobile devices into thinking it's a file it does not have, like: my.css?v=1, then v=2 for a css/js update. This largely works.

User browsers also, by the way, if left to their defaults, as of 2016, as I continuously discover (we do a LOT of changes and updates to our site) also fail to check for last modified dates on such files, but the query string method fixes that issue. This is something I've noticed with clients and office people who tend to use basic normal user defaults on their browsers, and have no awareness of caching issues with css/js etc, almost invariably fail to get the new css/js on change, which means the defaults for their browsers, mostly MSIE / Firefox, are not doing what they are told to do, they ignore changes and ignore last modified dates and do not validate, even with Expires: 0 set explicitly.

This was a good thread with a lot of good technical information, but it's also important to note how bad the support for this stuff is in particularly mobile devices. Every few months I have to add more layers of protection against their failure to follow the header commands they receive, or to properly interpet those commands.

Command failed due to signal: Segmentation fault: 11

You can get this error when the compiler gets too confused about what's going on in your code. I noticed you have a number of what appear to be functions nested within functions. You might try commenting out some of that at a time to see if the error goes away. That way you can zero in on the problem area. You can't use breakpoints because it's a compile time error, not a run time error.

Finding the layers and layer sizes for each Docker image

I've solved this problem by using the search function on Docker's website where '*' is a valid search that returns 200k repositories and then I crawled each invididual page. HTML parsing allows me to extract all the image names on each page.

C++ [Error] no matching function for call to

You are trying to call DeckOfCards::shuffle with a deckOfCards parameter:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck

But the method takes a vector<Card>&:

void deckOfCards::shuffle(vector<Card>& deck)

The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.

Error:

[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'

Paraphrased:

Hey, pal. You're trying to call a function called shuffle which apparently takes a single parameter of type reference-to-deckOfCards, but there is no such function.

Error:

[Note] candidate is:

In file included from main.cpp

[Note] void deckOfCards::shuffle(std::vector&)

Paraphrased:

I mean, maybe you meant this other function called shuffle, but that one takes a reference-tovector<something>.

Error:

[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'

Which I'd be happy to call if I knew how to convert from a deckOfCards to a vector; but I don't. So I won't.

How to import or copy images to the "res" folder in Android Studio?

Goto Settings > Plugin > Browse Repository > Serach Android Drawable Import

This plugin consists of 4 main features.

  • AndroidIcons Drawable Import
  • Material Icons Drawable Import
  • Scaled Drawable
  • Multisource-Drawable

Edit : After Android Studios 1.5 android support Vector Asset Studio.


Follow this, which says:

To start Vector Asset Studio:

  1. In Android Studio, open an Android app project.
  2. In the Project window, select the Android view.
  3. Right-click the res folder and select New > Vector Asset.

enter image description here

Javascript/Jquery Convert string to array

Change

var trainindIdArray = traingIds.split(',');

to

var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');

That will basically remove [ and ] and then split the string

Rename specific column(s) in pandas

data.rename(columns={'gdp':'log(gdp)'}, inplace=True)

The rename show that it accepts a dict as a param for columns so you just pass a dict with a single entry.

Also see related

ld: framework not found Pods

In my case, I created the workspace before installing the pods, so when I installed the pods, the workspace included my project only, add the Pods project to your workspace, clean and rebuild solved the issue in my case

Reading specific columns from a text file in python

It may help:

import csv
with open('csv_file','r') as f:
    # Printing Specific Part of CSV_file
    # Printing last line of second column
    lines = list(csv.reader(f, delimiter = ' ', skipinitialspace = True))
    print(lines[-1][1])
    # For printing a range of rows except 10 last rows of second column
    for i in range(len(lines)-10):
        print(lines[i][1])

Does uninstalling a package with "pip" also remove the dependent packages?

You can install and use the pip-autoremove utility to remove a package plus unused dependencies.

# install pip-autoremove
pip install pip-autoremove
# remove "somepackage" plus its dependencies:
pip-autoremove somepackage -y

What does .pack() do?

The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes.

Powershell command to hide user from exchange address lists

I was getting the exact same error, however I solved it by running $false first and then $true.