Programs & Examples On #Cyclic reference

A cyclic reference is established if object A holds a reference to B while B holds a reference to A.

Circular (or cyclic) imports in Python

Suppose you are running a test python file named request.py In request.py, you write

import request

so this also most likely a circular import.

Solution:

Just change your test file to another name such as aaa.py, other than request.py.

Do not use names that are already used by other libs.

How do I convert a decimal to an int in C#?

System.Decimal implements the IConvertable interface, which has a ToInt32() member.

Does calling System.Decimal.ToInt32() work for you?

Message 'src refspec master does not match any' when pushing commits in Git

This happened to me when I did not refer to the master branch of the origin. So, you can try the following:

git pull origin master

This creates a reference to the master branch of the origin in the local repository. Then you can push the local repository to the origin.

git push -u origin master

How can I shuffle an array?

You could use the Fisher-Yates Shuffle (code adapted from this site):

function shuffle(array) {
    let counter = array.length;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        let index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        let temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}

Does Ruby have a string.startswith("abc") built in method?

If this is for a non-Rails project, I'd use String#index:

"foobar".index("foo") == 0  # => true

Copy data from one existing row to another existing row in SQL?

Use SELECT to Insert records

INSERT tracking (userID, courseID, course, bookmark, course_date, posttest, post_attempts, post_score, post_date, complete, complete_date, exempted, exempted_date, exempted_reason, emailSent) 
SELECT userID, 11, course, bookmark, course_date, posttest, post_attempts, post_score, post_date, complete, complete_date, exempted, exempted_date, exempted_reason, emailSent
FROM tracking WHERE courseID = 6 AND course_date > '08-01-2008'

How do I replace whitespaces with underscore?

Django has a 'slugify' function which does this, as well as other URL-friendly optimisations. It's hidden away in the defaultfilters module.

>>> from django.template.defaultfilters import slugify
>>> slugify("This should be connected")

this-should-be-connected

This isn't exactly the output you asked for, but IMO it's better for use in URLs.

I ran into a merge conflict. How can I abort the merge?

If you end up with merge conflict and doesn't have anything to commit, but still a merge error is being displayed. After applying all the below mentioned commands,

git reset --hard HEAD
git pull --strategy=theirs remote_branch
git fetch origin
git reset --hard origin

Please remove

.git\index.lock

File [cut paste to some other location in case of recovery] and then enter any of below command depending on which version you want.

git reset --hard HEAD
git reset --hard origin

Hope that helps!!!

Pdf.js: rendering a pdf file using a base64 file source instead of url

Used the Accepted Answer to do a check for IE and convert the dataURI to UInt8Array; an accepted form by PDFJS

_x000D_
_x000D_
        Ext.isIE ? pdfAsDataUri = me.convertDataURIToBinary(pdfAsDataUri): '';_x000D_
_x000D_
        convertDataURIToBinary: function(dataURI) {_x000D_
          var BASE64_MARKER = ';base64,',_x000D_
            base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length,_x000D_
            base64 = dataURI.substring(base64Index),_x000D_
            raw = window.atob(base64),_x000D_
            rawLength = raw.length,_x000D_
            array = new Uint8Array(new ArrayBuffer(rawLength));_x000D_
_x000D_
          for (var i = 0; i < rawLength; i++) {_x000D_
            array[i] = raw.charCodeAt(i);_x000D_
          }_x000D_
          return array;_x000D_
        },
_x000D_
_x000D_
_x000D_

angularjs directive call function specified in attribute and pass an argument to it

Marko's solution works well.

To contrast with recommended Angular way (as shown by treeface's plunkr) is to use a callback expression which does not require defining the expressionHandler. In marko's example change:

In template

<div my-method="theMethodToBeCalled(myParam)"></div>

In directive link function

$(element).click(function( e, rowid ) {
  scope.method({myParam: id});
});

This does have one disadvantage compared to marko's solution - on first load theMethodToBeCalled function will be invoked with myParam === undefined.

A working exampe can be found at @treeface Plunker

How to filter keys of an object with lodash?

Just change filter to omitBy

_x000D_
_x000D_
const data = { aaa: 111, abb: 222, bbb: 333 };_x000D_
const result = _.omitBy(data, (value, key) => !key.startsWith("a"));_x000D_
console.log(result);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

how can I check if a file exists?

an existing folder will FAIL with FileExists

Function FileExists(strFileName)
' Check if a file exists - returns True or False

use instead or in addition:

Function FolderExists(strFolderPath)
' Check if a path exists

Export multiple classes in ES6 modules

@webdeb's answer didn't work for me, I hit an unexpected token error when compiling ES6 with Babel, doing named default exports.

This worked for me, however:

// Foo.js
export default Foo
...

// bundle.js
export { default as Foo } from './Foo'
export { default as Bar } from './Bar'
...

// and import somewhere..
import { Foo, Bar } from './bundle'

deny directory listing with htaccess

Options -Indexes returns a 403 forbidden error for a protected directory. The same behaviour can be achived by using the following Redirect in htaccess :

RedirectMatch 403 ^/folder/?$ 

This will return a forbidden error for example.com/folder/ .

You can also use mod-rewrite to forbid a request for folder.

RewriteEngine on

RewriteRule ^folder/?$ - [F]

If your htaccess is in the folder that you are going to forbid , change RewriteRule's pattern from ^folder/?$ to ^$ .

Plotting categorical data with pandas and matplotlib

You can simply use value_counts on the series:

df['colour'].value_counts().plot(kind='bar')

enter image description here

What is the basic difference between the Factory and Abstract Factory Design Patterns?

I think we can understand the difference between these two by seeing a Java8 example code:

  interface Something{}

  interface OneWhoCanProvideSomething {
     Something getSomething();
  }

  interface OneWhoCanProvideCreatorsOfSomething{
     OneWhoCanProvideSomething getCreator();
  }


public class AbstractFactoryExample {

    public static void main(String[] args) {
        //I need something
        //Let's create one
        Something something = new Something() {};

        //Or ask someone (FACTORY pattern)
        OneWhoCanProvideSomething oneWhoCanProvideSomethingOfTypeA = () -> null;
        OneWhoCanProvideSomething oneWhoCanProvideSomethingOfTypeB = () -> null;

        //Or ask someone who knows soemone who can create something (ABSTRACT FACTORY pattern)
        OneWhoCanProvideCreatorsOfSomething oneWhoCanProvideCreatorsOfSomething = () -> null;

        //Same thing, but you don't need to write you own interfaces
        Supplier<Something> supplierOfSomething = () -> null;
        Supplier<Supplier<Something>> supplierOfSupplier = () -> null;
    }

}

Now the question is which way of creation should you use and why: The first way (no pattern, just plain constructor): creating by yourself is not a good idea, you have to do all the work, and your client code is tied to the particular implementation.

The second way (using Factory pattern): provides you the benefit that you can pass any type of implementation, which can provide different type of something based on some condition (maybe a parameter passed to creational method).

The third way (using Abstract Factory pattern): This gives you more flexibility. You can find different types of creators of something based on some condition (maybe a parameter passed).

Note that you can always get away with Factory pattern by combining two conditions together (which slightly increases code complexity, and coupling), I guess that's why we rarely see real life use cases of Abstract Factory pattern.

How to call a function after a div is ready?

To do something after certain div load from function .load(). I think this exactly what you need:

  $('#divIDer').load(document.URL +  ' #divIDer',function() {

       // call here what you want .....


       //example
       $('#mydata').show();
  });

Input placeholders for Internet Explorer

I created my own jQuery plugin after becoming frustrated that the existing shims would hide the placeholder on focus, which creates an inferior user experience and also does not match how Firefox, Chrome and Safari handle it. This is especially the case if you want an input to be focused when a page or popup first loads, while still showing the placeholder until text is entered.

https://github.com/nspady/jquery-placeholder-labels/

How to get package name from anywhere?

You can use undocumented method android.app.ActivityThread.currentPackageName() :

Class<?> clazz = Class.forName("android.app.ActivityThread");
Method method  = clazz.getDeclaredMethod("currentPackageName", null);
String appPackageName = (String) method.invoke(clazz, null);

Caveat: This must be done on the main thread of the application.

Thanks to this blog post for the idea: http://blog.javia.org/static-the-android-application-package/ .

Html code as IFRAME source rather than a URL

iframe srcdoc: This attribute contains HTML content, which will override src attribute. If a browser does not support the srcdoc attribute, it will fall back to the URL in the src attribute.

Let's understand it with an example

<iframe 
    name="my_iframe" 
    srcdoc="<h1 style='text-align:center; color:#9600fa'>Welcome to iframes</h1>"
    src="https://www.birthdaycalculatorbydate.com/"
    width="500px"
    height="200px"
></iframe>

Original content is taken from iframes.

How to disable 'X-Frame-Options' response header in Spring Security?

By default X-Frame-Options is set to denied, to prevent clickjacking attacks. To override this, you can add the following into your spring security config

<http>    
    <headers>
        <frame-options policy="SAMEORIGIN"/>
    </headers>
</http>

Here are available options for policy

  • DENY - is a default value. With this the page cannot be displayed in a frame, regardless of the site attempting to do so.
  • SAMEORIGIN - I assume this is what you are looking for, so that the page will be (and can be) displayed in a frame on the same origin as the page itself
  • ALLOW-FROM - Allows you to specify an origin, where the page can be displayed in a frame.

For more information take a look here.

And here to check how you can configure the headers using either XML or Java configs.

Note, that you might need also to specify appropriate strategy, based on needs.

Vue - Deep watching an array of objects and calculating the change?

It is well defined behaviour. You cannot get the old value for a mutated object. That's because both the newVal and oldVal refer to the same object. Vue will not keep an old copy of an object that you mutated.

Had you replaced the object with another one, Vue would have provided you with correct references.

Read the Note section in the docs. (vm.$watch)

More on this here and here.

Scanning Java annotations at runtime

Google Reflections seems to be much faster than Spring. Found this feature request that adresses this difference: http://www.opensaga.org/jira/browse/OS-738

This is a reason to use Reflections as startup time of my application is really important during development. Reflections seems also to be very easy to use for my use case (find all implementers of an interface).

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

Adding a css class to select using @Html.DropDownList()

Try below code:

@Html.DropDownList("ProductTypeID",null,"",new { @class = "form-control"})

download a file from Spring boot rest service

    @GetMapping("/downloadfile/{productId}/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable(value = "productId") String productId,
        @PathVariable String fileName, HttpServletRequest request) {
    // Load file as Resource
    Resource resource;

    String fileBasePath = "C:\\Users\\v_fzhang\\mobileid\\src\\main\\resources\\data\\Filesdown\\" + productId
            + "\\";
    Path path = Paths.get(fileBasePath + fileName);
    try {
        resource = new UrlResource(path.toUri());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }

    // Try to determine file's content type
    String contentType = null;
    try {
        contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
    } catch (IOException ex) {
        System.out.println("Could not determine file type.");
    }

    // Fallback to the default content type if type could not be determined
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
            .body(resource);
}

To test it, use postman

http://localhost:8080/api/downloadfile/GDD/1.zip

Entity framework linq query Include() multiple children entities

Might be it will help someone, 4 level and 2 child's on each level

Library.Include(a => a.Library.Select(b => b.Library.Select(c => c.Library)))
            .Include(d=>d.Book.)
            .Include(g => g.Library.Select(h=>g.Book))
            .Include(j => j.Library.Select(k => k.Library.Select(l=>l.Book)))

How to retrieve SQL result column value using column name in Python?

This post is old but may come up via searching.

Now you can use mysql.connector to retrive a dictionary as shown here: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

Here is the example on the mysql site:

cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")

print("Countries in Europe:")
for row in cursor:
    print("* {Name}".format(Name=row['Name']))

How to Clear Console in Java?

You need to instruct the console to clear.

For serial terminals this was typically done through so called "escape sequences", where notably the vt100 set has become very commonly supported (and its close ANSI-cousin).

Windows has traditionally not supported such sequences "out-of-the-box" but relied on API-calls to do these things. For DOS-based versions of Windows, however, the ANSI.SYS driver could be installed to provide such support.

So if you are under Windows, you need to interact with the appropriate Windows API. I do not believe the standard Java runtime library contains code to do so.

'"SDL.h" no such file or directory found' when compiling

the simplest idea is to add pkg-config --cflags --libs sdl2 while compiling the code.

g++ file.cpp `pkg-config --cflags --libs sdl2`

How does Google reCAPTCHA v2 work behind the scenes?

My Bots are running well against ReCaptcha.

Here my Solution.

Let your Bot do this Steps:

First write a Human Mouse Move Function to move your Mouse like a B-Spline (Ask me for Source Code). This is the most important Point.

Also use for better results a VPN like https://www.purevpn.com

For every Recpatcha do these Steps:

  1. If you use VPN switch IP first

  2. Clear all Browser Cookies

  3. Clear all Browser Cache

  4. Set one of these Useragents by Random:

    a. Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)

    b. Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0

5 Move your Mouse with the Human Mouse Move Funktion from a RandomPoint into the I am not a Robot Image every time with different 10x10 Randomrange

  1. Then Click ever with random delay between

    WM_LBUTTONDOWN

    and

    WM_LBUTTONUP

  2. Take Screenshot from Image Captcha

  3. Send Screenshot to

    http://www.deathbycaptcha.com

    or

    https://2captcha.com

and let they solve.

  1. After receiving click cooridinates from captcha solver use your Human Mouse move Funktion to move and Click Recaptcha Images

  2. Use your Human Mouse Move Funktion to move and Click to the Recaptcha Verify Button

In 75% all trys Recaptcha will solved

Chears Google

Tom

drop down list value in asp.net

VB Code:

Dim ListItem1 As New ListItem()
ListItem1.Text = "put anything here"
ListItem1.Value = "0"
drpTag.DataBind()
drpTag.Items.Insert(0, ListItem1)

View:

<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator" ControlToValidate="drpTag" 
  ValueToCompare="0">
</asp:CompareValidator>

How to SELECT the last 10 rows of an SQL table which has no ID field?

executing a count(*) query on big data is expensive. i think using "SELECT * FROM table ORDER BY id DESC LIMIT n" where n is your number of rows per page is better and lighter

How to start an Intent by passing some parameters to it?

In order to pass the parameters you create new intent and put a parameter map:

Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);

In order to get the parameters values inside the started activity, you must call the get[type]Extra() on the same intent:

// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"

If your parameters are ints you would use getIntExtra() instead etc. Now you can use your parameters like you normally would.

Skipping every other element after the first

There are more ways than one to skin a cat. - Seba Smith

arr = list(range(10)) # Range from 0-9

# List comprehension: Range with conditional
print [arr[index] for index in range(len(arr)) if index % 2 == 0]

# List comprehension: Range with step
print [arr[index] for index in range(0, len(arr), 2)]

# List comprehension: Enumerate with conditional
print [item for index, item in enumerate(arr) if index % 2 == 0]

# List filter: Index in range
print filter(lambda index: index % 2 == 0, range(len(arr)))

# Extended slice
print arr[::2]

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

One of the problems you might need to check is, Does the registry requires VPN, Enable your VPN and try pulling again.

Thanks.

How to Empty Caches and Clean All Targets Xcode 4 and later

Command-Option-Shift-K should do it. Alternatively, go to product menu, press the option key, now the option "Clean" will change to "Clean Build Folder ..." select that option.

How to copy a collection from one database to another in MongoDB

If between two remote mongod instances, use

{ cloneCollection: "<collection>", from: "<hostname>", query: { <query> }, copyIndexes: <true|false> } 

See http://docs.mongodb.org/manual/reference/command/cloneCollection/

Woocommerce, get current product id

Retrieve the ID of the current item in the WordPress Loop.

echo get_the_ID(); 

hence works for the product id too. #tested #woo-commerce

How to insert a row between two rows in an existing excel with HSSF (Apache POI)

For people who are looking to insert a row between two rows in an existing excel with XSSF (Apache POI), there is already a method "copyRows" implemented in the XSSFSheet.

import org.apache.poi.ss.usermodel.CellCopyPolicy;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class App2 throws Exception{
    public static void main(String[] args){
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream("input.xlsx"));
        XSSFSheet sheet = workbook.getSheet("Sheet1");
        sheet.copyRows(0, 2, 3, new CellCopyPolicy());
        FileOutputStream out = new FileOutputStream("output.xlsx");
        workbook.write(out);
        out.close();
    }
}

html div onclick event

I would have used stopPropagation like this:

$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
     alert('123');
 });

$('#ancherComplaint').on('click',function(e){
    e.stopPropagation();
    alert('hiiiiiiiiii');
});

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

I'm guessing you didn't run this command after the commit failed so just actually run this to create the remote :

 git remote add origin https://github.com/VijayNew/NewExample.git

And the commit failed because you need to git add some files you want to track.

How do I use Join-Path to combine more than two strings into a file path?

Since PowerShell 6.0, Join-Path has a new parameter called -AdditionalChildPath and can combine multiple parts of a path out-of-the-box. Either by providing the extra parameter or by just supplying a list of elements.

Example from the documentation:

Join-Path a b c d e f g
a\b\c\d\e\f\g

So in PowerShell 6.0 and above your variant

$path = Join-Path C: "Program Files" "Microsoft Office"

works as expected!

jQuery if Element has an ID?

You can do

document.getElementById(id) or 
$(id).length > 0

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

Printing variables in Python 3.4

Version 3.6+: Use a formatted string literal, f-string for short

print(f"{i}. {key} appears {wordBank[key]} times.")

How do I exit from the text window in Git?

First type

 i

to enter the commit message then press ESC then type

 :wq

to save the commit message and to quit. Or type

 :q!

to quit without saving the message.

Where is the syntax for TypeScript comments documented?

You can add information about parameters, returns, etc. as well using:

/**
* This is the foo function
* @param bar This is the bar parameter
* @returns returns a string version of bar
*/
function foo(bar: number): string {
    return bar.toString()
}

This will cause editors like VS Code to display it as the following:

enter image description here

How can I scroll a web page using selenium webdriver in python?

The ScrollTo() function doesn't work anymore. This is what I used and it worked fine.

driver.execute_script("document.getElementById('mydiv').scrollIntoView();")

Retrieve WordPress root directory path?

echo ABSPATH; // This shows the absolute path of WordPress

ABSPATH is a constant defined in the wp-config.php file.

How to open a local disk file with JavaScript?

Here's an example using FileReader:

_x000D_
_x000D_
function readSingleFile(e) {
  var file = e.target.files[0];
  if (!file) {
    return;
  }
  var reader = new FileReader();
  reader.onload = function(e) {
    var contents = e.target.result;
    displayContents(contents);
  };
  reader.readAsText(file);
}

function displayContents(contents) {
  var element = document.getElementById('file-content');
  element.textContent = contents;
}

document.getElementById('file-input')
  .addEventListener('change', readSingleFile, false);
_x000D_
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<pre id="file-content"></pre>
_x000D_
_x000D_
_x000D_


Specs

http://dev.w3.org/2006/webapi/FileAPI/

Browser compatibility

  • IE 10+
  • Firefox 3.6+
  • Chrome 13+
  • Safari 6.1+

http://caniuse.com/#feat=fileapi

Mocking a class: Mock() or patch()?

Key points which explain difference and provide guidance upon working with unittest.mock

  1. Use Mock if you want to replace some interface elements(passing args) of the object under test
  2. Use patch if you want to replace internal call to some objects and imported modules of the object under test
  3. Always provide spec from the object you are mocking
    • With patch you can always provide autospec
    • With Mock you can provide spec
    • Instead of Mock, you can use create_autospec, which intended to create Mock objects with specification.

In the question above the right answer would be to use Mock, or to be more precise create_autospec (because it will add spec to the mock methods of the class you are mocking), the defined spec on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some

from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch


class MyClass:
    
    @staticmethod
    def method(foo, bar):
        print(foo)


def something(some_class: MyClass):
    arg = 1
    # Would fail becuase of wrong parameters passed to methd.
    return some_class.method(arg)


def second(some_class: MyClass):
    arg = 1
    return some_class.unexisted_method(arg)


class TestSomethingTestCase(TestCase):
    def test_something_with_autospec(self):
        mock = create_autospec(MyClass)
        mock.method.return_value = True
        # Fails because of signature misuse.
        result = something(mock)
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
    
    def test_something(self):
        mock = Mock()  # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
        mock.method.return_value = True
        
        result = something(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
        
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)


class TestSecondTestCase(TestCase):
    def test_second_with_autospec(self):
        mock = Mock(spec=MyClass)
        # Fails because of signature misuse.
        result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second(self):
        mock = Mock()
        mock.unexisted_method.return_value = True
        
        result = second(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)

The test cases with defined spec used fail because methods called from something and second functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock will display.

As a side note there is one more option: use patch.object to mock just the class method which is called with.

The good use cases for patch would be the case when the class is used as inner part of function:

def something():
    arg = 1
    return MyClass.method(arg)

Then you will want to use patch as a decorator to mock the MyClass.

RSpec: how to test if a method was called?

The below should work

describe "#foo"
  it "should call 'bar' with appropriate arguments" do
     subject.stub(:bar)
     subject.foo
     expect(subject).to have_received(:bar).with("Invalid number of arguments")
  end
end

Documentation: https://github.com/rspec/rspec-mocks#expecting-arguments

Logical Operators, || or OR?

I don't think one is inherently better than another one, but I would suggest sticking with || because it is the default in most languages.

EDIT: As others have pointed out there is indeed a difference between the two.

arranging div one below the other

You don't even need the float:left;

It seems the default behavior is to render one below the other, if it doesn't happen it's because they are inheriting some style from above.

CSS:

#wrapper{
    margin-left:auto;
    margin-right:auto;
    height:auto; 
    width:auto;
}
</style>

HTML:

<div id="wrapper">
    <div id="inner1">inner1</div>
    <div id="inner2">inner2</div>
</div>

Simulating a click in jQuery/JavaScript on a link

You can use the the click function to trigger the click event on the selected element.

Example:

$( 'selector for your link' ).click ();

You can learn about various selectors in jQuery's documentation.

EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined. You could solve this with something like this:

var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
    document.location = linkEl.attr ( 'href' );
} else {
    linkEl.click ();
}

Don't know about addEventListener though.

c++ compile error: ISO C++ forbids comparison between pointer and integer

You must remember to use single quotes for char constants. So use

if (answer == 'y') return true;

Rather than

if (answer == "y") return true;

I tested this and it works

Set select option 'selected', by value

I think the easiest way is selecting to set val(), but you can check the following. See How to handle select and option tag in jQuery? for more details about options.

$('div.id_100  option[value="val2"]').prop("selected", true);

$('id_100').val('val2');

Not optimised, but the following logic is also useful in some cases.

$('.id_100 option').each(function() {
    if($(this).val() == 'val2') {
        $(this).prop("selected", true);
    }
});

Create Local SQL Server database

Your best bet over here to install XAMPP..Follow the link download it , it has an instruction file as well. You can setup your own MY SQL database and then connect to on your local machine.

https://www.apachefriends.org/download.html

Creating a chart in Excel that ignores #N/A or blank cells

I found a way to do it.

you can do an x,y scatterplot. it will ignore null records (i.e. rows)

How would I get a cron job to run every 30 minutes?

You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.

How many socket connections can a web server handle?

I think that the number of concurrent socket connections one web server can handle largely depends on the amount of resources each connection consumes and the amount of total resource available on the server barring any other web server resource limiting configuration.

To illustrate, if every socket connection consumed 1MB of server resource and the server has 16GB of RAM available (theoretically) this would mean it would only be able to handle (16GB / 1MB) concurrent connections. I think it's as simple as that... REALLY!

So regardless of how the web server handles connections, every connection will ultimately consume some resource.

Subset a dataframe by multiple factor levels

Try this:

> data[match(as.character(data$Code), selected, nomatch = FALSE), ]
    Code Value
1      A     1
2      B     2
1.1    A     1
1.2    A     1

Cannot enqueue Handshake after invoking quit

According to:

TL;DR You need to establish a new connection by calling the createConnection method after every disconnection.

and

Note: If you're serving web requests, then you shouldn't be ending connections on every request. Just create a connection on server startup and use the connection/client object to query all the time. You can listen on the error event to handle server disconnection and for reconnecting purposes. Full code here.


From:

It says:

Server disconnects

You may lose the connection to a MySQL server due to network problems, the server timing you out, or the server crashing. All of these events are considered fatal errors, and will have the err.code = 'PROTOCOL_CONNECTION_LOST'. See the Error Handling section for more information.

The best way to handle such unexpected disconnects is shown below:

function handleDisconnect(connection) {
  connection.on('error', function(err) {
    if (!err.fatal) {
      return;
    }

    if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
      throw err;
    }

    console.log('Re-connecting lost connection: ' + err.stack);

    connection = mysql.createConnection(connection.config);
    handleDisconnect(connection);
    connection.connect();
  });
}

handleDisconnect(connection);

As you can see in the example above, re-connecting a connection is done by establishing a new connection. Once terminated, an existing connection object cannot be re-connected by design.

With Pool, disconnected connections will be removed from the pool freeing up space for a new connection to be created on the next getConnection call.


I have tweaked the function such that every time a connection is needed, an initializer function adds the handlers automatically:

function initializeConnection(config) {
    function addDisconnectHandler(connection) {
        connection.on("error", function (error) {
            if (error instanceof Error) {
                if (error.code === "PROTOCOL_CONNECTION_LOST") {
                    console.error(error.stack);
                    console.log("Lost connection. Reconnecting...");

                    initializeConnection(connection.config);
                } else if (error.fatal) {
                    throw error;
                }
            }
        });
    }

    var connection = mysql.createConnection(config);

    // Add handlers.
    addDisconnectHandler(connection);

    connection.connect();
    return connection;
}

Initializing a connection:

var connection = initializeConnection({
    host: "localhost",
    user: "user",
    password: "password"
});

Minor suggestion: This may not apply to everyone but I did run into a minor issue relating to scope. If the OP feels this edit was unnecessary then he/she can choose to remove it. For me, I had to change a line in initializeConnection, which was var connection = mysql.createConnection(config); to simply just

connection = mysql.createConnection(config);

The reason being that if connection is a global variable in your program, then the issue before was that you were making a new connection variable when handling an error signal. But in my nodejs code, I kept using the same global connection variable to run queries on, so the new connection would be lost in the local scope of the initalizeConnection method. But in the modification, it ensures that the global connection variable is reset This may be relevant if you're experiencing an issue known as

Cannot enqueue Query after fatal error

after trying to perform a query after losing connection and then successfully reconnecting. This may have been a typo by the OP, but I just wanted to clarify.

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

The annotation @JoinColumn indicates that this entity is the owner of the relationship (that is: the corresponding table has a column with a foreign key to the referenced table), whereas the attribute mappedBy indicates that the entity in this side is the inverse of the relationship, and the owner resides in the "other" entity. This also means that you can access the other table from the class which you've annotated with "mappedBy" (fully bidirectional relationship).

In particular, for the code in the question the correct annotations would look like this:

@Entity
public class Company {
    @OneToMany(mappedBy = "company",
               orphanRemoval = true,
               fetch = FetchType.LAZY,
               cascade = CascadeType.ALL)
    private List<Branch> branches;
}

@Entity
public class Branch {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "companyId")
    private Company company;
}

how to change directory using Windows command line

Just type your desired drive initial in the command line and press enter

Like if you want to go L:\\ drive, Just type L: or l:

Pass parameters in setInterval function

That problem would be a nice demonstration for use of closures. The idea is that a function uses a variable of outer scope. Here is an example...

setInterval(makeClosure("Snowden"), 1000)

function makeClosure(name) {
var ret

ret = function(){
    console.log("Hello, " + name);
}

return ret;
}

Function "makeClosure" returns another function, which has access to outer scope variable "name". So, basically, you need pass in whatever variables to "makeClosure" function and use them in function assigned to "ret" variable. Affectingly, setInterval will execute function assigned to "ret".

Display text on MouseOver for image in html

You can use CSS hover
Link to jsfiddle here: http://jsfiddle.net/ANKwQ/5/

HTML:

<a><img src='https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQB3a3aouZcIPEF0di4r9uK4c0r9FlFnCasg_P8ISk8tZytippZRQ'></a>
<div>text</div>
?

CSS:

div {
    display: none;
    border:1px solid #000;
    height:30px;
    width:290px;
    margin-left:10px;
}

a:hover + div {
    display: block;
}?

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

How I redirect to an area is add it as a parameter

@Html.Action("Action", "Controller", new { area = "AreaName" })

for the href portion of a link I use

@Url.Action("Action", "Controller", new { area = "AreaName" })

Can someone post a well formed crossdomain.xml sample?

This is what I've been using for development:

<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>

This is a very liberal approach, but is fine for my application.

As others have pointed out below, beware the risks of this.

How can I clear the NuGet package cache using the command line?

Note that dnx has a different cache for feeding HTTP results:

Microsoft .NET Development Utility Clr-x86-1.0.0-rc1-16231
   CACHE https://www.nuget.org/api/v2/
   CACHE http://192.168.148.21/api/odata/

Which you can clear with

dnu clear-http-cache

Now we just need to find out what the command will be on the new dotnet CLI tool.

...and here it is:

dotnet restore --no-cache

Display a RecyclerView in Fragment

I faced same problem. And got the solution when I use this code to call context. I use Grid Layout. If you use another one you can change.

   recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),1));

if you have adapter to set. So you can follow this. Just call the getContext

  adapter = new Adapter(getContext(), myModelList);

If you have Toast to show, use same thing above

   Toast.makeText(getContext(), "Error in "+e, Toast.LENGTH_SHORT).show();

Hope this will work.

HappyCoding

Selecting a Record With MAX Value

The query answered by sandip giri was the correct answer, here a similar example getting the maximum id (PresupuestoEtapaActividadHistoricoId), after calculate the maximum value(Base)

select * 
from (
    select PEAA.PresupuestoEtapaActividadId,
        PEAH.PresupuestoEtapaActividadHistoricoId,             
        sum(PEAA.ValorTotalDesperdicioBase) as Base,
        sum(PEAA.ValorTotalDesperdicioEjecucion) as Ejecucion
    from hgc.PresupuestoActividadAnalisis as PEAA
    inner join hgc.PresupuestoEtapaActividad as PEA
        on PEAA.PresupuestoEtapaActividadId = PEA.PresupuestoEtapaActividadId
    inner join hgc.PresupuestoEtapaActividadHistorico as PEAH
        on PEA.PresupuestoEtapaActividadId = PEAH.PresupuestoEtapaActividadId                                                         
    group by PEAH.PresupuestoEtapaActividadHistoricoId, PEAA.PresupuestoEtapaActividadId    
) as t
where exists (
    select 1 
    from (
        select MAX(PEAH.PresupuestoEtapaActividadHistoricoId) as PresupuestoEtapaActividadHistoricoId                                                                     
        from hgc.PresupuestoEtapaActividadHistorico as PEAH                       
        group by PEAH.PresupuestoEtapaActividadId  
    ) as ti
    where t.PresupuestoEtapaActividadHistoricoId = ti.PresupuestoEtapaActividadHistoricoId 
)

Java 8: Difference between two LocalDateTime in multiple units

Here is a very simple answer to your question. It works.

import java.time.*;
import java.util.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class MyClass {
public static void main(String args[]) {
    DateTimeFormatter T = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
    Scanner h = new Scanner(System.in);

    System.out.print("Enter date of birth[dd/mm/yyyy hh:mm]: ");
    String b = h.nextLine();

    LocalDateTime bd = LocalDateTime.parse(b,T);
    LocalDateTime cd = LocalDateTime.now();

    long minutes = ChronoUnit.MINUTES.between(bd, cd);
    long hours = ChronoUnit.HOURS.between(bd, cd);

    System.out.print("Age is: "+hours+ " hours, or " +minutes+ " minutes old");
}
}

Python JSON encoding

Python lists translate to JSON arrays. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict:

>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'

More Pythonic Way to Run a Process X Times

How about?

while BoolIter(N, default=True, falseIndex=N-1):
    print 'some thing'

or in a more ugly way:

for _ in BoolIter(N):
    print 'doing somthing'

or if you want to catch the last time through:

for lastIteration in BoolIter(N, default=False, trueIndex=N-1):
    if not lastIteration:
        print 'still going'
    else:
        print 'last time'

where:

class BoolIter(object):

    def __init__(self, n, default=False, falseIndex=None, trueIndex=None, falseIndexes=[], trueIndexes=[], emitObject=False):
        self.n = n
        self.i = None
        self._default = default
        self._falseIndexes=set(falseIndexes)
        self._trueIndexes=set(trueIndexes)
        if falseIndex is not None:
            self._falseIndexes.add(falseIndex)
        if trueIndex is not None:
            self._trueIndexes.add(trueIndex)
        self._emitObject = emitObject


    def __iter__(self):
        return self

    def next(self):
        if self.i is None:
            self.i = 0
        else:
            self.i += 1
        if self.i == self.n:
            raise StopIteration
        if self._emitObject:
            return self
        else:
            return self.__nonzero__()

    def __nonzero__(self):
        i = self.i
        if i in self._trueIndexes:
            return True
        if i in self._falseIndexes:
            return False
        return self._default

    def __bool__(self):
        return self.__nonzero__()

Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.

I had to close and re-open my windows console (or open a new console), and then open the SDK manager (ran android), after which a bunch of updates and installs had to complete.

Generics in C#, using type of a variable as parameter

You can't use it in the way you describe. The point about generic types, is that although you may not know them at "coding time", the compiler needs to be able to resolve them at compile time. Why? Because under the hood, the compiler will go away and create a new type (sometimes called a closed generic type) for each different usage of the "open" generic type.

In other words, after compilation,

DoesEntityExist<int>

is a different type to

DoesEntityExist<string>

This is how the compiler is able to enfore compile-time type safety.

For the scenario you describe, you should pass the type as an argument that can be examined at run time.

The other option, as mentioned in other answers, is that of using reflection to create the closed type from the open type, although this is probably recommended in anything other than extreme niche scenarios I'd say.

Make $JAVA_HOME easily changable in Ubuntu

This will probably solve your problem: https://help.ubuntu.com/community/EnvironmentVariables

Session-wide environment variables

In order to set environment variables in a way that affects a particular user's environment, one should not place commands to set their values in particular shell script files in the user's home directory, but use:

~/.pam_environment - This file is specifically meant for setting a user's environment. It is not a script file, but rather consists of assignment expressions, one per line.

Not recommended:

~/.profile - This is probably the best file for placing environment variable assignments in, since it gets executed automatically by the DisplayManager during the startup process desktop session as well as by the login shell when one logs-in from the textual console.

Get the contents of a table row with a button click

function useAdress () { 
var id = $("#choose-address-table").find(".nr:first").text();
alert (id);
$("#resultas").append(id); // Testing: append the contents of the td to a div
};

then on your button:

onclick="useAdress()"

Currently running queries in SQL Server

Depending on your privileges, this query might work:

SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext

Ref: http://blog.sqlauthority.com/2009/01/07/sql-server-find-currently-running-query-t-sql

Insert into a MySQL table or update if exists

In case that you wanted to make a non-primary fields as criteria/condition for ON DUPLICATE, you can make a UNIQUE INDEX key on that table to trigger the DUPLICATE.

ALTER TABLE `table` ADD UNIQUE `unique_index`(`name`);

And in case you want to combine two fields to make it unique on the table, you can achieve this by adding more on the last parameter.

ALTER TABLE `table` ADD UNIQUE `unique_index`(`name`, `age`);

Note, just make sure to delete first all the data that has the same name and age value across the other rows.

DELETE table FROM table AS a, table AS b WHERE a.id < b.id 
AND a.name <=> b.name AND a.age <=> b.age;

After that, it should trigger the ON DUPLICATE event.

INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE    
name = VALUES(name), age = VALUES(age)

How to write inside a DIV box with javascript

_x000D_
_x000D_
document.getElementById('log').innerHTML += '<br>Some new content!';
_x000D_
<div id="log">initial content</div>
_x000D_
_x000D_
_x000D_

CSS On hover show another element

we just can show same label div on hovering like this

<style>
#b {
    display: none;
}

#content:hover~#b{
    display: block;
}

</style>

How to check if a variable is both null and /or undefined in JavaScript

A variable cannot be both null and undefined at the same time. However, the direct answer to your question is:

if (variable != null)

One =, not two.

There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null and the other being undefined, and the result is true for == and false for !=. Thus if the value of the variable is undefined, it's not != null, and if it's not null, it's obviously not != null.

Now, the case of an identifier not being defined at all, either as a var or let, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:

var isDefined = false;
try {
  (variable);
  isDefined = true;
}
catch (x) {}

I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window property (in browser JavaScript):

var isJqueryAvailable = window.jQuery != null;

or

var isJqueryAvailable = "jQuery" in window;

NodeJS: How to get the server's port?

With latest node.js (v0.3.8-pre): I checked the documentation, inspected the server instance returned by http.createServer(), and read the source code of server.listen()...

Sadly, the port is only stored temporarily as a local variable and ends up as an argument in a call to process.binding('net').bind() which is a native method. I did not look further.

It seems that there is no better way than keeping a reference to the port value that you provided to server.listen().

Java - Reading XML file

One of the possible implementations:

File file = new File("userdata.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
        .newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
String usr = document.getElementsByTagName("user").item(0).getTextContent();
String pwd = document.getElementsByTagName("password").item(0).getTextContent();

when used with the XML content:

<credentials>
    <user>testusr</user>
    <password>testpwd</password>
</credentials>

results in "testusr" and "testpwd" getting assigned to the usr and pwd references above.

How to force child div to be 100% of parent div's height without specifying parent's height?

After long searching and try, nothing solved my problem except

style = "height:100%;"

on the children div

and for parent apply this

.parent {
    display: flex;
    flex-direction: column;
}

also, I am using bootstrap and this did not corrupt the responsive for me.

Python Function to test ping

It looks like you want the return keyword

def check_ping():
    hostname = "taylor"
    response = os.system("ping -c 1 " + hostname)
    # and then check the response...
    if response == 0:
        pingstatus = "Network Active"
    else:
        pingstatus = "Network Error"

    return pingstatus

You need to capture/'receive' the return value of the function(pingstatus) in a variable with something like:

pingstatus = check_ping()

NOTE: ping -c is for Linux, for Windows use ping -n

Some info on python functions:

http://www.tutorialspoint.com/python/python_functions.htm

http://www.learnpython.org/en/Functions

It's probably worth going through a good introductory tutorial to Python, which will cover all the fundamentals. I recommend investigating Udacity.com and codeacademy.com

How do I force my .NET application to run as administrator?

THIS DOES NOT FORCE APPLICATION TO WORK AS ADMINISTRATOR.
This is a simplified version of the this answer, above by @NG

public bool IsUserAdministrator()
{
    try
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch
    {
        return false;
    }
}

Calling a function in jQuery with click()

$("#closeLink").click(closeIt);

Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);
});

How to change a TextView's style at runtime

I did this by creating a new XML file res/values/style.xml as follows:

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

    <style name="boldText">
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">#FFFFFF</item>
    </style>

    <style name="normalText">
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">#C0C0C0</item>
    </style>

</resources>

I also have an entries in my "strings.xml" file like this:

<color name="highlightedTextViewColor">#000088</color>
<color name="normalTextViewColor">#000044</color>

Then, in my code I created a ClickListener to trap the tap event on that TextView: EDIT: As from API 23 'setTextAppearance' is deprecated

    myTextView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view){
                    //highlight the TextView
                    //myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
    if (Build.VERSION.SDK_INT < 23) {
       myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
    } else {
       myTextView.setTextAppearance(R.style.boldText);
    }
     myTextView.setBackgroundResource(R.color.highlightedTextViewColor);
                }
            });

To change it back, you would use this:

if (Build.VERSION.SDK_INT < 23) {
    myTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
} else{
   myTextView.setTextAppearance(R.style.normalText);
}
myTextView.setBackgroundResource(R.color.normalTextViewColor);

How to get the selected radio button’s value?

Try this

function findSelection(field) {
    var test = document.getElementsByName(field);
    var sizes = test.length;
    alert(sizes);
    for (i=0; i < sizes; i++) {
            if (test[i].checked==true) {
            alert(test[i].value + ' you got a value');     
            return test[i].value;
        }
    }
}


function submitForm() {

    var genderS =  findSelection("genderS");
    alert(genderS);
    return false;
}

A fiddle here.

How do I remove all non alphanumeric characters from a string except dash?

Based on the answer for this question, I created a static class and added these. Thought it might be useful for some people.

public static class RegexConvert
{
    public static string ToAlphaNumericOnly(this string input)
    {
        Regex rgx = new Regex("[^a-zA-Z0-9]");
        return rgx.Replace(input, "");
    }

    public static string ToAlphaOnly(this string input)
    {
        Regex rgx = new Regex("[^a-zA-Z]");
        return rgx.Replace(input, "");
    }

    public static string ToNumericOnly(this string input)
    {
        Regex rgx = new Regex("[^0-9]");
        return rgx.Replace(input, "");
    }
}

Then the methods can be used as:

string example = "asdf1234!@#$";
string alphanumeric = example.ToAlphaNumericOnly();
string alpha = example.ToAlphaOnly();
string numeric = example.ToNumericOnly();

Which exception should I raise on bad/illegal argument combinations in Python?

I would inherit from ValueError

class IllegalArgumentError(ValueError):
    pass

It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible.

If you need to catch that specific error, it is helpful to have a name.

What is the maximum possible length of a query string?

RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).

While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:

  • Microsoft Internet Explorer (Browser)
    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.

  • Microsoft Edge (Browser)
    The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge

  • Chrome
    It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.

  • Firefox (Browser)
    After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.

  • Safari (Browser)
    At least 80,000 characters will work. Testing was not tried beyond that.

  • Opera (Browser)
    At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable, copyable and pasteable URL in the location bar even at 190,000 characters.

  • Apache (Server)
    Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.

  • Microsoft Internet Information Server (Server)
    The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.

  • Perl HTTP::Daemon (Server)
    Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.

How to parse a query string into a NameValueCollection in .NET

There's a built-in .NET utility for this: HttpUtility.ParseQueryString

// C#
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);
' VB.NET
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)

You may need to replace querystring with new Uri(fullUrl).Query.

Add column to dataframe with constant value

Single liner works

df['Name'] = 'abc'

Creates a Name column and sets all rows to abc value

Is it possible to compile a program written in Python?

python compile on the fly when you run it.

Run a .py file by(linux): python abc.py

PHP: How to use array_filter() to filter array keys?

$elements_array = ['first', 'second'];

function to remove some array elements

function remove($arr, $data) {
    return array_filter($arr, function ($element) use ($data) {
        return $element != $data;
    });
}

call and print

print_r(remove($elements_array, 'second'));

the result Array ( [0] => first )

How do I rewrite URLs in a proxy response in NGINX

We should first read the documentation on proxy_pass carefully and fully.

The URI passed to upstream server is determined based on whether "proxy_pass" directive is used with URI or not. Trailing slash in proxy_pass directive means that URI is present and equal to /. Absense of trailing slash means hat URI is absent.

Proxy_pass with URI:

location /some_dir/ {
    proxy_pass http://some_server/;
}

With the above, there's the following proxy:

http:// your_server/some_dir/ some_subdir/some_file ->
http:// some_server/          some_subdir/some_file

Basically, /some_dir/ gets replaced by / to change the request path from /some_dir/some_subdir/some_file to /some_subdir/some_file.

Proxy_pass without URI:

location /some_dir/ {
    proxy_pass http://some_server;
}

With the second (no trailing slash): the proxy goes like this:

http:// your_server /some_dir/some_subdir/some_file ->
http:// some_server /some_dir/some_subdir/some_file

Basically, the full original request path gets passed on without changes.


So, in your case, it seems you should just drop the trailing slash to get what you want.


Caveat

Note that automatic rewrite only works if you don't use variables in proxy_pass. If you use variables, you should do rewrite yourself:

location /some_dir/ {
  rewrite    /some_dir/(.*) /$1 break;
  proxy_pass $upstream_server;
}

There are other cases where rewrite wouldn't work, that's why reading documentation is a must.


Edit

Reading your question again, it seems I may have missed that you just want to edit the html output.

For that, you can use the sub_filter directive. Something like ...

location /admin/ {
    proxy_pass http://localhost:8080/;
    sub_filter "http://your_server/" "http://your_server/admin/";
    sub_filter_once off;
}

Basically, the string you want to replace and the replacement string

fatal: early EOF fatal: index-pack failed

None of these worked for me, but using Heroku's built in tool did the trick.

heroku git:clone -a myapp

Documentation here: https://devcenter.heroku.com/articles/git-clone-heroku-app

PL/SQL print out ref cursor returned by a stored procedure

You can use a bind variable at the SQLPlus level to do this. Of course you have little control over the formatting of the output.

VAR x REFCURSOR;
EXEC GetGrantListByPI(args, :x);
PRINT x;

Using BigDecimal to work with currencies

1) If you are limited to the double precision, one reason to use BigDecimals is to realize operations with the BigDecimals created from the doubles.

2) The BigDecimal consists of an arbitrary precision integer unscaled value and a non-negative 32-bit integer scale, while the double wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double

3) It should make no difference

You should have no difficulties with the $ and precision. One way to do it is using System.out.printf

How to remove an app with active device admin enabled on Android?

On Samsung go to "Settings" -> "Lock screen and security" -> "Other security settings" -> "Phone administrators" and deselect the admin which you want to uninstall.

The "security" word was hidden on my display, so it was not obvious that I should click on "Lock screen".

Count elements with jQuery

use the .size() method or .length attribute

Angular 4 checkbox change value

This it what you are looking for:

<input type="checkbox" [(ngModel)]="isChecked" (change)="checkValue(isChecked?'A':'B')" />

Inside your class:

checkValue(event: any){
   console.log(event);
}

Also include FormsModule in app.module.ts to make ngModel work !

Hope it Helps!

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

The global type Function serves this purpose.

Additionally, if you intend to invoke this callback with 0 arguments and will ignore its return value, the type () => void matches all functions taking no arguments.


Update with details and improvements.

The answer and question here has way too many updoots not to mention the only-slightly more complex yet best-practice method:

Solution to your question

interface Easy_Fix_Solution {
    title: string;
    callback: Function;
}

NOTE: Please do not use Function as you most likely do not want any callback function. It's okay to be a little specific.

Improvement to that solution

interface Safer_Easy_Fix {
    title: string;
    callback: () => void;
}
interface Alternate_Syntax_4_Safer_Easy_Fix {
    title: string;
    callback(): void;
}

NOTE: The original author is correct, accepting no arguments and returning void is better.. it's much safer, it tells the consumer of your interface that you will not be doing anything with their return value, and that you will not be passing them any parameters.

And better yet Use generics. This interface would also work for the same () => void function types mentioned before.

interface Better_still_safe_but_way_more_flexible_fix {
    title: string;
    callback: <T = unknown, R = unknown>(args?: T) => R;
}
interface Alternate_Syntax_4_Better_still_safe_but_way_more_flexible_fix {
    title: string;
    callback<T = unknown, R = unknown>(args?: T): R;
}

NOTE: If you aren't 100% sure about the callback signature right now, please choose the void option above, or this generic option if you think you may extend functionality going forward. Callbacks usually receive some arguments of some sort, and sometimes the callback orchestrator even does something with the return value.

And a slightly more advanced usecase you shouldn't use unless you need it

This allows any number of arguments, of any type in T.

More details here.

interface Alternate_Syntax_4_Advanced {
    title: string;
    callback<T extends unknown[], R = unknown>(...args?: T): R;
}

CSS Cell Margin

Apply this to your first <td>:

padding-right:10px;

HTML example:

<table>
   <tr>
      <td style="padding-right:10px">data</td>
      <td>more data</td>
   </tr>
</table>

Matplotlib scatter plot legend

Other answers seem a bit complex, you can just add a parameter 'label' in scatter function and that will be the legend for your plot.

import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

lo = plt.scatter(random(10), random(10), marker='x', color=colors[0],label='Low Outlier')
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0],label='LoLo')
l  = plt.scatter(random(10), random(10), marker='o', color=colors[1],label='Lo')
a  = plt.scatter(random(10), random(10), marker='o', color=colors[2],label='Average')
h  = plt.scatter(random(10), random(10), marker='o', color=colors[3],label='Hi')
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4],label='HiHi')
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4],label='High Outlier')

plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
          fancybox=True, shadow=True, ncol=4)

plt.show()

This is your output:

img

Python matplotlib multiple bars

import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime

x = [
    datetime.datetime(2011, 1, 4, 0, 0),
    datetime.datetime(2011, 1, 5, 0, 0),
    datetime.datetime(2011, 1, 6, 0, 0)
]
x = date2num(x)

y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]

ax = plt.subplot(111)
ax.bar(x-0.2, y, width=0.2, color='b', align='center')
ax.bar(x, z, width=0.2, color='g', align='center')
ax.bar(x+0.2, k, width=0.2, color='r', align='center')
ax.xaxis_date()

plt.show()

enter image description here

I don't know what's the "y values are also overlapping" means, does the following code solve your problem?

ax = plt.subplot(111)
w = 0.3
ax.bar(x-w, y, width=w, color='b', align='center')
ax.bar(x, z, width=w, color='g', align='center')
ax.bar(x+w, k, width=w, color='r', align='center')
ax.xaxis_date()
ax.autoscale(tight=True)

plt.show()

enter image description here

How to see the values of a table variable at debug time in T-SQL?

I have come to the conclusion that this is not possible without any plugins.

How to check if String value is Boolean type in Java?

Actually, checking for a Boolean type in a String (which is a type) is impossible. Basically you're asking how to do a 'string compare'.

Like others stated. You need to define when you want to return "true" or "false" (under what conditions). Do you want it to be case(in)sensitive? What if the value is null?

I think Boolean.valueOf() is your friend, javadoc says:

Returns a Boolean with a value represented by the specified String. The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

Example: Boolean.valueOf("True") returns true.
Example: Boolean.valueOf("yes") returns false.

iterating through Enumeration of hastable keys throws NoSuchElementException error

for (String key : Collections.list(e))
    System.out.println(key);

Git: list only "untracked" files (also, custom commands)

To list untracked files try:

git ls-files --others --exclude-standard

If you need to pipe the output to xargs, it is wise to mind white spaces using git ls-files -z and xargs -0:

git ls-files -z -o --exclude-standard | xargs -0 git add

Nice alias for adding untracked files:

au = !git add $(git ls-files -o --exclude-standard)

Edit: For reference: git-ls-files

JSON.net: how to deserialize without using the default constructor?

Json.Net prefers to use the default (parameterless) constructor on an object if there is one. If there are multiple constructors and you want Json.Net to use a non-default one, then you can add the [JsonConstructor] attribute to the constructor that you want Json.Net to call.

[JsonConstructor]
public Result(int? code, string format, Dictionary<string, string> details = null)
{
    ...
}

It is important that the constructor parameter names match the corresponding property names of the JSON object (ignoring case) for this to work correctly. You do not necessarily have to have a constructor parameter for every property of the object, however. For those JSON object properties that are not covered by the constructor parameters, Json.Net will try to use the public property accessors (or properties/fields marked with [JsonProperty]) to populate the object after constructing it.

If you do not want to add attributes to your class or don't otherwise control the source code for the class you are trying to deserialize, then another alternative is to create a custom JsonConverter to instantiate and populate your object. For example:

class ResultConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Result));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Load the JSON for the Result into a JObject
        JObject jo = JObject.Load(reader);

        // Read the properties which will be used as constructor parameters
        int? code = (int?)jo["Code"];
        string format = (string)jo["Format"];

        // Construct the Result object using the non-default constructor
        Result result = new Result(code, format);

        // (If anything else needs to be populated on the result object, do that here)

        // Return the result
        return result;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Then, add the converter to your serializer settings, and use the settings when you deserialize:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new ResultConverter());
Result result = JsonConvert.DeserializeObject<Result>(jsontext, settings);

Facebook page automatic "like" URL (for QR Code)

In my opinion, it is not possible for the like button (and I hope it is not possible).

But, you can trigger a custom OpenGraph v2 action, or display a like button linked to your facebook page.

How to add elements to an empty array in PHP?

$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"[email protected]"));
echo "<pre>";
echo json_encode($products_arr,JSON_PRETTY_PRINT);
echo "</pre>";

//OR

$countries = array();
$countries["DK"] = array("code"=>"DK","name"=>"Denmark","d_code"=>"+45");
$countries["DJ"] = array("code"=>"DJ","name"=>"Djibouti","d_code"=>"+253");
$countries["DM"] = array("code"=>"DM","name"=>"Dominica","d_code"=>"+1");
foreach ($countries as $country){
echo "<pre>";
echo print_r($country);
echo "</pre>";
}

Current date without time

it should be as simple as

DateTime.Today

How do I include negative decimal numbers in this regular expression?

This will allow both positive and negative integers

ValidationExpression="^-?[0-9]\d*(\d+)?$"

How to get the innerHTML of selectable jquery element?

Use .val() instead of .innerHTML for getting value of selected option

Use .text() for getting text of selected option

Thanks for correcting :)

Serializing/deserializing with memory stream

BinaryFormatter may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.

If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer or XmlSerializer.

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

Notice: Undefined offset: 0 in

getAllVotes() isn't returning an array with the indexes 0 or 1. Make sure it's returning the data you want by calling var_dump() on the result.

How to indent a few lines in Markdown markup?

Check if you can use HTML with your markdown. Maybe this works out for you:

  • List entry one<br/>
    Indented line<br/>
    <br/>
    And some more..
  • Second entry
    • Subentry<br/>
      Hello there!

git am error: "patch does not apply"

I had the same problem. I had used

git format-patch <commit_hash>

to create the patch. My main problem was patch was failing due to some conflicts, but I could not see any merge conflict in the file content. I had used git am --3way <patch_file_path> to apply the patch.

The correct command to apply the patch should be:

git am --3way --ignore-space-change <patch_file_path>

If you execute the above command for patching, it will create a merge conflict if patch apply fails. Then you can fix the conflict in your files, like the same way merge conflicts are resolved for git merge

Jenkins pipeline how to change to another folder

Use WORKSPACE environment variable to change workspace directory.

If doing using Jenkinsfile, use following code :

dir("${env.WORKSPACE}/aQA"){
    sh "pwd"
}

Is there a better jQuery solution to this.form.submit();?

Your question in somewhat confusing in that that you don't explain what you mean by "current element".

If you have multiple forms on a page with all kinds of input elements and a button of type "submit", then hitting "enter" upon filling any of it's fields will trigger submission of that form. You don't need any Javascript there.

But if you have multiple "submit" buttons on a form and no other inputs (e.g. "edit row" and/or "delete row" buttons in table), then the line you posted could be the way to do it.

Another way (no Javascript needed) could be to give different values to all your buttons (that are of type "submit"). Like this:

<form action="...">
    <input type="hidden" name="rowId" value="...">
    <button type="submit" name="myaction" value="edit">Edit</button>
    <button type="submit" name="myaction" value="delete">Delete</button>
</form>

When you click a button only the form containing the button will be submitted, and only the value of the button you hit will be sent (along other input values).

Then on the server you just read the value of the variable "myaction" and decide what to do.

Adding values to an array in java

You always set x to 0 before changing array's value.

You can use:

int[] tall = new int[28123];

for (int j = 0;j<28123;j++){
    // Or whatever value you want to set.
    tall[j] = j + 1;
}

Or just remove the initialization of x (int x=0) before the for loop.

What is the difference between Nexus and Maven?

This has a good general description: https://gephi.wordpress.com/tag/maven/

Let me make a few statement that can put the difference in focus:

  1. We migrated our code base from Ant to Maven

  2. All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.

  3. Basic functionalities of a repository manager like Sonatype are:

    • Managing project dependencies,
    • Artifacts & Metadata,
    • Proxying external repositories
    • and deployment of packaged binaries and JARs to share those artifacts with other developers and end-users.

Oracle insert if not exists statement

MERGE INTO OPT
USING
    (SELECT 1 "one" FROM dual) 
ON
    (OPT.email= '[email protected]' and OPT.campaign_id= 100) 
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('[email protected]',100) 
;

Popup Message boxes

Ok, SO Basically I think I have a simple and effective solution.

package AnotherPopUpMessage;
import javax.swing.JOptionPane;
public class AnotherPopUp {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JOptionPane.showMessageDialog(null, "Again? Where do all these come from?", 
            "PopUp4", JOptionPane.CLOSED_OPTION);
    }
}

did you specify the right host or port? error on Kubernetes

Reinitialising gcloud with proper account and project worked for me.

gcloud init

After this retrying the below command was successful and kubeconfig entry was generated.

gcloud container clusters get-credentials "cluster_name"

check the cluster info with

kubectl cluster-info

adding text to an existing text element in javascript via DOM

What about this.

_x000D_
_x000D_
var p = document.getElementById("p")_x000D_
p.innerText = p.innerText+" And this is addon."
_x000D_
<p id ="p">This is some text</p>
_x000D_
_x000D_
_x000D_

Why am I getting error CS0246: The type or namespace name could not be found?

i also faced same problem,

Reason: why i faced this error is, rather then creating new partial view, i have created class and then renamed its extension from ".cs" to ".cshtml".

Solution: Just delete that rename view and re-create proper partial/full view. it will work fine after that.

HashMap allows duplicates?

Code example:

HashMap<Integer,String> h = new HashMap<Integer,String> ();

h.put(null,null);
h.put(null, "a");

System.out.println(h);

Output:

{null=a}

It overrides the value at key null.

Java out.println() how is this possible?

@sfussenegger's answer explains how to make this work. But I'd say don't do it!

Experienced Java programmers use, and expect to see

        System.out.println(...);

and not

        out.println(...);

A static import of System.out or System.err is (IMO) bad style because:

  • it breaks the accepted idiom, and
  • it makes it harder to track down unwanted trace prints that were added during testing and not removed.

If you find yourself doing lots of output to System.out or System.err, I think it is a better to abstract the streams into attributes, local variables or methods. This will make your application more reusable.

Split list into smaller lists (split in half)

10 years later.. I thought - why not add another:

arr = 'Some random string' * 10; n = 4
print([arr[e:e+n] for e in range(0,len(arr),n)])

SaveFileDialog setting default path and file type?

The SaveFileDialog control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.

  1. Set the property InitialDirectory to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.

  2. That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).

Just as a quick example (there are alternative ways to do it). savefile is a control of type SaveFileDialog

SaveFileDialog savefile = new SaveFileDialog(); 
// set a default file name
savefile.FileName = "unknown.txt";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

if (savefile.ShowDialog() == DialogResult.OK)
{
    using (StreamWriter sw = new StreamWriter(savefile.FileName))
        sw.WriteLine ("Hello World!");
}

lambda expression join multiple tables with select and where clause

If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):

    var UserInRole = db.UserProfiles.
        Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
        (u, uir) => new { u, uir }).
        Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
        .Where(m => m.r.u.UserId == 1)
        .Select (m => new AddUserToRole
        {
            UserName = m.r.u.UserName,
            RoleName = m.ro.RoleName
        });

Hope that helps.

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

Would the use of <caption> be allowed?

<ul>
  <caption> Title of List </caption>
  <li> Item 1 </li>
  <li> Item 2 </li>
</ul>

What does template <unsigned int N> mean?

You templatize your class based on an 'unsigned int'.

Example:

template <unsigned int N>
class MyArray
{
    public:
    private:
        double    data[N]; // Use N as the size of the array
};

int main()
{
    MyArray<2>     a1;
    MyArray<2>     a2;

    MyArray<4>     b1;

    a1 = a2;  // OK The arrays are the same size.
    a1 = b1;  // FAIL because the size of the array is part of the
              //      template and thus the type, a1 and b1 are different types.
              //      Thus this is a COMPILE time failure.
 }

how to delete a specific row in codeigniter?

a simple way:

in view(pass the id value):

<td><?php echo anchor('textarea/delete_row?id='.$row->id, 'DELETE', 'id="$row->id"'); ?></td>

in controller(receive the id):

$id = $this->input->get('id');
$this->load->model('mod1');
$this->mod1->row_delete($id);

in model(get the passed args):

function row_delete($id){}

Actually, you should use the ajax to POST the id value to controller and delete the row, not the GET.

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

Normally we face this issue when there is a problem mapping JSON node with that of Java object. I faced the same issue because in the swagger the node was defined as of Type array and the JSON object was having only one element , hence the system was having difficulty in mapping one element list to an array.

In Swagger the element was defined as

Test:
 "type": "array",
 "minItems": 1,
 "items": {
   "$ref": "#/definitions/TestNew"
  }

While it should be

Test:
    "$ref": "#/definitions/TestNew"

And TestNew should be of type array

Spring MVC @PathVariable with dot (.) is getting truncated

Spring considers that anything behind the last dot is a file extension such as .jsonor .xml and trucate it to retrieve your parameter.

So if you have /somepath/{variable} :

  • /somepath/param, /somepath/param.json, /somepath/param.xml or /somepath/param.anything will result in a param with value param
  • /somepath/param.value.json, /somepath/param.value.xml or /somepath/param.value.anything will result in a param with value param.value

if you change your mapping to /somepath/{variable:.+} as suggested, any dot, including the last one will be consider as part of your parameter :

  • /somepath/param will result in a param with value param
  • /somepath/param.json will result in a param with value param.json
  • /somepath/param.xml will result in a param with value param.xml
  • /somepath/param.anything will result in a param with value param.anything
  • /somepath/param.value.json will result in a param with value param.value.json
  • ...

If you don't care of extension recognition, you can disable it by overriding mvc:annotation-driven automagic :

<bean id="handlerMapping"
      class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    <property name="contentNegotiationManager" ref="contentNegotiationManager"/>
    <property name="useSuffixPatternMatch" value="false"/>
</bean>

So, again, if you have /somepath/{variable} :

  • /somepath/param, /somepath/param.json, /somepath/param.xml or /somepath/param.anything will result in a param with value param
  • /somepath/param.value.json, /somepath/param.value.xml or /somepath/param.value.anything will result in a param with value param.value

note : the difference from the default config is visible only if you have a mapping like somepath/something.{variable}. see Resthub project issue

if you want to keep extension management, since Spring 3.2 you can also set the useRegisteredSuffixPatternMatch property of RequestMappingHandlerMapping bean in order to keep suffixPattern recognition activated but limited to registered extension.

Here you define only json and xml extensions :

<bean id="handlerMapping"
      class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    <property name="contentNegotiationManager" ref="contentNegotiationManager"/>
    <property name="useRegisteredSuffixPatternMatch" value="true"/>
</bean>

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false"/>
    <property name="favorParameter" value="true"/>
    <property name="mediaTypes">
        <value>
            json=application/json
            xml=application/xml
        </value>
    </property>
</bean>

Note that mvc:annotation-driven accepts now a contentNegotiation option to provide a custom bean but the property of RequestMappingHandlerMapping has to be changed to true (default false) (cf. https://jira.springsource.org/browse/SPR-7632).

For that reason, you still have to override the all mvc:annotation-driven configuration. I opened a ticket to Spring to ask for a custom RequestMappingHandlerMapping : https://jira.springsource.org/browse/SPR-11253. Please vote if you are intereted in.

While overriding, be carreful to consider also custom Execution management overriding. Otherwise, all your custom Exception mappings will fail. You will have to reuse messageCoverters with a list bean :

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />

<util:list id="messageConverters">
    <bean class="your.custom.message.converter.IfAny"></bean>
    <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"></bean>
    <bean class="org.springframework.http.converter.StringHttpMessageConverter"></bean>
    <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"></bean>
    <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"></bean>
    <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"></bean>
    <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"></bean>
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
</util:list>

<bean name="exceptionHandlerExceptionResolver"
      class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver">
    <property name="order" value="0"/>
    <property name="messageConverters" ref="messageConverters"/>
</bean>

<bean name="handlerAdapter"
      class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="webBindingInitializer">
        <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
            <property name="conversionService" ref="conversionService" />
            <property name="validator" ref="validator" />
        </bean>
    </property>
    <property name="messageConverters" ref="messageConverters"/>
</bean>

<bean id="handlerMapping"
      class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
</bean>

I implemented, in the open source project Resthub that I am part of, a set of tests on these subjects : see https://github.com/resthub/resthub-spring-stack/pull/219/files & https://github.com/resthub/resthub-spring-stack/issues/217

Setting PHP tmp dir - PHP upload not working

My problem was selinux...

Go sestatus

If Current mode: enforcing

Then chcon -R -t httpd_sys_rw_content_t /var/www/html

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

You can also do

t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')

as in the Ruby on Rails API.

Is it correct to use DIV inside FORM?

You can use a <div> within a form - there is no problem there .... BUT if you are going to use the <div> as the label for the input dont ... label is a far better option :

<label for="myInput">My Label</label> 
<input type="textbox" name="MyInput" value="" />

get dataframe row count based on conditions

You are asking for the condition where all the conditions are true, so len of the frame is the answer, unless I misunderstand what you are asking

In [17]: df = DataFrame(randn(20,4),columns=list('ABCD'))

In [18]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)]
Out[18]: 
           A         B         C         D
12  0.491683  0.137766  0.859753 -1.041487
13  0.376200  0.575667  1.534179  1.247358
14  0.428739  1.539973  1.057848 -1.254489

In [19]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)].count()
Out[19]: 
A    3
B    3
C    3
D    3
dtype: int64

In [20]: len(df[(df['A']>0) & (df['B']>0) & (df['C']>0)])
Out[20]: 3

Table scroll with HTML and CSS

For those wondering how to implement Garry's solution with more than one header this is it:

_x000D_
_x000D_
#wrapper {_x000D_
  width: 235px;_x000D_
}_x000D_
_x000D_
table {_x000D_
  border: 1px solid black;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
th,_x000D_
td {_x000D_
  width: 100px;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
thead>tr {_x000D_
  position: relative;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
tbody {_x000D_
  display: block;_x000D_
  height: 80px;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>column1</th>_x000D_
        <th>column2</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>row1</td>_x000D_
        <td>row1</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>row2</td>_x000D_
        <td>row2</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>row3</td>_x000D_
        <td>row3</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>row4</td>_x000D_
        <td>row4</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

how to make div click-able?

If this div is a function I suggest use cursor:pointer in your style like style="cursor:pointer" and can use onclick function.

like this

<div onclick="myfunction()" style="cursor:pointer"></div>

but I suggest you use a JS framework like jquery or extjs

Select All Rows Using Entity Framework

You can simply iterate through the DbSet context.tablename

foreach(var row in context.tablename)
  Console.WriteLn(row.field);

or to evaluate immediately into your own list

var allRows = context.tablename.ToList();

How to set cookies in laravel 5 independently inside controller

Here is a sample code with explanation.

 //Create a response instance
 $response = new Illuminate\Http\Response('Hello World');

 //Call the withCookie() method with the response method
 $response->withCookie(cookie('name', 'value', $minutes));

 //return the response
 return $response;

Cookie can be set forever by using the forever method as shown in the below code.

$response->withCookie(cookie()->forever('name', 'value'));

Retrieving a Cookie

//’name’ is the name of the cookie to retrieve the value of
$value = $request->cookie('name');

How to replace all occurrences of a string in Javascript?

str = str.replace(/abc/g, '');

Or try the replaceAll function from here:

What are useful JavaScript methods that extends built-in objects?

str = str.replaceAll('abc', ''); OR

var search = 'abc';
str = str.replaceAll(search, '');

EDIT: Clarification about replaceAll availability

The 'replaceAll' method is added to String's prototype. This means it will be available for all string objects/literals.

E.g.

var output = "test this".replaceAll('this', 'that');  //output is 'test that'.
output = output.replaceAll('that', 'this'); //output is 'test this'

Android set height and width of Custom view programmatically

You can set height and width like this:

myGraphView.setLayoutParams(new LayoutParams(width, height));

error_log per Virtual Host?

Create Simple VirtualHost:

example hostname:- thecontrolist.localhost

  1. C:\Windows\System32\drivers\etc

    127.0.0.1 thecontrolist.localhost in hosts file

  2. C:\xampp\apache\conf\extra\httpd-vhosts.conf

    <VirtualHost *>
      ServerName thecontrolist.localhost
      ServerAlias thecontrolist.localhost
      DocumentRoot "/xampp/htdocs/thecontrolist"
      <Directory "/xampp/htdocs/thecontrolist">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
      </Directory>
    </VirtualHost>
    
  3. Don't Forget to restart Your apache. for more check this link

concat scope variables into string in angular directive expression

<a ngHref="/path/{{obj.val1}}/{{obj.val2}}">{{obj.val1}}, {{obj.val2}}</a>

Convert String to Double - VB

Dim text As String = "123.45"
Dim value As Double
If Double.TryParse(text, value) Then
    ' text is convertible to Double, and value contains the Double value now
Else
    ' Cannot convert text to Double
End If

Java error: Only a type can be imported. XYZ resolves to a package

Without further details, it sounds like an error in the import declaration of a class. Check, if all import declarations either import all classes from a package or a single class:

import all.classes.from.package.*;
import only.one.type.named.MyClass;

Edit

OK, after the edit, looks like it's a jsp problem.

Edit 2

Here is another forum entry, the problem seems to have similarities and the victim solved it by reinstalling eclipse. I'd try that one first - installing a second instance of eclipse with only the most necessary plugins, a new workspace, the project imported into that clean workspace, and hope for the best...

Batch / Find And Edit Lines in TXT file

If you are on Windows, you can use FART (Find And Replace Text). It is only 1 single *.exe file (no library needed).

All you need to is run:

fart.exe your_batch_file.bat ex3 ex5

How to force Laravel Project to use HTTPS for all routes?

Here are several ways. Choose most convenient.

  1. Configure your web server to redirect all non-secure requests to https. Example of a nginx config:

    server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name example.com www.example.com;
        return 301 https://example.com$request_uri;
    }
    
  2. Set your environment variable APP_URL using https:

    APP_URL=https://example.com
    
  3. Use helper secure_url() (Laravel5.6)

  4. Add following string to AppServiceProvider::boot() method (for version 5.4+):

    \Illuminate\Support\Facades\URL::forceScheme('https');
    

Update:

  1. Implicitly setting scheme for route group (Laravel5.6):

    Route::group(['scheme' => 'https'], function () {
        // Route::get(...)->name(...);
    });
    

Can two or more people edit an Excel document at the same time?

The new version of SharePoint and Office (SharePoint 2010 and Office 2010) respectively are supposed to allow for this. This also includes the web based versions. I have seen Word and Excel in action do this, not sure about other client applications.

I am not sure about the specific implementation features you are asking about in terms of security though. Sorry.,=

Here is a discussion

http://blogs.msdn.com/b/sharepoint/archive/2009/10/19/sharepoint-2010.aspx

Link to add to Google calendar

There is a comprehensive doc for google calendar and other calendar services: https://github.com/InteractionDesignFoundation/add-event-to-calendar-docs/blob/master/services/google.md

An example of working link: https://calendar.google.com/calendar/render?action=TEMPLATE&text=Bithday&dates=20201231T193000Z/20201231T223000Z&details=With%20clowns%20and%20stuff&location=North%20Pole

How to execute an oracle stored procedure?

Execute is sql*plus syntax .. try wrapping your call in begin .. end like this:

begin 
    temp_proc;
end;

(Although Jeffrey says this doesn't work in APEX .. but you're trying to get this to run in SQLDeveloper .. try the 'Run' menu there.)

How do I check my gcc C++ compiler version for my Eclipse?

gcc -dumpversion

-dumpversion Print the compiler version (for example, 3.0) — and don't do anything else.

The same works for following compilers/aliases:

cc -dumpversion
g++ -dumpversion
clang -dumpversion
tcc -dumpversion

Be careful with automate parsing the GCC output:

  • Output of --version might be localized (e.g. to Russian, Chinese, etc.)
  • GCC might be built with option --with-gcc-major-version-only. And some distros (e.g. Fedora) are already using that
  • GCC might be built with option --with-pkgversion. And --version output will contain something like Android (5220042 based on r346389c) clang version 8.0.7 (it's real version string)

Sending XML data using HTTP POST with PHP

Another option would be file_get_contents():

// $xml_str = your xml
// $url = target url

$post_data = array('xml' => $xml_str);
$stream_options = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
        'content' =>  http_build_query($post_data)));

$context  = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);

How to specify different Debug/Release output directories in QMake .pro file

The new version of Qt Creator also has a "profile" build option between debug and release. Here's how I'm detecting that:

CONFIG(debug, debug|release) {  DEFINES += DEBUG_MODE }
else:CONFIG(force_debug_info) { DEFINES += PROFILE_MODE }
else {                          DEFINES += RELEASE_MODE }

Which is the fastest algorithm to find prime numbers?

#include<stdio.h>
main()
{
    long long unsigned x,y,b,z,e,r,c;
    scanf("%llu",&x);
    if(x<2)return 0;
    scanf("%llu",&y);
    if(y<x)return 0;
    if(x==2)printf("|2");
    if(x%2==0)x+=1;
    if(y%2==0)y-=1;
    for(b=x;b<=y;b+=2)
    {
        z=b;e=0;
        for(c=2;c*c<=z;c++)
        {
            if(z%c==0)e++;
            if(e>0)z=3;
        }
        if(e==0)
        {
            printf("|%llu",z);
            r+=1;
        }
    }
    printf("|\n%llu outputs...\n",r);
    scanf("%llu",&r);
}    

Rename multiple columns by names

Lot's of sort-of-answers, so I just wrote the function so you can copy/paste.

rename <- function(x, old_names, new_names) {
    stopifnot(length(old_names) == length(new_names))
    # pull out the names that are actually in x
    old_nms <- old_names[old_names %in% names(x)]
    new_nms <- new_names[old_names %in% names(x)]

    # call out the column names that don't exist
    not_nms <- setdiff(old_names, old_nms)
    if(length(not_nms) > 0) {
        msg <- paste(paste(not_nms, collapse = ", "), 
            "are not columns in the dataframe, so won't be renamed.")
        warning(msg)
    }

    # rename
    names(x)[names(x) %in% old_nms] <- new_nms
    x
}

 x = data.frame(q = 1, w = 2, e = 3)
 rename(x, c("q", "e"), c("Q", "E"))

   Q w E
 1 1 2 3

Hot to get all form elements values using jQuery?

The answer already been accepted, I just write a short technique for the same purpose.

var fieldPair = '';
$(":input").each(function(){
fieldPair += $(this).attr("name") + ':' + $(this).val() + ';';
});

console.log(fieldPair);

How to convert the following json string to java object?

Check out Google's Gson: http://code.google.com/p/google-gson/

From their website:

Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

You would just need to make a MyType class (renamed, of course) with all the fields in the json string. It might get a little more complicated when you're doing the arrays, if you prefer to do all of the parsing manually (also pretty easy) check out http://www.json.org/ and download the Java source for the Json parser objects.

How to solve "The specified service has been marked for deletion" error

I had the same problem, finally I decide to kill service process.

for it try below steps:

  • get process id of service with

    sc queryex <service name>

  • kill process with

    taskkill /F /PID <Service PID>

Keyword not supported: "data source" initializing Entity Framework Context

Just use \" instead ", it should resolve the issue.

Jenkins returned status code 128 with github

I deleted my project (root folder) and created it again. It was the fastest and simplest way in my case.

Do not forget to save all you changes, before you delete you project!

Set Locale programmatically

Add a helper class with the following method:

public class LanguageHelper {
    public static final void setAppLocale(String language, Activity activity) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Resources resources = activity.getResources();
            Configuration configuration = resources.getConfiguration();
            configuration.setLocale(new Locale(language));
            activity.getApplicationContext().createConfigurationContext(configuration);
        } else {
            Locale locale = new Locale(language);
            Locale.setDefault(locale);
            Configuration config = activity.getResources().getConfiguration();
            config.locale = locale;
            activity.getResources().updateConfiguration(config,
                    activity.getResources().getDisplayMetrics());
        }

    }
}

And call it in your startup activity, like MainActivity.java:

public void onCreate(Bundle savedInstanceState) {
    ...
    LanguageHelper.setAppLocale("fa", this);
    ...
}

Android "Only the original thread that created a view hierarchy can touch its views."

For the people struggling in Kotlin, it works like this:

lateinit var runnable: Runnable //global variable

 runOnUiThread { //Lambda
            runnable = Runnable {

                //do something here

                runDelayedHandler(5000)
            }
        }

        runnable.run()

 //you need to keep the handler outside the runnable body to work in kotlin
 fun runDelayedHandler(timeToWait: Long) {

        //Keep it running
        val handler = Handler()
        handler.postDelayed(runnable, timeToWait)
    }

FFmpeg: How to split video efficiently?

Didn't test ist, but this looks promising:

Basic stream segmenter

It is obviously splitting AVI into segments of same size, which implies these chunks don't loose quality or increase memory or must be recalculated.

It also uses the codec copy - does that mean it can handle very large streams ? Because this is my problem, i want to break down my avi so i could use a filter to get rid of the distorsion. But a whole avi runs for hours.

"SyntaxError: Unexpected token < in JSON at position 0"

My problem was that I was getting the data back in a string which was not in a proper JSON format, which I was then trying to parse it. simple example: JSON.parse('{hello there}') will give an error at h. In my case the callback url was returning an unnecessary character before the objects: employee_names([{"name":.... and was getting error at e at 0. My callback URL itself had an issue which when fixed, returned only objects.

Java: parse int value from a char

Using binary AND with 0b1111:

String element = "el5";

char c = element.charAt(2);

System.out.println(c & 0b1111); // => '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5

// '0' & 0b1111 => 0b0011_0000 & 0b0000_1111 => 0
// '1' & 0b1111 => 0b0011_0001 & 0b0000_1111 => 1
// '2' & 0b1111 => 0b0011_0010 & 0b0000_1111 => 2
// '3' & 0b1111 => 0b0011_0011 & 0b0000_1111 => 3
// '4' & 0b1111 => 0b0011_0100 & 0b0000_1111 => 4
// '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5
// '6' & 0b1111 => 0b0011_0110 & 0b0000_1111 => 6
// '7' & 0b1111 => 0b0011_0111 & 0b0000_1111 => 7
// '8' & 0b1111 => 0b0011_1000 & 0b0000_1111 => 8
// '9' & 0b1111 => 0b0011_1001 & 0b0000_1111 => 9

Get the last non-empty cell in a column in Google Sheets

for a row:

=ARRAYFORMULA(INDIRECT("A"&MAX(IF(A:A<>"", ROW(A:A), ))))

for a column:

=ARRAYFORMULA(INDIRECT(ADDRESS(1, MAX(IF(1:1<>"", COLUMN(1:1), )), 4)))

How can I save multiple documents concurrently in Mongoose/Node.js?

Mongoose 4.4 added a method called insertMany

Shortcut for validating an array of documents and inserting them into MongoDB if they're all valid. This function is faster than .create() because it only sends one operation to the server, rather than one for each document.

Quoting vkarpov15 from issue #723:

The tradeoffs are that insertMany() doesn't trigger pre-save hooks, but it should have better performance because it only makes 1 round-trip to the database rather than 1 for each document.

The method's signature is identical to create:

Model.insertMany([ ... ], (err, docs) => {
  ...
})

Or, with promises:

Model.insertMany([ ... ]).then((docs) => {
  ...
}).catch((err) => {
  ...
})

jQuery - checkbox enable/disable

Change your markup slightly:

_x000D_
_x000D_
$(function() {_x000D_
  enable_cb();_x000D_
  $("#group1").click(enable_cb);_x000D_
});_x000D_
_x000D_
function enable_cb() {_x000D_
  if (this.checked) {_x000D_
    $("input.group1").removeAttr("disabled");_x000D_
  } else {_x000D_
    $("input.group1").attr("disabled", true);_x000D_
  }_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form name="frmChkForm" id="frmChkForm">_x000D_
  <input type="checkbox" name="chkcc9" id="group1">Check Me <br>_x000D_
  <input type="checkbox" name="chk9[120]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[140]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[150]" class="group1"><br>_x000D_
</form>
_x000D_
_x000D_
_x000D_

You can do this using attribute selectors without introducing the ID and classes but it's slower and (imho) harder to read.

SQL where datetime column equals today's date?

To get all the records where record created date is today's date Use the code after WHERE clause

WHERE  CAST(Submission_date AS DATE) = CAST( curdate() AS DATE)

MySQL string replace

UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/')
WHERE your_field LIKE '%articles/updates/%'

Now rows that were like

http://www.example.com/articles/updates/43

will be

http://www.example.com/articles/news/43

http://www.electrictoolbox.com/mysql-find-replace-text/

XAMPP Port 80 in use by "Unable to open process" with PID 4

Your port 80 is being used by the system.

  1. In Windows “World Wide Publishing" Service is using this port and it's process is system which PID is 4 maximum time and stopping this service(“World Wide Publishing") will free the port 80 and you can connect Apache using this port. To stop the service go to the “Task manager –> Services tab”, right click the “World Wide Publishing Service” and stop.
  2. If you don't find there then Then go to "Run > services.msc" and again find there and right click the “World Wide Publishing Service” and stop.
  3. If you didn't find “World Wide Publishing Service” there then go to "Run>>resmon.exe>> Network Tab>>Listening Ports" and see which process is using port 80

enter image description here

And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.

Video auto play is not working in Safari and Chrome desktop browser

I started out with playing all the visible videos, but old phones weren't performing well. So right now I play the one video that's closest to the center of the window and pause the rest. Vanilla JS. You can pick which algorithm you prefer.

//slowLooper(playAllVisibleVideos);
slowLooper(playVideoClosestToCenter);

function isVideoPlaying(elem) {
    if (elem.paused || elem.ended || elem.readyState < 2) {
        return false;
    } else {
        return true;
    }
}
function isScrolledIntoView(el) {
    var elementTop = el.getBoundingClientRect().top;
    var elementBottom = el.getBoundingClientRect().bottom;
    var isVisible = elementTop < window.innerHeight && elementBottom >= 0;
    return isVisible;
}
function playVideoClosestToCenter() {
    var vids = document.querySelectorAll('video');
    var smallestDistance = null;
    var smallestDistanceI = null;
    for (var i = 0; i < vids.length; i++) {
        var el = vids[i];
        var elementTop = el.getBoundingClientRect().top;
        var elementBottom = el.getBoundingClientRect().bottom;
        var elementCenter = (elementBottom + elementTop) / 2.0;
        var windowCenter = window.innerHeight / 2.0;
        var distance = Math.abs(windowCenter - elementCenter);
        if (smallestDistance === null || distance < smallestDistance) {
            smallestDistance = distance;
            smallestDistanceI = i;
        }
    }
    if (smallestDistanceI !== null) {
        vids[smallestDistanceI].play();
        for (var i = 0; i < vids.length; i++) {
            if (i !== smallestDistanceI) {
                vids[i].pause();
            }
        }
    }
}
function playAllVisibleVideos(timestamp) {
    // This fixes autoplay for safari
    var vids = document.querySelectorAll('video');
    for (var i = 0; i < vids.length; i++) {
        if (isVideoPlaying(vids[i]) && !isScrolledIntoView(vids[i])) {
            vids[i].pause();
        }
        if (!isVideoPlaying(vids[i]) && isScrolledIntoView(vids[i])) {
            vids[i].play();
        }
    }
}
function slowLooper(cb) {
    // Throttling requestAnimationFrame to a few fps so we don't waste cpu on this
    // We could have listened to scroll+resize+load events which move elements
    // but that would have been more complicated.
    function repeats() {
        cb();
        setTimeout(function() {
            window.requestAnimationFrame(repeats);
        }, 200);
    }
    repeats();
}

mongo - couldn't connect to server 127.0.0.1:27017

This was happening with me today and I resolved it in following way.

Machine: I'm using Windows 10 machine and downloaded the latest MongoDB - Community edition.

So, the problem was, I did not have C:\data\db created.

Without creating C:\data\db, I opened CMD terminal and started the database using mongod command at terminal

C:\YourInstallationPath\bin>mongod

And when I fired mongo command then I was getting the problem.

Twist, I created the necessary folders but still was getting the problem. And this is because mongo server was already running. To fix it, I fired up mongod command again, and it automatically referenced to C:\data\db.

Other users have suggested to add C:\data\db but did not talk about executing mongod again, which exactly solved my problem.

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

Set custom HTML5 required field validation message

Just need to get the element and use the method setCustomValidity.

Example

var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');

Error: Argument is not a function, got undefined

In my case (having an overview page and an "add" page) I got this with my routing setup like below. It was giving the message for the AddCtrl that could not be injected...

$routeProvider.
  when('/', {
    redirectTo: '/overview'
  }).      
  when('/overview', {
    templateUrl: 'partials/overview.html',
    controller: 'OverviewCtrl'
  }).
  when('/add', {
    templateUrl: 'partials/add.html',
    controller: 'AddCtrl'
  }).
  otherwise({
    redirectTo: '/overview'
  });

Because of the when('/' route all my routes went to the overview and the controller could not be matched on the /add route page rendering. This was confusing because I DID see the add.html template but its controller was nowhere to be found.

Removing the '/'-route when case fixed this issue for me.

Oracle SQL Query for listing all Schemas in a DB

SELECT username FROM all_users ORDER BY username;

Get list of all tables in Oracle?

Try selecting from user_tables which lists the tables owned by the current user.

How to plot multiple functions on the same figure, in Matplotlib?

Perhaps a more pythonic way of doing so.

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, t, b, t, c)
plt.show()

enter image description here

Cancel a UIView animation?

Swift version of Stephen Darlington's solution

UIView.beginAnimations(nil, context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(0.1)
// other animation properties

// set view properties
UIView.commitAnimations()

writing to serial port from linux command line

SCREEN:

NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo or printf

I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)

You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:

screen /dev/ttyS0 19200,cs8

(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.

ECHO:

Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0) while I was sending the echo command.

PRINTF:

I found that one can also use printf's '%x' command:

c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT

Again, for printf, start cat < /dev/ttyS0 before sending the command.

Registering for Push Notifications in Xcode 8/Swift 3.0?

Simply do the following in didFinishWithLaunching::

if #available(iOS 10.0, *) {

    let center = UNUserNotificationCenter.current()

    center.delegate = self
    center.requestAuthorization(options: []) { _, _ in
        application.registerForRemoteNotifications()
    }
}

Remember about import statement:

import UserNotifications

How to get current url in view in asp.net core 1.0

var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}{Context.Request.QueryString}";

How to remove stop words using nltk or python

Although the question is a bit old, here is a new library, which is worth mentioning, that can do extra tasks.

In some cases, you don't want only to remove stop words. Rather, you would want to find the stopwords in the text data and store it in a list so that you can find the noise in the data and make it more interactive.

The library is called 'textfeatures'. You can use it as follows:

! pip install textfeatures
import textfeatures as tf
import pandas as pd

For example, suppose you have the following set of strings:

texts = [
    "blue car and blue window",
    "black crow in the window",
    "i see my reflection in the window"]

df = pd.DataFrame(texts) # Convert to a dataframe
df.columns = ['text'] # give a name to the column
df

Now, call the stopwords() function and pass the parameters you want:

tf.stopwords(df,"text","stopwords") # extract stop words
df[["text","stopwords"]].head() # give names to columns

The result is going to be:

    text                                 stopwords
0   blue car and blue window             [and]
1   black crow in the window             [in, the]
2   i see my reflection in the window    [i, my, in, the]

As you can see, the last column has the stop words included in that docoument (record).

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

a similar issue is for Visual studio 2015 RC. Sometimes it loses the ability to open RC: you double click but editor do not one menus and dialogs.

Right click on the file *.rc, it will open:

enter image description here

And change as following:

enter image description here

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

One more point I want to add. In spring-servlet.xml we include component scan for Controller package. In following example we include filter annotation for controller package.

<!-- Scans for annotated @Controllers in the classpath -->
<context:component-scan base-package="org.test.web" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

In applicationcontext.xml we add filter for remaining package excluding controller.

<context:component-scan base-package="org.test">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>