Programs & Examples On #Incompatibletypeerror

Multiple left-hand assignment with JavaScript

a = (b = 'string is truthy'); // b gets string; a gets b, which is a primitive (copy)
a = (b = { c: 'yes' }); // they point to the same object; a === b (not a copy)

(a && b) is logically (a ? b : a) and behaves like multiplication (eg. !!a * !!b)

(a || b) is logically (a ? a : b) and behaves like addition (eg. !!a + !!b)

(a = 0, b) is short for not caring if a is truthy, implicitly return b


a = (b = 0) && "nope, but a is 0 and b is 0"; // b is falsey + order of operations
a = (b = "b is this string") && "a gets this string"; // b is truthy + order of ops

JavaScript Operator Precedence (Order of Operations)

Note that the comma operator is actually the least privileged operator, but parenthesis are the most privileged, and they go hand-in-hand when constructing one-line expressions.


Eventually, you may need 'thunks' rather than hardcoded values, and to me, a thunk is both the function and the resultant value (the same 'thing').

const windowInnerHeight = () => 0.8 * window.innerHeight; // a thunk

windowInnerHeight(); // a thunk

Moving Panel in Visual Studio Code to right side

VSCode 1.42 (January 2020) introduces:

Panel on the left/right

The panel can now be moved to the left side of the editor with the setting:

"workbench.panel.defaultLocation": "left"

This removes the command View: Toggle Panel Position (workbench.action.togglePanelPosition) in favor of the following new commands:

  • View: Move Panel Left (workbench.action.positionPanelLeft)
  • View: Move Panel Right (workbench.action.positionPanelRight)
  • View: Move Panel To Bottom (workbench.action.positionPanelBottom)

What is a reasonable code coverage % for unit tests (and why)?

Depending on the criticality of the code, anywhere from 75%-85% is a good rule of thumb. Shipping code should definitely be tested more thoroughly than in house utilities, etc.

Does --disable-web-security Work In Chrome Anymore?

just run this command from command prompt and it will launch chrome instance with CORS disabled:

C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp

MSOnline can't be imported on PowerShell (Connect-MsolService error)

After reviewing Microsoft's TechNet article "Azure Active Directory Cmdlets" -> section "Install the Azure AD Module", it seems that this process has been drastically simplified, thankfully.

As of 2016/06/30, in order to successfully execute the PowerShell commands Import-Module MSOnline and Connect-MsolService, you will need to install the following applications (64-bit only):

  1. Applicable Operating Systems: Windows 7 to 10
    Name: "Microsoft Online Services Sign-in Assistant for IT Professionals RTW"
    Version: 7.250.4556.0 (latest)
    Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=41950
    Installer file name: msoidcli_64.msi
  2. Applicable Operating Systems: Windows 7 to 10
    Name: "Windows Azure Active Directory Module for Windows PowerShell"
    Version: Unknown but the latest installer file's SHA-256 hash is D077CF49077EE133523C1D3AE9A4BF437D220B16D651005BBC12F7BDAD1BF313
    Installer URL: https://technet.microsoft.com/en-us/library/dn975125.aspx
    Installer file name: AdministrationConfig-en.msi
  3. Applicable Operating Systems: Windows 7 only
    Name: "Windows PowerShell 3.0"
    Version: 3.0 (later versions will probably work too)
    Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=34595
    Installer file name: Windows6.1-KB2506143-x64.msu

 

enter image description here enter image description here enter image description here

Swapping pointers in C (char, int)

In C, a string, as you know, is a character pointer (char *). If you want to swap two strings, you're swapping two char pointers, i.e. just two addresses. In order to do any swap in a function, you need to give it the addresses of the two things you're swapping. So in the case of swapping two pointers, you need a pointer to a pointer. Much like to swap an int, you just need a pointer to an int.

The reason your last code snippet doesn't work is because you're expecting it to swap two char pointers -- it's actually written to swap two characters!

Edit: In your example above, you're trying to swap two int pointers incorrectly, as R. Martinho Fernandes points out. That will swap the two ints, if you had:

int a, b;
intSwap(&a, &b);

Working with $scope.$emit and $scope.$on

First of all, parent-child scope relation does matter. You have two possibilities to emit some event:

  • $broadcast -- dispatches the event downwards to all child scopes,
  • $emit -- dispatches the event upwards through the scope hierarchy.

I don't know anything about your controllers (scopes) relation, but there are several options:

  1. If scope of firstCtrl is parent of the secondCtrl scope, your code should work by replacing $emit by $broadcast in firstCtrl:

    function firstCtrl($scope)
    {
        $scope.$broadcast('someEvent', [1,2,3]);
    }
    
    function secondCtrl($scope)
    {
        $scope.$on('someEvent', function(event, mass) { console.log(mass); });
    }
    
  2. In case there is no parent-child relation between your scopes you can inject $rootScope into the controller and broadcast the event to all child scopes (i.e. also secondCtrl).

    function firstCtrl($rootScope)
    {
        $rootScope.$broadcast('someEvent', [1,2,3]);
    }
    
  3. Finally, when you need to dispatch the event from child controller to scopes upwards you can use $scope.$emit. If scope of firstCtrl is parent of the secondCtrl scope:

    function firstCtrl($scope)
    {
        $scope.$on('someEvent', function(event, data) { console.log(data); });
    }
    
    function secondCtrl($scope)
    {
        $scope.$emit('someEvent', [1,2,3]);
    }
    

Convert .class to .java

I used the http://www.javadecompilers.com but in some classes it gives you the message "could not load this classes..."

INSTEAD download Android Studio, navigate to the folder containing the java class file and double click it. The code will show in the right pane and I guess you can copy it an save it as a java file from there

Difference between Java SE/EE/ME?

The SE(JDK) has all the libraries you will ever need to cut your teeth on Java. I recommend the Netbeans IDE as this comes bundled with the SE(JDK) straight from Oracle. Don't forget to set "path" and "classpath" variables especially if you are going to try command line. With a 64 bit system insert the "System Path" e.g. C:\Program Files (x86)\Java\jdk1.7.0 variable before the C:\Windows\system32; to direct the system to your JDK.

hope this helps.

How do I pretty-print existing JSON data with Java?

Use gson. https://www.mkyong.com/java/how-to-enable-pretty-print-json-output-gson/

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(my_bean);

output

{
  "name": "mkyong",
  "age": 35,
  "position": "Founder",
  "salary": 10000,
  "skills": [
    "java",
    "python",
    "shell"
  ]
}

How to convert JSON object to an Typescript array?

That's correct, your response is an object with fields:

{
    "page": 1,
    "results": [ ... ]
}

So you in fact want to iterate the results field only:

this.data = res.json()['results'];

... or even easier:

this.data = res.json().results;

How to generate a random number between 0 and 1?

In your version rand() % 10000 will yield an integer between 0 and 9999. Since RAND_MAX may be as little as 32767, and since this is not exactly divisible by 10000 and not large relative to 10000, there will be significant bias in the 'randomness' of the result, moreover, the maximum value will be 0.9999, not 1.0, and you have unnecessarily restricted your values to four decimal places.

It is simple arithmetic, a random number divided by the maximum possible random number will yield a number from 0 to 1 inclusive, while utilising the full resolution and distribution of the RNG

double r2()
{
    return (double)rand() / (double)RAND_MAX ;
}

Use (double)rand() / (double)((unsigned)RAND_MAX + 1) if exclusion of 1.0 was intentional.

How do I get to IIS Manager?

You need to make sure the IIS Management Console is installed.

SQL SELECT everything after a certain character

Try this in MySQL.

right(field,((CHAR_LENGTH(field))-(InStr(field,','))))

Is there a <meta> tag to turn off caching in all browsers?

pragma is your best bet:

<meta http-equiv="Pragma" content="no-cache">

How do you comment an MS-access Query?

You can add a comment to an MSAccess query as follows: Create a dummy field in the query. Not elegant but is self-documentating and contained in the query, which makes cheking it into source code control alot more feasible! Jere's an example. Go into SQL view and add the dummy field (you can do from design view too):

SELECT  "2011-01-21;JTR;Added FIELD02;;2011-01-20;JTR;Added qryHISTORY;;" as qryHISTORY,  ...rest of query here...

Run the query:

qryHISTORY                           FIELD01 FIELD02 ...
2011-01-21;JTR;Added FIELD02;;2011-01-20;JTR;Added qryHISTORY;;"  0000001  ABCDEF ...

Note the use of ";" as field delimiter in qryHISTORY field, and ";;" as an end of comment, and use of ISO date format and intials, as well as comment. Have tested this with up to 646 characters in the qryHISTORY field.

How can I split this comma-delimited string in Python?

How about a list?

mystring.split(",")

It might help if you could explain what kind of info we are looking at. Maybe some background info also?

EDIT:

I had a thought you might want the info in groups of two?

then try:

re.split(r"\d*,\d*", mystring)

and also if you want them into tuples

[(pair[0], pair[1]) for match in re.split(r"\d*,\d*", mystring) for pair in match.split(",")]

in a more readable form:

mylist = []
for match in re.split(r"\d*,\d*", mystring):
    for pair in match.split(",")
        mylist.append((pair[0], pair[1]))

In Java, can you modify a List while iterating through it?

Use Java 8's removeIf(),

To remove safely,

letters.removeIf(x -> !x.equals("A"));

How do I hide an element on a click event anywhere outside of the element?

This doesn't work - it hides the .myDIV when you click inside of it.

$('.openDiv').click(function(e) {
$('.myDiv').show(); 
e.stopPropagation();
})

$(document).click(function(){  
$('.myDiv').hide(); 

});

});

<a class="openDiv">DISPLAY DIV</a>

<div class="myDiv">HIDE DIV</div>

ASP.NET Button to redirect to another page

You can either do a Response.Redirect("YourPage.aspx"); or a Server.Transfer("YourPage.aspx"); on your button click event. So it's gonna be like the following:

protected void btnConfirm_Click(object sender, EventArgs e)
{
    Response.Redirect("YourPage.aspx");
    //or
    Server.Transfer("YourPage.aspx");
}

How to add List<> to a List<> in asp.net

Use List.AddRange(collection As IEnumerable(Of T)) method.

It allows you to append at the end of your list another collection/list.

Example:

List<string> initialList = new List<string>();
// Put whatever you want in the initial list
List<string> listToAdd = new List<string>();
// Put whatever you want in the second list
initialList.AddRange(listToAdd);

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

This error is often caused by incompatible jQuery versions. I encountered the same error with a foundation 6 repository. My repository was using jQuery 3, but foundation requires an earlier version. I then changed it and it worked.

If you look at the version of jQuery required by the foundation 5 dependencies it states "jquery": "~2.1.0".

Can you confirm that you are loading the correct version of jQuery?

I hope this helps.

Java ArrayList - how can I tell if two lists are equal, order not mattering?

Converting the lists to Guava's Multiset works very well. They are compared regardless of their order and duplicate elements are taken into account as well.

static <T> boolean equalsIgnoreOrder(List<T> a, List<T> b) {
    return ImmutableMultiset.copyOf(a).equals(ImmutableMultiset.copyOf(b));
}

assert equalsIgnoreOrder(ImmutableList.of(3, 1, 2), ImmutableList.of(2, 1, 3));
assert !equalsIgnoreOrder(ImmutableList.of(1), ImmutableList.of(1, 1));

How to set selected value from Combobox?

cmbEmployeeStatus.Text = "text"

PHP check if file is an image

The getimagesize() should be the most definite way of working out whether the file is an image:

if(@is_array(getimagesize($mediapath))){
    $image = true;
} else {
    $image = false;
}

because this is a sample getimagesize() output:

Array (
[0] => 800
[1] => 450
[2] => 2
[3] => width="800" height="450"
[bits] => 8
[channels] => 3
[mime] => image/jpeg)

Submit button not working in Bootstrap form

  • If you put type=submit it is a Submit Button
  • if you put type=button it is just a button, It does not submit your form inputs.

and also you don't want to use both of these

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

To sum up based on answers here and elsewhere:

  1. Check the .NET version of the app pool (e.g. 2.0 vs 4.0)
  2. Check that all IIS referenced modules are installed. In this case it was the AJAX extensions (probably not the case these days), but URL Rewrite is a common one.

Javascript - Open a given URL in a new tab by clicking a button

I just used target="_blank" under form tag and it worked fine with FF and Chrome where it opens in a new tag but with IE it opens in a new window.

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

Also, we can use it following ways

To get only first

 $cat_details = DB::table('an_category')->where('slug', 'people')->first();

To get by limit and offset

$top_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(0)->orderBy('id', 'DESC')->get();
$remaining_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(30)->orderBy('id', 'DESC')->get();

Entity Framework. Delete all rows in table

dataDb.Table.RemoveRange(dataDb.Table);
dataDb.SaveChanges();

Can a java lambda have more than 1 parameter?

For something with 2 parameters, you could use BiFunction. If you need more, you can define your own function interface, like so:

@FunctionalInterface
public interface FourParameterFunction<T, U, V, W, R> {
    public R apply(T t, U u, V v, W w);
}

If there is more than one parameter, you need to put parentheses around the argument list, like so:

FourParameterFunction<String, Integer, Double, Person, String> myLambda = (a, b, c, d) -> {
    // do something
    return "done something";
};

How to convert a String to CharSequence?

Straight answer:

String s = "Hello World!";

// String => CharSequence conversion:

CharSequence cs = s;  // String is already a CharSequence

CharSequence is an interface, and the String class implements CharSequence.

jQuery - add additional parameters on submit (NOT ajax)

You could write a jQuery function which allowed you to add hidden fields to a form:

// This must be applied to a form (or an object inside a form).
jQuery.fn.addHidden = function (name, value) {
    return this.each(function () {
        var input = $("<input>").attr("type", "hidden").attr("name", name).val(value);
        $(this).append($(input));
    });
};

And then add the hidden field before you submit:

var frm = $("#form").addHidden('SaveAndReturn', 'Save and Return')
                    .submit();

Python: printing a file to stdout

Sure. Assuming you have a string with the file's name called fname, the following does the trick.

with open(fname, 'r') as fin:
    print(fin.read())

Escaping regex string

Use the re.escape() function for this:

4.2.3 re Module Contents

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.

A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.

def simplistic_plural(word, text):
    word_or_plural = re.escape(word) + 's?'
    return re.match(word_or_plural, text)

How can you tell when a layout has been drawn?

An alternative to the usual methods is to hook into the drawing of the view.

OnPreDrawListener is called many times when displaying a view, so there is no specific iteration where your view has valid measured width or height. This requires that you continually verify (view.getMeasuredWidth() <= 0) or set a limit to the number of times you check for a measuredWidth greater than zero.

There is also a chance that the view will never be drawn, which may indicate other problems with your code.

final View view = [ACQUIRE REFERENCE]; // Must be declared final for inner class
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        if (view.getMeasuredWidth() > 0) {     
            view.getViewTreeObserver().removeOnPreDrawListener(this);
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
            //Do something with width and height here!
        }
        return true; // Continue with the draw pass, as not to stop it
    }
});

How to write the Fibonacci Sequence?

Time complexity :

The caching feature reduces the normal way of calculating Fibonacci series from O(2^n) to O(n) by eliminating the repeats in the recursive tree of Fibonacci series :

enter image description here

Code :

import sys

table = [0]*1000

def FastFib(n):
    if n<=1:
        return n
    else:
        if(table[n-1]==0):
            table[n-1] = FastFib(n-1)
        if(table[n-2]==0):
            table[n-2] = FastFib(n-2)
        table[n] = table[n-1] + table[n-2]
        return table[n]

def main():
    print('Enter a number : ')
    num = int(sys.stdin.readline())
    print(FastFib(num))

if __name__=='__main__':
    main()

How to setup Tomcat server in Netbeans?

I had same issue. No need to re install.

In Netbeans 6.0 , Find RunTime -> Servers - > Add server -> select Tomcat install 'root' directory

In Netbeans 7.x -> Tools -> Servers-> Add server -> select Tomcat install 'root' directory

Here is in Netbeans Wiki.

http://wiki.netbeans.org/AddExternalTomcat

how to write procedure to insert data in to the table in phpmyadmin?

This method work for me:

DELIMITER $$
DROP PROCEDURE IF EXISTS db.test $$
CREATE PROCEDURE db.test(IN id INT(12),IN NAME VARCHAR(255))
 BEGIN
 INSERT INTO USER VALUES(id,NAME);
 END$$
DELIMITER ;

Maven plugin not using Eclipse's proxy settings

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">

     <proxies>
       <proxy>
          <active>true</active>
          <protocol>http</protocol>
          <host>proxy.somewhere.com</host>
          <port>8080</port>
          <username>proxyuser</username>
          <password>somepassword</password>
          <nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
        </proxy>
      </proxies>

    </settings>

Window > Preferences > Maven > User Settings

enter image description here

What is the difference between And and AndAlso in VB.NET?

To understand with words not cods:

Use Case:
With “And” the compiler will check all conditions so if you are checking that an object could be “Nothing” and then you are checking one of it’s properties you will have a run time error.
But with AndAlso with the first “false” in the conditions it will checking the next one so you will not have an error.

What does "if (rs.next())" mean?

I'm presuming you're using Java 6 and that the ResultSet that you're using is a java.sql.ResultSet.

The JavaDoc for the ResultSet.next() method states:

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.

So, if(rs.next(){ //do something } means "If the result set still has results, move to the next result and do something".

As BalusC pointed out, you need to replace

ResultSet rs = stmt.executeQuery(sql);

with

ResultSet rs = stmt.executeQuery();

Because you've already set the SQL to use in the statement with your previous line

PreparedStatement stmt = conn.prepareStatement(sql);

If you weren't using the PreparedStatement, then ResultSet rs = stmt.executeQuery(sql); would work.

How to add one day to a date?

I prefer joda for date and time arithmetics because it is much better readable:

Date tomorrow = now().plusDays(1).toDate();

Or

endOfDay(now().plus(days(1))).toDate()
startOfDay(now().plus(days(1))).toDate()

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

Now there is a problem, if you have package-lock.json with npm 5+. You have to remove it before use of npm install --production.

How to use SearchView in Toolbar Android

If you would like to setup the search facility inside your Fragment, just add these few lines:

Step 1 - Add the search field to you toolbar:

<item
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_search"
    app:showAsAction="always|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView"
    android:title="Search"/>

Step 2 - Add the logic to your onCreateOptionsMenu()

import android.support.v7.widget.SearchView; // not the default !

@Override
public boolean onCreateOptionsMenu( Menu menu) {
    getMenuInflater().inflate( R.menu.main, menu);

    MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
    searchView = (SearchView) myActionMenuItem.getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            // Toast like print
            UserFeedback.show( "SearchOnQueryTextSubmit: " + query);
            if( ! searchView.isIconified()) {
                searchView.setIconified(true);
            }
            myActionMenuItem.collapseActionView();
            return false;
        }
        @Override
        public boolean onQueryTextChange(String s) {
            // UserFeedback.show( "SearchOnQueryTextChanged: " + s);
            return false;
        }
    });
    return true;
}

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

Java 8 Stream API to find Unique Object matching a property value

findAny & orElse

By using findAny() and orElse():

Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);

Stops looking after finding an occurrence.

findAny

Optional<T> findAny()

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)

Mysql: Select all data between two dates

you must add 1 day to the end date, using: DATE_ADD('$end_date', INTERVAL 1 DAY)

Error: vector does not name a type

You forgot to add std:: namespace prefix to vector class name.

SQL Inner join more than two tables

Please find inner join for more than 2 table here

Here are 4 table name like

  1. Orders
  2. Customers
  3. Student
  4. Lecturer

So the SQL code would be:

select o.orderid, c.customername, l.lname, s.studadd, s.studmarks 
from orders o 
    inner join customers c on o.customrid = c.customerid 
    inner join lecturer l  on o.customrid = l.id 
    inner join student s   on o.customrid=s.studmarks;

Refresh a page using PHP

You can do it with PHP:

header("Refresh:0");

It refreshes your current page, and if you need to redirect it to another page, use following:

header("Refresh:0; url=page2.php");

What does 'URI has an authority component' mean?

I also faced similar problem while working on Affable Bean e-commerce site development. I received an error:

Module has not been deployed.

I checked the sun-resources.xml file and found the following statements which resulted in the error.

<resources>
    <jdbc-resource enabled="true"
                   jndi-name="jdbc/affablebean"
                   object-type="user"
                   pool-name="AffableBeanPool">
    </jdbc-resource>

    <jdbc-connection-pool allow-non-component-callers="false"
                          associate-with-thread="false"
                          connection-creation-retry-attempts="0"
                          connection-creation-retry-interval-in-seconds="10"
                          connection-leak-reclaim="false"
                          connection-leak-timeout-in-seconds="0"
                          connection-validation-method="auto-commit"
                          datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
                          fail-all-connections="false"
                          idle-timeout-in-seconds="300"
                          is-connection-validation-required="false"
                          is-isolation-level-guaranteed="true"
                          lazy-connection-association="false"
                          lazy-connection-enlistment="false"
                          match-connections="false"
                          max-connection-usage-count="0"
                          max-pool-size="32"
                          max-wait-time-in-millis="60000"
                          name="AffableBeanPool"
                          non-transactional-connections="false"
                          pool-resize-quantity="2"
                          res-type="javax.sql.ConnectionPoolDataSource"
                          statement-timeout-in-seconds="-1"
                          steady-pool-size="8"
                          validate-atmost-once-period-in-seconds="0"
                          wrap-jdbc-objects="false">

        <description>Connects to the affablebean database</description>
        <property name="URL" value="jdbc:mysql://localhost:3306/affablebean"/>
        <property name="User" value="root"/>
        <property name="Password" value="nbuser"/>
    </jdbc-connection-pool>
</resources>

Then I changed the statements to the following which is simple and works. I was able to run the file successfully.

<resources>
    <jdbc-resource enabled="true" jndi-name="jdbc/affablebean" object-type="user" pool-name="AffablebeanPool">
        <description/>
    </jdbc-resource>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="AffablebeanPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.ConnectionPoolDataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="URL" value="jdbc:mysql://localhost:3306/AffableBean"/>
        <property name="User" value="root"/>
        <property name="Password" value="nbuser"/>
    </jdbc-connection-pool>
</resources>

Joining Spark dataframes on the key

From https://spark.apache.org/docs/1.5.1/api/java/org/apache/spark/sql/DataFrame.html, use join:

Inner equi-join with another DataFrame using the given column.

PersonDf.join(ProfileDf,$"personId")

OR

PersonDf.join(ProfileDf,PersonDf("personId") === ProfileDf("personId"))

Update:

You can also save the DFs as temp table using df.registerTempTable("tableName") and you can write sql queries using sqlContext.

CSS3 Transform Skew One Side

You try with the :before was pretty close, the only thing you had to change was actually using skew instead of the borders: http://jsfiddle.net/Hfkk7/1101/

Edit: Your border approach would work too, the only thing you did wrong was having the before element on top of your div, so the transparent border wasnt showing. If you would have position the pseudo element to the left of your div, everything would have worked too: http://jsfiddle.net/Hfkk7/1102/

How to insert a SQLite record with a datetime set to 'now' in Android application?

To me, the problem looks like you're sending "datetime('now')" as a string, rather than a value.

My thought is to find a way to grab the current date/time and send it to your database as a date/time value, or find a way to use SQLite's built-in (DATETIME('NOW')) parameter

Check out the anwsers at this SO.com question - they might lead you in the right direction.

Hopefully this helps!

What is so bad about singletons?

Misko Hevery, from Google, has some interesting articles on exactly this topic...

Singletons are Pathological Liars has a unit testing example that illustrates how singletons can make it difficult to figure out dependency chains and start or test an application. It is a fairly extreme example of abuse, but the point that he makes is still valid:

Singletons are nothing more than global state. Global state makes it so your objects can secretly get hold of things which are not declared in their APIs, and, as a result, Singletons make your APIs into pathological liars.

Where have all the Singletons Gone makes the point that dependency injection has made it easy to get instances to constructors that require them, which alleviates the underlying need behind the bad, global Singletons decried in the first article.

Delete file from internal storage

File file = new File(getFilePath(imageUri.getValue())); 
boolean b = file.delete();

is not working in my case.

boolean b = file.delete();                 // returns false
boolean b = file.getAbsolutePath.delete(); // returns false 

always returns false.

The issue has been resolved by using the code below:

ContentResolver contentResolver = getContentResolver();
contentResolver.delete(uriDelete, null, null);

How to determine the installed webpack version

Just another way not mentioned yet:

If you installed it locally to a project then open up the node_modules folder and check your webpack module.

$cd /node_modules/webpack/package.json

Open the package.json file and look under version

enter image description here

Open button in new window?

I couldn't get your method to work @Damien-at-SF...

So I resorted to my old knowledge.

By encasing the input type="button" within a hyperlink element, you can simply declare the target property as so:

<a href="http://www.site.org" target="_blank">
<input type="button" class="button" value="Open" />
</a>

The 'target="_blank"' is the property which makes the browser open the link within a new tab. This attribute has other properties, See: http://www.w3schools.com/tags/att_a_target.asp for further details.

Since the 'value=""' attribute on buttons will write the contained string to the button, a span is not necessary.

Instead of writing:

<element></element>

for most HTML elements you can simply close them with a trailing slash, like so:

<element />

Oh, and finally... a 'button' element has a refresh trigger within it, so I use an 'input type[button]' to avoid triggering the form.

Good Luck Programmers.

Due to StackOverflow's policy I had to change the domain in the example: https://meta.stackexchange.com/questions/208963/why-are-certain-example-urls-like-http-site-com-and-http-mysite-com-blocke

Change the selected value of a drop-down list with jQuery

With hidden field you need to use like this:

$("._statusDDL").val(2);
$("._statusDDL").change();

or

$("._statusDDL").val(2).change();

Jquery how to find an Object by attribute in an Array

copied from polyfill Array.prototype.find code of Array.find, and added the array as first parameter.

you can pass the search term as predicate function

_x000D_
_x000D_
// Example_x000D_
var listOfObjects = [{key: "1", value: "one"}, {key: "2", value: "two"}]_x000D_
var result = findInArray(listOfObjects, function(element) {_x000D_
  return element.key == "1";_x000D_
});_x000D_
console.log(result);_x000D_
_x000D_
// the function you want_x000D_
function findInArray(listOfObjects, predicate) {_x000D_
      if (listOfObjects == null) {_x000D_
        throw new TypeError('listOfObjects is null or not defined');_x000D_
      }_x000D_
_x000D_
      var o = Object(listOfObjects);_x000D_
_x000D_
      var len = o.length >>> 0;_x000D_
_x000D_
      if (typeof predicate !== 'function') {_x000D_
        throw new TypeError('predicate must be a function');_x000D_
      }_x000D_
_x000D_
      var thisArg = arguments[1];_x000D_
_x000D_
      var k = 0;_x000D_
_x000D_
      while (k < len) {_x000D_
        var kValue = o[k];_x000D_
        if (predicate.call(thisArg, kValue, k, o)) {_x000D_
          return kValue;_x000D_
        }_x000D_
        k++;_x000D_
      }_x000D_
_x000D_
      return undefined;_x000D_
}
_x000D_
_x000D_
_x000D_

posting hidden value

You have to use $_POST['date'] instead of $date if it's coming from a POST request ($_GET if it's a GET request).

SQL to Entity Framework Count Group-By

Here is a simple example of group by in .net core 2.1

var query = this.DbContext.Notifications.
            Where(n=> n.Sent == false).
            GroupBy(n => new { n.AppUserId })
            .Select(g => new { AppUserId = g.Key, Count =  g.Count() });

var query2 = from n in this.DbContext.Notifications
            where n.Sent == false
            group n by n.AppUserId into g
            select new { id = g.Key,  Count = g.Count()};

Which translates to:

SELECT [n].[AppUserId], COUNT(*) AS [Count]
FROM [Notifications] AS [n]
WHERE [n].[Sent] = 0
GROUP BY [n].[AppUserId]

Git says local branch is behind remote branch, but it's not

You probably did some history rewriting? Your local branch diverged from the one on the server. Run this command to get a better understanding of what happened:

gitk HEAD @{u}

I would strongly recommend you try to understand where this error is coming from. To fix it, simply run:

git push -f

The -f makes this a “forced push” and overwrites the branch on the server. That is very dangerous when you are working in team. But since you are on your own and sure that your local state is correct this should be fine. You risk losing commit history if that is not the case.

How to disable XDebug

If you are using MAMP Pro on Mac OS X it's done via the MAMP client by unchecking Activate Xdebug under the PHP tab:

Disabling Xdebug in MAMP Pro

Any way to declare an array in-line?

Another way to do that, if you want the result as a List inline, you can do it like this:

Arrays.asList(new String[] { "String1", "string2" });

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

How can I check whether a variable is defined in Node.js?

if ( typeof query !== 'undefined' && query )
{
  //do stuff if query is defined and not null
}
else
{

}

Creating an instance of class

  1. Allocates some dynamic memory from the free store, and creates an object in that memory using its default constructor. You never delete it, so the memory is leaked.
  2. Does exactly the same as 1; in the case of user-defined types, the parentheses are optional.
  3. Allocates some automatic memory, and creates an object in that memory using its default constructor. The memory is released automatically when the object goes out of scope.
  4. Similar to 3. Notionally, the named object foo4 is initialised by default-constructing, copying and destroying a temporary object; usually, this is elided giving the same result as 3.
  5. Allocates a dynamic object, then initialises a second by copying the first. Both objects are leaked; and there's no way to delete the first since you don't keep a pointer to it.
  6. Does exactly the same as 5.
  7. Does not compile. Foo foo5 is a declaration, not an expression; function (and constructor) arguments must be expressions.
  8. Creates a temporary object, and initialises a dynamic object by copying it. Only the dynamic object is leaked; the temporary is destroyed automatically at the end of the full expression. Note that you can create the temporary with just Foo() rather than the equivalent Foo::Foo() (or indeed Foo::Foo::Foo::Foo::Foo())

When do I use each?

  1. Don't, unless you like unnecessary decorations on your code.
  2. When you want to create an object that outlives the current scope. Remember to delete it when you've finished with it, and learn how to use smart pointers to control the lifetime more conveniently.
  3. When you want an object that only exists in the current scope.
  4. Don't, unless you think 3 looks boring and what to add some unnecessary decoration.
  5. Don't, because it leaks memory with no chance of recovery.
  6. Don't, because it leaks memory with no chance of recovery.
  7. Don't, because it won't compile
  8. When you want to create a dynamic Bar from a temporary Foo.

How to get instance variables in Python?

You normally can't get instance attributes given just a class, at least not without instantiating the class. You can get instance attributes given an instance, though, or class attributes given a class. See the 'inspect' module. You can't get a list of instance attributes because instances really can have anything as attribute, and -- as in your example -- the normal way to create them is to just assign to them in the __init__ method.

An exception is if your class uses slots, which is a fixed list of attributes that the class allows instances to have. Slots are explained in http://www.python.org/2.2.3/descrintro.html, but there are various pitfalls with slots; they affect memory layout, so multiple inheritance may be problematic, and inheritance in general has to take slots into account, too.

Paste in insert mode?

No not directly. What you can do though is quickly exit insert mode for a single normal mode operation with Ctrl-O and then paste from there which will end by putting you back in insert mode.

Key Combo: Ctrl-O p

EDIT: Interesting. It does appear that there is a way as several other people have listed.

Check if URL has certain string with PHP

I think the easiest way is:

if (strpos($_SERVER['REQUEST_URI'], "car") !== false){
// car found
}

Color a table row with style="color:#fff" for displaying in an email

Try to use the <font> tag

?<table> 
    <thead> 
        <tr> 
            <th><font color="#FFF">Header 1</font></th> 
            <th><font color="#FFF">Header 1</font></th> 
            <th><font color="#FFF">Header 1</font></th> 
        </tr> 
    </thead> 
    <tbody> 
        <tr> 
            <td>blah blah</td> 
            <td>blah blah</td> 
            <td>blah blah</td> 
        </tr> 
    </tbody> 
</table>

But I think this should work, too:

?<table> 
    <thead> 
        <tr> 
            <th color="#FFF">Header 1</th> 
            <th color="#FFF">Header 1</th> 
            <th color="#FFF">Header 1</th> 
        </tr> 
    </thead> 
    <tbody> 
        <tr> 
            <td>blah blah</td> 
            <td>blah blah</td> 
            <td>blah blah</td> 
        </tr> 
    </tbody> 
</table>

EDIT:

Crossbrowser solution:

use capitals in HEX-color.

<th bgcolor="#5D7B9D" color="#FFFFFF"><font color="#FFFFFF">Header 1</font></th>

How do I shutdown, restart, or log off Windows via a bat file?

When remoted into a machine (target is Windows XP anyway; I am not sure about target Windows Vista), although Shutdown on the start menu is replaced by Disconnect Session or something like that, there should be one called 'Windows Security' which also does the same thing as Ctrl + Alt + End as pointed to by Owen.

Remove Safari/Chrome textinput/textarea glow

I found it helpful to remove the outline on a "sliding door" type of input button, because the outline doesn't cover the right "cap" of the sliding door image making the focus state look a little wonky.

input.slidingdoorbutton:focus { outline: none;}

How to run server written in js with Node.js

You don't need to go in node.js prompt, you just need to use standard command promt and write

node c:/node/server.js

this also works:

node c:\node\server.js

and then in your browser:

http://localhost:1337

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

Using number_format method in Laravel

Here's another way of doing it, add in app\Providers\AppServiceProvider.php

use Illuminate\Support\Str;

...

public function boot()
{
    // add Str::currency macro
    Str::macro('currency', function ($price)
    {
        return number_format($price, 2, '.', '\'');
    });
}

Then use Str::currency() in the blade templates or directly in the Expense model.

@foreach ($Expenses as $Expense)
    <tr>
        <td>{{{ $Expense->type }}}</td>
        <td>{{{ $Expense->narration }}}</td>
        <td>{{{ Str::currency($Expense->price) }}}</td>
        <td>{{{ $Expense->quantity }}}</td>
        <td>{{{ Str::currency($Expense->amount) }}}</td>                                                            
    </tr>
@endforeach

How can I pass an argument to a PowerShell script?

You can use also the $args variable (that's like position parameters):

$step = $args[0]

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + $step
}

Then it can be called like:

powershell.exe -file itunersforward.ps1 15

Closing JFrame with button click

You cat use setVisible () method of JFrame (and set visibility to false) or dispose () method which is more similar to close operation.

Face recognition Library

pam-face-authentication a PAM Module for Face Authentication: but it would require some work to get what you want. A quick test showed, that the recognition rate are not as good as those of VeriLook from NeuroTechnology.

Malic is another open source face recognition software, which uses Gabor Wavelet descriptors. But the last update to the source is 3 years old.

From the website: "Malic is an opensource face recognition software which uses gabor wavelet. It is realtime face recognition system that based on Malib and CSU Face Identification Evaluation System (csuFaceIdEval).Uses Malib library for realtime image processing and some of csuFaceIdEval for face recognition."

Further this could be of interest:

gaborboosting: A scientific program applied on Face Recognition with Gabor Wavelet and AdaBoost Algorithm

Feature Extraction Library - FELib refers to "Face Annotation by Transductive Kernel Fisher Discriminant,"

Jenkins pipeline how to change to another folder

You can use the dir step, example:

dir("folder") {
    sh "pwd"
}

The folder can be relative or absolute path.

<Django object > is not JSON serializable

I found that this can be done rather simple using the ".values" method, which also gives named fields:

result_list = list(my_queryset.values('first_named_field', 'second_named_field'))
return HttpResponse(json.dumps(result_list))

"list" must be used to get data as iterable, since the "value queryset" type is only a dict if picked up as an iterable.

Documentation: https://docs.djangoproject.com/en/1.7/ref/models/querysets/#values

How to force R to use a specified factor level as reference in a regression?

Others have mentioned the relevel command which is the best solution if you want to change the base level for all analyses on your data (or are willing to live with changing the data).

If you don't want to change the data (this is a one time change, but in the future you want the default behavior again), then you can use a combination of the C (note uppercase) function to set contrasts and the contr.treatments function with the base argument for choosing which level you want to be the baseline.

For example:

lm( Sepal.Width ~ C(Species,contr.treatment(3, base=2)), data=iris )

iPhone system font

Swift

You should always use the system defaults and not hard coding the font name because the default font could be changed by Apple at any time.

There are a couple of system default fonts(normal, bold, italic) with different sizes(label, button, others):

let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
let font2 = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)
let font3 = UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)

beaware that the default font size depends on the target view (label, button, others)

Examples:

let labelFont = UIFont.systemFont(ofSize: UIFont.labelFontSize)
let buttonFont = UIFont.systemFont(ofSize: UIFont.buttonFontSize)
let textFieldFont = UIFont.systemFont(ofSize: UIFont.systemFontSize)

Looping through GridView rows and Checking Checkbox Control

Loop like

foreach (GridViewRow row in grid.Rows)
{
   if (((CheckBox)row.FindControl("chkboxid")).Checked)
   {
    //read the label            
   }            
}

What key shortcuts are to comment and uncomment code?

Keyboard accelerators are configurable. You can find out which keyboard accelerators are bound to a command in Tools -> Options on the Environment -> Keyboard page.

These commands are named Edit.CommentSelection and Edit.UncommentSelection.

(With my settings, these are bound to Ctrl+K, Ctrl+C and Ctrl+K, Ctrl+U. I would guess that these are the defaults, at least in the C++ defaults, but I don't know for sure. The best way to find out is to check your settings.)

Converting NSString to NSDate (and back again)

As per Swift 2.2

You can get easily NSDate from String and String from NSDate. e.g.

First set date formatter

let formatter = NSDateFormatter();
formatter.dateStyle = NSDateFormatterStyle.MediumStyle
formatter.timeStyle = .NoStyle
formatter.dateFormat = "MM/dd/yyyy"

Now get date from string and vice versa.

let strDate = formatter.stringFromDate(NSDate())
print(strDate)
let dateFromStr = formatter.dateFromString(strDate)
print(dateFromStr)

Now enjoy.

Are there such things as variables within an Excel formula?

There isn't a way to define a variable in the formula bar of Excel. As a workaround you could place the function in another cell (optionally, hiding the contents or placing it in a separate sheet). Otherwise you could create a VBA function.

How to find the statistical mode?

Another possible solution:

Mode <- function(x) {
    if (is.numeric(x)) {
        x_table <- table(x)
        return(as.numeric(names(x_table)[which.max(x_table)]))
    }
}

Usage:

set.seed(100)
v <- sample(x = 1:100, size = 1000000, replace = TRUE)
system.time(Mode(v))

Output:

   user  system elapsed 
   0.32    0.00    0.31 

Get today date in google appScript

Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")

You can change the format by doing swapping the values.

  • dd = day(31)
  • MM = Month(12) - Case sensitive
  • yyyy = Year(2017)
function changeDate() {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
    // You could use now Date(); on its own but it will not look nice.
    var date = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
    var endDate = date
}

Better way to convert file sizes in Python

Here's a version that matches the output of ls -lh.

def human_size(num: int) -> str:
    base = 1
    for unit in ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']:
        n = num / base
        if n < 9.95 and unit != 'B':
            # Less than 10 then keep 1 decimal place
            value = "{:.1f}{}".format(n, unit)
            return value
        if round(n) < 1000:
            # Less than 4 digits so use this
            value = "{}{}".format(round(n), unit)
            return value
        base *= 1024
    value = "{}{}".format(round(n), unit)
    return value

Excel VBA: AutoFill Multiple Cells with Formulas

The approach you're looking for is FillDown. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:

Sub FillDown()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("Sheet1")
        strFormulas(1) = "=SUM(A2:B2)"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("C2:E2").Formula = strFormulas
        .Range("C2:E11").FillDown
    End With

End Sub

Screenshots:

Result as of line: .Range("C2:E2").Formula = strFormulas:

enter image description here

Result as of line: .Range("C2:E11").FillDown:

enter image description here

Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown, much like what you did.

Hope this helps!

How to upgrade glibc from version 2.13 to 2.15 on Debian?

Your script contains errors as well, for example if you have dos2unix installed your install works but if you don't like I did then it will fail with dependency issues.

I found this by accident as I was making a script file of this to give to my friend who is new to Linux and because I made the scripts on windows I directed him to install it, at the time I did not have dos2unix installed thus I got errors.

here is a copy of the script I made for your solution but have dos2unix installed.

#!/bin/sh
echo "deb http://ftp.debian.org/debian sid main" >> /etc/apt/sources.list
apt-get update
apt-get -t sid install libc6 libc6-dev libc6-dbg
echo "Please remember to hash out sid main from your sources list. /etc/apt/sources.list"

this script has been tested on 3 machines with no errors.

How to make script execution wait until jquery is loaded

A tangential note on the approaches here that load use setTimeout or setInterval. In those cases it's possible that when your check runs again, the DOM will already have loaded, and the browser's DOMContentLoaded event will have been fired, so you can't detect that event reliably using these approaches. What I found is that jQuery's ready still works, though, so you can embed your usual

jQuery(document).ready(function ($) { ... }

inside your setTimeout or setInterval and everything should work as normal.

MySQL Select Query - Get only first 10 characters of a value

Have a look at either Left or Substring if you need to chop it up even more.

Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.

Best cross-browser method to capture CTRL+S with JQuery?

You could use a shortcut library to handle the browser specific stuff.

shortcut.add("Ctrl+S",function() {
    alert("Hi there!");
});

Android studio: emulator is running but not showing up in Run App "choose a running device"

For anyone else having the issue - none of the answers provided worked for me.

My case may be different to others but I had Android Studio installed first which installs the SDK by default to: C:\Users\[user]\AppData\Local\Android\sdk. We then decided to use Xamarin for our projects, so Xamarin was installed and installed an additional SDK by default, located here: C:\Program Files (x86)\Android\android-sdk.

Changing Xamarin to match the same SDK path worked for me which I did in the registry (although through the VS settings I'd guess it's the same):

\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Android SDK Tools\Path

Change the path to match the Android Studio SDK path, close everything, start the VS Emulator, run Android Studio, ensure ADB integration is off and try. It worked for me.

How to parse this string in Java?

 String result;
 String str = "/usr/local/apache2/resumes/dir1/dir2/dir3/dir4";
 String regex ="(dir)+[\\d]";
 Matcher matcher = Pattern.compile( regex ).matcher( str);
  while (matcher.find( ))
  {
  result = matcher.group();     
  System.out.println(result);                 
}

output-- dir1 dir2 dir3 dir4

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

After validation and before INSERT check if username already exists, using mysqli(procedural). This works:

//check if username already exists
       include 'phpscript/connect.php'; //connect to your database

       $sql = "SELECT username FROM users WHERE username = '$username'";
       $result = $conn->query($sql);

       if($result->num_rows > 0) {
           $usernameErr =  "username already taken"; //takes'em back to form
       } else { // go on to INSERT new record

How can I set a css border on one side only?

If you want to set 4 sides separately use:

border-width: 1px 2em 5px 0; /* top right bottom left */
border-style: solid dotted inset double;
border-color: #f00 #0f0 #00f #ff0;

How to fix "'System.AggregateException' occurred in mscorlib.dll"

The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.

Task.Factory.StartNew(x=>
   throw new Exception("I didn't account for this");
)

However, if we do this, at least the application does not crash.

Task.Factory.StartNew(x=>
   try {
      throw new Exception("I didn't account for this");
   }
   catch(Exception ex) {
      //Log ex
   }
)

In excel how do I reference the current row but a specific column?

If you dont want to hard-code the cell addresses you can use the ROW() function.

eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))

Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.

Update some specific field of an entity in android Room

I think you don't need to update only some specific field. Just update whole data.

@Update query

It is a given query basically. No need to make some new query.

@Dao
interface MemoDao {

    @Insert
    suspend fun insert(memo: Memo)

    @Delete
    suspend fun delete(memo: Memo)

    @Update
    suspend fun update(memo: Memo)
}

Memo.class

@Entity
data class Memo (
    @PrimaryKey(autoGenerate = true) val id: Int,
    @ColumnInfo(name = "title") val title: String?,
    @ColumnInfo(name = "content") val content: String?,
    @ColumnInfo(name = "photo") val photo: List<ByteArray>?
)

Only thing you need to know is 'id'. For instance, if you want to update only 'title', you can reuse 'content' and 'photo' from already inserted data. In real code, use like this

val memo = Memo(id, title, content, byteArrayList)
memoViewModel.update(memo)

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

You can use this methode to check if a view has children or not .

public static boolean hasChildren(ViewGroup viewGroup) {
    return viewGroup.getChildCount() > 0;
 }

Select Rows with id having even number

Try this:

SELECT DISTINCT city FROM STATION WHERE ID%2=0 ORDER BY CITY;

Echo newline in Bash prints literal \n

POSIX 7 on echo

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html

-e is not defined and backslashes are implementation defined:

If the first operand is -n, or if any of the operands contain a <backslash> character, the results are implementation-defined.

unless you have an optional XSI extension.

So I recommend that you should use printf instead, which is well specified:

format operand shall be used as the format string described in XBD File Format Notation [...]

the File Format Notation:

\n <newline> Move the printing position to the start of the next line.

Also keep in mind that Ubuntu 15.10 and most distros implement echo both as:

  • a Bash built-in: help echo
  • a standalone executable: which echo

which can lead to some confusion.

AttributeError: can't set attribute in python

items[node.ind] = items[node.ind]._replace(v=node.v)

(Note: Don't be discouraged to use this solution because of the leading underscore in the function _replace. Specifically for namedtuple some functions have leading underscore which is not for indicating they are meant to be "private")

Shortcut to Apply a Formula to an Entire Column in Excel

Try double-clicking on the bottom right hand corner of the cell (ie on the box that you would otherwise drag).

How do you run a Python script as a service in Windows?

There are a couple alternatives for installing as a service virtually any Windows executable.

Method 1: Use instsrv and srvany from rktools.exe

For Windows Home Server or Windows Server 2003 (works with WinXP too), the Windows Server 2003 Resource Kit Tools comes with utilities that can be used in tandem for this, called instsrv.exe and srvany.exe. See this Microsoft KB article KB137890 for details on how to use these utils.

For Windows Home Server, there is a great user friendly wrapper for these utilities named aptly "Any Service Installer".

Method 2: Use ServiceInstaller for Windows NT

There is another alternative using ServiceInstaller for Windows NT (download-able here) with python instructions available. Contrary to the name, it works with both Windows 2000 and Windows XP as well. Here are some instructions for how to install a python script as a service.

Installing a Python script

Run ServiceInstaller to create a new service. (In this example, it is assumed that python is installed at c:\python25)

Service Name  : PythonTest
Display Name : PythonTest 
Startup : Manual (or whatever you like)
Dependencies : (Leave blank or fill to fit your needs)
Executable : c:\python25\python.exe
Arguments : c:\path_to_your_python_script\test.py
Working Directory : c:\path_to_your_python_script

After installing, open the Control Panel's Services applet, select and start the PythonTest service.

After my initial answer, I noticed there were closely related Q&A already posted on SO. See also:

Can I run a Python script as a service (in Windows)? How?

How do I make Windows aware of a service I have written in Python?

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

Same error i faced in eclipse version Oxygen.3a Release (4.7.3a) . There is issue in Maven Dependencies mismatch.To solve i have updated my Pom.xml with following dependecies.

http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.netapp.junitnmactiopractice JunitAndMactioPractice 0.0.1-SNAPSHOT

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <junit.jupiter.version>5.1.1</junit.jupiter.version>
    <junit.platform.version>1.1.1</junit.platform.version>
</properties>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${junit.jupiter.version}</version>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-runner</artifactId>
        <version>${junit.platform.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Clearing state es6 React

use deep copy, you can do it with lodash:

import _ from "lodash";

const INITIAL_STATE = {};

constructor(props) {
    super(props);
    this.state = _.cloneDeep(INITIAL_STATE);
}

reset() {
    this.setState(_.cloneDeep(INITIAL_STATE));
}

Adding a SVN repository in Eclipse

It is probably of little help to you, but I enter that URL into Subclipse and the repository adds fine and I can browse and Show History on it.

Do you perhaps need to configure a proxy? You have to configure that in the Subversion runtime configuration area as Subclipse uses the Subversion libraries to connect to the server.

Return char[]/string from a function

char* charP = createStr();

Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.

How to play a sound in C#, .NET

Additional Information.

This is a bit high-level answer for applications which want to seamlessly fit into the Windows environment. Technical details of playing particular sound were provided in other answers. Besides that, always note these two points:

  1. Use five standard system sounds in typical scenarios, i.e.

    • Asterisk - play when you want to highlight current event

    • Question - play with questions (system message box window plays this one)

    • Exclamation - play with excalamation icon (system message box window plays this one)

    • Beep (default system sound)

    • Critical stop ("Hand") - play with error (system message box window plays this one)
       

    Methods of class System.Media.SystemSounds will play them for you.
     

  2. Implement any other sounds as customizable by your users in Sound control panel

    • This way users can easily change or remove sounds from your application and you do not need to write any user interface for this – it is already there
    • Each user profile can override these sounds in own way
    • How-to:

Nginx -- static file serving confusion with root & alias

as say as @treecoder

In case of the root directive, full path is appended to the root including the location part, whereas in case of the alias directive, only the portion of the path NOT including the location part is appended to the alias.

A picture is worth a thousand words

for root:

enter image description here

for alias:

enter image description here

How to change the default charset of a MySQL table?

Change table's default charset:

ALTER TABLE etape_prospection
  CHARACTER SET utf8,
  COLLATE utf8_general_ci;

To change string column charset exceute this query:

ALTER TABLE etape_prospection
  CHANGE COLUMN etape_prosp_comment etape_prosp_comment TEXT CHARACTER SET utf8 COLLATE utf8_general_ci;

How to center an unordered list?

_x000D_
_x000D_
ul {_x000D_
  display: table;_x000D_
  margin: 0 auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <ul>_x000D_
    <li>56456456</li>_x000D_
    <li>4564564564564649999999999999999999999999999996</li>_x000D_
    <li>45645</li>_x000D_
  </ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

python: how to send mail with TO, CC and BCC?

It did not worked for me until i created:

#created cc string
cc = ""[email protected];
#added cc to header
msg['Cc'] = cc

and than added cc in recipient [list] like:

s.sendmail(me, [you,cc], msg.as_string())

Single vs double quotes in JSON

import json
data = json.dumps(list)
print(data)

The above code snippet should work.

What is the difference between varchar and nvarchar?

I have to say here (I realise that I'm probably going to open myself up to a slating!), but surely the only time when NVARCHAR is actually more useful (notice the more there!) than VARCHAR is when all of the collations on all of the dependant systems and within the database itself are the same...? If not then collation conversion has to happen anyway and so makes VARCHAR just as viable as NVARCHAR.

To add to this, some database systems, such as SQL Server (before 2012) have a page size of approx. 8K. So, if you're looking at storing searchable data not held in something like a TEXT or NTEXT field then VARCHAR provides the full 8k's worth of space whereas NVARCHAR only provides 4k (double the bytes, double the space).

I suppose, to summarise, the use of either is dependent on:

  • Project or context
  • Infrastructure
  • Database system

Month name as a string

For getting month in string variable use the code below

For example the month of September:

M -> 9

MM -> 09

MMM -> Sep

MMMM -> September

String monthname=(String)android.text.format.DateFormat.format("MMMM", new Date())

What is the difference between '/' and '//' when used for division?

As everyone has already answered, // is floor division.

Why this is important is that // is unambiguously floor division, in all Python versions from 2.2, including Python 3.x versions.

The behavior of / can change depending on:

  • Active __future__ import or not (module-local)
  • Python command line option, either -Q old or -Q new

Do not want scientific notation on plot axis

The R graphics package has the function axTicks that returns the tick locations of the ticks that the axis and plot functions would set automatically. The other answers given to this question define the tick locations manually which might not be convenient in some situations.

myTicks = axTicks(1)
axis(1, at = myTicks, labels = formatC(myTicks, format = 'd'))

A minimal example would be

plot(10^(0:10), 0:10, log = 'x', xaxt = 'n')
myTicks = axTicks(1)
axis(1, at = myTicks, labels = formatC(myTicks, format = 'd'))

There is also an log parameter in the axTicks function but in this situation it does not need to be set to get the proper logarithmic axis tick location.

write() versus writelines() and concatenated strings

Why am I unable to use a string for a newline in write() but I can use it in writelines()?

The idea is the following: if you want to write a single string you can do this with write(). If you have a sequence of strings you can write them all using writelines().

write(arg) expects a string as argument and writes it to the file. If you provide a list of strings, it will raise an exception (by the way, show errors to us!).

writelines(arg) expects an iterable as argument (an iterable object can be a tuple, a list, a string, or an iterator in the most general sense). Each item contained in the iterator is expected to be a string. A tuple of strings is what you provided, so things worked.

The nature of the string(s) does not matter to both of the functions, i.e. they just write to the file whatever you provide them. The interesting part is that writelines() does not add newline characters on its own, so the method name can actually be quite confusing. It actually behaves like an imaginary method called write_all_of_these_strings(sequence).

What follows is an idiomatic way in Python to write a list of strings to a file while keeping each string in its own line:

lines = ['line1', 'line2']
with open('filename.txt', 'w') as f:
    f.write('\n'.join(lines))

This takes care of closing the file for you. The construct '\n'.join(lines) concatenates (connects) the strings in the list lines and uses the character '\n' as glue. It is more efficient than using the + operator.

Starting from the same lines sequence, ending up with the same output, but using writelines():

lines = ['line1', 'line2']
with open('filename.txt', 'w') as f:
    f.writelines("%s\n" % l for l in lines)

This makes use of a generator expression and dynamically creates newline-terminated strings. writelines() iterates over this sequence of strings and writes every item.

Edit: Another point you should be aware of:

write() and readlines() existed before writelines() was introduced. writelines() was introduced later as a counterpart of readlines(), so that one could easily write the file content that was just read via readlines():

outfile.writelines(infile.readlines())

Really, this is the main reason why writelines has such a confusing name. Also, today, we do not really want to use this method anymore. readlines() reads the entire file to the memory of your machine before writelines() starts to write the data. First of all, this may waste time. Why not start writing parts of data while reading other parts? But, most importantly, this approach can be very memory consuming. In an extreme scenario, where the input file is larger than the memory of your machine, this approach won't even work. The solution to this problem is to use iterators only. A working example:

with open('inputfile') as infile:
    with open('outputfile') as outfile:
        for line in infile:
            outfile.write(line)

This reads the input file line by line. As soon as one line is read, this line is written to the output file. Schematically spoken, there always is only one single line in memory (compared to the entire file content being in memory in case of the readlines/writelines approach).

CSS - How to Style a Selected Radio Buttons Label?

_x000D_
_x000D_
.radio-toolbar input[type="radio"] {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.radio-toolbar label {_x000D_
  display: inline-block;_x000D_
  background-color: #ddd;_x000D_
  padding: 4px 11px;_x000D_
  font-family: Arial;_x000D_
  font-size: 16px;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.radio-toolbar input[type="radio"]:checked+label {_x000D_
  background-color: #bbb;_x000D_
}
_x000D_
<div class="radio-toolbar">_x000D_
  <input type="radio" id="radio1" name="radios" value="all" checked>_x000D_
  <label for="radio1">All</label>_x000D_
_x000D_
  <input type="radio" id="radio2" name="radios" value="false">_x000D_
  <label for="radio2">Open</label>_x000D_
_x000D_
  <input type="radio" id="radio3" name="radios" value="true">_x000D_
  <label for="radio3">Archived</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

First of all, you probably want to add the name attribute on the radio buttons. Otherwise, they are not part of the same group, and multiple radio buttons can be checked.

Also, since I placed the labels as siblings (of the radio buttons), I had to use the id and for attributes to associate them together.

Oracle insert if not exists statement

insert into OPT       (email,        campaign_id) 
select 'mom@coxnet' as email, 100 as campaign_id from dual MINUS
select                 email,        campaign_id from OPT;

If there is already a record with [email protected]/100 in OPT, the MINUS will subtract this record from the select 'mom@coxnet' as email, 100 as campaign_id from dual record and nothing will be inserted. On the other hand, if there is no such record, the MINUS does not subract anything and the values mom@coxnet/100 will be inserted.

As p.marino has already pointed out, merge is probably the better (and more correct) solution for your problem as it is specifically designed to solve your task.

Spring mvc @PathVariable

If you have url with path variables, example www.myexampl.com/item/12/update where 12 is the id and create is the variable you want to use for specifying your execution for instance in using a single form to do an update and create, you do this in your controller.

   @PostMapping(value = "/item/{id}/{method}")
    public String getForm(@PathVariable("id") String itemId ,  
        @PathVariable("method") String methodCall , Model model){

     if(methodCall.equals("create")){
            //logic
      }
     if(methodCall.equals("update")){
            //logic
      }

      return "path to your form";
    }

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

How to get process ID of background process?

  • $$ is the current script's pid
  • $! is the pid of the last background process

Here's a sample transcript from a bash session (%1 refers to the ordinal number of background process as seen from jobs):

$ echo $$
3748

$ sleep 100 &
[1] 192

$ echo $!
192

$ kill %1

[1]+  Terminated              sleep 100

CSS3 gradient background set on body doesn't stretch but instead repeats?

I have used this CSS code and it worked for me:

html {
  height: 100%;
}
body {
  background: #f6cb4a; /* Old browsers */
  background: -moz-linear-gradient(top, #f2b600 0%, #f6cb4a 100%); /* FF3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f2b600), color-stop(100%,#f6cb4a)); /* Chrome,Safari4+ */
  background: -webkit-linear-gradient(top, #f2b600 0%,#f6cb4a 100%); /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(top, #f2b600 0%,#f6cb4a 100%); /* Opera 11.10+ */
  background: -ms-linear-gradient(top, #f2b600 0%,#f6cb4a 100%); /* IE10+ */
  background: linear-gradient(top, #f2b600 0%,#f6cb4a 100%); /* W3C */
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f2b600', endColorstr='#f6cb4a',GradientType=0 ); /* IE6-9 */
  height: 100%;
  background-repeat: no-repeat;
  background-attachment: fixed;
  width: 100%;
  background-position: 0px 0px;
}

A related information is that you can create your own great gradients at http://www.colorzilla.com/gradient-editor/

/Sten

Check if Nullable Guid is empty in c#

Check Nullable<T>.HasValue

if(!SomeProperty.HasValue ||SomeProperty.Value == Guid.Empty)
{
 //not valid GUID
}
else
{
 //Valid GUID
}

Converting JSON data to Java object

The easiest way is that you can use this softconvertvalue method which is a custom method in which you can convert jsonData into your specific Dto class.

Dto response = softConvertValue(jsonData, Dto.class);


public static <T> T softConvertValue(Object fromValue, Class<T> toValueType) 
{
    ObjectMapper objMapper = new ObjectMapper();
    return objMapper
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .convertValue(fromValue, toValueType);
}

Apache and IIS side by side (both listening to port 80) on windows2003

I see this is quite an old post, but came across this looking for an answer for this problem. After reading some of the answers they seem very long winded, so after about 5 mins I managed to solve the problem very simply as follows:

httpd.conf for Apache leave the listen port as 80 and 'Server Name' as FQDN/IP :80.

Now for IIS go to Administrative Services > IIS Manager > 'Sites' in the Left hand nav drop down > in the right window select the top line (default web site) then bindings on the right.

Now select http > edit and change to 81 and enter your local IP for the server/pc and in domain enter either your FQDN (www.domain.com) or external IP close.

Restart both servers ensure your ports are open on both router and firewall, done.

This sounds long winded but literally took 5 mins of playing about. works perfectly.

System: Windows 8, IIS 8, Apache 2.2

Delete an element in a JSON object

Let's assume you want to overwrite the same file:

import json

with open('data.json', 'r') as data_file:
    data = json.load(data_file)

for element in data:
    element.pop('hours', None)

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

dict.pop(<key>, not_found=None) is probably what you where looking for, if I understood your requirements. Because it will remove the hours key if present and will not fail if not present.

However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?

Now, if you really want to use del instead of pop, here is how you could make your code work:

import json

with open('data.json') as data_file:
    data = json.load(data_file)

for element in data:
    if 'hours' in element:
        del element['hours']

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.

I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.

with is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.

Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.

I hope it's clear enough...

SECOND EDIT

This time, it seems clear that you need to do this:

with open('dest_file.json', 'w') as dest_file:
    with open('source_file.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            dest_file.write(json.dumps(element))

OnClick Send To Ajax

Tried and working. you are using,

<textarea name='Status'> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

I am using javascript , (don't know about php), use id ="status" in textarea like

<textarea name='Status' id="status"> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

then make a call to servlet sending the status to backend for updating using whatever strutucre(like MVC in java or anyother) you like, like this in your UI in script tag

<srcipt>
function UpdateStatus(){

//make an ajax call and get status value using the same 'id'
var var1= document.getElementById("status").value;
$.ajax({

        type:"GET",//or POST
        url:'http://localhost:7080/ajaxforjson/Testajax',
                           //  (or whatever your url is)
        data:{data1:var1},
        //can send multipledata like {data1:var1,data2:var2,data3:var3
        //can use dataType:'text/html' or 'json' if response type expected 
        success:function(responsedata){
               // process on data
               alert("got response as "+"'"+responsedata+"'");

        }
     })

}
</script>

and jsp is like

the servlet will look like:   //webservlet("/zcvdzv") is just for url annotation
@WebServlet("/Testajax")

public class Testajax extends HttpServlet {
private static final long serialVersionUID = 1L;
public Testajax() {
    super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String data1=request.getParameter("data1");
    //do processing on datas pass in other java class to add to DB
    // i am adding or concatenate
    String data="i Got : "+"'"+data1+"' ";
    System.out.println(" data1 : "+data1+"\n data "+data);
    response.getWriter().write(data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

Command to open file with git

You can create an alias to open a file in your default editor by appending the following line to your .gitconfig file:

edit = "!f() { $(git config core.editor) -- $@; }; f"

Then, git edit foo.txt will open the file foo.txt for editing.

It's much easier to open .gitconfig with git config --global --edit and paste the line, rather than figure out how to escape all the characters to enter the alias directly from the command line with git config alias.edit "..."

How it works

  • ! starts a bash command, not an internal git command
  • f() {...}; starts a function
  • $(git config core.editor) will get the name of your editor, from the local config, or the global if the local is not set. Unfortunately it will not look in $VISUAL or $EDITOR for this, if none is set.
  • -- separates the editor command with the file list. This works for most command line editors, so is safer to put in. If skipped and the core.editor is not set then it is possible that an executable file is executed instead of being edited. With it here, the command will just fail.
  • $@ will add the files entered at the command line.
  • f will execute the function after it is defined.

Use case

The other answers express doubt as to why you would want this. My use case is that I want to edit files as part of other git functions that I am building, and I want to edit them in the same editor that the user has configured. For example, the following is one of my aliases:

reedit = "!f() { $(git config core.editor) -- $(git diff --name-only $1); }; f"

Then, git reedit will open all the files that I have already started modifying, and git reedit --cached will open all the staged files.

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Suppose we have streaming in video tag and id is video - <video id="video"></video> then we should have following code -

var videoEl = document.getElementById('video');
// now get the steam 
stream = videoEl.srcObject;
// now get all tracks
tracks = stream.getTracks();
// now close each track by having forEach loop
tracks.forEach(function(track) {
   // stopping every track
   track.stop();
});
// assign null to srcObject of video
videoEl.srcObject = null;

TypeScript Objects as Dictionary types as in C#

Lodash has a simple Dictionary implementation and has good TypeScript support

Install Lodash:

npm install lodash @types/lodash --save

Import and usage:

import { Dictionary } from "lodash";
let properties : Dictionary<string> = {
    "key": "value"        
}
console.log(properties["key"])

NodeJs : TypeError: require(...) is not a function

For me, when I do Immediately invoked function, I need to put ; at the end of require().

Error:

const fs = require('fs')

(() => {
  console.log('wow')
})()

Good:

const fs = require('fs');

(() => {
  console.log('wow')
})()

Python pandas: fill a dataframe row by row

df['y'] will set a column

since you want to set a row, use .loc

Note that .ix is equivalent here, yours failed because you tried to assign a dictionary to each element of the row y probably not what you want; converting to a Series tells pandas that you want to align the input (for example you then don't have to to specify all of the elements)

In [7]: df = pandas.DataFrame(columns=['a','b','c','d'], index=['x','y','z'])

In [8]: df.loc['y'] = pandas.Series({'a':1, 'b':5, 'c':2, 'd':3})

In [9]: df
Out[9]: 
     a    b    c    d
x  NaN  NaN  NaN  NaN
y    1    5    2    3
z  NaN  NaN  NaN  NaN

Find integer index of rows with NaN in pandas dataframe

One line solution. However it works for one column only.

df.loc[pandas.isna(df["b"]), :].index

How to escape indicator characters (i.e. : or - ) in YAML

Another way that works with the YAML parser used in Jekyll:

title: My Life&#58; A Memoir

Colons not followed by spaces don't seem to bother Jekyll's YAML parser, on the other hand. Neither do dashes.

How do you convert Html to plain text?

public static string StripTags2(string html) { return html.Replace("<", "<").Replace(">", ">"); }

By this you escape all "<" and ">" in a string. Is this what you want?

How to change the background color of Action Bar's Option Menu in Android 4.2?

My simple trick to change background color and color of the text in Popup Menu / Option Menu

<style name="CustomActionBarTheme"
       parent="@android:style/Theme.Holo">
    <item name="android:popupMenuStyle">@style/MyPopupMenu</item>
    <item name="android:itemTextAppearance">@style/TextAppearance</item>
</style>
<!-- Popup Menu Background Color styles -->
<style name="MyPopupMenu" 
       parent="@android:style/Widget.Holo.ListPopupWindow">
    <item name="android:popupBackground">@color/Your_color_for_background</item> 
</style>
<!-- Popup Menu Text Color styles -->
<style name="TextAppearance">
    <item name="android:textColor">@color/Your_color_for_text</item>
</style>

Shuffle DataFrame rows

shuffle the pandas data frame by taking a sample array in this case index and randomize its order then set the array as an index of data frame. Now sort the data frame according to index. Here goes your shuffled dataframe

import random
df = pd.DataFrame({"a":[1,2,3,4],"b":[5,6,7,8]})
index = [i for i in range(df.shape[0])]
random.shuffle(index)
df.set_index([index]).sort_index()

output

    a   b
0   2   6
1   1   5
2   3   7
3   4   8

Insert you data frame in the place of mine in above code .

Exploring Docker container's file system

UPDATE: EXPLORING!

This command should let you explore a running docker container:

docker exec -it name-of-container bash

The equivalent for this in docker-compose would be:

docker-compose exec web bash

(web is the name-of-service in this case and it has tty by default.)

Once you are inside do:

ls -lsa

or any other bash command like:

cd ..

This command should let you explore a docker image:

docker run --rm -it --entrypoint=/bin/bash name-of-image

once inside do:

ls -lsa

or any other bash command like:

cd ..

The -it stands for interactive... and tty.


This command should let you inspect a running docker container or image:

docker inspect name-of-container-or-image

You might want to do this and find out if there is any bash or sh in there. Look for entrypoint or cmd in the json return.

NOTE: This answer relies on commen tool being present, but if there is no bash shell or common tools like ls present you could first add one in a layer if you have access to the Dockerfile: example for alpine:

RUN apk add --no-cache bash

Otherwise if you don't have access to the Dockerfile then just copy the files out of a newly created container and look trough them by doing:

docker create <image>  # returns container ID the container is never started.
docker cp <container ID>:<source_path> <destination_path>
docker rm <container ID>
cd <destination_path> && ls -lsah

see docker exec documentation

see docker-compose exec documentation

see docker inspect documentation

see docker create documentation

Why do we need middleware for async flow in Redux?

You don't.

But... you should use redux-saga :)

Dan Abramov's answer is right about redux-thunk but I will talk a bit more about redux-saga that is quite similar but more powerful.

Imperative VS declarative

  • DOM: jQuery is imperative / React is declarative
  • Monads: IO is imperative / Free is declarative
  • Redux effects: redux-thunk is imperative / redux-saga is declarative

When you have a thunk in your hands, like an IO monad or a promise, you can't easily know what it will do once you execute. The only way to test a thunk is to execute it, and mock the dispatcher (or the whole outside world if it interacts with more stuff...).

If you are using mocks, then you are not doing functional programming.

Seen through the lens of side-effects, mocks are a flag that your code is impure, and in the functional programmer's eye, proof that something is wrong. Instead of downloading a library to help us check the iceberg is intact, we should be sailing around it. A hardcore TDD/Java guy once asked me how you do mocking in Clojure. The answer is, we usually don't. We usually see it as a sign we need to refactor our code.

Source

The sagas (as they got implemented in redux-saga) are declarative and like the Free monad or React components, they are much easier to test without any mock.

See also this article:

in modern FP, we shouldn’t write programs — we should write descriptions of programs, which we can then introspect, transform, and interpret at will.

(Actually, Redux-saga is like a hybrid: the flow is imperative but the effects are declarative)

Confusion: actions/events/commands...

There is a lot of confusion in the frontend world on how some backend concepts like CQRS / EventSourcing and Flux / Redux may be related, mostly because in Flux we use the term "action" which can sometimes represent both imperative code (LOAD_USER) and events (USER_LOADED). I believe that like event-sourcing, you should only dispatch events.

Using sagas in practice

Imagine an app with a link to a user profile. The idiomatic way to handle this with each middleware would be:

redux-thunk

<div onClick={e => dispatch(actions.loadUserProfile(123)}>Robert</div>

function loadUserProfile(userId) {
  return dispatch => fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'USER_PROFILE_LOADED', data }),
      err => dispatch({ type: 'USER_PROFILE_LOAD_FAILED', err })
    );
}

redux-saga

<div onClick={e => dispatch({ type: 'USER_NAME_CLICKED', payload: 123 })}>Robert</div>


function* loadUserProfileOnNameClick() {
  yield* takeLatest("USER_NAME_CLICKED", fetchUser);
}

function* fetchUser(action) {
  try {
    const userProfile = yield fetch(`http://data.com/${action.payload.userId }`)
    yield put({ type: 'USER_PROFILE_LOADED', userProfile })
  } 
  catch(err) {
    yield put({ type: 'USER_PROFILE_LOAD_FAILED', err })
  }
}

This saga translates to:

every time a username gets clicked, fetch the user profile and then dispatch an event with the loaded profile.

As you can see, there are some advantages of redux-saga.

The usage of takeLatest permits to express that you are only interested to get the data of the last username clicked (handle concurrency problems in case the user click very fast on a lot of usernames). This kind of stuff is hard with thunks. You could have used takeEvery if you don't want this behavior.

You keep action creators pure. Note it's still useful to keep actionCreators (in sagas put and components dispatch), as it might help you to add action validation (assertions/flow/typescript) in the future.

Your code becomes much more testable as the effects are declarative

You don't need anymore to trigger rpc-like calls like actions.loadUser(). Your UI just needs to dispatch what HAS HAPPENED. We only fire events (always in the past tense!) and not actions anymore. This means that you can create decoupled "ducks" or Bounded Contexts and that the saga can act as the coupling point between these modular components.

This means that your views are more easy to manage because they don't need anymore to contain that translation layer between what has happened and what should happen as an effect

For example imagine an infinite scroll view. CONTAINER_SCROLLED can lead to NEXT_PAGE_LOADED, but is it really the responsibility of the scrollable container to decide whether or not we should load another page? Then he has to be aware of more complicated stuff like whether or not the last page was loaded successfully or if there is already a page that tries to load, or if there is no more items left to load? I don't think so: for maximum reusability the scrollable container should just describe that it has been scrolled. The loading of a page is a "business effect" of that scroll

Some might argue that generators can inherently hide state outside of redux store with local variables, but if you start to orchestrate complex things inside thunks by starting timers etc you would have the same problem anyway. And there's a select effect that now permits to get some state from your Redux store.

Sagas can be time-traveled and also enables complex flow logging and dev-tools that are currently being worked on. Here is some simple async flow logging that is already implemented:

saga flow logging

Decoupling

Sagas are not only replacing redux thunks. They come from backend / distributed systems / event-sourcing.

It is a very common misconception that sagas are just here to replace your redux thunks with better testability. Actually this is just an implementation detail of redux-saga. Using declarative effects is better than thunks for testability, but the saga pattern can be implemented on top of imperative or declarative code.

In the first place, the saga is a piece of software that permits to coordinate long running transactions (eventual consistency), and transactions across different bounded contexts (domain driven design jargon).

To simplify this for frontend world, imagine there is widget1 and widget2. When some button on widget1 is clicked, then it should have an effect on widget2. Instead of coupling the 2 widgets together (ie widget1 dispatch an action that targets widget2), widget1 only dispatch that its button was clicked. Then the saga listen for this button click and then update widget2 by dispaching a new event that widget2 is aware of.

This adds a level of indirection that is unnecessary for simple apps, but make it more easy to scale complex applications. You can now publish widget1 and widget2 to different npm repositories so that they never have to know about each others, without having them to share a global registry of actions. The 2 widgets are now bounded contexts that can live separately. They do not need each others to be consistent and can be reused in other apps as well. The saga is the coupling point between the two widgets that coordinate them in a meaningful way for your business.

Some nice articles on how to structure your Redux app, on which you can use Redux-saga for decoupling reasons:

A concrete usecase: notification system

I want my components to be able to trigger the display of in-app notifications. But I don't want my components to be highly coupled to the notification system that has its own business rules (max 3 notifications displayed at the same time, notification queueing, 4 seconds display-time etc...).

I don't want my JSX components to decide when a notification will show/hide. I just give it the ability to request a notification, and leave the complex rules inside the saga. This kind of stuff is quite hard to implement with thunks or promises.

notifications

I've described here how this can be done with saga

Why is it called a Saga?

The term saga comes from the backend world. I initially introduced Yassine (the author of Redux-saga) to that term in a long discussion.

Initially, that term was introduced with a paper, the saga pattern was supposed to be used to handle eventual consistency in distributed transactions, but its usage has been extended to a broader definition by backend developers so that it now also covers the "process manager" pattern (somehow the original saga pattern is a specialized form of process manager).

Today, the term "saga" is confusing as it can describe 2 different things. As it is used in redux-saga, it does not describe a way to handle distributed transactions but rather a way to coordinate actions in your app. redux-saga could also have been called redux-process-manager.

See also:

Alternatives

If you don't like the idea of using generators but you are interested by the saga pattern and its decoupling properties, you can also achieve the same with redux-observable which uses the name epic to describe the exact same pattern, but with RxJS. If you're already familiar with Rx, you'll feel right at home.

const loadUserProfileOnNameClickEpic = action$ =>
  action$.ofType('USER_NAME_CLICKED')
    .switchMap(action =>
      Observable.ajax(`http://data.com/${action.payload.userId}`)
        .map(userProfile => ({
          type: 'USER_PROFILE_LOADED',
          userProfile
        }))
        .catch(err => Observable.of({
          type: 'USER_PROFILE_LOAD_FAILED',
          err
        }))
    );

Some redux-saga useful resources

2017 advises

  • Don't overuse Redux-saga just for the sake of using it. Testable API calls only are not worth it.
  • Don't remove thunks from your project for most simple cases.
  • Don't hesitate to dispatch thunks in yield put(someActionThunk) if it makes sense.

If you are frightened of using Redux-saga (or Redux-observable) but just need the decoupling pattern, check redux-dispatch-subscribe: it permits to listen to dispatches and trigger new dispatches in listener.

const unsubscribe = store.addDispatchListener(action => {
  if (action.type === 'ping') {
    store.dispatch({ type: 'pong' });
  }
});

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

Dictionary returning a default value if the key does not exist

I know this is an old post and I do favor extension methods, but here's a simple class I use from time to time to handle dictionaries when I need default values.

I wish this were just part of the base Dictionary class.

public class DictionaryWithDefault<TKey, TValue> : Dictionary<TKey, TValue>
{
  TValue _default;
  public TValue DefaultValue {
    get { return _default; }
    set { _default = value; }
  }
  public DictionaryWithDefault() : base() { }
  public DictionaryWithDefault(TValue defaultValue) : base() {
    _default = defaultValue;
  }
  public new TValue this[TKey key]
  {
    get { 
      TValue t;
      return base.TryGetValue(key, out t) ? t : _default;
    }
    set { base[key] = value; }
  }
}

Beware, however. By subclassing and using new (since override is not available on the native Dictionary type), if a DictionaryWithDefault object is upcast to a plain Dictionary, calling the indexer will use the base Dictionary implementation (throwing an exception if missing) rather than the subclass's implementation.

Why can't I inherit static classes?

My answer: poor design choice. ;-)

This is an interesting debate focused on syntax impact. The core of the argument, in my view, is that a design decision led to sealed static classes. A focus on transparency of the static class's names appearing at the top level instead of hiding ('confusing') behind child names? One can image a language implementation that could access the base or the child directly, confusing.

A pseudo example, assuming static inheritance was defined in some way.

public static class MyStaticBase
{
    SomeType AttributeBase;
}

public static class MyStaticChild : MyStaticBase
{
    SomeType AttributeChild;
}

would lead to:

 // ...
 DoSomethingTo(MyStaticBase.AttributeBase);
// ...

which could (would?) impact the same storage as

// ...
DoSomethingTo(MyStaticChild.AttributeBase);
// ...

Very confusing!

But wait! How would the compiler deal with MyStaticBase and MyStaticChild having the same signature defined in both? If the child overrides than my above example would NOT change the same storage, maybe? This leads to even more confusion.

I believe there is a strong informational space justification for limited static inheritance. More on the limits shortly. This pseudocode shows the value:

public static class MyStaticBase<T>
{
   public static T Payload;
   public static void Load(StorageSpecs);
   public static void Save(StorageSpecs);
   public static SomeType AttributeBase
   public static SomeType MethodBase(){/*...*/};
}

Then you get:

public static class MyStaticChild : MyStaticBase<MyChildPlayloadType>
{
   public static SomeType AttributeChild;
   public static SomeType SomeChildMethod(){/*...*/};
   // No need to create the PlayLoad, Load(), and Save().
   // You, 'should' be prevented from creating them, more on this in a sec...
} 

Usage looks like:

// ...
MyStaticChild.Load(FileNamePath);
MyStaticChild.Save(FileNamePath);
doSomeThing(MyStaticChild.Payload.Attribute);
doSomething(MyStaticChild.AttributeBase);
doSomeThing(MyStaticChild.AttributeChild);
// ...

The person creating the static child does not need to think about the serialization process as long as they understand any limitations that might be placed on the platform's or environment's serialization engine.

Statics (singletons and other forms of 'globals') often come up around configuration storage. Static inheritance would allow this sort of responsibility allocation to be cleanly represented in the syntax to match a hierarchy of configurations. Though, as I showed, there is plenty of potential for massive ambiguity if basic static inheritance concepts are implemented.

I believe the right design choice would be to allow static inheritance with specific limitations:

  1. No override of anything. The child cannot replace the base attributes, fields, or methods,... Overloading should be ok, as long as there is a difference in signature allowing the compiler to sort out child vs base.
  2. Only allow generic static bases, you cannot inherit from a non-generic static base.

You could still change the same store via a generic reference MyStaticBase<ChildPayload>.SomeBaseField. But you would be discouraged since the generic type would have to be specified. While the child reference would be cleaner: MyStaticChild.SomeBaseField.

I am not a compiler writer so I am not sure if I am missing something about the difficulties of implementing these limitations in a compiler. That said, I am a strong believer that there is an informational space need for limited static inheritance and the basic answer is that you can't because of a poor (or over simple) design choice.

C++ program converts fahrenheit to celsius

Mine worked perfectly!

/* Two common temperature scales are Fahrenheit and Celsius.
** The boiling point of water is 212° F, and 100° C.
** The freezing point of water is 32° F, and 0° C.
** Assuming that the relationship bewtween these two
** temperature scales is: F = 9/5C+32,
** Celsius = (f-32) * 5/9.
***********************/

#include <iostream> // cin, cout

using namespace std; // System definition of cin and cout commands,
                     // if not, programmer would have to write every
                     // single line as: std::cout or std::cin

int main () // Main function

{

    /* Declare variables */
    double c, f;

    cout << "\nProgram that changes temperature from Celsius to Fahrenheit.\n";
    cout << "Please enter a temperature in Celsius: ";

    cin >> c;
    f = c * 9 / 5 + 32;
    cout << "\nA temperature of " << c << "° Celsius, is equivalent to "
         << f << "° Fahrenheit.\n";
    return 0;

}

How do I copy a hash in Ruby?

Clone is slow. For performance should probably start with blank hash and merge. Doesn't cover case of nested hashes...

require 'benchmark'

def bench  Benchmark.bm do |b|    
    test = {'a' => 1, 'b' => 2, 'c' => 3, 4 => 'd'}
    b.report 'clone' do
      1_000_000.times do |i|
        h = test.clone
        h['new'] = 5
      end
    end
    b.report 'merge' do
      1_000_000.times do |i|
        h = {}
        h['new'] = 5
        h.merge! test
      end
    end
    b.report 'inject' do
      1_000_000.times do |i|
        h = test.inject({}) do |n, (k, v)|
          n[k] = v;
          n
        end
        h['new'] = 5
      end
    end
  end
end

  bench  user      system      total        ( real)
  clone  1.960000   0.080000    2.040000    (  2.029604)
  merge  1.690000   0.080000    1.770000    (  1.767828)
  inject 3.120000   0.030000    3.150000    (  3.152627)
  

Copy Notepad++ text with formatting?

Select the text.

Right Click.

Plugin Commands -> Copy Text with Syntax Highlighting

Paste it into Word or whatever.

adding onclick event to dynamically added button?

I was having a similar issue but none of these fixes worked. The problem was that my button was not yet on the page. The fix for this ended up being going from this:

//Bad code.
var btn = document.createElement('button');
btn.onClick = function() {  console.log("hey");  }

to this:

//Working Code.  I don't like it, but it works. 
var btn = document.createElement('button');
var wrapper = document.createElement('div');
wrapper.appendChild(btn);

document.body.appendChild(wrapper);
var buttons = wrapper.getElementsByTagName("BUTTON");
buttons[0].onclick = function(){  console.log("hey");  }

I have no clue at all why this works. Adding the button to the page and referring to it any other way did not work.

What is the height of iPhone's onscreen keyboard?

I can't find latest answer, so I check it all with simulator.(iOS 11.0)


Device | Screen Height | Portrait | Landscape

iPhone 4s | 480.0 | 216.0 | 162.0

iPhone 5, iPhone 5s, iPhone SE | 568.0 | 216.0 | 162.0

iPhone 6, iPhone 6s, iPhone 7, iPhone 8, iPhone X | 667.0 | 216.0 | 162.0

iPhone 6 plus, iPhone 7 plus, iPhone 8 plus | 736.0 | 226.0 | 162.0

iPad 5th generation, iPad Air, iPad Air 2, iPad Pro 9.7, iPad Pro 10.5, iPad Pro 12.9 | 1024.0 | 265.0 | 353.0


Thanks!

Ring Buffer in Java

A very interesting project is disruptor. It has a ringbuffer and is used from what I know in financial applications.

See here: code of ringbuffer

I checked both Guava's EvictingQueue and ArrayDeque.

ArrayDeque does not limit growth if it's full it will double size and hence is not precisely acting like a ringbuffer.

EvictingQueue does what it promises but internally uses a Deque to store things and just bounds memory.

Hence, if you care about memory being bounded ArrayDeque is not fullfilling your promise. If you care about object count EvictingQueue uses internal composition (bigger object size).

A simple and memory efficient one can be stolen from jmonkeyengine. verbatim copy

import java.util.Iterator;
import java.util.NoSuchElementException;

public class RingBuffer<T> implements Iterable<T> {

  private T[] buffer;          // queue elements
  private int count = 0;          // number of elements on queue
  private int indexOut = 0;       // index of first element of queue
  private int indexIn = 0;       // index of next available slot

  // cast needed since no generic array creation in Java
  public RingBuffer(int capacity) {
    buffer = (T[]) new Object[capacity];
  }

  public boolean isEmpty() {
    return count == 0;
  }

  public int size() {
    return count;
  }

  public void push(T item) {
    if (count == buffer.length) {
        throw new RuntimeException("Ring buffer overflow");
    }
    buffer[indexIn] = item;
    indexIn = (indexIn + 1) % buffer.length;     // wrap-around
    count++;
  }

  public T pop() {
    if (isEmpty()) {
        throw new RuntimeException("Ring buffer underflow");
    }
    T item = buffer[indexOut];
    buffer[indexOut] = null;                  // to help with garbage collection
    count--;
    indexOut = (indexOut + 1) % buffer.length; // wrap-around
    return item;
  }

  public Iterator<T> iterator() {
    return new RingBufferIterator();
  }

  // an iterator, doesn't implement remove() since it's optional
  private class RingBufferIterator implements Iterator<T> {

    private int i = 0;

    public boolean hasNext() {
        return i < count;
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }

    public T next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        return buffer[i++];
    }
  }
}

Convert a String to int?

Well, no. Why there should be? Just discard the string if you don't need it anymore.

&str is more useful than String when you need to only read a string, because it is only a view into the original piece of data, not its owner. You can pass it around more easily than String, and it is copyable, so it is not consumed by the invoked methods. In this regard it is more general: if you have a String, you can pass it to where an &str is expected, but if you have &str, you can only pass it to functions expecting String if you make a new allocation.

You can find more on the differences between these two and when to use them in the official strings guide.

Launching an application (.EXE) from C#?

If you have problems using System.Diagnostics like I had, use the following simple code that will work without it:

using System.Diagnostics;

Process notePad = new Process();
notePad.StartInfo.FileName   = "notepad.exe";
notePad.StartInfo.Arguments = "mytextfile.txt";
notePad.Start();

How do I find the location of my Python site-packages directory?

The native system packages installed with python installation in Debian based systems can be found at :

/usr/lib/python2.7/dist-packages/

In OSX - /Library/Python/2.7/site-packages

by using this small code :

from distutils.sysconfig import get_python_lib
print get_python_lib()

However, the list of packages installed via pip can be found at :

/usr/local/bin/

Or one can simply write the following command to list all paths where python packages are.

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

Note: the location might vary based on your OS, like in OSX

>>> import site; site.getsitepackages()
['/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/site-python', '/Library/Python/2.7/site-packages']

Global variables in c#.net

/// <summary>
/// Contains global variables for project.
/// </summary>
public static class GlobalVar
{
/// <summary>
/// Global variable that is constant.
/// </summary>
public const string GlobalString = "Important Text";

/// <summary>
/// Static value protected by access routine.
/// </summary>
static int _globalValue;

/// <summary>
/// Access routine for global variable.
/// </summary>
public static int GlobalValue
{
get
{
    return _globalValue;
}
set
{
    _globalValue = value;
}
}

/// <summary>
/// Global static field.
/// </summary>
public static bool GlobalBoolean;
}

Unsigned keyword in C++

Does the unsigned keyword default to a data type in C++

Yes,signed and unsigned may also be used as standalone type specifiers

The integer data types char, short, long and int can be either signed or unsigned depending on the range of numbers needed to be represented. Signed types can represent both positive and negative values, whereas unsigned types can only represent positive values (and zero).

An unsigned integer containing n bits can have a value between 0 and 2n - 1 (which is 2n different values).

However,signed and unsigned may also be used as standalone type specifiers, meaning the same as signed int and unsigned int respectively. The following two declarations are equivalent:

unsigned NextYear;
unsigned int NextYear;

How to split a string to 2 strings in C

This is how you implement a strtok() like function (taken from a BSD licensed string processing library for C, called zString).

Below function differs from the standard strtok() in the way it recognizes consecutive delimiters, whereas the standard strtok() does not.

char *zstring_strtok(char *str, const char *delim) {
    static char *static_str=0;      /* var to store last address */
    int index=0, strlength=0;       /* integers for indexes */
    int found = 0;                  /* check if delim is found */

    /* delimiter cannot be NULL
    * if no more char left, return NULL as well
    */
    if (delim==0 || (str == 0 && static_str == 0))
        return 0;

    if (str == 0)
        str = static_str;

    /* get length of string */
    while(str[strlength])
        strlength++;

    /* find the first occurance of delim */
    for (index=0;index<strlength;index++)
        if (str[index]==delim[0]) {
            found=1;
            break;
        }

    /* if delim is not contained in str, return str */
    if (!found) {
        static_str = 0;
        return str;
    }

    /* check for consecutive delimiters
    *if first char is delim, return delim
    */
    if (str[0]==delim[0]) {
        static_str = (str + 1);
        return (char *)delim;
    }

    /* terminate the string
    * this assignmetn requires char[], so str has to
    * be char[] rather than *char
    */
    str[index] = '\0';

    /* save the rest of the string */
    if ((str + index + 1)!=0)
        static_str = (str + index + 1);
    else
        static_str = 0;

        return str;
}

Below is an example code that demonstrates the usage

  Example Usage
      char str[] = "A,B,,,C";
      printf("1 %s\n",zstring_strtok(s,","));
      printf("2 %s\n",zstring_strtok(NULL,","));
      printf("3 %s\n",zstring_strtok(NULL,","));
      printf("4 %s\n",zstring_strtok(NULL,","));
      printf("5 %s\n",zstring_strtok(NULL,","));
      printf("6 %s\n",zstring_strtok(NULL,","));

  Example Output
      1 A
      2 B
      3 ,
      4 ,
      5 C
      6 (null)

You can even use a while loop (standard library's strtok() would give the same result here)

char s[]="some text here;
do {
    printf("%s\n",zstring_strtok(s," "));
} while(zstring_strtok(NULL," "));

PyCharm error: 'No Module' when trying to import own module (python script)

Pycharm 2017.1.1

  1. Click on View->ToolBar & View->Tool Buttons
  2. On the left pane Project would be visible, right click on it and press Autoscroll to source and then run your code.

This worked for me.

Python error when trying to access list by index - "List indices must be integers, not str"

players is a list which needs to be indexed by integers. You seem to be using it like a dictionary. Maybe you could use unpacking -- Something like:

name, score = player

(if the player list is always a constant length).

There's not much more advice we can give you without knowing what query is and how it works.

It's worth pointing out that the entire code you posted doesn't make a whole lot of sense. There's an IndentationError on the second line. Also, your function is looping over some iterable, but unconditionally returning during the first iteration which isn't usually what you actually want to do.

Remove '\' char from string c#

Why not simply this?

resultString = Regex.Replace(subjectString, @"\\", "");

Call Activity method from adapter

Original:

I understand the current answer but needed a more clear example. Here is an example of what I used with an Adapter(RecyclerView.Adapter) and an Activity.

In your Activity:

This will implement the interface that we have in our Adapter. In this example, it will be called when the user clicks on an item in the RecyclerView.

public class MyActivity extends Activity implements AdapterCallback {

    private MyAdapter myAdapter;

    @Override
    public void onMethodCallback() {
       // do something
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myAdapter = new MyAdapter(this);
    }
}

In your Adapter:

In the Activity, we initiated our Adapter and passed this as an argument to the constructer. This will initiate our interface for our callback method. You can see that we use our callback method for user clicks.

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private AdapterCallback adapterCallback;

    public MyAdapter(Context context) {
        try {
            adapterCallback = ((AdapterCallback) context);
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement AdapterCallback.", e);
        }
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int position) {
        // simple example, call interface here
        // not complete
        viewHolder.itemView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    adapterCallback.onMethodCallback();
                } catch (ClassCastException e) {
                   // do something
                }
            }
        });
    }

    public static interface AdapterCallback {
        void onMethodCallback();
    }
}

@JsonProperty annotation on field as well as getter/setter

My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:

For eg. consider a slight modification of your case:

@JsonProperty("fileName")
private String fileName;

@JsonProperty("fileName")
public String getFileName()
{
    return fileName;
}

@JsonProperty("fileName1")
public void setFileName(String fileName)
{
    this.fileName = fileName;
}

Both fileName field, and method getFileName, have the correct property name of fileName and setFileName has a different one fileName1, in this case Jackson will look for a fileName1 attribute in json at the point of deserialization and will create a attribute called fileName1 at the point of serialization.

Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName, it would just pick one of them as the attribute(FILENAME), and had any on of the three differed, it would have thrown an exception:

java.lang.IllegalStateException: Conflicting property name definitions

Executing a batch script on Windows shutdown

For the above code to function; you need to make sure the following directories exist (mine didn't). Just add the following to a bat and run it:

mkdir C:\Windows\System32\GroupPolicy\Machine\Scripts\Startup
mkdir C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown
mkdir C:\Windows\System32\GroupPolicy\User\Scripts\Startup
mkdir C:\Windows\System32\GroupPolicy\User\Scripts\Shutdown

It's just that GP needs those directories to exist for:

Group Policy\Local Computer Policy\Windows Settings\Scripts (Startup/Shutdown)

to function properly.

How to resolve git status "Unmerged paths:"?

All you should need to do is:

# if the file in the right place isn't already committed:
git add <path to desired file>

# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai

# commit the merge:
git commit

Switch case in C# - a constant value is expected

You can't use a switch statement for this as the case values cannot be evaluated expressions. For this you have to use an an if/else ...

public static void Output<T>(IEnumerable<T> dataSource) where T : class
{   
    dataSourceName = (typeof(T).Name);
    if(string.Compare(dataSourceName, typeof(CustomerDetails).Name.ToString(), true)==0)
    {
        var t = 123;
    }
    else if (/*case 2 conditional*/)
    {
        //blah
    }
    else
    {
        //default case
        Console.WriteLine("Test");
    }
}

I also took the liberty of tidying up your conditional statement. There is no need to cast to string after calling ToString(). This will always return a string anyway. When comparing strings for equality, bare in mind that using the == operator will result in a case sensitive comparison. Better to use string compare = 0 with the last argument to set case sensitive on/off.

Making the Android emulator run faster

Enabling this option worked for me.

AVD Manager -> Select device and click Edit-> Enable the option 'Use Host GPU'

enter image description here

Need to find element in selenium by css

By.cssSelector(".ban") or By.cssSelector(".hot") or By.cssSelector(".ban.hot") should all select it unless there is another element that has those classes.

In CSS, .name means find an element that has a class with name. .foo.bar.baz means to find an element that has all of those classes (in the same element).

However, each of those selectors will select only the first element that matches it on the page. If you need something more specific, please post the HTML of the other elements that have those classes.

Disable submit button when form invalid with AngularJS

We can create a simple directive and disable the button until all the mandatory fields are filled.

angular.module('sampleapp').directive('disableBtn',
function() {
 return {
  restrict : 'A',
  link : function(scope, element, attrs) {
   var $el = $(element);
   var submitBtn = $el.find('button[type="submit"]');
   var _name = attrs.name;
   scope.$watch(_name + '.$valid', function(val) {
    if (val) {
     submitBtn.removeAttr('disabled');
    } else {
     submitBtn.attr('disabled', 'disabled');
    }
   });
  }
 };
}
);

For More Info click here

What is the best way to programmatically detect porn images?

A graduate student from National Cheng Kung University in Taiwan did a research on this subject in 2004. He was able to achieve success rate of 89.79% in detecting nude pictures downloaded from the Internet. Here is the link to his thesis: The Study on Naked People Image Detection Based on Skin Color
It's in Chinese therefore you may need a translator in case you can't read it.

HTML form with multiple "actions"

As @AliK mentioned, this can be done easily by looking at the value of the submit buttons.

When you submit a form, unset variables will evaluate false. If you set both submit buttons to be part of the same form, you can just check and see which button has been set.

HTML:

<form action="handle_user.php" method="POST" />
  <input type="submit" value="Save" name="save" />
  <input type="submit" value="Submit for Approval" name="approve" />
</form>

PHP

if($_POST["save"]) {
  //User hit the save button, handle accordingly
}
//You can do an else, but I prefer a separate statement
if($_POST["approve"]) {
  //User hit the Submit for Approval button, handle accordingly
}

EDIT


If you'd rather not change your PHP setup, try this: http://pastebin.com/j0GUF7MV
This is the JavaScript method @AliK was reffering to.

Related:

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

Try to comment out \App\Http\Middleware\EncryptCookies::class in \app\Http\Kernel.php I have similar problem and solved it by doing so. Probably not the best solution because the security but at least it worked.

Previously I tried:

  • Clear cache
  • Generate new app key
  • Run my app in various Browsers (Chrome 70, Mozilla Firefox 57, and IE 11)
  • Run my app in another computer
  • Comment out \App\Http\Middleware\VerifyCsrfToken::class in \app\Http\Kernel.php
  • Comment out \Illuminate\Session\Middleware\AuthenticateSession::class in \app\Http\Kernel.php
  • Upgrade and downgrade Laravel (between 5.6 and 5.7)

But none of these above worked for me.

EDIT

My case here is every time I login, a new session file will be created (The old one is still persist, but suddenly forgotten. Check storage/framework/sessions) and new CSRF token is generated. So the problem is not with VerifyCsrfToken.

As @Vladd mentioned in comment section, you should never comment out \App\Http\Middleware\VerifyCsrfToken::class. You have to check that you sent the right CSRF TOKEN to the server.

How to use <md-icon> in Angular Material?

The simplest way today would be to simply request the Material Icons font from Google Fonts, for example in your HTML header tag:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

or in your stylesheet:

@import url(https://fonts.googleapis.com/icon?family=Material+Icons);

and then use as font icon with ligatures as explained in the md-icon directive. For example:

<md-icon aria-label="Menu" class="material-icons">menu</md-icon>

The complete list of icons/ligatures is at https://www.google.com/design/icons/

How to determine the longest increasing subsequence using dynamic programming?

here is java O(nlogn) implementation

import java.util.Scanner;

public class LongestIncreasingSeq {


    private static int binarySearch(int table[],int a,int len){

        int end = len-1;
        int beg = 0;
        int mid = 0;
        int result = -1;
        while(beg <= end){
            mid = (end + beg) / 2;
            if(table[mid] < a){
                beg=mid+1;
                result = mid;
            }else if(table[mid] == a){
                return len-1;
            }else{
                end = mid-1;
            }
        }
        return result;
    }
    
    public static void main(String[] args) {        
        
//        int[] t = {1, 2, 5,9,16};
//        System.out.println(binarySearch(t , 9, 5));
        Scanner in = new Scanner(System.in);
        int size = in.nextInt();//4;
        
        int A[] = new int[size];
        int table[] = new int[A.length]; 
        int k = 0;
        while(k<size){
            A[k++] = in.nextInt();
            if(k<size-1)
                in.nextLine();
        }        
        table[0] = A[0];
        int len = 1; 
        for (int i = 1; i < A.length; i++) {
            if(table[0] > A[i]){
                table[0] = A[i];
            }else if(table[len-1]<A[i]){
                table[len++]=A[i];
            }else{
                table[binarySearch(table, A[i],len)+1] = A[i];
            }            
        }
        System.out.println(len);
    }    
}

//TreeSet can be used

Best practice when adding whitespace in JSX

Because &nbsp causes you to have non-breaking spaces, you should only use it where necessary. In most cases, this will have unintended side effects.

Older versions of React, I believe all those before v14, would automatically insert <span> </span> when you had a newline inside of a tag.

While they no longer do this, that's a safe way to handle this in your own code. Unless you have styling that specifically targets span (bad practice in general), then this is the safest route.

Per your example, you can put them on a single line together as it's pretty short. In longer-line scenarios, this is how you should probably do it:

  <div className="top-element-formatting">
    Hello <span className="second-word-formatting">World!</span>
    <span> </span>
    So much more text in this box that it really needs to be on another line.
  </div>

This method is also safe against auto-trimming text editors.

The other method is using {' '} which doesn't insert random HTML tags. This could be more useful when styling, highlighting elements, and removes clutter from the DOM. If you don't need backwards compatibility with React v14 or earlier, this should be your preferred method.

  <div className="top-element-formatting">
    Hello <span className="second-word-formatting">World!</span>
    {' '}
    So much more text in this box that it really needs to be on another line.
  </div>

Returning JSON object from an ASP.NET page

If you get code behind, use some like this

        MyCustomObject myObject = new MyCustomObject();
        myObject.name='try';
        //OBJECT -> JSON
        var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string myObjectJson = javaScriptSerializer.Serialize(myObject);
        //return JSON   
        Response.Clear();     
        Response.ContentType = "application/json; charset=utf-8";
        Response.Write(myObjectJson );
        Response.End();

So you return a json object serialized with all attributes of MyCustomObject.

Linking dll in Visual Studio

I find it useful to understand the underlying tools. These are cl.exe (compiler) and link.exe (linker). You need to tell the compiler the signatures of the functions you want to call in the dynamic library (by including the library's header) and you need to tell the linker what the library is called and how to call it (by including the "implib" or import library).

This is roughly the same process gcc uses for linking to dynamic libraries on *nix, only the library object file differs.

Knowing the underlying tools means you can more quickly find the appropriate settings in the IDE and allows you to check that the commandlines generated are correct.

Example

Say A.exe depends B.dll. You need to include B's header in A.cpp (#include "B.h") then compile and link with B.lib:

cl A.cpp /c /EHsc
link A.obj B.lib

The first line generates A.obj, the second generates A.exe. The /c flag tells cl not to link and /EHsc specifies what kind of C++ exception handling the binary should use (there's no default, so you have to specify something).

If you don't specify /c cl will call link for you. You can use the /link flag to specify additional arguments to link and do it all at once if you like:

cl A.cpp /EHsc /link B.lib

If B.lib is not on the INCLUDE path you can give a relative or absolute path to it or add its parent directory to your include path with the /I flag.

If you're calling from cygwin (as I do) replace the forward slashes with dashes.

If you write #pragma comment(lib, "B.lib") in A.cpp you're just telling the compiler to leave a comment in A.obj telling the linker to link to B.lib. It's equivalent to specifying B.lib on the link commandline.

How to style an asp.net menu with CSS

I feel your pain and I wasted all night/morning trying to figure this out. With sheer brute force I figured out a solution. Call it a workaround - but it's simple.

Add the CssClass property to your Menu Control's declaration like so:

<asp:Menu ID="NavigationMenu" DataSourceID="NavigationSiteMapDataSource"
        CssClass="SomeMenuClass"
        StaticMenuStyle-CssClass="StaticMenuStyle"
        StaticMenuItemStyle-CssClass="StaticMenuItemStyle"
        Orientation="Horizontal" 
        MaximumDynamicDisplayLevels="0" 
        runat="server">
</asp:Menu>

Just rip out the StaticSelectedStyle-CssClass and StaticHoverStyle-CssClass attributes as they simply don't do jack.

Now create the "SomeMenuClass", doesn't matter what you put in it. It should look something like this:

.SomeMenuClass
{
    color:Green;
}

Next add the following two CSS Classes:

For "Hover" Styling add:

.SomeMenuClass a.static.highlighted
{
    color:Red !important;
}

For "Selected" Styling add:

.SomeMenuClass a.static.selected
{
    color:Blue !important;
}

There, that's it. You're done. Hope this saves some of you the frustration I went through. BTW: You mentioned:

I seem to be the first one to ever report on what seems to be a bug.

You also seemed to think it was a new .NET 4.0 bug. I found this: http://www.velocityreviews.com/forums/t649530-problem-with-staticselectedstyle-and-statichoverstyle.html posted back in 2008 regarding Asp.Net 2.0 . How are we the only 3 people on the planet complaining about this?

How I found the workaround (study the HTML output):

Here is the HTML output when I set StaticHoverStyle-BackColor="Red":

#NavigationMenu a.static.highlighted
{
    background-color:Red;
}

This is the HTML output when setting StaticSelectedStyle-BackColor="Blue":

#NavigationMenu a.static.selected
{
    background-color:Blue;
    text-decoration:none;
}

Therefore, the logical way to override this markup was to create classes for SomeMenuClass a.static.highlighted and SomeMenuClass a.static.selected

Special Notes:

You MUST also use "!important" on ALL the settings in these classes because the HTML output uses "#NavigationMenu", and that means any styles Asp.Net decides to throw in there for you will have inheritance priority over any other styles for the Menu Control with the ID "NavigationMenu". One thing I struggled with was padding, till I figured out Asp.Net was using "#NavigationMenu" to set the left and right padding to 15em. I tacked on "!important" to my SomeMenuClass styles and it worked.

What's the difference between struct and class in .NET?

Every variable or field of a primitive value type or structure type holds a unique instance of that type, including all its fields (public and private). By contrast, variables or fields of reference types may hold null, or may refer to an object, stored elsewhere, to which any number of other references may also exist. The fields of a struct will be stored in the same place as the variable or field of that structure type, which may be either on the stack or may be part of another heap object.

Creating a variable or field of a primitive value type will create it with a default value; creating a variable or field of a structure type will create a new instance, creating all fields therein in the default manner. Creating a new instance of a reference type will start by creating all fields therein in the default manner, and then running optional additional code depending upon the type.

Copying one variable or field of a primitive type to another will copy the value. Copying one variable or field of structure type to another will copy all the fields (public and private) of the former instance to the latter instance. Copying one variable or field of reference type to another will cause the latter to refer to the same instance as the former (if any).

It's important to note that in some languages like C++, the semantic behavior of a type is independent of how it is stored, but that isn't true of .NET. If a type implements mutable value semantics, copying one variable of that type to another copies the properties of the first to another instance, referred to by the second, and using a member of the second to mutate it will cause that second instance to be changed, but not the first. If a type implements mutable reference semantics, copying one variable to another and using a member of the second to mutate the object will affect the object referred to by the first variable; types with immutable semantics do not allow mutation, so it doesn't matter semantically whether copying creates a new instance or creates another reference to the first.

In .NET, it is possible for value types to implement any of the above semantics, provided that all of their fields can do likewise. A reference type, however, can only implement mutable reference semantics or immutable semantics; value types with fields of mutable reference types are limited to either implementing mutable reference semantics or weird hybrid semantics.

How to set text size in a button in html

Belated. If need any fancy button than anyone can try this.

_x000D_
_x000D_
#startStopBtn {_x000D_
    font-size: 30px;_x000D_
    font-weight: bold;_x000D_
    display: inline-block;_x000D_
    margin: 0 auto;_x000D_
    color: #dcfbb4;_x000D_
    background-color: green;_x000D_
    border: 0.4em solid #d4f7da;_x000D_
    border-radius: 50%;_x000D_
    transition: all 0.3s;_x000D_
    box-sizing: border-box;_x000D_
    width: 4em;_x000D_
    height: 4em;_x000D_
    line-height: 3em;_x000D_
    cursor: pointer;_x000D_
    box-shadow: 0 0 0 rgba(0,0,0,0.1), inset 0 0 0 rgba(0,0,0,0.1);_x000D_
    text-align: center;_x000D_
}_x000D_
#startStopBtn:hover{_x000D_
    box-shadow: 0 0 2em rgba(0,0,0,0.1), inset 0 0 1em rgba(0,0,0,0.1);_x000D_
    background-color: #29a074;_x000D_
  }
_x000D_
<div id="startStopBtn" onclick="startStop()" class=""> Go!</div>
_x000D_
_x000D_
_x000D_

failed to load ad : 3

If error continues last try is create a new placement in admob. This works for me. Without changing anything(except placement id string) else in code ads start displaying.

How to add more than one machine to the trusted hosts list using winrm

Same as @Altered-Ego but with txt.file:

Get-Content "C:\ServerList.txt"
machineA,machineB,machineC,machineD


$ServerList = Get-Content "C:\ServerList.txt"
    $currentTrustHost=(get-item WSMan:\localhost\Client\TrustedHosts).value
    if ( ($currentTrustHost).Length -gt "0" ) {
        $currentTrustHost+= ,$ServerList
        set-item WSMan:\localhost\Client\TrustedHosts –value $currentTrustHost -Force -ErrorAction SilentlyContinue
        }
    else {
        $currentTrustHost+= $ServerList
        set-item WSMan:\localhost\Client\TrustedHosts –value $currentTrustHost -Force -ErrorAction SilentlyContinue
    }

The "-ErrorAction SilentlyContinue" is required in old PS version to avoid fake error message:

PS C:\Windows\system32> get-item WSMan:\localhost\Client\TrustedHosts


   WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client

Type            Name                           SourceOfValue   Value
----            ----                           -------------   -----
System.String   TrustedHosts                                   machineA,machineB,machineC,machineD

libpng warning: iCCP: known incorrect sRGB profile

To add to Glenn's great answer, here's what I did to find which files were faulty:

find . -name "*.png" -type f -print0 | xargs \
       -0 pngcrush_1_8_8_w64.exe -n -q > pngError.txt 2>&1

I used the find and xargs because pngcrush could not handle lots of arguments (which were returned by **/*.png). The -print0 and -0 is required to handle file names containing spaces.

Then search in the output for these lines: iCCP: Not recognizing known sRGB profile that has been edited.

./Installer/Images/installer_background.png:    
Total length of data found in critical chunks            =     11286  
pngcrush: iCCP: Not recognizing known sRGB profile that has been edited

And for each of those, run mogrify on it to fix them.

mogrify ./Installer/Images/installer_background.png

Doing this prevents having a commit changing every single png file in the repository when only a few have actually been modified. Plus it has the advantage to show exactly which files were faulty.

I tested this on Windows with a Cygwin console and a zsh shell. Thanks again to Glenn who put most of the above, I'm just adding an answer as it's usually easier to find than comments :)

Remove Duplicate objects from JSON Array

I needed to do some de-duping of JSON objects so I stumbled across this page. However, I went with the short ES6 solution (no need for external libs), running this in Chrome Dev Tools Snippets:

const data = [ /* any list of objects */ ];
const set = new Set(data.map(item => JSON.stringify(item)));
const dedup = [...set].map(item => JSON.parse(item));
console.log(`Removed ${data.length - dedup.length} elements`);
console.log(dedup);

How to access the local Django webserver from outside world

I had to add this line to settings.py in order to make it work (otherwise it showed an error when accessed from another computer)

ALLOWED_HOSTS = ['*']

then ran the server with:

python manage.py runserver 0.0.0.0:9595

Also ensure that the firewall allows connections to that port

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

If, like me, none of the above quite works, it might be worth also specifically trying a lower TLS version alone. I had tried both of the following, but didn't seem to solve my problem:

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls

In the end, it was only when I targetted TLS 1.0 (specifically remove 1.1 and 1.2 in the code) that it worked:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls

The local server (that this was being attempted on) is fine with TLS 1.2, although the remote server (which was previously "confirmed" as fine for TLS 1.2 by a 3rd party) seems not to be.

Hope this helps someone.

Filtering array of objects with lodash based on property value

With lodash:

const myArr = [ {name: "john", age: 23},
                {name: "john", age: 43},
                {name: "jim", age: 101},
                {name: "bob", age: 67} ];

const johnArr = _.filter(myArr, person => person.name === 'john');
console.log(johnArr)

enter image description here

Vanilla JavaScript:

const myArr = [ {name: "john", age: 23},
                {name: "john", age: 43},
                {name: "jim", age: 101},
                {name: "bob", age: 67} ];

const johnArr = myArr.filter(person => person.name === 'john');
console.log(johnArr);

enter image description here