Programs & Examples On #Dde

Dynamic Data Exchange (DDE) is a form of interprocess communication on Windows that uses shared memory to exchange data between applications. Applications can use DDE for one-time data transfers and for ongoing exchanges and updating of data.

How much should a function trust another function

My 2 cents.

This is a loaded question imho. A rule of thumb I use to is see how this function will be called. If the caller is something I have control over then , its ok to assume that it will be called with the right parameters and with proper initialization.

On the other hand if its some client I don't control then it is a good idea to do thorough error checking.

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

Template not provided using create-react-app

1)

npm uninstall -g create-react-app

or

yarn global remove create-react-app

2)

There seems to be a bug where create-react-app isn't properly uninstalled and using one of the new commands lead to:

A template was not provided. This is likely because you're using an outdated version of create-react-app.

After uninstalling it with npm uninstall -g create-react-app, check whether you still have it "installed" with which create-react-app (Windows: where create-react-app) on your command line. If it returns something (e.g. /usr/local/bin/create-react-app), then do a rm -rf /usr/local/bin/create-react-app to delete manually.

3)

Then one of these ways:

npx create-react-app my-app
npm init react-app my-app
yarn create react-app my-app

Server Discovery And Monitoring engine is deprecated

working sample code for mongo, reference link

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url,{ useUnifiedTopology: true }, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  dbo.createCollection("customers", function(err, res) {
    if (err) throw err;
    console.log("Collection created!");
    db.close();
  });
});

dotnet ef not found in .NET Core 3

I was having this problem after I installed the dotnet-ef tool using Ansible with sudo escalated previllage on Ubuntu. I had to add become: no for the Playbook task, then the dotnet-ef tool became available to the current user.

  - name: install dotnet tool dotnet-ef
    command: dotnet tool install --global dotnet-ef --version {{dotnetef_version}}
    become: no

Angular @ViewChild() error: Expected 2 arguments, but got 1

Angular 8

In Angular 8, ViewChild has another param

@ViewChild('nameInput', {static: false}) component : Component

You can read more about it here and here

Angular 9 & Angular 10

In Angular 9 default value is static: false, so doesn't need to provide param unless you want to use {static: true}

Why am I getting Unknown error in line 1 of pom.xml?

I was getting same error in Version 3. It worked after upgrading STS to latest version: 4.5.1.RELEASE. No change in code or configuration in latest STS was required.

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

In my case everything solved after re-cloning the repo and launching it again.

Setup: Xcode 12.4 Mac M1

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

I had to reinstall protractor for it to pull the updated webdriver-manager module. Also, per @Mark’s comment, the package-lock.json may be locking the dependency.

npm uninstall protractor
npm install --save-dev protractor

Then, make sure to check the maxChromedriver value in node_modules/protractor/node_modules/webdriver-manager/config.json after re-install to verify it matches the desired Chrome driver version.

react hooks useEffect() cleanup for only componentWillUnmount?

To add to the accepted answer, I had a similar issue and solved it using a similar approach with the contrived example below. In this case I needed to log some parameters on componentWillUnmount and as described in the original question I didn't want it to log every time the params changed.

const componentWillUnmount = useRef(false)

// This is componentWillUnmount
useEffect(() => {
    return () => {
        componentWillUnmount.current = true
    }
}, [])

useEffect(() => {
    return () => {
        // This line only evaluates to true after the componentWillUnmount happens 
        if (componentWillUnmount.current) {
            console.log(params)
        }
    }

}, [params]) // This dependency guarantees that when the componentWillUnmount fires it will log the latest params

How do I prevent Conda from activating the base environment by default?

I faced the same problem. Initially I deleted the .bash_profile but this is not the right way. After installing anaconda it is showing the instructions clearly for this problem. Please check the image for solution provided by Anaconda

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

Error: Java: invalid target release: 11 - IntelliJ IDEA

i also got same error , i just change the java version in pom.xml from 11 to 1.8 and it's work fine.

Git fatal: protocol 'https' is not supported

There is something fishy going on. Probably a github bug that is not consistent (A/B testing?)

I am on windows10, using firefox. I have just copied a checkout URL and got an extra character. But only the first time. A second time it wasn't there. I had to look at my history file to see it!

here is my history:

git clone --recursive https://github.com/amzeratul/halley-template
git clone --recursive http://github.com/amzeratul/halley-template
git clone --recursive github.com/amzeratul/halley-template
git clone --recursive https://github.com/amzeratul/halley-template

the history command doesn't show the extra char. Just like it wasn't rendered when i was copy-pasting it into the terminal. You can see how i tried to remove the 's' and then the entire protocol? I was only triggered to investigate further when the backspace key moved one less character than i was expecting!

I saved my shell history file onto a machine with an hex editor and:

00000000  xx xx xx xx xx xx xx 0a  67 69 74 20 63 6c 6f 6e  |xxxxxxx.git clon|
00000010  65 20 2d 2d 72 65 63 75  72 73 69 76 65 20 c2 96  |e --recursive ..|
00000020  68 74 74 70 73 3a 2f 2f  67 69 74 68 75 62 2e 63  |https://github.c|
00000030  6f 6d 2f 61 6d 7a 65 72  61 74 75 6c 2f 68 61 6c  |om/amzeratul/hal|
00000040  6c 65 79 2d 74 65 6d 70  6c 61 74 65 0a 67 69 74  |ley-template.git|
00000050  20 2d 2d 68 65 6c 70 0a  67 69 74 20 75 70 64 61  | --help.git upda|
00000060  74 65 2d 67 69 74 2d 66  6f 72 2d 77 69 6e 64 6f  |te-git-for-windo|
00000070  77 73 0a 67 69 74 20 63  6c 6f 6e 65 20 2d 2d 72  |ws.git clone --r|
00000080  65 63 75 72 73 69 76 65  20 c2 96 68 74 74 70 73  |ecursive ..https|
00000090  3a 2f 2f 67 69 74 68 75  62 2e 63 6f 6d 2f 61 6d  |://github.com/am|
000000a0  7a 65 72 61 74 75 6c 2f  68 61 6c 6c 65 79 2d 74  |zeratul/halley-t|
000000b0  65 6d 70 6c 61 74 65 0a  63 75 72 6c 20 2d 2d 76  |emplate.curl --v|
000000c0  65 72 73 69 6f 6e 0a 63  64 20 63 6f 64 65 0a 67  |ersion.cd code.g|
000000d0  69 74 20 63 6c 6f 6e 65  20 2d 2d 72 65 63 75 72  |it clone --recur|
000000e0  73 69 76 65 20 c2 96 68  74 74 70 73 3a 2f 2f 67  |sive ..https://g|
000000f0  69 74 68 75 62 2e 63 6f  6d 2f 61 6d 7a 65 72 61  |ithub.com/amzera|
00000100  74 75 6c 2f 68 61 6c 6c  65 79 2d 74 65 6d 70 6c  |tul/halley-templ|
00000110  61 74 65 0a 67 69 74 20  63 6c 6f 6e 65 20 2d 2d  |ate.git clone --|
00000120  72 65 63 75 72 73 69 76  65 20 c2 96 68 74 74 70  |recursive ..http|
00000130  3a 2f 2f 67 69 74 68 75  62 2e 63 6f 6d 2f 61 6d  |://github.com/am|
00000140  7a 65 72 61 74 75 6c 2f  68 61 6c 6c 65 79 2d 74  |zeratul/halley-t|
00000150  65 6d 70 6c 61 74 65 0a  67 69 74 20 63 6c 6f 6e  |emplate.git clon|
00000160  65 20 2d 2d 72 65 63 75  72 73 69 76 65 20 67 69  |e --recursive gi|
00000170  74 68 75 62 2e 63 6f 6d  2f 61 6d 7a 65 72 61 74  |thub.com/amzerat|
00000180  75 6c 2f 68 61 6c 6c 65  79 2d 74 65 6d 70 6c 61  |ul/halley-templa|
00000190  74 65 0a 67 69 74 20 63  6c 6f 6e 65 20 2d 2d 72  |te.git clone --r|
000001a0  65 63 75 72 73 69 76 65  20 68 74 74 70 73 3a 2f  |ecursive https:/|
000001b0  2f 67 69 74 68 75 62 2e  63 6f 6d 2f 61 6d 7a 65  |/github.com/amze|
000001c0  72 61 74 75 6c 2f 68 61  6c 6c 65 79 2d 74 65 6d  |ratul/halley-tem|
000001d0  70 6c 61 74 65 0a                                 |plate.|
000001d6

There i a c2 96 char inserted before the url. No idea what that is. Is it not extended ASCII (where it would be –) and it was hidden from almost every place i pasted while it was on the clipboard. The closest i've found with this hex value would be https://www.fileformat.info/info/unicode/char/c298/index.htm but i didn't see the utf prefix anywhere (again, might have been lost)

This all might be misleading as I lost the page/clipboard and am working exclusively from the saved shell history file, which might very well be missing data from the original bug/malicious injection.

Can't perform a React state update on an unmounted component

I know that you're not using history, but in my case I was using the useHistory hook from React Router DOM, which unmounts the component before the state is persisted in my React Context Provider.

To fix this problem I have used the hook withRouter nesting the component, in my case export default withRouter(Login), and inside the component const Login = props => { ...; props.history.push("/dashboard"); .... I have also removed the other props.history.push from the component, e.g, if(authorization.token) return props.history.push('/dashboard') because this causes a loop, because the authorization state.

An alternative to push a new item to history.

HTTP Error 500.30 - ANCM In-Process Start Failure

From ASP.NET Core 3.0+ and visual studio 19 version 16.3+ You will find section in project .csproj file are like below-

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

There is no AspNetCoreHostingModel property there. You will find Hosting model selection in the properties of the project. Right-click the project name in the solution explorer. Click properties.

enter image description here

Click the Debug menu.

enter image description here

enter image description here

Scroll down to find the Hosting Model option.

enter image description here

Select Out of Process.

enter image description here

Save the project and run IIS Express.

UPDATE For Server Deployment:

When you publish your application in the server there is a web config file like below:

enter image description here

change value of 'hostingModel' from 'inprocess' to 'outofprocess' like below:

enter image description here

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

For others who have the same problem in IntelliJ:

upgrading to the latest IDE version should resolve the issue.

In my case going from 2018.1 -> 2018.3.3

What does double question mark (??) operator mean in PHP

$myVar = $someVar ?? 42;

Is equivalent to :

$myVar = isset($someVar) ? $someVar : 42;

For constants, the behaviour is the same when using a constant that already exists :

define("FOO", "bar");
define("BAR", null);

$MyVar = FOO ?? "42";
$MyVar2 = BAR ?? "42";

echo $MyVar . PHP_EOL;  // bar
echo $MyVar2 . PHP_EOL; // 42

However, for constants that don't exist, this is different :

$MyVar3 = IDONTEXIST ?? "42"; // Raises a warning
echo $MyVar3 . PHP_EOL;       // IDONTEXIST

Warning: Use of undefined constant IDONTEXIST - assumed 'IDONTEXIST' (this will throw an Error in a future version of PHP)

Php will convert the non-existing constant to a string.

You can use constant("ConstantName") that returns the value of the constant or null if the constant doesn't exist, but it will still raise a warning. You can prepended the function with the error control operator @ to ignore the warning message :

$myVar = @constant("IDONTEXIST") ?? "42"; // No warning displayed anymore
echo $myVar . PHP_EOL; // 42

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

I tried all the answers provided here. However none of them worked for me in shared hosting. However, soultion mentioned here works for me How to solve "CSRF Token Mismatch" in Laravel l

Can't compile C program on a Mac after upgrade to Mojave

TL;DR

Make sure you have downloaded the latest 'Command Line Tools' package and run this from a terminal (command line):

open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

For some information on Catalina, see Can't compile a C program on a Mac after upgrading to Catalina 10.15.


Extracting a semi-coherent answer from rather extensive comments…

Preamble

Very often, xcode-select --install has been the correct solution, but it does not seem to help this time. Have you tried running the main Xcode GUI interface? It may install some extra software for you and clean up. I did that after installing Xcode 10.0, but a week or more ago, long before upgrading to Mojave.

I observe that if your GCC is installed in /usr/local/bin, you probably aren't using the GCC from Xcode; that's normally installed in /usr/bin.

I too have updated to macOS 10.14 Mojave and Xcode 10.0. However, both the system /usr/bin/gcc and system /usr/bin/clang are working for me (Apple LLVM version 10.0.0 (clang-1000.11.45.2) Target: x86_64-apple-darwin18.0.0 for both.) I have a problem with my home-built GCC 8.2.0 not finding headers in /usr/include, which is parallel to your problem with /usr/local/bin/gcc not finding headers either.

I've done a bit of comparison, and my Mojave machine has no /usr/include at all, yet /usr/bin/clang is able to compile OK. A header (_stdio.h, with leading underscore) was in my old /usr/include; it is missing now (hence my problem with GCC 8.2.0). I ran xcode-select --install and it said "xcode-select: note: install requested for command line developer tools" and then ran a GUI installer which showed me a licence which I agreed to, and it downloaded and installed the command line tools — or so it claimed.

I then ran Xcode GUI (command-space, Xcode, return) and it said it needed to install some more software, but still no /usr/include. But I can compile with /usr/bin/clang and /usr/bin/gcc — and the -v option suggests they're using

InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

Working solution

Then Maxxx noted:

I've found a way. If we are using Xcode 10, you will notice that if you navigate to the /usr in the Finder, you will not see a folder called 'include' any more, which is why the terminal complains of the absence of the header files which is contained inside the 'include' folder. In the Xcode 10.0 Release Notes, it says there is a package:

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg 

and you should install that package to have the /usr/include folder installed. Then you should be good to go.

When all else fails, read the manual or, in this case, the release notes. I'm not dreadfully surprised to find Apple wanting to turn their backs on their Unix heritage, but I am disappointed. If they're careful, they could drive me away. Thank you for the information.

Having installed the package using the following command at the command line, I have /usr/include again, and my GCC 8.2.0 works once more.

open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

Downloading Command Line Tools

As Vesal points out in a valuable comment, you need to download the Command Line Tools package for Xcode 10.1 on Mojave 10.14, and you can do so from:

You need to login with an Apple ID to be able to get the download. When you've done the download, install the Command Line Tools package. Then install the headers as described in the section 'Working Solution'.

This worked for me on Mojave 10.14.1. I must have downloaded this before, but I'd forgotten by the time I was answering this question.

Upgrade to Mojave 10.14.4 and Xcode 10.2

On or about 2019-05-17, I updated to Mojave 10.14.4, and the Xcode 10.2 command line tools were also upgraded (or Xcode 10.1 command line tools were upgraded to 10.2). The open command shown above fixed the missing headers. There may still be adventures to come with upgrading the main Xcode to 10.2 and then re-reinstalling the command line tools and the headers package.

Upgrade to Xcode 10.3 (for Mojave 10.14.6)

On 2019-07-22, I got notice via the App Store that the upgrade to Xcode 10.3 is available and that it includes SDKs for iOS 12.4, tvOS 12.4, watchOS 5.3 and macOS Mojave 10.14.6. I installed it one of my 10.14.5 machines, and ran it, and installed extra components as it suggested, and it seems to have left /usr/include intact.

Later the same day, I discovered that macOS Mojave 10.14.6 was available too (System Preferences ? Software Update), along with a Command Line Utilities package IIRC (it was downloaded and installed automatically). Installing the o/s update did, once more, wipe out /usr/include, but the open command at the top of the answer reinstated it again. The date I had on the file for the open command was 2019-07-15.

Upgrade to XCode 11.0 (for Catalina 10.15)

The upgrade to XCode 11.0 ("includes Swift 5.1 and SDKs for iOS 13, tvOS 13, watchOS 6 and macOS Catalina 10.15") was released 2019-09-21. I was notified of 'updates available', and downloaded and installed it onto machines running macOS Mojave 10.14.6 via the App Store app (updates tab) without problems, and without having to futz with /usr/include. Immediately after installation (before having run the application itself), I tried a recompilation and was told:

Agreeing to the Xcode/iOS license requires admin privileges, please run “sudo xcodebuild -license” and then retry this command.

Running that (sudo xcodebuild -license) allowed me to run the compiler. Since then, I've run the application to install extra components it needs; still no problem. It remains to be seen what happens when I upgrade to Catalina itself — but my macOS Mojave 10.14.6 machines are both OK at the moment (2019-09-24).

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

In my case

build.gradle(Project)

was

ext.kotlin_version = '1.2.71'

updated to

ext.kotlin_version = '1.3.0'

looks problem has gone for now

Best way to "push" into C# array

This is acceptable as assigning to an array. But if you are asking for pushing, I am pretty sure its not possible in array. Rather it can be achieved by using Stack, Queue or any other data structure. Real arrays doesn't have such functions. But derived classes such as ArrayList have it.

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

I had the same issue when using the alpine image.

My .sh file had the following first line:

#!/bin/bash

Alpine does not have bash. So changing the line to

#!/bin/sh

or installing bash with

apk add --no-cache bash

solved the issue for me.

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Failed to resolve: com.android.support:appcompat-v7:28.0

some guys who still might have the problem like me (FOR IRANIAN and all the coutries who have sanctions) , this is error can be fixed with proxy i used this free proxy for android studio 3.2 https://github.com/freedomofdevelopers/fod just to to Settings (Ctrl + Alt + S) and search HTTP proxy then check Manual proxy configuration then add fodev.org for host name and 8118 for Port number

Screenshot of proxy settings in android studio

How can I add raw data body to an axios request?

axios({
  method: 'post',     //put
  url: url,
  headers: {'Authorization': 'Bearer'+token}, 
  data: {
     firstName: 'Keshav', // This is the body part
     lastName: 'Gera'
  }
});

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

Try this:

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

Install-PackageProvider NuGet -Force

Set-PSRepository PSGallery -InstallationPolicy Trusted

Xcode couldn't find any provisioning profiles matching

Try to check Signing settings in Build settings for your project and target. Be sure that code signing identity section has correct identities for Debug and Release.

image description here

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

I have add this annotation on the main class of my spring boot application and everything work perfectly

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })

Axios having CORS issue

May help to someone:

I'm sending data from react application to golang server.

Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*"). Error has fixed.

React form submit function:

async handleSubmit(e) {
    e.preventDefault();

    const headers = {
        'Content-Type': 'text/plain'
    };

    await axios.post(
        'http://localhost:3001/login',
        {
            user_name: this.state.user_name,
            password: this.state.password,
        },
        {headers}
        ).then(response => {
            console.log("Success ========>", response);
        })
        .catch(error => {
            console.log("Error ========>", error);
        }
    )
}

Go server got Router,

func main()  {
    router := mux.NewRouter()

    router.HandleFunc("/login", Login.Login).Methods("POST")

    log.Fatal(http.ListenAndServe(":3001", router))
}

Login.go,

func Login(w http.ResponseWriter, r *http.Request)  {

    var user = Models.User{}
    data, err := ioutil.ReadAll(r.Body)

    if err == nil {
        err := json.Unmarshal(data, &user)
        if err == nil {
            user = Postgres.GetUser(user.UserName, user.Password)
            w.Header().Set("Access-Control-Allow-Origin", "*")
            json.NewEncoder(w).Encode(user)
        }
    }
}

How to add image in Flutter

I think the error is caused by the redundant ,

flutter:
  uses-material-design: true, # <<< redundant , at the end of the line
  assets:
    - images/lake.jpg

I'd also suggest to create an assets folder in the directory that contains the pubspec.yaml file and move images there and use

flutter:
  uses-material-design: true
  assets:
    - assets/images/lake.jpg

The assets directory will get some additional IDE support that you won't have if you put assets somewhere else.

Trying to merge 2 dataframes but get ValueError

Additional: when you save df to .csv format, the datetime (year in this specific case) is saved as object, so you need to convert it into integer (year in this specific case) when you do the merge. That is why when you upload both df from csv files, you can do the merge easily, while above error will show up if one df is uploaded from csv files and the other is from an existing df. This is somewhat annoying, but have an easy solution if kept in mind.

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

This error is usually observed when your machine is low on disk space. Steps to be followed to avoid this error message

  1. Resetting the read-only index block on the index:

    $ curl -X PUT -H "Content-Type: application/json" http://127.0.0.1:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
    
    Response
    ${"acknowledged":true}
    
  2. Updating the low watermark to at least 50 gigabytes free, a high watermark of at least 20 gigabytes free, and a flood stage watermark of 10 gigabytes free, and updating the information about the cluster every minute

     Request
     $curl -X PUT "http://127.0.0.1:9200/_cluster/settings?pretty" -H 'Content-Type: application/json' -d' { "transient": { "cluster.routing.allocation.disk.watermark.low": "50gb", "cluster.routing.allocation.disk.watermark.high": "20gb", "cluster.routing.allocation.disk.watermark.flood_stage": "10gb", "cluster.info.update.interval": "1m"}}'
    
      Response
      ${
       "acknowledged" : true,
       "persistent" : { },
       "transient" : {
       "cluster" : {
       "routing" : {
       "allocation" : {
       "disk" : {
         "watermark" : {
           "low" : "50gb",
           "flood_stage" : "10gb",
           "high" : "20gb"
         }
       }
     }
    }, 
    "info" : {"update" : {"interval" : "1m"}}}}}
    

After running these two commands, you must run the first command again so that the index does not go again into read-only mode

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

mongoose.connect('mongodb://localhost:27017/').then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});

Better just connect to the localhost Mongoose Database only and create your own collections. Don't forget to mention the port number. (Default: 27017)

For the best view, download Mongoose-compass for MongoDB UI.

Set focus on <input> element

Modify the show search method like this

showSearch(){
  this.show = !this.show;  
  setTimeout(()=>{ // this will make the execution after the above boolean has changed
    this.searchElement.nativeElement.focus();
  },0);  
}

Importing json file in TypeScript

Enable "resolveJsonModule": true in tsconfig.json file and implement as below code, it's work for me:

const config = require('./config.json');

You must add a reference to assembly 'netstandard, Version=2.0.0.0

I have run into this before and trying a number of things has fixed it for me:

  • Delete a bin folder if it exists
  • Delete the hidden .vs folder
  • Make sure the 4.6.1 targeting pack is installed
  • Last Ditch Effort: Add a reference to System.Runtime (right click project -> add -> reference -> tick the box next to System.Runtime), although I think I've always figured out one of the above has solved it instead of doing this.

Also, if this is a .net core app running on the full framework, I've found you have to include a global.json file at the root of your project and point it to the SDK you want to use for that project:

{
  "sdk": {
    "version": "1.0.0-preview2-003121"
  }
}

Angular 5 ngHide ngShow [hidden] not working

Try this:

<button (click)="click()">Click me</button>

<input class="txt" type="password" [(ngModel)]="input_pw" [ngClass]="{'hidden': isHidden}" />

component.ts:

isHidden: boolean = false;
click(){
    this.isHidden = !this.isHidden;
}

Adding an .env file to React Project

If in case you are getting the values as undefined, then you should consider restarting the node server and recompile again.

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

Go to resources folder where the application.properties is present, update the below code in that.

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I know it's a relative old post but, I would like to share what worked for me: I've simply input "http://" before "localhost" in the url. Hope it helps somebody.

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

I downgrade the support

previously it was
implementation 'com.android.support:appcompat-v7:27.0.2'

Use it

implementation 'com.android.support:appcompat-v7:27.1.0'

implementation 'com.android.support:design:27.1.0'

Its Working Happy Codng

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

This happened to me because I was using:

app.datasource.url=jdbc:mysql://localhost/test

When I replaced url by jdbc-url then it worked:

app.datasource.jdbc-url=jdbc:mysql://localhost/test

Angular 5 Reactive Forms - Radio Button Group

IF you want to derive usg Boolean true False need to add "[]" around value

<form [formGroup]="form">
  <input type="radio" [value]=true formControlName="gender" >Male
  <input type="radio" [value]=false formControlName="gender">Female
</form>

ReactJS: Maximum update depth exceeded error

1.If we want to pass argument in the call then we need to call the method like below As we are using arrow functions no need to bind the method in cunstructor.

onClick={() => this.save(id)} 

when we bind the method in constructor like this

this.save= this.save.bind(this);

then we need to call the method without passing any argument like below

onClick={this.save}

and we try to pass argument while calling the function as shown below then error comes like maximum depth exceeded.

 onClick={this.save(id)}

Issue in installing php7.2-mcrypt

As an alternative, you can install 7.1 version of mcrypt and create a symbolic link to it:

Install php7.1-mcrypt:

sudo apt install php7.1-mcrypt

Create a symbolic link:

sudo ln -s /etc/php/7.1/mods-available/mcrypt.ini /etc/php/7.2/mods-available

After enabling mcrypt by sudo phpenmod mcrypt, it gets available.

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

How to show code but hide output in RMarkdown?

For muting library("name_of_library") codes, meanly just showing the codes, {r loadlib, echo=T, results='hide', message=F, warning=F} is great. And imho a better way than library(package, warn.conflicts=F, quietly=T)

The type WebMvcConfigurerAdapter is deprecated

In Spring every request will go through the DispatcherServlet. To avoid Static file request through DispatcherServlet(Front contoller) we configure MVC Static content.

Spring 3.1. introduced the ResourceHandlerRegistry to configure ResourceHttpRequestHandlers for serving static resources from the classpath, the WAR, or the file system. We can configure the ResourceHandlerRegistry programmatically inside our web context configuration class.

  • we have added the /js/** pattern to the ResourceHandler, lets include the foo.js resource located in the webapp/js/ directory
  • we have added the /resources/static/** pattern to the ResourceHandler, lets include the foo.html resource located in the webapp/resources/ directory
@Configuration
@EnableWebMvc
public class StaticResourceConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");
        registry.addResourceHandler("/resources/static/**")
                .addResourceLocations("/resources/");

        registry
            .addResourceHandler("/js/**")
            .addResourceLocations("/js/")
            .setCachePeriod(3600)
            .resourceChain(true)
            .addResolver(new GzipResourceResolver())
            .addResolver(new PathResourceResolver());
    }
}

XML Configuration

<mvc:annotation-driven />
  <mvc:resources mapping="/staticFiles/path/**" location="/staticFilesFolder/js/"
                 cache-period="60"/>

Spring Boot MVC Static Content if the file is located in the WAR’s webapp/resources folder.

spring.mvc.static-path-pattern=/resources/static/**

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

I have added dataType: 'jsonp' and it works!

$.ajax({
   type: 'POST',
   crossDomain: true,
   dataType: 'jsonp',
   url: '',
   success: function(jsondata){

   }
})

JSONP is a method for sending JSON data without worrying about cross-domain issues. Read More

How to add CORS request in header in Angular 5

please import requestoptions from angular cors

    import {RequestOptions, Request, Headers } from '@angular/http';

and add request options in your code like given below

    let requestOptions = new RequestOptions({ headers:null, withCredentials: 
    true });

send request option in your api request

code snippet below-

     let requestOptions = new RequestOptions({ headers:null, 
     withCredentials: true });
     return this.http.get(this.config.baseUrl + 
     this.config.getDropDownListForProject, requestOptions)
     .map(res => 
     {
      if(res != null)
      { 
        return res.json();
        //return true;
      }
    })
  .catch(this.handleError);
   }  

and add CORS in your backend PHP code where all api request will land first.

try this and let me know if it is working or not i had a same issue i was adding CORS from angular5 that was not working then i added CORS to backend and it worked for me

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Many answer above are correct but same time convoluted with other aspects of authN/authZ. What actually resolves the exception in question is this line:

services.AddScheme<YourAuthenticationOptions, YourAuthenticationHandler>(YourAuthenticationSchemeName, options =>
    {
        options.YourProperty = yourValue;
    })

No provider for HttpClient

In angular github page, this problem was discussed and found solution. https://github.com/angular/angular/issues/20355

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

How to generate components in a specific folder with Angular CLI?

The above options were not working for me because unlike creating a directory or file in the terminal, when the CLI generates a component, it adds the path src/app by default to the path you enter.

If I generate the component from my main app folder like so (WRONG WAY)

ng g c ./src/app/child/grandchild 

the component that was generated was this:

src/app/src/app/child/grandchild.component.ts

so I only had to type

ng g c child/grandchild 

Hopefully this helps someone

Angular + Material - How to refresh a data source (mat-table)

I don't know if the ChangeDetectorRef was required when the question was created, but now this is enough:

import { MatTableDataSource } from '@angular/material/table';

// ...

dataSource = new MatTableDataSource<MyDataType>();

refresh() {
  this.myService.doSomething().subscribe((data: MyDataType[]) => {
    this.dataSource.data = data;
  }
}

Example:
StackBlitz

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

I am using UniServer Zero XIV 13.x.x UniController XIV V2.3.1:

enter image description here

From the command line I did this:

mysql> CREATE USER 'pmauser'@'%' IDENTIFIED BY 'MyPasswordHere!';
Query OK, 0 rows affected (0.07 sec)

mysql> GRANT ALL PRIVILEGES ON *.* TO 'pmauser'@'%' WITH GRANT OPTION;
Query OK, 0 rows affected (0.02 sec)

Then I went to C:\...\wamp\ZeroXIV_unicontroller_2_3_1\UniServerZ\home\us_opt1\config.inc.php and modified the file to have this:

/* PMA User advanced features */
//////////$cfg['Servers'][$i]['controluser']    = 'pma';
//////////$cfg['Servers'][$i]['controlpass']    = $password;
$cfg['Servers'][$i]['controluser']    = 'pmauser';
$cfg['Servers'][$i]['controlpass']    = 'MyPasswordHere!';

I restarted Apache and MySQL. The error is gone!

How to sign in kubernetes dashboard?

As of release 1.7 Dashboard supports user authentication based on:

Dashboard on Github

Token

Here Token can be Static Token, Service Account Token, OpenID Connect Token from Kubernetes Authenticating, but not the kubeadm Bootstrap Token.

With kubectl, we can get an service account (eg. deployment controller) created in kubernetes by default.

$ kubectl -n kube-system get secret
# All secrets with type 'kubernetes.io/service-account-token' will allow to log in.
# Note that they have different privileges.
NAME                                     TYPE                                  DATA      AGE
deployment-controller-token-frsqj        kubernetes.io/service-account-token   3         22h

$ kubectl -n kube-system describe secret deployment-controller-token-frsqj
Name:         deployment-controller-token-frsqj
Namespace:    kube-system
Labels:       <none>
Annotations:  kubernetes.io/service-account.name=deployment-controller
              kubernetes.io/service-account.uid=64735958-ae9f-11e7-90d5-02420ac00002

Type:  kubernetes.io/service-account-token

Data
====
ca.crt:     1025 bytes
namespace:  11 bytes
token:      eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkZXBsb3ltZW50LWNvbnRyb2xsZXItdG9rZW4tZnJzcWoiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGVwbG95bWVudC1jb250cm9sbGVyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNjQ3MzU5NTgtYWU5Zi0xMWU3LTkwZDUtMDI0MjBhYzAwMDAyIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRlcGxveW1lbnQtY29udHJvbGxlciJ9.OqFc4CE1Kh6T3BTCR4XxDZR8gaF1MvH4M3ZHZeCGfO-sw-D0gp826vGPHr_0M66SkGaOmlsVHmP7zmTi-SJ3NCdVO5viHaVUwPJ62hx88_JPmSfD0KJJh6G5QokKfiO0WlGN7L1GgiZj18zgXVYaJShlBSz5qGRuGf0s1jy9KOBt9slAN5xQ9_b88amym2GIXoFyBsqymt5H-iMQaGP35tbRpewKKtly9LzIdrO23bDiZ1voc5QZeAZIWrizzjPY5HPM1qOqacaY9DcGc7akh98eBJG_4vZqH2gKy76fMf0yInFTeNKr45_6fWt8gRM77DQmPwb3hbrjWXe1VvXX_g

Kubeconfig

The dashboard needs the user in the kubeconfig file to have either username & password or token, but admin.conf only has client-certificate. You can edit the config file to add the token that was extracted using the method above.

$ kubectl config set-credentials cluster-admin --token=bearer_token

Alternative (Not recommended for Production)

Here are two ways to bypass the authentication, but use for caution.

Deploy dashboard with HTTP

$ kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/master/src/deploy/alternative/kubernetes-dashboard.yaml

Dashboard can be loaded at http://localhost:8001/ui with kubectl proxy.

Granting admin privileges to Dashboard's Service Account

$ cat <<EOF | kubectl create -f -
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: kubernetes-dashboard
  labels:
    k8s-app: kubernetes-dashboard
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: kubernetes-dashboard
  namespace: kube-system
EOF

Afterwards you can use Skip option on login page to access Dashboard.

If you are using dashboard version v1.10.1 or later, you must also add --enable-skip-login to the deployment's command line arguments. You can do so by adding it to the args in kubectl edit deployment/kubernetes-dashboard --namespace=kube-system.

Example:

      containers:
      - args:
        - --auto-generate-certificates
        - --enable-skip-login            # <-- add this line
        image: k8s.gcr.io/kubernetes-dashboard-amd64:v1.10.1

MongoError: connect ECONNREFUSED 127.0.0.1:27017

Please ensure that your mongo DB is set Automatic and running at Control Panel/Administrative Tools/Services like below. That way you wont have to start mongod.exe manually each time.

enter image description here

How to view Plugin Manager in Notepad++

  1. You can download the latest Plugin Manager version PluginManager_latest_version_x64.zip.

  2. Unzip the file.

  3. Copy

PluginManager_latest_version_x64.zip\updater\gpup.exe

into

path-to-installed-notepad\notepad++\updater\

  1. Copy

PluginManager_latest_version_x64.zip\plugins\PluginManager.dll

into

path-to-installed-notepad\notepad++\plugins\

  1. Start or restart Notepad++.
  2. Enjoy!

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

Change arrow colors in Bootstraps carousel

Currently Bootstrap 4 uses a background-image with embbed SVG data info that include the color of the SVG shape. Something like:

.carousel-control-prev-icon { background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E"); }

Note the part about fill='%23fff' it fills the shape with a color, in this case #fff (white), for red simply replace with #f00

Finally, it is safe to include this (same change for next-icon):

.carousel-control-prev-icon {background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23f00' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E"); }

exporting multiple modules in react.js

You can have only one default export which you declare like:

export default App; or export default class App extends React.Component {...

and later do import App from './App'

If you want to export something more you can use named exports which you declare without default keyword like:

export {
  About,
  Contact,
}

or:

export About;
export Contact;

or:

export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);

and later you import them like:

import App, { About, Contact } from './App';

EDIT:

There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js file. Other than that why export anything if it is no used outside the file?. Correct main.js :

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute  } from 'react-router'

class App extends React.Component {
...
}

class Home extends React.Component {
...
}


class About extends React.Component {
...
}


class Contact extends React.Component {
...
}


ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>

), document.getElementById('app'))

EDIT2:

another thing is that this tutorial is based on react-router-V3 which has different api than v4.

Only on Firefox "Loading failed for the <script> with source"

I ran into the same issue (exact error message) and after digging for a couple of hours, I found that the content header needs to be set to application/javascript instead of the application/json that I had. After changing that, it now works.

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Spring Boot 2.2.2 / Gradle:

Gradle (build.gradle):

implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")

Entity (User.class):

LocalDate dateOfBirth;

Code:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
User user = mapper.readValue(json, User.class);

Add class to an element in Angular 4

If you want to set only one specific class, you might write a TypeScript function returning a boolean to determine when the class should be appended.

TypeScript

function hideThumbnail():boolean{
    if (/* Your criteria here */)
        return true;
}

CSS:

.request-card-hidden {
    display: none;
}

HTML:

<ion-note [class.request-card-hidden]="hideThumbnail()"></ion-note>

Node.js: Python not found exception due to node-sass and node-gyp

I had to:

Delete node_modules
Uninstall/reinstall node
npm install [email protected]

worked fine after forcing it to the right sass version, according to the version said to be working with the right node.

NodeJS  Minimum node-sass version   Node Module
Node 12 4.12+   72
Node 11 4.10+   67
Node 10 4.9+    64
Node 8  4.5.3+  57

There was lots of other errors that seemed to be caused by the wrong sass version defined.

CSS Grid Layout not working in IE11 even with prefixes

To support IE11 with auto-placement, I converted grid to table layout every time I used the grid layout in 1 dimension only. I also used margin instead of grid-gap.

The result is the same, see how you can do it here https://jsfiddle.net/hp95z6v1/3/

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I had the issue when I put jcenter() before google() in project level build.gradle. When I changed the order and put google() before jcenter() in build.gradle the problem disappeared

Here is my final build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.3'


        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Bootstrap 4 (^beta) has changed the classes for responsive hiding/showing elements. See this link for correct classes to use: http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

In my case I am using Visual Studio and Nuget packages its failing because have duplicated libraries one in the same folder as jQuery and another in the folder umd. By removing the popper javascript files from the same level as jQuery and refere to the popper.js inside the umd folder fixed my issue and I can see the tooltips correctly.

No String-argument constructor/factory method to deserialize from String value ('')

I found a different way to handle this error. (the variables is according to the original question)

   JsonNode parsedNodes = mapper.readValue(jsonMessage , JsonNode.class);
        Response response = xmlMapper.enable(ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,ACCEPT_SINGLE_VALUE_AS_ARRAY )
                .disable(FAIL_ON_UNKNOWN_PROPERTIES, FAIL_ON_IGNORED_PROPERTIES)
                .convertValue(parsedNodes, Response.class);

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

try this,

goto Android->sdk make sure you have all depenencies required . if not , download them . then goto File-->Settigs-->Build,Execution,Depoyment-->Gradle

choose use default gradle wapper (recommended)

and untick Offline work

gradle build finishes successfully for once you can change the settings

Specifying onClick event type with Typescript and React.Konva

You're probably out of luck without some hack-y workarounds

You could try

onClick={(event: React.MouseEvent<HTMLElement>) => {
 makeMove(ownMark, (event.target as any).index)
}}

I'm not sure how strict your linter is - that might shut it up just a little bit

I played around with it for a bit, and couldn't figure it out, but you can also look into writing your own augmented definitions: https://www.typescriptlang.org/docs/handbook/declaration-merging.html

edit: please use the implementation in this reply it is the proper way to solve this issue (and also upvote him, while you're at it).

Angular 4 img src is not found

You must use this code in angular to add the image path. if your images are under assets folder then.

<img src="../assets/images/logo.png" id="banner-logo" alt="Landing Page"/>

if not under the assets folder then you can use this code.

<img src="../images/logo.png" id="banner-logo" alt="Landing Page"/>

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Add FormsModule in Imports Array.
i.e

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})

Or this can be done without using [(ngModel)] by using

<input [value]='hero.name' (input)='hero.name=$event.target.value' placeholder="name">

instead of

<input [(ngModel)]="hero.name" placeholder="Name">

Vue js error: Component template should contain exactly one root element

Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.

The right approach is

<template>
  <div> <!-- The root -->
    <p></p> 
    <p></p>
  </div>
</template>

The wrong approach

<template> <!-- No root Element -->
    <p></p> 
    <p></p>
</template>

Multi Root Components

The way around to that problem is using functional components, they are components where you have to pass no reactive data means component will not be watching for any data changes as well as not updating it self when something in parent component changes.

As this is a work around it comes with a price, functional components don't have any life cycle hooks passed to it, they are instance less as well you cannot refer to this anymore and everything is passed with context.

Here is how you can create a simple functional component.

Vue.component('my-component', {
    // you must set functional as true
  functional: true,
  // Props are optional
  props: {
    // ...
  },
  // To compensate for the lack of an instance,
  // we are now provided a 2nd context argument.
  render: function (createElement, context) {
    // ...
  }
})

Now that we have covered functional components in some detail lets cover how to create multi root components, for that I am gonna present you with a generic example.

<template>
 <ul>
     <NavBarRoutes :routes="persistentNavRoutes"/>
     <NavBarRoutes v-if="loggedIn" :routes="loggedInNavRoutes" />
     <NavBarRoutes v-else :routes="loggedOutNavRoutes" />
 </ul>
</template>

Now if we take a look at NavBarRoutes template

<template>
 <li
 v-for="route in routes"
 :key="route.name"
 >
 <router-link :to="route">
 {{ route.title }}
 </router-link>
 </li>
</template>

We cant do some thing like this we will be violating single root component restriction

Solution Make this component functional and use render

{
functional: true,
render(h, { props }) {
 return props.routes.map(route =>
  <li key={route.name}>
    <router-link to={route}>
      {route.title}
    </router-link>
  </li>
 )
}

Here you have it you have created a multi root component, Happy coding

Reference for more details visit: https://blog.carbonteq.com/vuejs-create-multi-root-components/

Bootstrap 4, how to make a col have a height of 100%?

Use bootstrap class vh-100 for exp:

<div class="vh-100">

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

I follow all recommendations and all requirements. I install my self signed root CA on my iPhone. I make it trusted. I put certificate signed with this root CA on my local development server and I still get certificated error on safari iOS. Working on all other platforms.

Python TypeError must be str not int

you need to cast int to str before concatenating. for that use str(temperature). Or you can print the same output using , if you don't want to convert like this.

print("the furnace is now",temperature , "degrees!")

Angular 4 Pipe Filter

I know this is old, but i think i have good solution. Comparing to other answers and also comparing to accepted, mine accepts multiple values. Basically filter object with key:value search parameters (also object within object). Also it works with numbers etc, cause when comparing, it converts them to string.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'filter'})
export class Filter implements PipeTransform {
    transform(array: Array<Object>, filter: Object): any {
        let notAllKeysUndefined = false;
        let newArray = [];

        if(array.length > 0) {
            for (let k in filter){
                if (filter.hasOwnProperty(k)) {
                    if(filter[k] != undefined && filter[k] != '') {
                        for (let i = 0; i < array.length; i++) {
                            let filterRule = filter[k];

                            if(typeof filterRule === 'object') {
                                for(let fkey in filterRule) {
                                    if (filter[k].hasOwnProperty(fkey)) {
                                        if(filter[k][fkey] != undefined && filter[k][fkey] != '') {
                                            if(this.shouldPushInArray(array[i][k][fkey], filter[k][fkey])) {
                                                newArray.push(array[i]);
                                            }
                                            notAllKeysUndefined = true;
                                        }
                                    }
                                }
                            } else {
                                if(this.shouldPushInArray(array[i][k], filter[k])) {
                                    newArray.push(array[i]);
                                }
                                notAllKeysUndefined = true;
                            }
                        }
                    }
                }
            }
            if(notAllKeysUndefined) {
                return newArray;
            }
        }

        return array;
    }

    private shouldPushInArray(item, filter) {
        if(typeof filter !== 'string') {
            item = item.toString();
            filter = filter.toString();
        }

        // Filter main logic
        item = item.toLowerCase();
        filter = filter.toLowerCase();
        if(item.indexOf(filter) !== -1) {
            return true;
        }
        return false;
    }
}

Keras input explanation: input_shape, units, batch_size, dim, etc

Units:

The amount of "neurons", or "cells", or whatever the layer has inside it.

It's a property of each layer, and yes, it's related to the output shape (as we will see later). In your picture, except for the input layer, which is conceptually different from other layers, you have:

  • Hidden layer 1: 4 units (4 neurons)
  • Hidden layer 2: 4 units
  • Last layer: 1 unit

Shapes

Shapes are consequences of the model's configuration. Shapes are tuples representing how many elements an array or tensor has in each dimension.

Ex: a shape (30,4,10) means an array or tensor with 3 dimensions, containing 30 elements in the first dimension, 4 in the second and 10 in the third, totaling 30*4*10 = 1200 elements or numbers.

The input shape

What flows between layers are tensors. Tensors can be seen as matrices, with shapes.

In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data.

Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3). Then your input layer tensor, must have this shape (see details in the "shapes in keras" section).

Each type of layer requires the input with a certain number of dimensions:

  • Dense layers require inputs as (batch_size, input_size)
    • or (batch_size, optional,...,optional, input_size)
  • 2D convolutional layers need inputs as:
    • if using channels_last: (batch_size, imageside1, imageside2, channels)
    • if using channels_first: (batch_size, channels, imageside1, imageside2)
  • 1D convolutions and recurrent layers use (batch_size, sequence_length, features)

Now, the input shape is the only one you must define, because your model cannot know it. Only you know that, based on your training data.

All the other shapes are calculated automatically based on the units and particularities of each layer.

Relation between shapes and units - The output shape

Given the input shape, all other shapes are results of layers calculations.

The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).

Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)

Let's show what happens with "Dense" layers, which is the type shown in your graph.

A dense layer has an output shape of (batch_size,units). So, yes, units, the property of the layer, also defines the output shape.

  • Hidden layer 1: 4 units, output shape: (batch_size,4).
  • Hidden layer 2: 4 units, output shape: (batch_size,4).
  • Last layer: 1 unit, output shape: (batch_size,1).

Weights

Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.

In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.

In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.

Shapes in Keras

Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3).

Since the input shape is the only one you need to define, Keras will demand it in the first layer.

But in this definition, Keras ignores the first dimension, which is the batch size. Your model should be able to deal with any batch size, so you define only the other dimensions:

input_shape = (50,50,3)
    #regardless of how many images I have, each image has this shape        

Optionally, or when it's required by certain kinds of models, you can pass the shape containing the batch size via batch_input_shape=(30,50,50,3) or batch_shape=(30,50,50,3). This limits your training possibilities to this unique batch size, so it should be used only when really required.

Either way you choose, tensors in the model will have the batch dimension.

So, even if you used input_shape=(50,50,3), when keras sends you messages, or when you print the model summary, it will show (None,50,50,3).

The first dimension is the batch size, it's None because it can vary depending on how many examples you give for training. (If you defined the batch size explicitly, then the number you defined will appear instead of None)

Also, in advanced works, when you actually operate directly on the tensors (inside Lambda layers or in the loss function, for instance), the batch size dimension will be there.

  • So, when defining the input shape, you ignore the batch size: input_shape=(50,50,3)
  • When doing operations directly on tensors, the shape will be again (30,50,50,3)
  • When keras sends you a message, the shape will be (None,50,50,3) or (30,50,50,3), depending on what type of message it sends you.

Dim

And in the end, what is dim?

If your input shape has only one dimension, you don't need to give it as a tuple, you give input_dim as a scalar number.

So, in your model, where your input layer has 3 elements, you can use any of these two:

  • input_shape=(3,) -- The comma is necessary when you have only one dimension
  • input_dim = 3

But when dealing directly with the tensors, often dim will refer to how many dimensions a tensor has. For instance a tensor with shape (25,10909) has 2 dimensions.


Defining your image in Keras

Keras has two ways of doing it, Sequential models, or the functional API Model. I don't like using the sequential model, later you will have to forget it anyway because you will want models with branches.

PS: here I ignored other aspects, such as activation functions.

With the Sequential model:

from keras.models import Sequential  
from keras.layers import *  

model = Sequential()    

#start from the first hidden layer, since the input is not actually a layer   
#but inform the shape of the input, with 3 elements.    
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input

#further layers:    
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer   

With the functional API Model:

from keras.models import Model   
from keras.layers import * 

#Start defining the input tensor:
inpTensor = Input((3,))   

#create the layers and pass them the input tensor to get the output tensor:    
hidden1Out = Dense(units=4)(inpTensor)    
hidden2Out = Dense(units=4)(hidden1Out)    
finalOut = Dense(units=1)(hidden2Out)   

#define the model's start and end points    
model = Model(inpTensor,finalOut)

Shapes of the tensors

Remember you ignore batch sizes when defining layers:

  • inpTensor: (None,3)
  • hidden1Out: (None,4)
  • hidden2Out: (None,4)
  • finalOut: (None,1)

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Worked by lowering the spring boot starter parent to 1.5.13

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.13.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

'router-outlet' is not a known element

Its just better to create a routing component that would handle all your routes! From the angular website documentation! That's good practice!

ng generate module app-routing --flat --module=app

The above CLI generates a routing module and adds to your app module, all you need to do from the generated component is to declare your routes, also don't forget to add this:

exports: [
    RouterModule
  ],

to your ng-module decorator as it doesn't come with the generated app-routing module by default!

Pandas create empty DataFrame with only column names

Creating colnames with iterating

df = pd.DataFrame(columns=['colname_' + str(i) for i in range(5)])
print(df)

# Empty DataFrame
# Columns: [colname_0, colname_1, colname_2, colname_3, colname_4]
# Index: []

to_html() operations

print(df.to_html())

# <table border="1" class="dataframe">
#   <thead>
#     <tr style="text-align: right;">
#       <th></th>
#       <th>colname_0</th>
#       <th>colname_1</th>
#       <th>colname_2</th>
#       <th>colname_3</th>
#       <th>colname_4</th>
#     </tr>
#   </thead>
#   <tbody>
#   </tbody>
# </table>

this seems working

print(type(df.to_html()))
# <class 'str'>

The problem is caused by

when you create df like this

df = pd.DataFrame(columns=COLUMN_NAMES)

it has 0 rows × n columns, you need to create at least one row index by

df = pd.DataFrame(columns=COLUMN_NAMES, index=[0])

now it has 1 rows × n columns. You are be able to add data. Otherwise its df that only consist colnames object(like a string list).

Angular 2 'component' is not a known element

I am beginning Angular and in my case, the issue was that I hadn't saved the file after adding the 'import' statement.

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

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

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

    enter image description here

  2. Reconnect the device.

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

enter image description here

  1. Select the device and click on next button

enter image description here

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

enter image description here

  1. Click on Done button.

enter image description here

  1. Now, click on connect via network.

enter image description here

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

enter image description here

How to enable CORS in ASP.net Core WebAPI

I'm using .Net CORE 3.1 and I spent ages banging my head against a wall with this one when I realised that my code has started actually working but my debugging environment was broken, so here's 2 hints if you're trying to troubleshoot the problem:

  1. If you're trying to log response headers using ASP.NET middleware, the "Access-Control-Allow-Origin" header will never show up even if it's there. I don't know how but it seems to be added outside the pipeline (in the end I had to use wireshark to see it).

  2. .NET CORE won't send the "Access-Control-Allow-Origin" in the response unless you have an "Origin" header in your request. Postman won't set this automatically so you'll need to add it yourself.

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

I was having the same problem in Linux Ubuntu 18. After the update from Ubuntu 17.10, every git command would show that message.

The way to solve it is to make sure that you have the correct permission on the id_rsa and id_rsa.pub.

Check the current chmod number by using stat --format '%a' <file>. It should be 600 for id_rsa and 644 for id_rsa.pub.

To change the permission on the files use

chmod 600 id_rsa
chmod 644 id_rsa.pub

That solved my issue with the update.

Redirecting to a page after submitting form in HTML

You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href.

Example:

 var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      window.location.href = 'https://website.com/my-account';
    }
  };
  xhttp.open("POST", "demo_post.asp", true);
  xhttp.send();

RestClientException: Could not extract response. no suitable HttpMessageConverter found

While the accepted answer solved the OP's original problem, most people finding this question through a Google search are likely having an entirely different problem which just happens to throw the same no suitable HttpMessageConverter found exception.

What happens under the covers is that MappingJackson2HttpMessageConverter swallows any exceptions that occur in its canRead() method, which is supposed to auto-detect whether the payload is suitable for json decoding. The exception is replaced by a simple boolean return that basically communicates sorry, I don't know how to decode this message to the higher level APIs (RestClient). Only after all other converters' canRead() methods return false, the no suitable HttpMessageConverter found exception is thrown by the higher-level API, totally obscuring the true problem.

For people who have not found the root cause (like you and me, but not the OP), the way to troubleshoot this problem is to place a debugger breakpoint on onMappingJackson2HttpMessageConverter.canRead(), then enable a general breakpoint on any exception, and hit Continue. The next exception is the true root cause.

My specific error happened to be that one of the beans referenced an interface that was missing the proper deserialization annotations.

UPDATE FROM THE FUTURE

This has proven to be such a recurring issue across so many of my projects, that I've developed a more proactive solution. Whenever I have a need to process JSON exclusively (no XML or other formats), I now replace my RestTemplate bean with an instance of the following:

public class JsonRestTemplate extends RestTemplate {

    public JsonRestTemplate(
            ClientHttpRequestFactory clientHttpRequestFactory) {
        super(clientHttpRequestFactory);

        // Force a sensible JSON mapper.
        // Customize as needed for your project's definition of "sensible":
        ObjectMapper objectMapper = new ObjectMapper()
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule())
                .configure(
                        SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter() {

            public boolean canRead(java.lang.Class<?> clazz,
                    org.springframework.http.MediaType mediaType) {
                return true;
            }    
            public boolean canRead(java.lang.reflect.Type type,
                    java.lang.Class<?> contextClass,
                    org.springframework.http.MediaType mediaType) {
                return true;
            }
            protected boolean canRead(
                    org.springframework.http.MediaType mediaType) {
                return true;
            }
        };

        jsonMessageConverter.setObjectMapper(objectMapper);
        messageConverters.add(jsonMessageConverter);
        super.setMessageConverters(messageConverters);

    }
}

This customization makes the RestClient incapable of understanding anything other than JSON. The upside is that any error messages that may occur will be much more explicit about what's wrong.

Xcode Error: "The app ID cannot be registered to your development team."

None of the above answers worked for me, and as said in the original question I had also to keep the same bundle identifier since the app was already published in the store by the client.

The solution for me was to ask the client to change my access from App Manager to Admin, so that I had "Access to Certificates, Identifiers & Profiles.", you can check if it is the case in the App Store Connect => Users and Access => and then click on your profile (be sure to choose the right team if you belong to multiple).

Once you are admin go back to Xcode and in the signing tab select 'Automatically manage signing', then in Team dropdown you should be able to select the right team and the signature will work.

How to make primary key as autoincrement for Room Persistence lib

@Entity(tableName = "user")
data class User(

@PrimaryKey(autoGenerate = true)  var id: Int?,
       var name: String,
       var dob: String,
       var address: String,
       var gender: String
)
{
    constructor():this(null,
        "","","","")
}

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Since Django 2.0 the ForeignKey field requires two positional arguments:

  1. the model to map to
  2. the on_delete argument
categorie = models.ForeignKey('Categorie', on_delete=models.PROTECT)

Here are some methods can used in on_delete

  1. CASCADE

Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey

  1. PROTECT

Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

  1. DO_NOTHING

Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.

you can find more about on_delete by reading the documentation.

Angular 4/5/6 Global Variables

You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.

How to include css files in Vue 2

As you can see, the import command did work but is showing errors because it tried to locate the resources in vendor.css and couldn't find them

You should also upload your project structure and ensure that there aren't any path issues. Also, you could include the css file in the index.html or the Component template and webpack loader would extract it when built

How to import functions from different js file in a Vue+webpack+vue-loader project

After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?

BUT there was an import that was screwing the rest of it up:

Use require in .vue files

<script>
  var mylib = require('./mylib');
  export default {
  ....

Exports in mylib

 exports.myfunc = () => {....}

Avoid import

The actual issue in my case (which I didn't think was relevant!) was that mylib.js was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack but anyway I had:

import models from './model/models'
import axios from 'axios'

This works so long as I'm not using mylib in a .vue component. However as soon as I use mylib there, the error described in this issue arises.

I changed to:

let models = require('./model/models');
let axios = require('axios');

And all works as expected.

Component is part of the declaration of 2 modules

If your pages is created by using CLI then it creates a file with filename.module.ts then you have to register your filename.module.ts in imports array in app.module.ts file and don't insert that page in declarations array.

eg.

import { LoginPageModule } from '../login/login.module';


declarations: [
    MyApp,
    LoginPageModule,// remove this and add it below array i.e. imports
],

imports: [
        BrowserModule,
        HttpModule,
        IonicModule.forRoot(MyApp, {
           scrollPadding: false,
           scrollAssist: true,
           autoFocusAssist: false,
           tabsHideOnSubPages:false
        }),
       LoginPageModule,
],

React-Native Button style not work

If you do not want to create your own button component, a quick and dirty solution is to wrap the button in a view, which allows you to at least apply layout styling.

For example this would create a row of buttons:

<View style={{flexDirection: 'row'}}>
    <View style={{flex:1 , marginRight:10}} >
        <Button title="Save" onPress={() => {}}></Button>
    </View>
    <View style={{flex:1}} >
        <Button title="Cancel" onPress={() => {}}></Button>
    </View>
</View>

Spring boot: Unable to start embedded Tomcat servlet container

You need to Tomcat Dependency and also extend your Application Class from extends SpringBootServletInitializer

@SpringBootApplication  
public class App extend SpringBootServletInitializer
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, "hello");
    }
}

Visual Studio Code pylint: Unable to import 'protorpc'

I got the same error on my vscode where I had a library installed and the code working when running from the terminal, but for some reason, the vscode pylint was not able to pick the installed package returning the infamous error:

Unable to import 'someLibrary.someModule' pylint(import-error)

The problem might arise due to the multiple Python installations. Basically you have installed a library/package on one, and vscode pylint is installed and running from another installation. For example, on macOS and many Linux distros, there are by default Python2 installed and when you install Python3 this might cause confusion. Also on windows the Chocolatey package manager might cause some mess and you end up with multiple Python installations. To figure it out if you are on a *nix machine (i.e., macOS, GNU/Linux, BSD...), use the which command, and if you are on Windows, use the where command to find the installed Python interpreters. For example, on *nix machines:

which python3

and on Windows

where python

then you may want to uninstall the ones you don't want. and the one you want to use check if the package causing above issue is installed by

python -c "import someLibrary"

if you get an error then you should install it by for example pip:

pip install someLibrary

then on vscode press ??P if you are on a mac and CtrlShiftP on other operating systems. Then type-select the >python: Select Interpreter option and select the one you know have the library installed. At this moment vscode might asks you to install pyling again, which you just go on with.

How to pass a parameter to Vue @click event handler

When you are using Vue directives, the expressions are evaluated in the context of Vue, so you don't need to wrap things in {}.

@click is just shorthand for v-on:click directive so the same rules apply.

In your case, simply use @click="addToCount(item.contactID)"

onKeyDown event not working on divs in React

You're missing the binding of the method in the constructor. This is how React suggests that you do it:

class Whatever {
  constructor() {
    super();
    this.onKeyPressed = this.onKeyPressed.bind(this);
  }

  onKeyPressed(e) {
    // your code ...
  }

  render() {
    return (<div onKeyDown={this.onKeyPressed} />);
  }
}

There are other ways of doing this, but this will be the most efficient at runtime.

Error: the entity type requires a primary key

I found a bit different cause of the error. It seems like SQLite wants to use correct primary key class property name. So...

Wrong PK name

public class Client
{
  public int SomeFieldName { get; set; }  // It is the ID
  ...
}

Correct PK name

public class Client
{
  public int Id { get; set; }  // It is the ID
  ...
}

public class Client
{
  public int ClientId { get; set; }  // It is the ID
  ...
}

It still posible to use wrong PK name but we have to use [Key] attribute like

public class Client
{
   [Key]
   public int SomeFieldName { get; set; }  // It is the ID
   ...
}

Bootstrap 4 File Input

For Bootstrap v.5

document.querySelectorAll('.form-file-input')
        .forEach(el => el.addEventListener('change', e => e.target.parentElement.querySelector('.form-file-text').innerText = e.target.files[0].name));

Affect all file input element. No need to specify elements id.

What is the role of "Flatten" in Keras?

It is rule of thumb that the first layer in your network should be the same shape as your data. For example our data is 28x28 images, and 28 layers of 28 neurons would be infeasible, so it makes more sense to 'flatten' that 28,28 into a 784x1. Instead of wriitng all the code to handle that ourselves, we add the Flatten() layer at the begining, and when the arrays are loaded into the model later, they'll automatically be flattened for us.

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

While using formControl, you have to import ReactiveFormsModule to your imports array.

Example:

import {FormsModule, ReactiveFormsModule} from '@angular/forms';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    MaterialModule,
  ],
  ...
})
export class AppModule {}

CSS hide scroll bar, but have element scrollable

if you use sass, you can try this

&::-webkit-scrollbar { 

}

How to remove an item from an array in Vue.js

It is even funnier when you are doing it with inputs, because they should be bound. If you are interested in how to do it in Vue2 with options to insert and delete, please see an example:

please have a look an js fiddle

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    finds: [] _x000D_
  },_x000D_
  methods: {_x000D_
    addFind: function () {_x000D_
      this.finds.push({ value: 'def' });_x000D_
    },_x000D_
    deleteFind: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.finds.splice(index, 1);_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Finds</h1>_x000D_
  <div v-for="(find, index) in finds">_x000D_
    <input v-model="find.value">_x000D_
    <button @click="deleteFind(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addFind">_x000D_
    New Find_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

On Windows:

To get started, open the command prompt by clicking on Start and then typing cmd. In the command window, go ahead and type in the following command:

netstat -a -n -o

In the command above, the -o parameter is what will add the PID to the end of the table. Press enter and you should see something like this:

enter image description here

Now to see the name of the process that is using that port, go to Task Manager by pressing CTRL + SHIFT + ESC and then click on the Process tab. In Windows 10, you should click on the Details tab.

By default, the task manager does not display the process ID, so you have to click on View and then Select Columns.

You might also need to look into services running in background. To do that right-click and select open services as shown below:

enter image description here

Hope it helps :)

How can I add a .npmrc file?

There are a few different points here:

  1. Where is the .npmrc file created.
  2. How can you download private packages

Running npm config ls -l will show you all the implicit settings for npm, including what it thinks is the right place to put the .npmrc. But if you have never logged in (using npm login) it will be empty. Simply log in to create it.

Another thing is #2. You can actually do that by putting a .npmrc file in the NPM package's root. It will then be used by NPM when authenticating. It also supports variable interpolation from your shell so you could do stuff like this:

; Get the auth token to use for fetching private packages from our private scope
; see http://blog.npmjs.org/post/118393368555/deploying-with-npm-private-modules
; and also https://docs.npmjs.com/files/npmrc
//registry.npmjs.org/:_authToken=${NPM_TOKEN}

Pointers

Disable back button in react navigation

ReactNavigation v 5.0 - Stack option:

options={{
headerLeft: () => { 
 return <></>; 
}
}}

Vuejs and Vue.set(), update array

One alternative - and more lightweight approach to your problem - might be, just editing the array temporarily and then assigning the whole array back to your variable. Because as Vue does not watch individual items it will watch the whole variable being updated.

So you this should work as well:

var tempArray[];

tempArray = this.items;

tempArray[targetPosition]  = value;

this.items = tempArray;

This then should also update your DOM.

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

I tried all the solutions here, but to no avail. Eventually, I solved it by opening the new csproj file and manually added the following section:

<Reference Include="System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<HintPath>..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll</HintPath>
</Reference>

'ls' in CMD on Windows is not recognized

Use the command dir to list all the directories and files in a directory; ls is a unix command.

How to download Visual Studio 2017 Community Edition for offline installation?

Check your %temp% folder after download. In my case, download went both in temp folder and one I specified. After download was completed, files from temp folder were not deleted.
Also, make sure to have enough space on system partition (or wherever your %temp% is) in the first place. For community edition download is over 16GB for everything.

Bootstrap 4 Change Hamburger Toggler Color

EDIT : my bad! With my answer, the icon won't behave as a toggler Actually, it will be shown even when not collapsed... Still searching...

This would work :

<button class="btn btn-primary" type="button" data-toggle="collapse" 
    data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
    aria-expanded="false" aria-label="Toggle navigation">
    <span>
        <i class="fas fa-bars"></i>
    </span>
</button>

The trick proposed by my answer is to replace the navbar-toggler with a classical button class btn and then, as answered earlier, use an icon font.

Note, that if you keep <button class="navbar-toggler">, the button will have a "strange" shape.

As stated in this post on github, bootstrap uses some "css trickery", so users don't have to rely on fonts.

So, just don't use the "navbar-toggler" class on your button if you want to use an icon font.

Cheers.

How can I serve static html from spring boot?

In Spring boot, /META-INF/resources/, /resources/, static/ and public/ directories are available to serve static contents.

So you can create a static/ or public/ directory under resources/ directory and put your static contents there. And they will be accessible by: http://localhost:8080/your-file.ext. (assuming the server.port is 8080)

You can customize these directories using spring.resources.static-locations in the application.properties.

For example:

spring.resources.static-locations=classpath:/custom/

Now you can use custom/ folder under resources/ to serve static files.

Update:

This is also possible using java config:

@Configuration
public class StaticConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/custom/");
    }
}

This confugration maps contents of custom directory to the http://localhost:8080/static/** url.

Jenkins: Can comments be added to a Jenkinsfile?

Comments work fine in any of the usual Java/Groovy forms, but you can't currently use groovydoc to process your Jenkinsfile (s).

First, groovydoc chokes on files without extensions with the wonderful error

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109)
    at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDocAssembler.<init>(SimpleGroovyClassDocAssembler.java:67)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.parseGroovy(GroovyRootDocBuilder.java:131)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.getClassDocsFromSingleSource(GroovyRootDocBuilder.java:83)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.processFile(GroovyRootDocBuilder.java:213)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.buildTree(GroovyRootDocBuilder.java:168)
    at org.codehaus.groovy.tools.groovydoc.GroovyDocTool.add(GroovyDocTool.java:82)
    at org.codehaus.groovy.tools.groovydoc.GroovyDocTool$add.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at org.codehaus.groovy.tools.groovydoc.Main.execute(Main.groovy:214)
    at org.codehaus.groovy.tools.groovydoc.Main.main(Main.groovy:180)
    ... 6 more

... and second, as far as I can tell Javadoc-style commments at the start of a groovy script are ignored. So even if you copy/rename your Jenkinsfile to Jenkinsfile.groovy, you won't get much useful output.

I want to be able to use a

/**
 * Document my Jenkinsfile's overall purpose here
 */

comment at the start of my Jenkinsfile. No such luck (yet).

groovydoc will process classes and methods defined in your Jenkinsfile if you pass -private to the command, though.

How to window.scrollTo() with a smooth effect

$('html, body').animate({scrollTop:1200},'50');

You can do this!

Vertical Align Center in Bootstrap 4

<div class="row">
  <div class="col-md-6">
     <img src="/assets/images/ebook2.png" alt="" class="img-fluid">
  </div>
  <div class="col-md-6 my-auto">
     <h3>Heading</h3>
     <p>Some text.</p>
   </div>
</div>

This line is where the magic happens <div class="col-md-6 my-auto">, the my-auto will center the content of the column. This works great with situations like the code sample above where you might have a variable sized image and need to have the text in the column to the right line up with it.

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

I had this issue when working on a Java Project in Debian 10 with Tomcat as the application server.

The issue was that the application already had https defined as it's default protocol while I was using http to call the application in the browser. So when I try running the application I get this error in my log file:

INFO [http-nio-80-exec-4461] org.apache.coyote.http11.AbstractHttp11Processor.process Error parsing HTTP request header

Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.

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

I however tried using the https protocol in the browser but it didn't connect throwing the error:

Here's how I solved it:

You need a certificate to setup the https protocol for the application. You can obtain certificates from Let's Encrypt. For me the easiest route was creating a obtaining a self-signed certificate. .

I first had to create a keystore file for the application, more like a self-signed certificate for the https protocol:

sudo keytool -genkey -keyalg RSA -alias tomcat -keystore /usr/share/tomcat.keystore

Note: You need to have Java installed on the server to be able to do this. Java can be installed using sudo apt install default-jdk.

Next, I added a https Tomcat server connector for the application in the Tomcat server configuration file (/opt/tomcat/conf/server.xml):

sudo nano /opt/tomcat/conf/server.xml

Add the following to the configuration of the application. Notice that the keystore file location and password are specified. Also a port for the https protocol is defined, which is different from the port for the http protocol:

<Connector protocol="org.apache.coyote.http11.Http11Protocol"
           port="8443" maxThreads="200" scheme="https"
           secure="true" SSLEnabled="true"
           keystoreFile="/usr/share/tomcat.keystore"
           keystorePass="my-password"
           clientAuth="false" sslProtocol="TLS"
           URIEncoding="UTF-8"
           compression="force"
           compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css"/>

So the full server configuration for the application looked liked this in the Tomcat server configuration file (/opt/tomcat/conf/server.xml):

<Service name="my-application">
  <Connector protocol="org.apache.coyote.http11.Http11Protocol"
             port="8443" maxThreads="200" scheme="https"
             secure="true" SSLEnabled="true"
             keystoreFile="/usr/share/tomcat.keystore"
             keystorePass="my-password"
             clientAuth="false" sslProtocol="TLS"
             URIEncoding="UTF-8"
             compression="force"
             compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css"/>

  <Connector port="8009" protocol="HTTP/1.1"
             connectionTimeout="20000"
             redirectPort="8443" />

  <Engine name="my-application" defaultHost="localhost">
     <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>
    </Realm>

    <Host name="localhost"  appBase="webapps"
          unpackWARs="true" autoDeploy="true">

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
             prefix="localhost_access_log" suffix=".txt"
             pattern="%h %l %u %t &quot;%r&quot; %s %b" />

    </Host>
  </Engine>
</Service>

This time when I tried accessing the application from the browser using:

https://my-server-ip-address:https-port

In my case it was:

https:35.123.45.6:8443

it worked fine. Although, I had to accept a warning which added a security exception for the website since the certificate used is a self-signed one.

That's all.

I hope this helps

Add Insecure Registry to Docker

Creating /etc/docker/daemon.json file and adding the below content and then doing a docker restart on CentOS 7 resolved the issue.

{
    "insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}

Laravel 5.4 redirection to custom url after login

in accord with Laravel documentation, I create in app/Http/Controllers/Auth/LoginController.php the following method :

protected function redirectTo()
{
    $user=Auth::user();

    if($user->account_type == 1){
        return '/admin';
    }else{
        return '/home';
    }

}

to get the user information from my db I used "Illuminate\Support\Facades\Auth;".

How to define and use function inside Jenkins Pipeline config?

First off, you shouldn't add $ when you're outside of strings ($class in your first function being an exception), so it should be:

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
...

Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:

...
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1', null)
    }
}

... or you need to add a default value to the functions' second argument:

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere($projectName)
}

Getting Error "Form submission canceled because the form is not connected"

Quick answer : append the form to the body.

document.body.appendChild(form);

Or, if you're using jQuery as above: $(document.body).append(form);

Details : According to the HTML standards, if the form is not associated to the browsing context(document), the form submission will be aborted.

HTML SPEC see 4.10.21.3.2

In Chrome 56, this spec was applied.

Chrome code diff see @@ -347,9 +347,16 @@

P.S about your question #1. In my opinion, unlike ajax, form submission causes instant page move.
So, showing 'deprecated warning message' is almost impossible.
I also think it's unacceptable that this serious change is not included in the feature change list. Chrome 56 features - www.chromestatus.com/features#milestone%3D56

Uncaught TypeError: (intermediate value)(...) is not a function

Error Case:

var userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;

Output:

TypeError: (intermediate value)(intermediate value) is not a function

Fix: You are missing a semi-colon (;) to separate the expressions

userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}; // Without a semi colon, the error is produced

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;

MultipartException: Current request is not a multipart request

It looks like the problem is request to server is not a multi-part request. Basically you need to modify your client-side form. For example:

<form action="..." method="post" enctype="multipart/form-data">
  <input type="file" name="file" />
</form>

Hope this helps.

How to restart VScode after editing extension's config?

You can do the following

  1. Click on extensions
  2. Type Reload
  3. Then install

It will add a reload button on your right hand at the bottom of the vs code.

How to parse JSON in Kotlin?

This uses kotlinx.serialization like Elisha's answer. Meanwhile the API is being stabilized for the upcoming 1.0 release. Note that e.g. JSON.parse was renamed to Json.parse and is now Json.decodeFromString. Also it is imported in gradle differently starting in Kotlin 1.4.0:

dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-core:1.0.0-RC"
}
apply plugin: 'kotlinx-serialization'

Example usage:

@Serializable
data class Properties(val nid: Int, val tid: Int)
@Serializable
data class Feature(val pos: List<Double>, val properties: Properties? = null, 
    val count: Int? = null)
@Serializable
data class Root(val features: List<Feature>)


val root = Json.decodeFromString<Root>(jsonStr)
val rootAlt = Json.decodeFromString(Root.serializer(), jsonStr)  // equivalent

val str = Json.encodeToString(root)  // type 'Root' can be inferred!

// For a *top-level* list (does not apply in my case) you would use 
val fList = Json.decodeFromString<List<Feature>>(jsonStr)
val fListAlt = Json.decodeFromString(ListSerializer(Feature.serializer()), jsonStr)

Kotlin's data class defines a class that mainly holds data and has .toString() and other methods (e.g. destructuring declarations) automatically defined. I'm using nullable (?) types here for optional fields.

Clear git local cache

if you do any changes on git ignore then you have to clear you git cache also

> git rm -r --cached . 
> git add . 
> git commit -m 'git cache cleared'
> git push

if want to remove any particular folder or file then

git rm  --cached filepath/foldername

Plotting images side by side using matplotlib

One thing that I found quite helpful to use to print all images :

_, axs = plt.subplots(n_row, n_col, figsize=(12, 12))
axs = axs.flatten()
for img, ax in zip(imgs, axs):
    ax.imshow(img)
plt.show()

adding text to an existing text element in javascript via DOM

remove .textContent from var t = document.getElementById("p").textContent;

_x000D_
_x000D_
var t = document.getElementById("p");_x000D_
var y = document.createTextNode("This just got added");_x000D_
_x000D_
t.appendChild(y);
_x000D_
<p id ="p">This is some text</p>
_x000D_
_x000D_
_x000D_

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment as you can see above).

Try checking to see if Hibernate core is put in as dependency:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.0.11.Final</version>
  <scope>compile</scope>
</dependency>

Bootstrap 4, How do I center-align a button?

Here is the full HTML that I use to center by button in Bootsrap form after closing form-group:

<div class="form-row text-center">
    <div class="col-12">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
 </div>

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

You must add it to entryComponents, as specified in the docs.

@NgModule({
  imports: [
    // ...
  ],
  entryComponents: [
    DialogInvokingComponent, 
    DialogResultExampleDialog
  ],
  declarations: [
    DialogInvokingComponent,   
    DialogResultExampleDialog
  ],
  // ...
})

Here is a full example for an app module file with a dialog defined as entryComponents.

Bootstrap 4 align navbar items to the right

Using the bootstrap flex box helps us to control the placement and alignment of your navigation element. for the problem above adding mr-auto is a better solution to it .

<div id="app" class="container">
  <nav class="navbar navbar-toggleable-md navbar-light bg-faded">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Navbar</a>
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricingg</a>
      </li>
    </ul>
    <ul class="navbar-nav  " >
      <li  class="nav-item">
        <a class="nav-link" href="{{ url('/login') }}">Login</a>
      </li>
      <li  class="nav-item">
        <a class="nav-link" href="{{ url('/register') }}">Register</a>
      </li>
    </ul>
  </nav>
  @yield('content')
</div>

other placement may include

fixed- top
    fixed bottom
    sticky-top

UnsatisfiedDependencyException: Error creating bean with name

Considering that your package scanning is correctly set either through XML configuration or annotation based configuration.

You will need a @Repository on your ClientRepository implementation as well to allow Spring to use it in an @Autowired. Since it's not here we can only suppose that's what's missing.

As a side note, it would be cleaner to put your @Autowired/@Qualifier directly on your member if the setter method is only used for the @Autowired.

@Autowired
@Qualifier("clientRepository")
private ClientRepository clientRepository;

Lastly, you don't need the @Qualifier is there is only one class implementing the bean definition so unless you have several implementation of ClientService and ClientRepository you can remove the @Qualifier

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

As already pointed out, b += 1 updates b in-place, while a = a + 1 computes a + 1 and then assigns the name a to the result (now a does not refer to a row of A anymore).

To understand the += operator properly though, we need also to understand the concept of mutable versus immutable objects. Consider what happens when we leave out the .reshape:

C = np.arange(12)
for c in C:
    c += 1
print(C)  # [ 0  1  2  3  4  5  6  7  8  9 10 11]

We see that C is not updated, meaning that c += 1 and c = c + 1 are equivalent. This is because now C is a 1D array (C.ndim == 1), and so when iterating over C, each integer element is pulled out and assigned to c.

Now in Python, integers are immutable, meaning that in-place updates are not allowed, effectively transforming c += 1 into c = c + 1, where c now refers to a new integer, not coupled to C in any way. When you loop over the reshaped arrays, whole rows (np.ndarray's) are assigned to b (and a) at a time, which are mutable objects, meaning that you are allowed to stick in new integers at will, which happens when you do a += 1.

It should be mentioned that though + and += are meant to be related as described above (and very much usually are), any type can implement them any way it wants by defining the __add__ and __iadd__ methods, respectively.

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

1.You need to create privacy policy page on your website and update your privacy policy for the permissions you are asking.

2.Update new SDK remove unwanted permissions and resubmit the app.

Violation Long running JavaScript task took xx ms

This is not an error just simple a message. To execute this message change
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> (example)
to
<!DOCTYPE html>(the Firefox source expect this)

The message was shown in Google Chrome 74 and Opera 60 . After changing it was clear, 0 verbose.
A solution approach

Adding Lombok plugin to IntelliJ project

Be sure to activate the plugin for the project in the Intellij settings.

  1. Click Settings Other Settings Lombok Plugin.
  2. Ensure Enable Lombock plugin... is checked.

Lombok Plugin Settings

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

Actually there is another solution, but it's a workaround, that should not be done in a properly managed project. However I met a situation, where it was not possible to go down the better road :)

You can update the schame_version table, and actually change the checksum to the new one. This will cause the migration to go through, but can have other side effects.

When deploying to different environments (test, uat, prod, etc) then it might happen, that you have to update the same checksum on more environments. And when it comes to gitflow, and release branches, you can easily mix up the whole.

How to correctly set Http Request Header in Angular 2

The simpler and current approach for adding header to a single request is:

// Step 1

const yourHeader: HttpHeaders = new HttpHeaders({
    Authorization: 'Bearer JWT-token'
});

// POST request

this.http.post(url, body, { headers: yourHeader });

// GET request

this.http.get(url, { headers: yourHeader });

Angular 1.6.0: "Possibly unhandled rejection" error

You could mask the problem by turning off errorOnUnhandledRejections, but the error says you're needing to "handle a possible rejection" so you just need to add a catch to your promise.

resource.get().$promise
    .then(function (response) {
    // do something with the response
    }).catch(function (error)) {
        // pass the error to the error service
        return errorService.handleError(error);
    });

Reference: https://github.com/angular-ui/ui-router/issues/2889

Spring Boot Java Config Set Session Timeout

server.session.timeout in the application.properties file is now deprecated. The correct setting is:

server.servlet.session.timeout=60s

Also note that Tomcat will not allow you to set the timeout any less than 60 seconds. For details about that minimum setting see https://github.com/spring-projects/spring-boot/issues/7383.

vuejs update parent data from child component

In child component:

this.$emit('eventname', this.variable)

In parent component:

<component @eventname="updateparent"></component>

methods: {
    updateparent(variable) {
        this.parentvariable = variable
    }
}

Removing object from array in Swift 3

In Swift 5, Use this Extension:

extension Array where Element: Equatable{
    mutating func remove (element: Element) {
        if let i = self.firstIndex(of: element) {
            self.remove(at: i)
        }
    }
}

example:

var array = ["alpha", "beta", "gamma"]
array.remove(element: "beta")

In Swift 3, Use this Extension:

extension Array where Element: Equatable{
    mutating func remove (element: Element) {
        if let i = self.index(of: element) {
            self.remove(at: i)
        }
    }
}

example:

var array = ["alpha", "beta", "gamma"]
array.remove(element: "beta")

Windows- Pyinstaller Error "failed to execute script " When App Clicked

In my case i have a main.py that have dependencies with other files. After I build that app with py installer using this command:

pyinstaller --onefile --windowed main.py

I got the main.exe inside dist folder. I double clicked on this file, and I raised the error mentioned above. To fix this, I just copy the main.exe from dist directory to previous directory, which is the root directory of my main.py and the dependency files, and I got no error after run the main.exe.

How to add a file to the last commit in git?

If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^. Then add all files and commit again.

Getting permission denied (public key) on gitlab

In my case it did not work in the WSL (Windows Subsystem for Linux).

When I start the WSL, I must

  • start ssh-agent_ eval $(ssh-agent -s)
  • add the key to the ssh-agent: ssh-add ~/.ssh/id_rsa
  • if prompted, enter the password

Now the connection works.
We can test this with ssh -T [email protected]

notes:

Spring security CORS Filter

Ok, after over 2 days of searching we finally fixed the problem. We deleted all our filter and configurations and instead used this 5 lines of code in the application class.

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        final ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:3000");
            }
        };
    }
}

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

Try configuring the project structure as given below:

Put all the repo, service, packages in the child package of the main package:

package com.leisure.moviemax;  //Parent package
        
@SpringBootApplication
@PropertySource(value={"classpath:conf.properties"})
    
public class MoviemaxApplication implements CommandLineRunner {
        
package com.leisure.moviemax.repo; //child package

@Repository
public interface UsrRepository extends JpaRepository<UserEntity,String> {

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

This question already has a great answer, but I ran into the same error, in a different scenario: displaying a List in an EditorTemplate.

I have a model like this:

public class Foo
{
    public string FooName { get; set; }
    public List<Bar> Bars { get; set; }
}

public class Bar
{
    public string BarName { get; set; }
}

And this is my main view:

@model Foo

@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })  
@Html.EditorFor(m => m.Bars)

And this is my Bar EditorTemplate (Bar.cshtml)

@model List<Bar>

<div class="some-style">
    @foreach (var item in Model)
    {
        <label>@item.BarName</label>
    }
</div>

And I got this error:

The model item passed into the dictionary is of type 'Bar', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Bar]


The reason for this error is that EditorFor already iterates the List for you, so if you pass a collection to it, it would display the editor template once for each item in the collection.

This is how I fixed this problem:

Brought the styles outside of the editor template, and into the main view:

@model Foo

@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })  
<div class="some-style">
    @Html.EditorFor(m => m.Bars)
</div>

And changed the EditorTemplate (Bar.cshtml) to this:

@model Bar

<label>@Model.BarName</label>

Deserialize Java 8 LocalDateTime with JacksonMapper

You used wrong letter case for year in line:

@JsonFormat(pattern = "YYYY-MM-dd HH:mm")

Should be:

@JsonFormat(pattern = "yyyy-MM-dd HH:mm")

With this change everything is working as expected.

How to Call a Function inside a Render in React/Jsx

_x000D_
_x000D_
class App extends React.Component {_x000D_
  _x000D_
  buttonClick(){_x000D_
    console.log("came here")_x000D_
    _x000D_
  }_x000D_
  _x000D_
  subComponent() {_x000D_
    return (<div>Hello World</div>);_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    return ( _x000D_
      <div className="patient-container">_x000D_
          <button onClick={this.buttonClick.bind(this)}>Click me</button>_x000D_
          {this.subComponent()}_x000D_
       </div>_x000D_
     )_x000D_
  }_x000D_
  _x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App/>, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

it depends on your need, u can use either this.renderIcon() or bind this.renderIcon.bind(this)

UPDATE

This is how you call a method outside the render.

buttonClick(){
    console.log("came here")
}

render() {
   return (
       <div className="patient-container">
          <button onClick={this.buttonClick.bind(this)}>Click me</button>
       </div>
   );
}

The recommended way is to write a separate component and import it.

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

I second Shobhit Verma, and I have a little note to add : in his post he told that in Chrome (Opera for myself) the players need to be muted in order for the autoplay to succeed... And ironically, if you elevate the volume after load, it will still play... It's like all those anti-pop-ups mechanic that ignore invisible frame slid into your code... php-echoed html and javascript is : 10-second setTimeout onLoad of body tag that rises volume to maximum, video with autoplay and muted='muted' (yeah that $muted_code part is = "muted='muted")

echo "<body style='margin-bottom:0pt; margin-top:0pt; margin-left:0pt; margin-right:0pt' onLoad=\"setTimeout(function() {var vid = document.getElementById('hourglass_video'); vid.volume = 1.0;},10000);\">";
    echo "<div id='hourglass_container' width='100%' height='100%' align='center' style='text-align:right; vertical-align:bottom'>";
    echo "<video autoplay {$muted_code}title=\"!!! Pausing this video will immediately end your turn!!!\" oncontextmenu=\"dont_stop_hourglass(event);\" onPause=\"{$action}\" id='hourglass_video' frameborder='0' style='width:95%; margin-top:28%'>";

how to implement Pagination in reactJs

I've implemented pagination in pure React JS recently. Here is a working demo: http://codepen.io/PiotrBerebecki/pen/pEYPbY

You would of course have to adjust the logic and the way page numbers are displayed so that it meets your requirements.

Full code:

class TodoApp extends React.Component {
  constructor() {
    super();
    this.state = {
      todos: ['a','b','c','d','e','f','g','h','i','j','k'],
      currentPage: 1,
      todosPerPage: 3
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(event) {
    this.setState({
      currentPage: Number(event.target.id)
    });
  }

  render() {
    const { todos, currentPage, todosPerPage } = this.state;

    // Logic for displaying todos
    const indexOfLastTodo = currentPage * todosPerPage;
    const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
    const currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);

    const renderTodos = currentTodos.map((todo, index) => {
      return <li key={index}>{todo}</li>;
    });

    // Logic for displaying page numbers
    const pageNumbers = [];
    for (let i = 1; i <= Math.ceil(todos.length / todosPerPage); i++) {
      pageNumbers.push(i);
    }

    const renderPageNumbers = pageNumbers.map(number => {
      return (
        <li
          key={number}
          id={number}
          onClick={this.handleClick}
        >
          {number}
        </li>
      );
    });

    return (
      <div>
        <ul>
          {renderTodos}
        </ul>
        <ul id="page-numbers">
          {renderPageNumbers}
        </ul>
      </div>
    );
  }
}


ReactDOM.render(
  <TodoApp />,
  document.getElementById('app')
);

When to use 'npm start' and when to use 'ng serve'?

If you want to run angular app ported from another machine without ng command then edit package.json as follows

"scripts": {
    "ng": "ng",
    "start": "node node_modules/.bin/ng serve",
    "build": "node node_modules/.bin/ng build",
    "test": "node node_modules/.bin/ng test",
    "lint": "node node_modules/.bin/ng lint",
    "e2e": "node node_modules/.bin/ng e2e"
  }

Finally run usual npm start command to start build server.

Align nav-items to right side in bootstrap-4

In my case, I was looking for a solution that allows one of the navbar items to be right aligned. In order to do this, you must add style="width:100%;" to the <ul class="navbar-nav"> and then add the ml-auto class to your navbar item.

How to request Location Permission at runtime

You need to actually request the Location permission at runtime (notice the comments in your code stating this).

Here is tested and working code to request the Location permission.

Be sure to import android.Manifest:

import android.Manifest;

Then put this code in the Activity:

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

public boolean checkLocationPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            new AlertDialog.Builder(this)
                    .setTitle(R.string.title_location_permission)
                    .setMessage(R.string.text_location_permission)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Prompt the user once explanation has been shown
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                    MY_PERMISSIONS_REQUEST_LOCATION);
                        }
                    })
                    .create()
                    .show();


        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // location-related task you need to do.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    //Request location updates:
                    locationManager.requestLocationUpdates(provider, 400, 1, this);
                }

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.

            }
            return;
        }

    }
}

Then call the checkLocationPermission() method in onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //.........

    checkLocationPermission();
}

You can then use onResume() and onPause() exactly as it is in the question.

Here is a condensed version that is a bit more clean:

@Override
protected void onResume() {
    super.onResume();
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {

        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }
}

@Override
protected void onPause() {
    super.onPause();
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {

        locationManager.removeUpdates(this);
    }
}

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

On Linux Machine, save the bash script and execute it. If you want to free port 8080, Input 8080 when prompted

echo "Enter port number to be closed :: "
read port
sudo kill $(sudo lsof -t -i:$port)

Default FirebaseApp is not initialized

If you're using Xamarin and came here searching for a solution for this problem, here it's from Microsoft:

In some cases, you may see this error message: Java.Lang.IllegalStateException: Default FirebaseApp is not initialized in this process Make sure to call FirebaseApp.initializeApp(Context) first.

This is a known problem that you can work around by cleaning the solution and rebuilding the project (Build > Clean Solution, Build > Rebuild Solution).

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

In my case, deleting any of the below annotations cause the error message 'entityManagerFactory' to show, for example.

 @Id
  @GeneratedValue(strategy=GenerationType.AUTO)

or

@ManyToMany(targetEntity=listOfObject_x.class)

The error message disappears after adding the missing annotation(s).

package mypackage_unameit;
import javax.persistence.PrePersist;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import lombok.Data;

@Data
@Entity
public class Someclasss {

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;

  @NotNull
  @Size(min=5, message="Name must be at least 5 characters long")
  private String name;

  private Date createdAt;

  @ManyToMany(targetEntity=listOfObject_x.class)
  @Size(min=1, message="You must choose at least 1 ingredient")
  private List<listOfObject_x>   = new ArrayList<>();

  @PrePersist
  void createdAt() {
    this.createdAt = new Date();
  }
}

Deep-Learning Nan loss reasons

Although most of the points are already discussed. But I would like to highlight again one more reason for NaN which is missing.

tf.estimator.DNNClassifier(
    hidden_units, feature_columns, model_dir=None, n_classes=2, weight_column=None,
    label_vocabulary=None, optimizer='Adagrad', activation_fn=tf.nn.relu,
    dropout=None, config=None, warm_start_from=None,
    loss_reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE, batch_norm=False
)

By default activation function is "Relu". It could be possible that intermediate layer's generating a negative value and "Relu" convert it into the 0. Which gradually stops training.

I observed the "LeakyRelu" able to solve such problems.

How to loop an object in React?

const tifOptions = [];

for (const [key, value] of Object.entries(tifs)) {
    tifOptions.push(<option value={key} key={key}>{value}</option>);
}

return (
   <select id="tif" name="tif" onChange={this.handleChange}>  
      { tifOptions }          
   </select>
)

'python3' is not recognized as an internal or external command, operable program or batch file

In my case I have a git hook on commit, specified by admin. So it was not very convenient for me to change the script (with python3 calls).

And the simplest workaround was just to copy python.exe to python3.exe.

Now I could launch both python and python3.

Request Permission for Camera and Library in iOS 10 - Info.plist

Use the plist settings mentioned above and the appropriate accessor (AVCaptureDevice or PHPhotoLibrary), but also alert them and send them to settings if you really need this, like so:

Swift 4.0 and 4.1

func proceedWithCameraAccess(identifier: String){
    // handler in .requestAccess is needed to process user's answer to our request
    AVCaptureDevice.requestAccess(for: .video) { success in
      if success { // if request is granted (success is true)
        DispatchQueue.main.async {
          self.performSegue(withIdentifier: identifier, sender: nil)
        }
      } else { // if request is denied (success is false)
        // Create Alert
        let alert = UIAlertController(title: "Camera", message: "Camera access is absolutely necessary to use this app", preferredStyle: .alert)

        // Add "OK" Button to alert, pressing it will bring you to the settings app
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
          UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!)
        }))
        // Show the alert with animation
        self.present(alert, animated: true)
      }
    }
  }

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

util.component.ts

@Component({
    selector: 'app-logout',
    template: `<button class="btn btn-primary"(click)="logout()">Logout</button>`
})
export class LogoutComponent{}

util.module.ts

@NgModule({
    imports: [...],
    exports: [
        LogoutComponent
    ],
    declarations: [LogoutComponent]
})
export class AccountModule{};

LogoutComponent Needs to be exported

dashboard.module.ts
import AccountModule in module where we want to use <app-logout> import { AccountModule } from 'util.module';

@NgModule({
  imports: [
    CommonModule, AccountModule
  ],
  declarations: [DashboardComponent]
})
export class DashboardModule { }

dashboard.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-dashboard',
  template: `<div><app-logout></app-logout></div>`
})
export class DashboardComponent implements OnInit {
  constructor() {}
  ngOnInit() {}
}

I am not required to import and use CUSTOM_ELEMENTS_SCHEMA.
however its not working when dashboard.module is lazy loaded.
When using CUSTOM_ELEMENTS_SCHEMA in case of lazy loading, error is suppressed but the component is not added to dom.

http post - how to send Authorization header?

you need RequestOptions

 let headers = new Headers({'Content-Type': 'application/json'});  
 headers.append('Authorization','Bearer ')
 let options = new RequestOptions({headers: headers});
 return this.http.post(APIname,body,options)
  .map(this.extractData)
  .catch(this.handleError);

for more check this link

@ViewChild in *ngIf

My goal was to avoid any hacky methods that assume something (e.g. setTimeout) and I ended up implementing the accepted solution with a bit of RxJS flavour on top:

  private ngUnsubscribe = new Subject();
  private tabSetInitialized = new Subject();
  public tabSet: TabsetComponent;
  @ViewChild('tabSet') set setTabSet(tabset: TabsetComponent) {
    if (!!tabSet) {
      this.tabSet = tabSet;
      this.tabSetInitialized.next();
    }
  }

  ngOnInit() {
    combineLatest(
      this.route.queryParams,
      this.tabSetInitialized
    ).pipe(
      takeUntil(this.ngUnsubscribe)
    ).subscribe(([queryParams, isTabSetInitialized]) => {
      let tab = [undefined, 'translate', 'versions'].indexOf(queryParams['view']);
      this.tabSet.tabs[tab > -1 ? tab : 0].active = true;
    });
  }

My scenario: I wanted to fire an action on a @ViewChild element depending on the router queryParams. Due to a wrapping *ngIf being false until the HTTP request returns the data, the initialization of the @ViewChild element happens with a delay.

How does it work: combineLatest emits a value for the first time only when each of the provided Observables emit the first value since the moment combineLatest was subscribed to. My Subject tabSetInitialized emits a value when the @ViewChild element is being set. Therewith, I delay the execution of the code under subscribe until the *ngIf turns positive and the @ViewChild gets initialized.

Of course don't forget to unsubscribe on ngOnDestroy, I do it using the ngUnsubscribe Subject:

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

How to embed new Youtube's live video permanent URL?

The embed URL for a channel's live stream is:

https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID

You can find your CHANNEL_ID at https://www.youtube.com/account_advanced

"CSV file does not exist" for a filename with embedded quotes

You are missing '/' before Users. I assume that you are using a MAC guessing from the file path names. You root directory is '/'.

How to enable directory listing in apache web server

I had to disable selinux to make this work. Note. The system needs to be rebooted for selinux to take effect.

How do I access Configuration in any class in ASP.NET Core?

In ASP.NET Core, there are configuration providers for reading configurations from almost anywhere such as files e.g. JSON, INI or XML, environment variables, Azure key vault, command-line arguments, etc. and many more sources. I have written a step by step guide to show you how can you configure your application settings in various files such as JSON, INI or XML and how can you read those settings from your application code. I will also demonstrate how can you read application settings as custom .NET types (classes) and how can you use the built-in ASP.NET Core dependency injection to read your configuration settings in multiple classes, services or even projects available in your solution.

Read A Step by Step Guide for ASP.NET Core Configuration

'gulp' is not recognized as an internal or external command

If you have mysql install in your windows 10 try uninstall every myqsl app from your computer. Its work for me. exactly when i installed the mysql in my computer gulp command and some other commands stop working and then i have tried everything but not nothing worked for me.

@viewChild not working - cannot read property nativeElement of undefined

it just simple :import this directory

import {Component, Directive, Input, ViewChild} from '@angular/core';

How to add SHA-1 to android application

If you are using Google Play App Signing, you don't need to add your SHA-1 keys manually, just login into Firebase go into "project settings"->"integration" and press a button to link Google Play with firebase, SHA-1 will be added automatically.

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I ran into the same error, when I just forgot to declare my custom component in my NgModule - check there, if the others solutions won't work for you.

How to get `DOM Element` in Angular 2?

Use ViewChild with #localvariable as shown here,

<textarea  #someVar  id="tasknote"
                  name="tasknote"
                  [(ngModel)]="taskNote"
                  placeholder="{{ notePlaceholder }}"
                  style="background-color: pink"
                  (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} 

</textarea>

In component,

OLDEST Way

import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

ngAfterViewInit()
{
   this.el.nativeElement.focus();
}


OLD Way

import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer) {}
ngAfterViewInit() {
    this.rd.invokeElementMethod(this.el.nativeElement,'focus');
}


Updated on 22/03(March)/2017

NEW Way

Please note from Angular v4.0.0-rc.3 (2017-03-10) few things have been changed. Since Angular team will deprecate invokeElementMethod, above code no longer can be used.

BREAKING CHANGES

since 4.0 rc.1:

rename RendererV2 to Renderer2
rename RendererTypeV2 to RendererType2
rename RendererFactoryV2 to RendererFactory2

import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer2) {}

ngAfterViewInit() {
      console.log(this.rd); 
      this.el.nativeElement.focus();      //<<<=====same as oldest way
}

console.log(this.rd) will give you following methods and you can see now invokeElementMethod is not there. Attaching img as yet it is not documented.

NOTE: You can use following methods of Rendere2 with/without ViewChild variable to do so many things.

enter image description here

Specifying java version in maven - differences between properties and compiler plugin

How to specify the JDK version?

Use any of three ways: (1) Spring Boot feature, or use Maven compiler plugin with either (2) source & target or (3) with release.

Spring Boot

  1. <java.version> is not referenced in the Maven documentation.
    It is a Spring Boot specificity.
    It allows to set the source and the target java version with the same version such as this one to specify java 1.8 for both :

    1.8

Feel free to use it if you use Spring Boot.

maven-compiler-plugin with source & target

  1. Using maven-compiler-plugin or maven.compiler.source/maven.compiler.target properties are equivalent.

That is indeed :

<plugins>
    <plugin>    
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
</plugins>

is equivalent to :

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

according to the Maven documentation of the compiler plugin since the <source> and the <target> elements in the compiler configuration use the properties maven.compiler.source and maven.compiler.target if they are defined.

source

The -source argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.source.

target

The -target argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.target.

About the default values for source and target, note that since the 3.8.0 of the maven compiler, the default values have changed from 1.5 to 1.6.

maven-compiler-plugin with release instead of source & target

  1. The maven-compiler-plugin 3.6 and later versions provide a new way :

    org.apache.maven.plugins maven-compiler-plugin 3.8.0 9

You could also declare just :

<properties>
    <maven.compiler.release>9</maven.compiler.release>
</properties>

But at this time it will not work as the maven-compiler-plugin default version you use doesn't rely on a recent enough version.

The Maven release argument conveys release : a new JVM standard option that we could pass from Java 9 :

Compiles against the public, supported and documented API for a specific VM version.

This way provides a standard way to specify the same version for the source, the target and the bootstrap JVM options.
Note that specifying the bootstrap is a good practice for cross compilations and it will not hurt if you don't make cross compilations either.


Which is the best way to specify the JDK version?

The first way (<java.version>) is allowed only if you use Spring Boot.

For Java 8 and below :

About the two other ways : valuing the maven.compiler.source/maven.compiler.target properties or using the maven-compiler-plugin, you can use one or the other. It changes nothing in the facts since finally the two solutions rely on the same properties and the same mechanism : the maven core compiler plugin.

Well, if you don't need to specify other properties or behavior than Java versions in the compiler plugin, using this way makes more sense as this is more concise:

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

From Java 9 :

The release argument (third point) is a way to strongly consider if you want to use the same version for the source and the target.

What happens if the version differs between the JDK in JAVA_HOME and which one specified in the pom.xml?

It is not a problem if the JDK referenced by the JAVA_HOME is compatible with the version specified in the pom but to ensure a better cross-compilation compatibility think about adding the bootstrap JVM option with as value the path of the rt.jar of the target version.

An important thing to consider is that the source and the target version in the Maven configuration should not be superior to the JDK version referenced by the JAVA_HOME.
A older version of the JDK cannot compile with a more recent version since it doesn't know its specification.

To get information about the source, target and release supported versions according to the used JDK, please refer to java compilation : source, target and release supported versions.


How handle the case of JDK referenced by the JAVA_HOME is not compatible with the java target and/or source versions specified in the pom?

For example, if your JAVA_HOME refers to a JDK 1.7 and you specify a JDK 1.8 as source and target in the compiler configuration of your pom.xml, it will be a problem because as explained, the JDK 1.7 doesn't know how to compile with.
From its point of view, it is an unknown JDK version since it was released after it.
In this case, you should configure the Maven compiler plugin to specify the JDK in this way :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <compilerVersion>1.8</compilerVersion>      
        <fork>true</fork>
        <executable>D:\jdk1.8\bin\javac</executable>                
    </configuration>
</plugin>

You could have more details in examples with maven compiler plugin.


It is not asked but cases where that may be more complicated is when you specify source but not target. It may use a different version in target according to the source version. Rules are particular : you can read about them in the Cross-Compilation Options part.


Why the compiler plugin is traced in the output at the execution of the Maven package goal even if you don't specify it in the pom.xml?

To compile your code and more generally to perform all tasks required for a maven goal, Maven needs tools. So, it uses core Maven plugins (you recognize a core Maven plugin by its groupId : org.apache.maven.plugins) to do the required tasks : compiler plugin for compiling classes, test plugin for executing tests, and so for... So, even if you don't declare these plugins, they are bound to the execution of the Maven lifecycle.
At the root dir of your Maven project, you can run the command : mvn help:effective-pom to get the final pom effectively used. You could see among other information, attached plugins by Maven (specified or not in your pom.xml), with the used version, their configuration and the executed goals for each phase of the lifecycle.

In the output of the mvn help:effective-pom command, you could see the declaration of these core plugins in the <build><plugins> element, for example :

...
<plugin>
   <artifactId>maven-clean-plugin</artifactId>
   <version>2.5</version>
   <executions>
     <execution>
       <id>default-clean</id>
       <phase>clean</phase>
       <goals>
         <goal>clean</goal>
       </goals>
     </execution>
   </executions>
 </plugin>
 <plugin>
   <artifactId>maven-resources-plugin</artifactId>
   <version>2.6</version>
   <executions>
     <execution>
       <id>default-testResources</id>
       <phase>process-test-resources</phase>
       <goals>
         <goal>testResources</goal>
       </goals>
     </execution>
     <execution>
       <id>default-resources</id>
       <phase>process-resources</phase>
       <goals>
         <goal>resources</goal>
       </goals>
     </execution>
   </executions>
 </plugin>
 <plugin>
   <artifactId>maven-compiler-plugin</artifactId>
   <version>3.1</version>
   <executions>
     <execution>
       <id>default-compile</id>
       <phase>compile</phase>
       <goals>
         <goal>compile</goal>
       </goals>
     </execution>
     <execution>
       <id>default-testCompile</id>
       <phase>test-compile</phase>
       <goals>
         <goal>testCompile</goal>
       </goals>
     </execution>
   </executions>
 </plugin>
  ...

You can have more information about it in the introduction of the Maven lifeycle in the Maven documentation.

Nevertheless, you can declare these plugins when you want to configure them with other values as default values (for example, you did it when you declared the maven-compiler plugin in your pom.xml to adjust the JDK version to use) or when you want to add some plugin executions not used by default in the Maven lifecycle.

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

import {FormControl,FormGroup} from '@angular/forms';

import {FormsModule,ReactiveFormsModule} from '@angular/forms';

You should also add the missing ones.

React Native: Possible unhandled promise rejection

According to this post, you should enable it in XCode.

  1. Click on your project in the Project Navigator
  2. Open the Info tab
  3. Click on the down arrow left to the "App Transport Security Settings"
  4. Right click on "App Transport Security Settings" and select Add Row
  5. For created row set the key “Allow Arbitrary Loads“, type to boolean and value to YES.

enter image description here

Css transition from display none to display block, navigation with subnav

Generally when people are trying to animate display: none what they really want is:

  1. Fade content in, and
  2. Have the item not take up space in the document when hidden

Most popular answers use visibility, which can only achieve the first goal, but luckily it's just as easy to achieve both by using position.

Since position: absolute removes the element from typing document flow spacing, you can toggle between position: absolute and position: static (global default), combined with opacity. See the below example.

_x000D_
_x000D_
.content-page {_x000D_
  position:absolute;_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
.content-page.active {_x000D_
  position: static;_x000D_
  opacity: 1;_x000D_
  transition: opacity 1s linear;_x000D_
}
_x000D_
_x000D_
_x000D_

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

TL;DR

Just returning response()->json($promotion) won't solve the issue in this question. $promotion is an Eloquent object, which Laravel will automatically json_encode for the response. The json encoding is failing because of the img property, which is a PHP stream resource, and cannot be encoded.

Details

Whatever you return from your controller, Laravel is going to attempt to convert to a string. When you return an object, the object's __toString() magic method will be invoked to make the conversion.

Therefore, when you just return $promotion from your controller action, Laravel is going to call __toString() on it to convert it to a string to display.

On the Model, __toString() calls toJson(), which returns the result of json_encode. Therefore, json_encode is returning false, meaning it is running into an error.

Your dd shows that your img attribute is a stream resource. json_encode cannot encode a resource, so this is probably causing the failure. You should add your img attribute to the $hidden property to remove it from the json_encode.

class Promotion extends Model
{
    protected $hidden = ['img'];

    // rest of class
}

How to change the port number for Asp.Net core app?

Go to your program.cs file add UseUrs method to set your url, make sure you don't use a reserved url or port

 public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()

                // params string[] urls
                .UseUrls(urls: "http://localhost:10000")

                .Build();
    }

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

React eslint error missing in props validation

It seems that the problem is in eslint-plugin-react.

It can not correctly detect what props were mentioned in propTypes if you have annotated named objects via destructuring anywhere in the class.

There was similar problem in the past

ImportError: No module named google.protobuf

I got the same error message as in the title, but in my case import google was working and import google.protobuf wasn't (on python3.5, ubuntu 16.04).

It turned out that I've installed python3-google-apputils package (using apt) and it was installed to '/usr/lib/python3/dist-packages/google/apputils/', while protobuf (which was installed using pip) was in "/usr/lib/python3.5/dist-packages/google/protobuf/" - and it was a "google" namespace collapse.

Uninstalling google-apputils (from apt, and reinstalling it using pip) solved the problem.

sudo apt remove python3-google-apputils
sudo pip3 install google-apputils

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

One need to update Newtonsoft.Json -Version GO to Tools => NuGet Package Manager => Package Manager Console and Type Install-Package Newtonsoft.Json -Version 12.0.2 in Package Manager Console Window.

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

Useful link here: Access Tomcat Manager App from different host

From Tomcat version 8 onward's, manager/html url won't be accessible to anyone except localhost.

In order to access /manager/html url, you need to do below change in context.xml of manager app. 1. Go to /apache-tomcat-8.5.23/webapps/manager/META-INF location, then edit context.xml

<Context antiResourceLocking="false" privileged="true" >
  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="^.*$" />
 ......
</Context>
  1. Restart the server.

Import JavaScript file and call functions using webpack, ES6, ReactJS

Named exports:

Let's say you create a file called utils.js, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:

export function add(x, y) {
  return x + y
}

export function mutiply(x, y) {
  return x * y
}

Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:

import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.

Or if you prefer, place the entire module's contents under a common namespace:

import * as utils from './utils.js'; 
...
utils.multiply(2,3)

Default exports:

If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js, with only one function that logs out whatever argument it's called with:

export default function log(message) {
  console.log(message);
}

This can now be used like this:

import log from './log.js';
...
log('test') // Would print 'test' in the console.

You don't have to call it log when you import it, you could actually call it whatever you want:

import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.

Combined:

A module can have both a default export (max 1), and named exports (imported either one by one, or using * with an alias). React actually has this, consider:

import React, { Component, PropTypes } from 'react';

Vue equivalent of setTimeout?

If you want to use the this keyword in your function, you need to write the setTimeout function in ES6

setTimeout(() => {
   this.filters.max_budget_gt_eq = this.budgetHigherValue;
}, 1000);

When is a timestamp (auto) updated?

I think you have to define the timestamp column like this

CREATE TABLE t1 
(
    ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

See here

Remove Last Comma from a string

This will remove the last comma and any whitespace after it:

str = str.replace(/,\s*$/, "");

It uses a regular expression:

  • The / mark the beginning and end of the regular expression

  • The , matches the comma

  • The \s means whitespace characters (space, tab, etc) and the * means 0 or more

  • The $ at the end signifies the end of the string

Finding the type of an object in C++

This is called RTTI, but you almost surely want to reconsider your design here, because finding the type and doing special things based on it makes your code more brittle.

Define a fixed-size list in Java

This should do it if memory serves:

List<MyType> fixed = Arrays.asList(new MyType[100]);

How to install MySQLdb package? (ImportError: No module named setuptools)

I am experiencing the same problem right now. According to this post you need to have a C Compiler or GCC. I'll try to fix the problem by installing C compiler. I'll inform you if it works (we'll I guess you don't need it anymore, but I'll post the result anyway) :)

Best way to check if a character array is empty

The second one is fastest. Using strlen will be close if the string is indeed empty, but strlen will always iterate through every character of the string, so if it is not empty, it will do much more work than you need it to.

As James mentioned, the third option wipes the string out before checking, so the check will always succeed but it will be meaningless.

How do you increase the max number of concurrent connections in Apache?

change the MaxClients directive. it is now on 256.

Any way to break if statement in PHP?

Because you can break out of a do/while loop, let us "do" one round. With a while(false) at the end, the condition is never true and will not repeat, again.

do
{
    $subjectText = trim(filter_input(INPUT_POST, 'subject'));
    if(!$subjectText)
    {
        $smallInfo = 'Please give a subject.';
        break;
    }

    $messageText = trim(filter_input(INPUT_POST, 'message'));
    if(!$messageText)
    {
        $smallInfo = 'Please supply a message.';
        break;
    }
} while(false);

Cast a Double Variable to Decimal

You can cast a double to a decimal like this, without needing the M literal suffix:

double dbl = 1.2345D;
decimal dec = (decimal) dbl;

You should use the M when declaring a new literal decimal value:

decimal dec = 123.45M;

(Without the M, 123.45 is treated as a double and will not compile.)

javascript close current window

In JavaScript, we can close a window only if it is opened by using window.open method:

window.open('https://www.google.com');
window.close();

But to close a window which has not been opened using window.open(), you must

  1. Open any other URL or a blank page in the same tab
  2. Close this newly opened tab (this will work because it was opened by window.open())
window.open("", "_self");
window.close();

C - The %x format specifier

From http://en.wikipedia.org/wiki/Printf_format_string

use 0 instead of spaces to pad a field when the width option is specified. For example, printf("%2d", 3) results in " 3", while printf("%02d", 3) results in "03".

How to position a div scrollbar on the left hand side?

No, you can't change scrollbars placement without any additional issues.

You can change text-direction to right-to-left ( rtl ), but it also change text position inside block.

This code can helps you, but I not sure it works in all browsers and OS.

<element style="direction: rtl; text-align: left;" />

generate days from date range

The old school solution for doing this without a loop/cursor is to create a NUMBERS table, which has a single Integer column with values starting at 1.

CREATE TABLE  `example`.`numbers` (
  `id` int(10) unsigned NOT NULL auto_increment,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

You need to populate the table with enough records to cover your needs:

INSERT INTO NUMBERS (id) VALUES (NULL);

Once you have the NUMBERS table, you can use:

SELECT x.start_date + INTERVAL n.id-1 DAY
  FROM NUMBERS n
  JOIN (SELECT STR_TO_DATE('2010-01-20', '%Y-%m-%d') AS start_date 
          FROM DUAL) x
 WHERE x.start_date + INTERVAL n.id-1 DAY <= '2010-01-24'

The absolute low-tech solution would be:

SELECT STR_TO_DATE('2010-01-20', '%Y-%m-%d')
 FROM DUAL
UNION ALL
SELECT STR_TO_DATE('2010-01-21', '%Y-%m-%d')
 FROM DUAL
UNION ALL
SELECT STR_TO_DATE('2010-01-22', '%Y-%m-%d')
 FROM DUAL
UNION ALL
SELECT STR_TO_DATE('2010-01-23', '%Y-%m-%d')
 FROM DUAL
UNION ALL
SELECT STR_TO_DATE('2010-01-24', '%Y-%m-%d')
 FROM DUAL

What would you use it for?


To generate lists of dates or numbers in order to LEFT JOIN on to. You would to this in order to see where there are gaps in the data, because you are LEFT JOINing onto a list of sequencial data - null values will make it obvious where gaps exist.

'Invalid update: invalid number of rows in section 0

Swift Version --> Remove the object from your data array before you call

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        print("Deleted")

        currentCart.remove(at: indexPath.row) //Remove element from your array 
        self.tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

How to return rows from left table not found in right table?

This is an example from real life work, I was asked to supply a list of users that bought from our site in the last 6 months but not in the last 3 months.

For me, the most understandable way I can think of is like so:

--Users that bought from us 6 months ago and between 3 months ago.
DECLARE @6To3MonthsUsers table (UserID int,OrderDate datetime)
INSERT @6To3MonthsUsers
    select u.ID,opd.OrderDate
        from OrdersPaid opd
        inner join Orders o
        on opd.OrderID = o.ID
        inner join Users u
        on o.BuyerID = u.ID
        where 1=1 
        and opd.OrderDate BETWEEN DATEADD(m,-6,GETDATE()) and DATEADD(m,-3,GETDATE())

--Users that bought from us in the last 3 months
DECLARE @Last3MonthsUsers table (UserID int,OrderDate datetime)
INSERT @Last3MonthsUsers
    select u.ID,opd.OrderDate
        from OrdersPaid opd
        inner join Orders o
        on opd.OrderID = o.ID
        inner join Users u
        on o.BuyerID = u.ID
        where 1=1 
        and opd.OrderDate BETWEEN DATEADD(m,-3,GETDATE()) and GETDATE()

Now, with these 2 tables in my hands I need to get only the users from the table @6To3MonthsUsers that are not in @Last3MonthsUsers table.

There are 2 simple ways to achieve that:

  1. Using Left Join:

    select distinct a.UserID
    from @6To3MonthsUsers a
    left join @Last3MonthsUsers b
    on a.UserID = b.UserID
    where b.UserID is null
    
  2. Not in:

    select distinct a.UserID
    from @6To3MonthsUsers a
    where a.UserID not in (select b.UserID from @Last3MonthsUsers b)
    

Both ways will get me the same result, I personally prefer the second way because it's more readable.

How can I create a "Please Wait, Loading..." animation using jQuery?

You can grab an animated GIF of a spinning circle from Ajaxload - stick that somewhere in your website file heirarchy. Then you just need to add an HTML element with the correct code, and remove it when you're done. This is fairly simple:

function showLoadingImage() {
    $('#yourParentElement').append('<div id="loading-image"><img src="path/to/loading.gif" alt="Loading..." /></div>');
}

function hideLoadingImage() {
    $('#loading-image').remove();
}

You then just need to use these methods in your AJAX call:

$.load(
     'http://example.com/myurl',
     { 'random': 'data': 1: 2, 'dwarfs': 7},
     function (responseText, textStatus, XMLHttpRequest) {
         hideLoadingImage();
     }
);

// this will be run immediately after the AJAX call has been made,
// not when it completes.
showLoadingImage();

This has a few caveats: first of all, if you have two or more places the loading image can be shown, you're going to need to kep track of how many calls are running at once somehow, and only hide when they're all done. This can be done using a simple counter, which should work for almost all cases.

Secondly, this will only hide the loading image on a successful AJAX call. To handle the error states, you'll need to look into $.ajax, which is more complex than $.load, $.get and the like, but a lot more flexible too.

How does HttpContext.Current.User.Identity.Name know which usernames exist?

For windows authentication

select your project.

Press F4

Disable "Anonymous Authentication" and enable "Windows Authentication"

enter image description here

Is it possible to declare a public variable in vba and assign a default value?

Sure you know, but if its a constant then const MyVariable as Integer = 123 otherwise your out of luck; the variable must be assigned an initial value elsewhere.

You could:

public property get myIntegerThing() as integer
    myIntegerThing= 123
end property

In a Class module then globally create it;

public cMyStuff as new MyStuffClass

So cMyStuff.myIntegerThing is available immediately.

Deprecated meaning?

Deprecated means they don't recommend using it, and that it isn't undergoing further development. But it should not work differently than it did in a previous version unless documentation explicitly states that.

  1. Yes, otherwise it wouldn't be called "deprecated"

  2. Unless stated otherwise in docs, it should be the same as before

  3. No, but if there were problems in v1 they aren't about to fix them

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

Even after 9 years of the original post, this helped me.

If you are receiving these types of errors without any clue, there should be a trigger, function related to the table, and obviously it should end up with an SP, or function with selecting/filtering data NOT USING Primary Unique column. If you are searching/filtering using the Primary Unique column there won't be any multiple results. Especially when you are assigning value for a declared variable. The SP never gives you en error but only an runtime error.

 "System.Data.SqlClient.SqlException (0x80131904): Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
    The statement has been terminated."

In my case obviously there was no clue, but only this error message. There was a trigger connected to the table and the table updating by the trigger also had another trigger likewise it ended up with two triggers and in the end with an SP. The SP was having a select clause which was resulting in multiple rows.

SET @Variable1 =(
        SELECT column_gonna_asign
        FROM dbo.your_db
        WHERE Non_primary_non_unique_key= @Variable2

If this returns multiple rows, you are in trouble.

JavaScriptSerializer - JSON serialization of enum as string

You can create JsonSerializerSettings with the call to JsonConverter.SerializeObject as below:

var result = JsonConvert.SerializeObject
            (
                dataObject,
                new JsonSerializerSettings
                {
                    Converters = new [] {new StringEnumConverter()}
                }
            );

Use css gradient over background image

The accepted answer works well. Just for completeness (and since I like it's shortness), I wanted to share how to to it with compass (SCSS/SASS):

body{
  $colorStart: rgba(0,0,0,0);
  $colorEnd: rgba(0,0,0,0.8);
  @include background-image(linear-gradient(to bottom, $colorStart, $colorEnd), url("bg.jpg"));
}

When do you use the "this" keyword?

Any time you need a reference to the current object.

One particularly handy scenario is when your object is calling a function and wants to pass itself into it.

Example:

void onChange()
{
    screen.draw(this);
}

Generics/templates in python?

Look at how the built-in containers do it. dict and list and so on contain heterogeneous elements of whatever types you like. If you define, say, an insert(val) function for your tree, it will at some point do something like node.value = val and Python will take care of the rest.

Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time

Regarding number of days in month just use static switch command and check if (year % 4 == 0) in which case February will have 29 days.

Minute, hour, day etc:

var someMillisecondValue = 511111222127;
var date = new Date(someMillisecondValue);
var minute = date.getMinutes();
var hour = date.getHours();
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
alert([minute, hour, day, month, year].join("\n"));

How to build PDF file from binary string returned from a web-service using javascript

I saw another question on just this topic recently (streaming pdf into iframe using dataurl only works in chrome).

I've constructed pdfs in the ast and streamed them to the browser. I was creating them first with fdf, then with a pdf class I wrote myself - in each case the pdf was created from data retrieved from a COM object based on a couple of of GET params passed in via the url.

From looking at your data sent recieved in the ajax call, it looks like you're nearly there. I haven't played with the code for a couple of years now and didn't document it as well as I'd have cared to, but - I think all you need to do is set the target of an iframe to be the url you get the pdf from. Though this may not work - the file that oututs the pdf may also have to outut a html response header first.

In a nutshell, this is the output code I used:

//We send to a browser
header('Content-Type: application/pdf');
if(headers_sent())
    $this->Error('Some data has already been output, can\'t send PDF file');
header('Content-Length: '.strlen($this->buffer));
header('Content-Disposition: inline; filename="'.$name.'"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
echo $this->buffer;

So, without seeing the full response text fro the ajax call I can't really be certain what it is, though I'm inclined to think that the code that outputs the pdf you're requesting may only be doig the equivalent of the last line in the above code. If it's code you have control over, I'd try setting the headers - then this way the browser can just deal with the response text - you don't have to bother doing a thing to it.

I simply constructed a url for the pdf I wanted (a timetable) then created a string that represented the html for an iframe of the desired sie, id etc that used the constructed url as it's src. As soon as I set the inner html of a div to the constructed html string, the browser asked for the pdf and then displayed it when it was received.

function  showPdfTt(studentId)
{
    var url, tgt;
    title = byId("popupTitle");
    title.innerHTML = "Timetable for " + studentId;
    tgt = byId("popupContent");
    url = "pdftimetable.php?";
    url += "id="+studentId;
    url += "&type=Student";
    tgt.innerHTML = "<iframe onload=\"centerElem(byId('box'))\" src='"+url+"' width=\"700px\" height=\"500px\"></iframe>";
}

EDIT: forgot to mention - you can send binary pdf's in this manner. The streams they contain don't need to be ascii85 or hex encoded. I used flate on all the streams in the pdf and it worked fine.

How to convert string to integer in UNIX

Any of these will work from the shell command line. bc is probably your most straight forward solution though.

Using bc:

$ echo "$d1 - $d2" | bc

Using awk:

$ echo $d1 $d2 | awk '{print $1 - $2}'

Using perl:

$ perl -E "say $d1 - $d2"

Using Python:

$ python -c "print $d1 - $d2"

all return

4

Could not resolve all dependencies for configuration ':classpath'

I got this issue solved by switching internet from Wifi to mobile hot-spot. It means this issue occurs due to network issue. I could also see below logs which confirms my understanding,

Connect to jcenter.bintray.com:443 [jcenter.bintray.com/75.126.118.188] failed: Connection timed out: connect

and

Connect to repo1.maven.org:443 [repo1.maven.org/151.101.36.209] failed: Connection timed out: connect

Hope it helps.

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

I might be replying late on this. But removing this can be helpful for some people who are still looking for solutions to this problem and has this in their code. We had below entry since long in our tsconfig.json file:

  "angularCompilerOptions": {
    "enableIvy": false
  }

We also face same problem. After lot of experiments, we removed this block from tsconfig.json. Now our code is not complaining this problem anymore.

What is an optional value in Swift?

Well...

? (Optional) indicates your variable may contain a nil value while ! (unwrapper) indicates your variable must have a memory (or value) when it is used (tried to get a value from it) at runtime.

The main difference is that optional chaining fails gracefully when the optional is nil, whereas forced unwrapping triggers a runtime error when the optional is nil.

To reflect the fact that optional chaining can be called on a nil value, the result of an optional chaining call is always an optional value, even if the property, method, or subscript you are querying returns a nonoptional value. You can use this optional return value to check whether the optional chaining call was successful (the returned optional contains a value), or did not succeed due to a nil value in the chain (the returned optional value is nil).

Specifically, the result of an optional chaining call is of the same type as the expected return value, but wrapped in an optional. A property that normally returns an Int will return an Int? when accessed through optional chaining.

var defaultNil : Int?  // declared variable with default nil value
println(defaultNil) >> nil  

var canBeNil : Int? = 4
println(canBeNil) >> optional(4)

canBeNil = nil
println(canBeNil) >> nil

println(canBeNil!) >> // Here nil optional variable is being unwrapped using ! mark (symbol), that will show runtime error. Because a nil optional is being tried to get value using unwrapper

var canNotBeNil : Int! = 4
print(canNotBeNil) >> 4

var cantBeNil : Int = 4
cantBeNil = nil // can't do this as it's not optional and show a compile time error

Here is basic tutorial in detail, by Apple Developer Committee: Optional Chaining

How to change the integrated terminal in visual studio code or VSCode

I was successful via settings > Terminal > Integrated > Shell: Linux

from there I edited the path of the shell to be /bin/zsh from the default /bin/bash

  • there are also options for OSX and Windows as well

screencap of vs settings view

@charlieParker - here's what i'm seeing for available commands in the command pallette

enter image description here

Suppress console output in PowerShell

Try redirecting the output to Out-Null. Like so,

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null

_csv.Error: field larger than field limit (131072)

You can use read_csv from pandas to skip these lines.

import pandas as pd

data_df = pd.read_csv('data.csv', error_bad_lines=False)

Is it possible to disable scrolling on a ViewPager

How about this :
I used CustomViewPager
and next, override scrollTo method
I checked the movement when doing a lot of small swipes, it doesn't scroll to other pages.

public class CustomViewPager extends ViewPager {

    private boolean enabled;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.enabled = true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.enabled) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.enabled) {
            return super.onInterceptTouchEvent(event);
        }

        return false;
    }

    public void setPagingEnabled(boolean enabled) {
        this.enabled = enabled;
    } 

    @Override
    public void scrollTo(int x, int y) {
       if(enabled) {
          super.scrollTo(x, y);
       }
    }
}

How to see the proxy settings on windows?

An update to @rleelr:
It's possible to view proxy settings in Google Chrome:

chrome://net-internals/#http2

Then select

View live HTTP/2 sessions

Then select one of the live sessions (you need to have some tabs open). There you find:

[...]
t=504112 [st= 0] +HTTP2_SESSION  [dt=?]
                  --> host = "play.google.com:443"
                  --> proxy = "PROXY www.xxx.yyy.zzz:8080"
[...]
                              ============================

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

It's the default formatting that Oracle provides. If you want leading zeros on output, you'll need to explicitly provide the format. Use:

SELECT TO_CHAR(0.56,'0.99') FROM DUAL;

or even:

SELECT TO_CHAR(.56,'0.99') FROM DUAL;

The same is true for trailing zeros:

SQL> SELECT TO_CHAR(.56,'0.990') val FROM DUAL;

VAL
------
 0.560

The general form of the TO_CHAR conversion function is:

TO_CHAR(number, format)

How do I use PHP namespaces with autoload?

had the same issue and just found this :

When you create a subfolder structure matching the namespaces of the containing classes, you will never even have to define an autoloader.

    spl_autoload_extensions(".php"); // comma-separated list
    spl_autoload_register();

It worked like a charm

More info here : http://www.php.net/manual/en/function.spl-autoload-register.php#92514

EDIT: this causes problem on Linux because of backslash... See here for working solution by immeëmosol

Namespace Autoload works under windows, but not on Linux

How to secure the ASP.NET_SessionId cookie?

Adding onto @JoelEtherton's solution to fix a newly found security vulnerability. This vulnerability happens if users request HTTP and are redirected to HTTPS, but the sessionid cookie is set as secure on the first request to HTTP. That is now a security vulnerability, according to McAfee Secure.

This code will only secure cookies if request is using HTTPS. It will expire the sessionid cookie, if not HTTPS.

    // this code will mark the forms authentication cookie and the
    // session cookie as Secure.
    if (Request.IsSecureConnection)
    {
        if (Response.Cookies.Count > 0)
        {
            foreach (string s in Response.Cookies.AllKeys)
            {
                if (s == FormsAuthentication.FormsCookieName || s.ToLower() == "asp.net_sessionid")
                {
                    Response.Cookies[s].Secure = true;
                }
            }
        }
    }
    else
    {
        //if not secure, then don't set session cookie
        Response.Cookies["asp.net_sessionid"].Value = string.Empty;
        Response.Cookies["asp.net_sessionid"].Expires = new DateTime(2018, 01, 01);
    }

how to access the command line for xampp on windows

Like all other had said above, you need to add path. But not sure for what reason if I add C:\xampp\php in path of System Variable won't work but if I add it in path of User Variable work fine.

Although I had added and using other command line tools by adding in system variables work fine

So just in case if someone had same problem as me. Windows 10

enter image description here

How to use log levels in java

Here is a good introduction to logging in Java: http://www.javapractices.com/topic/TopicAction.do?Id=143

Java comes with a logging API since it's 1.4.2 version: http://download.oracle.com/javase/1.4.2/docs/guide/util/logging/overview.html

You can also use other logging frameworks like Apache Log4j which is the most popular one: http://logging.apache.org/log4j

I suggest you to use a logging abstraction framework which allows you to change your logging framework without re-factoring you code. So you can starts by using Jul (Java Util Logging) then swith to Log4j without changing you code. The most popular logging facade is slf4j: http://www.slf4j.org/

Regards,

How do I compile a Visual Studio project from the command-line?

I know of two ways to do it.

Method 1
The first method (which I prefer) is to use msbuild:

msbuild project.sln /Flags...

Method 2
You can also run:

vcexpress project.sln /build /Flags...

The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.

Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).

So, the end result might be:

os.system("msbuild project.sln /p:Configuration=Debug")

You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).

jQuery textbox change event

You can achieve it:

 $(document).ready(function(){              
     $('#textBox').keyup(function () {alert('changed');});
 });

or with change (handle copy paste with right click):

 $(document).ready(function(){              
     $('#textBox2').change(function () {alert('changed');});
 });

Here is Demo

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

Getting DOM elements by classname

DOMDocument is slow to type and phpQuery has bad memory leak issues. I ended up using:

https://github.com/wasinger/htmlpagedom

To select a class:

include 'includes/simple_html_dom.php';

$doc = str_get_html($html);
$href = $doc->find('.lastPage')[0]->href;

I hope this helps someone else as well

How to run travis-ci locally

It is possible to SSH to Travis CI environment via a bounce host. The feature isn't built in Travis CI, but it can be achieved by the following steps.

  1. On the bounce host, create travis user and ensure that you can SSH to it.
  2. Put these lines in the script: section of your .travis.yml (e.g. at the end).

    - echo travis:$sshpassword | sudo chpasswd
    - sudo sed -i 's/ChallengeResponseAuthentication no/ChallengeResponseAuthentication yes/' /etc/ssh/sshd_config
    - sudo service ssh restart
    - sudo apt-get install sshpass
    - sshpass -p $sshpassword ssh -R 9999:localhost:22 -o StrictHostKeyChecking=no travis@$bouncehostip
    

    Where $bouncehostip is the IP/host of your bounce host, and $sshpassword is your defined SSH password. These variables can be added as encrypted variables.

  3. Push the changes. You should be able to make an SSH connection to your bounce host.

Source: Shell into Travis CI Build Environment.


Here is the full example:

# use the new container infrastructure
sudo: required
dist: trusty

language: python
python: "2.7"

script:
- echo travis:$sshpassword | sudo chpasswd
- sudo sed -i 's/ChallengeResponseAuthentication no/ChallengeResponseAuthentication yes/' /etc/ssh/sshd_config
- sudo service ssh restart
- sudo apt-get install sshpass
- sshpass -p $sshpassword ssh -R 9999:localhost:22 -o StrictHostKeyChecking=no travisci@$bouncehostip

See: c-mart/travis-shell at GitHub.


See also: How to reproduce a travis-ci build environment for debugging

What causes a Python segmentation fault?

This happens when a python extension (written in C) tries to access a memory beyond reach.

You can trace it in following ways.

  • Add sys.settrace at the very first line of the code.
  • Use gdb as described by Mark in this answer.. At the command prompt

    gdb python
    (gdb) run /path/to/script.py
    ## wait for segfault ##
    (gdb) backtrace
    ## stack trace of the c code
    

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

I use the following method in my project

-(NSArray*)networkErrorCodes
{
    static NSArray *codesArray;
    if (![codesArray count]){
        @synchronized(self){
            const int codes[] = {
                //kCFURLErrorUnknown,     //-998
                //kCFURLErrorCancelled,   //-999
                //kCFURLErrorBadURL,      //-1000
                //kCFURLErrorTimedOut,    //-1001
                //kCFURLErrorUnsupportedURL, //-1002
                //kCFURLErrorCannotFindHost, //-1003
                kCFURLErrorCannotConnectToHost,     //-1004
                kCFURLErrorNetworkConnectionLost,   //-1005
                kCFURLErrorDNSLookupFailed,         //-1006
                //kCFURLErrorHTTPTooManyRedirects,    //-1007
                kCFURLErrorResourceUnavailable,     //-1008
                kCFURLErrorNotConnectedToInternet,  //-1009
                //kCFURLErrorRedirectToNonExistentLocation,   //-1010
                kCFURLErrorBadServerResponse,               //-1011
                //kCFURLErrorUserCancelledAuthentication,     //-1012
                //kCFURLErrorUserAuthenticationRequired,      //-1013
                //kCFURLErrorZeroByteResource,        //-1014
                //kCFURLErrorCannotDecodeRawData,     //-1015
                //kCFURLErrorCannotDecodeContentData, //-1016
                //kCFURLErrorCannotParseResponse,     //-1017
                kCFURLErrorInternationalRoamingOff, //-1018
                kCFURLErrorCallIsActive,                //-1019
                //kCFURLErrorDataNotAllowed,              //-1020
                //kCFURLErrorRequestBodyStreamExhausted,  //-1021
                kCFURLErrorFileDoesNotExist,            //-1100
                //kCFURLErrorFileIsDirectory,             //-1101
                kCFURLErrorNoPermissionsToReadFile,     //-1102
                //kCFURLErrorDataLengthExceedsMaximum,     //-1103
            };
            int size = sizeof(codes)/sizeof(int);
            NSMutableArray *array = [[NSMutableArray alloc] init];
            for (int i=0;i<size;++i){
                [array addObject:[NSNumber numberWithInt:codes[i]]];
            }
            codesArray = [array copy];
        }
    }
    return codesArray;
}

Then I just check the error code and show alert if it is in the list

if ([[self networkErrorCodes] containsObject:[NSNumber
numberWithInt:[error code]]]){ 
// Fire Alert View Here
}

But as you can see I commented out codes that I think does not fit to my definition of NO INTERNET. E.g the code of -1012 (Authentication fail.) You may edit the list as you like.

In my project I use it at username/password entering from user. And in my view (physical) network connection errors could be the only reason to show alert view in your network based app. In any other case (e.g. incorrect username/password pair) I prefer to do some custom user friendly animation, OR just repeat the failed attempt again without any attention of the user. Especially if the user didn't explicitly initiated a network call.

Regards to martinezdelariva for a link to documentation.

How do I disable a Button in Flutter?

According to the docs:

"If the onPressed callback is null, then the button will be disabled and by default will resemble a flat button in the disabledColor."

https://docs.flutter.io/flutter/material/RaisedButton-class.html

So, you might do something like this:

    RaisedButton(
      onPressed: calculateWhetherDisabledReturnsBool() ? null : () => whatToDoOnPressed,
      child: Text('Button text')
    );

How to check if mysql database exists

From the shell like bash

if [[ ! -z "`mysql -qfsBe "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='db'" 2>&1`" ]];
then
  echo "DATABASE ALREADY EXISTS"
else
  echo "DATABASE DOES NOT EXIST"
fi

make *** no targets specified and no makefile found. stop

This may happen if there is any read and write permission denial to the user. Like C:\Windows\System32\ have restricted access and you are cloned and trying to make from such restricted directory.

A SQL Query to select a string between two known strings

Hope this helps : Declared a variable , in case of any changes need to be made thats only once .

declare @line  varchar(100)

set @line ='[email protected]'

select SUBSTRING(@line ,(charindex('-',@line)+1), CHARINDEX('@',@line)-charindex('-',@line)-1)

The identity used to sign the executable is no longer valid

I came through this error. The problem was The developer identity and Mobile Provisioning Profile mismatch.

Delete keychain certificates and fresh install matching provisioning profile and developer certificate fixed the problem.

Connect Device to Mac localhost Server?

make sure you phone and mac machine both connected to the same wifi and you good to go your http://<machine-name>.local

mysql select from n last rows

I know this may be a bit old, but try using PDO::lastInsertId. I think it does what you want it to, but you would have to rewrite your application to use PDO (Which is a lot safer against attacks)

Reset Windows Activation/Remove license key

On Windows XP -

  1. Reboot into "Safe mode with Command Prompt"
  2. Type "explorer" in the command prompt that comes up and push [Enter]
  3. Click on Start>Run, and type the following :

    rundll32.exe syssetup,SetupOobeBnk

Reboot, and login as normal.

This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

You are mixing mysqli and mysql function.

If your are using mysql function then instead mysqli_real_escape_string($your_variable); use

$username = mysql_real_escape_string($_POST['username']);
$pass = mysql_real_escape_string($_POST['pass']);
$pass1 = mysql_real_escape_string($_POST['pass1']);
$email = mysql_real_escape_string($_POST['email']);

If your using mysqli_* function then you have to include your connection to database into mysqli_real_escape function :

$username = mysqli_real_escape_string($your_connection, $_POST['username']);
$pass = mysqli_real_escape_string($your_connection, $_POST['pass']);
$pass1 = mysqli_real_escape_string($your_connection, $_POST['pass1']);
$email = mysqli_real_escape_string($your_connection, $_POST['email']);

Note : Use mysqli_* function since mysql has been deprecated. For information please read mysqli_*

How to solve "The directory is not empty" error when running rmdir command in a batch script?

The reason rd /s refuses to delete certain files is most likely due to READONLY file attributes on files in the directory.

The proper way to fix this, is to make sure you reset the attributes on all files first:

attrib -r %directory% /s /d
rd /s %directory%

There could be others such as hidden or system files, so if you want to play it safe:

attrib -h -r -s %directory% /s /d
rd /s %directory%

Can I hide/show asp:Menu items based on role?

You can remove unwanted menu items in Page_Load, like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("Admin"))
        {
            MenuItemCollection menuItems = mTopMenu.Items;
            MenuItem adminItem = new MenuItem();
            foreach (MenuItem menuItem in menuItems)
            {
                if (menuItem.Text == "Roles")
                    adminItem = menuItem;
            }
            menuItems.Remove(adminItem);
        }
    }

I'm sure there's a neater way to find the right item to remove, but this one works. You could also add all the wanted menu items in a Page_Load method, instead of adding them in the markup.

MySQL - Replace Character in Columns

Replace below characters

~ ! @ # $ % ^ & * ( ) _ +
` - = 
{ } |
[ ] \
: " 
; '

< > ?
, . 

with this SQL

SELECT note as note_original, 

    REPLACE(
        REPLACE(
            REPLACE(
                REPLACE(
                    REPLACE(
                        REPLACE(
                            REPLACE(
                                REPLACE(
                                    REPLACE(
                                        REPLACE(
                                            REPLACE(
                                                REPLACE(
                                                    REPLACE(
                                                        REPLACE(
                                                            REPLACE(
                                                                REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(
                                                                                                REPLACE(
                                                                                                    REPLACE(
                                                                                                        REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(note, '\"', ''),
                                                                                        '.', ''),
                                                                                    '?', ''),
                                                                                '`', ''),
                                                                            '<', ''),
                                                                        '=', ''),
                                                                    '{', ''),
                                                                                                        '}', ''),
                                                                                                    '[', ''),
                                                                                                ']', ''),
                                                                                            '|', ''),
                                                                                        '\'', ''),
                                                                                    ':', ''),
                                                                                ';', ''),
                                                                            '~', ''),
                                                                        '!', ''),
                                                                    '@', ''),
                                                                '#', ''),
                                                            '$', ''),
                                                        '%', ''),
                                                    '^', ''),
                                                '&', ''),
                                            '*', ''),
                                        '_', ''),
                                    '+', ''),
                                ',', ''),
                            '/', ''),
                        '(', ''),
                    ')', ''),
                '-', ''),
            '>', ''),
        ' ', '-'),
    '--', '-') as note_changed FROM invheader

HTTP Error 500.19 and error code : 0x80070021

Check if IIS server installed the URL rewrite feature.
If it is not installed then make sure your web.config file don't have the URL rewrite related configuration

<!-- Make sure don't have below config, if server have not installed url rewrite feature. -->
<rewrite>
  <rules>
    <rule name="Fail bad requests">
      <match url=".*"/> ...

Some time we copied the config from legacy server and straight away deploy to brand new server, then we may encounter such kind of 500 issue.

How do I change UIView Size?

Hi create this extends if you want. Update 2021 Swift 5

Create File Extends.Swift and add this code (add import foundation where you want change height)

extension UIView {
    /**
    Get Set x Position
    
    - parameter x: CGFloat
    */
    var x:CGFloat {
        get {
            return self.frame.origin.x
        }
        set {
            self.frame.origin.x = newValue
        }
    }
    /**
    Get Set y Position
    
    - parameter y: CGFloat
    */
    var y:CGFloat {
        get {
            return self.frame.origin.y
        }
        set {
            self.frame.origin.y = newValue
        }
    }
    /**
    Get Set Height
    
    - parameter height: CGFloat
    */
    var height:CGFloat {
        get {
            return self.frame.size.height
        }
        set {
            self.frame.size.height = newValue
        }
    }
    /**
    Get Set Width
    
    - parameter width: CGFloat
    */
    var width:CGFloat {
        get {
            return self.frame.size.width
        }
        set {
            self.frame.size.width = newValue
        }
    }
}

For Use (inherits Of UIView)

inheritsOfUIView.height = 100
button.height = 100
print(view.height)

Gradle finds wrong JAVA_HOME even though it's correctly set

Try installing latest version of gradle,

sudo add-apt-repository ppa:cwchien/gradle

sudo apt-get update

sudo apt-get install gradle

If we install from ubuntu repo, it will install the old version , (for me it was gradle 1.4). In older version, it sets java home from gradle as export JAVA_HOME=/usr/lib/jvm/default-java. Latest version don't have this issue.

How do I set multipart in axios with react?

ok. I tried the above two ways but it didnt work for me. After trial and error i came to know that actually the file was not getting saved in 'this.state.file' variable.

fileUpload = (e) => {
    let data = e.target.files
    if(e.target.files[0]!=null){
        this.props.UserAction.fileUpload(data[0], this.fallBackMethod)
    }
}

here fileUpload is a different js file which accepts two params like this

export default (file , callback) => {
const formData = new FormData();
formData.append('fileUpload', file);

return dispatch => {
    axios.put(BaseUrl.RestUrl + "ur/url", formData)
        .then(response => {
            callback(response.data);
        }).catch(error => {
         console.log("*****  "+error)
    });
}

}

don't forget to bind method in the constructor. Let me know if you need more help in this.

Is there a vr (vertical rule) in html?

I find it easy to make an image of a line, and then insert it into the code as a "rule", setting the width and/or height as needed. These have all been horizontal-rule images, but there's nothing stopping me (or you) from using a "vertical-rule" image.

This is cool for many reasons; you can use different lines, colors, or patterns easily as "rules", and since they would have no text, even if you had done it the "normal" way using hr in HTML, it shouldn't impact SEO or other stuff like that. And the image file would/should be very tiny (1 or 2KB at most).

IOS: verify if a point is inside a rect

In Swift that would look like this:

let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = CGRectContainsPoint(someFrame, point)

Swift 3 version:

let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = someFrame.contains(point)

Link to documentation . Please remember to check containment if both are in the same coordinate system if not then conversions are required (some example)

How do you get the path to the Laravel Storage folder?

You can use the storage_path(); function to get storage folder path.

storage_path(); // Return path like: laravel_app\storage

Suppose you want to save your logfile mylog.log inside Log folder of storage folder. You have to write something like

storage_path() . '/LogFolder/mylog.log'

Github Windows 'Failed to sync this branch'

This is probably an edge case, but every time I've got this specific error it is because I've recently mapped a drive in Windows, and powershell cannot find it.

A computer restart (of all things) fixes the error for me, as powershell can now pick up the newly mapped drive. Just make sure you connect to the mapped drive BEFORE opening the github client.

SQL SERVER DATETIME FORMAT

Compatibility Supports Says that Under compatibility level 110, the default style for CAST and CONVERT operations on time and datetime2 data types is always 121. If your query relies on the old behavior, use a compatibility level less than 110, or explicitly specify the 0 style in the affected query.

That means by default datetime2 is CAST as varchar to 121 format. For ex; col1 and col2 formats (below) are same (other than the 0s at the end)

SELECT CONVERT(varchar, GETDATE(), 121) col1,
       CAST(convert(datetime2,GETDATE()) as varchar) col2,
       CAST(GETDATE() as varchar) col3

SQL FIDDLE DEMO

--Results
COL1                    | COL2                          | COL3
2013-02-08 09:53:56.223 | 2013-02-08 09:53:56.2230000   | Feb 8 2013 9:53AM

FYI, if you use CONVERT instead of CAST you can use a third parameter to specify certain formats as listed here on MSDN

Display the current date and time using HTML and Javascript with scrollable effects in hta application

Method 1:


With marquee tag.

HTML

<marquee behavior="scroll" bgcolor="yellow" loop="-1" width="30%">
   <i>
      <font color="blue">
        Today's date is : 
        <strong>
         <span id="time"></span>
        </strong>           
      </font>
   </i>
</marquee> 

JS

var today = new Date();
document.getElementById('time').innerHTML=today;

Fiddle demo here


Method 2:


Without marquee tag and with CSS.

HTML

<p class="marquee">
    <span id="dtText"></span>
</p>

CSS

.marquee {
   width: 350px;
   margin: 0 auto;
   background:yellow;
   white-space: nowrap;
   overflow: hidden;
   box-sizing: border-box;
   color:blue;
   font-size:18px;
}

.marquee span {
   display: inline-block;
   padding-left: 100%;
   text-indent: 0;
   animation: marquee 15s linear infinite;
}

.marquee span:hover {
    animation-play-state: paused
}

@keyframes marquee {
    0%   { transform: translate(0, 0); }
    100% { transform: translate(-100%, 0); }
}

JS

var today = new Date();
document.getElementById('dtText').innerHTML=today;

Fiddle demo here

C++ convert hex string to signed integer

Working example with strtoul will be:

#include <cstdlib>
#include <iostream>
using namespace std;

int main() { 
    string s = "fffefffe";
    char * p;
    long n = strtoul( s.c_str(), & p, 16 ); 
    if ( * p != 0 ) {  
        cout << "not a number" << endl;
    }    else {  
        cout << n << endl;
    }
}

strtol converts string to long. On my computer numeric_limits<long>::max() gives 0x7fffffff. Obviously that 0xfffefffe is greater than 0x7fffffff. So strtol returns MAX_LONG instead of wanted value. strtoul converts string to unsigned long that's why no overflow in this case.

Ok, strtol is considering input string not as 32-bit signed integer before convertation. Funny sample with strtol:

#include <cstdlib>
#include <iostream>
using namespace std;

int main() { 
    string s = "-0x10002";
    char * p;
    long n = strtol( s.c_str(), & p, 16 ); 
    if ( * p != 0 ) {  
        cout << "not a number" << endl;
    }    else {  
        cout << n << endl;
    }
}

The code above prints -65538 in console.

Python Variable Declaration

Variables have scope, so yes it is appropriate to have variables that are specific to your function. You don't always have to be explicit about their definition; usually you can just use them. Only if you want to do something specific to the type of the variable, like append for a list, do you need to define them before you start using them. Typical example of this.

list = []
for i in stuff:
  list.append(i)

By the way, this is not really a good way to setup the list. It would be better to say:

list = [i for i in stuff] # list comprehension

...but I digress.

Your other question. The custom object should be a class itself.

class CustomObject(): # always capitalize the class name...this is not syntax, just style.
  pass
customObj = CustomObject()

docker mounting volumes on host

The VOLUME command will mount a directory inside your container and store any files created or edited inside that directory on your hosts disk outside the container file structure, bypassing the union file system.

The idea is that your volumes can be shared between your docker containers and they will stay around as long as there's a container (running or stopped) that references them.

You can have other containers mount existing volumes (effectively sharing them between containers) by using the --volumes-from command when you run a container.

The fundamental difference between VOLUME and -v is this: -v will mount existing files from your operating system inside your docker container and VOLUME will create a new, empty volume on your host and mount it inside your container.

Example:

  1. You have a Dockerfile that defines a VOLUME /var/lib/mysql.
  2. You build the docker image and tag it some-volume
  3. You run the container

And then,

  1. You have another docker image that you want to use this volume
  2. You run the docker container with the following: docker run --volumes-from some-volume docker-image-name:tag
  3. Now you have a docker container running that will have the volume from some-volume mounted in /var/lib/mysql

Note: Using --volumes-from will mount the volume over whatever exists in the location of the volume. I.e., if you had stuff in /var/lib/mysql, it will be replaced with the contents of the volume.

Calculating percentile of dataset column

table_ages <- subset(infert, select=c("age"))
summary(table_ages)
#            age       
#  Min.   :21.00  
#  1st Qu.:28.00  
#  Median :31.00  
#  Mean   :31.50  
#  3rd Qu.:35.25  
#  Max.   :44.00  

This is probably what they're looking for. summary(...) applied to a numeric returns the min, max, mean, median, and 25th and 75th percentile of the data.

Note that

summary(infert$age)
#    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#   21.00   28.00   31.00   31.50   35.25   44.00 

The numbers are the same but the format is different. This is because table_ages is a data frame with one column (ages), whereas infert$age is a numeric vector. Try typing summary(infert).

How to swap String characters in Java?

I think this should help.

import java.util.*;

public class StringSwap{

public static void main(String ar[]){
    Scanner in = new Scanner(System.in);
    String s = in.next();
    System.out.println(new StringBuffer(s.substring(0,2)).reverse().toString().concat(s.substring(2)));
  }
}

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

A different case in which I encountered this was when I was using echo to pipe the JSON into my python script and carelessly wrapped the JSON string in double quotes:

echo "{"thumbnailWidth": 640}" | myscript.py

Note that the JSON string itself has quotes and I should have done:

echo '{"thumbnailWidth": 640}' | myscript.py

As it was, this is what the python script received: {thumbnailWidth: 640}; the double quotes were effectively stripped.

Passing data into "router-outlet" child components

There are 3 ways to pass data from Parent to Children

  1. Through shareable service : you should store into a service the data you would like to share with the children
  2. Through Children Router Resolver if you have to receive different data

    this.data = this.route.snaphsot.data['dataFromResolver'];
    
  3. Through Parent Router Resolver if your have to receive the same data from parent

    this.data = this.route.parent.snaphsot.data['dataFromResolver'];
    

Note1: You can read about resolver here. There is also an example of resolver and how to register the resolver into the module and then retrieve data from resolver into the component. The resolver registration is the same on the parent and child.

Note2: You can read about ActivatedRoute here to be able to get data from router

Make Axios send cookies in its requests automatically

I am not familiar with Axios, but as far as I know in javascript and ajax there is an option

withCredentials: true

This will automatically send the cookie to the client-side. As an example, this scenario is also generated with passportjs, which sets a cookie on the server

Run php function on button click

You are trying to call a javascript function. If you want to call a PHP function, you have to use for example a form:

    <form action="action_page.php">
       First name:<br>
       <input type="text" name="firstname" value="Mickey">
       <br>
       Last name:<br>
       <input type="text" name="lastname" value="Mouse">
       <br><br>
       <input type="submit" value="Submit">
     </form> 

(Original Code from: http://www.w3schools.com/html/html_forms.asp)

So if you want do do a asynchron call, you could use 'Ajax' - and yeah, that's the Javascript-Way. But I think, that my code example is enough for this time :)

Apache SSL Configuration Error (SSL Connection Error)

I solved it by commenting out:

AcceptFilter https none

in httpd.conf

according to: http://www.apachelounge.com/viewtopic.php?t=4461

Running Facebook application on localhost

So I got this to work today. My URL is http://localhost:8888. The domain I gave facebook is localhost. I thought that it was not working because I was trying to pull data using the FB.api method. I kept on getting an "undefined" name and an image without a source, so definitely didn't have access to the Graph.

Later I realized that my problem was really that I was only passing a first argument of /me to FB.api, and I didn't have a token. So you'll need to use the FB.getLoginStatus function to get a token, which should be added to the /me argument.

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

Better way to find index of item in ArrayList?

ArrayList<String> alphabetList = new ArrayList<String>();
alphabetList.add("A"); // 0 index
alphabetList.add("B"); // 1 index
alphabetList.add("C"); // 2 index
alphabetList.add("D"); // 3 index
alphabetList.add("E"); // 4 index
alphabetList.add("F"); // 5 index
alphabetList.add("G"); // 6 index
alphabetList.add("H"); // 7 index
alphabetList.add("I"); // 8 index

int position = -1;
position = alphabetList.indexOf("H");
if (position == -1) {
    Log.e(TAG, "Object not found in List");
} else {
    Log.i(TAG, "" + position);
}

Output: List Index : 7

If you pass H it will return 7, if you pass J it will return -1 as we defined default value to -1.

Done

Unable to resolve host "<insert URL here>" No address associated with hostname

I got the same error and for the issue was that I was on VPN and I didn't realize that. After disconnecting the VPN and reconnecting the wifi resolved it.

adb is not recognized as internal or external command on windows

If you get your adb from Android Studio (which most will nowadays since Android is deprecated on Eclipse), your adb program will most likely be located here:

%USERPROFILE%\AppData\Local\Android\sdk\platform-tools

Where %USERPROFILE% represents something like C:\Users\yourName.

If you go into your computer's environmental variables and add %USERPROFILE%\AppData\Local\Android\sdk\platform-tools to the PATH (just copy-paste that line, even with the % --- it will work fine, at least on Windows, you don't need to hardcode your username) then it should work now. Open a new command prompt and type adb to check.

How to make a TextBox accept only alphabetic characters?

        if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z]+$"))
        { 
        }
        else
        {
            textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
            MessageBox.Show("Enter only Alphabets");


        }

Please Try this

Eclipse "Invalid Project Description" when creating new project from existing source

paste the project source and support libs to any other newly created folder and try to import from there. It worked for me.

C++ inheritance - inaccessible base?

By default, inheritance is private. You have to explicitly use public:

class Bar : public Foo

Java current machine name and logged in user?

To get the currently logged in user:

System.getProperty("user.name");

To get the host name of the machine:

InetAddress.getLocalHost().getHostName();

To answer the last part of your question, the Java API says that getHostName() will return

the host name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.

@import vs #import - iOS 7

Nice answer you can find in book Learning Cocoa with Objective-C (ISBN: 978-1-491-90139-7)

Modules are a new means of including and linking files and libraries into your projects. To understand how modules work and what benefits they have, it is important to look back into the history of Objective-C and the #import statement Whenever you want to include a file for use, you will generally have some code that looks like this:

#import "someFile.h"

Or in the case of frameworks:

#import <SomeLibrary/SomeFile.h>

Because Objective-C is a superset of the C programming language, the #import state- ment is a minor refinement upon C’s #include statement. The #include statement is very simple; it copies everything it finds in the included file into your code during compilation. This can sometimes cause significant problems. For example, imagine you have two header files: SomeFileA.h and SomeFileB.h; SomeFileA.h includes SomeFileB.h, and SomeFileB.h includes SomeFileA.h. This creates a loop, and can confuse the coimpiler. To deal with this, C programmers have to write guards against this type of event from occurring.

When using #import, you don’t need to worry about this issue or write header guards to avoid it. However, #import is still just a glorified copy-and-paste action, causing slow compilation time among a host of other smaller but still very dangerous issues (such as an included file overriding something you have declared elsewhere in your own code.)

Modules are an attempt to get around this. They are no longer a copy-and-paste into source code, but a serialised representation of the included files that can be imported into your source code only when and where they’re needed. By using modules, code will generally compile faster, and be safer than using either #include or #import.

Returning to the previous example of importing a framework:

#import <SomeLibrary/SomeFile.h>

To import this library as a module, the code would be changed to:

@import SomeLibrary;

This has the added bonus of Xcode linking the SomeLibrary framework into the project automatically. Modules also allow you to only include the components you really need into your project. For example, if you want to use the AwesomeObject component in the AwesomeLibrary framework, normally you would have to import everything just to use the one piece. However, using modules, you can just import the specific object you want to use:

@import AwesomeLibrary.AwesomeObject;

For all new projects made in Xcode 5, modules are enabled by default. If you want to use modules in older projects (and you really should) they will have to be enabled in the project’s build settings. Once you do that, you can use both #import and @import statements in your code together without any concern.

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

On particular table

_x000D_
_x000D_
<table style="border-collapse: separate; border-spacing: 10px;" >_x000D_
    <tr>_x000D_
      <td>Hi</td>_x000D_
      <td>Hello</td>_x000D_
    <tr/>_x000D_
    <tr>_x000D_
      <td>Hola</td>_x000D_
      <td>Oi!</td>_x000D_
    <tr/>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How does Junit @Rule work?

Rules are used to enhance the behaviour of each test method in a generic way. Junit rule intercept the test method and allows us to do something before a test method starts execution and after a test method has been executed.

For example, Using @Timeout rule we can set the timeout for all the tests.

public class TestApp {
    @Rule
    public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);

    ......
    ......

 }

@TemporaryFolder rule is used to create temporary folders, files. Every time the test method is executed, a temporary folder is created and it gets deleted after the execution of the method.

public class TempFolderTest {

 @Rule
 public TemporaryFolder tempFolder= new TemporaryFolder();

 @Test
 public void testTempFolder() throws IOException {
  File folder = tempFolder.newFolder("demos");
  File file = tempFolder.newFile("Hello.txt");

  assertEquals(folder.getName(), "demos");
  assertEquals(file.getName(), "Hello.txt");

 }


}

You can see examples of some in-built rules provided by junit at this link.

req.query and req.param in ExpressJS

Passing params

GET request to "/cars/honda" 

returns a list of Honda car models

Passing query

GET request to "/car/honda?color=blue"

returns a list of Honda car models, but filtered so only models with an stock color of blue are returned.

It doesn't make sense to add those filters into the URL parameters (/car/honda/color/blue) because according to REST, that would imply that we want to get a bunch of information about the color "blue". Since what we really want is a filtered list of Honda models, we use query strings to filter down the results that get returned.

Notice that the query strings are really just { key: value } pairs in a slightly different format: ?key1=value1&key2=value2&key3=value3.

What does LINQ return when the results are empty

In Linq-to-SQL if you try to get the first element on a query with no results you will get sequence contains no elements error. I can assure you that the mentioned error is not equal to object reference not set to an instance of an object. in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;)

Unrecognized escape sequence for path string containing backslashes

You can either use a double backslash each time

string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";

or use the @ symbol

string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";

How to read input with multiple lines in Java

package pac001;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Entry_box{



    public static final String[] relationship = {"Marrid", "Unmarried"};


    public static void main(String[] args)
    {
         //TAKING USER ID NUMBER
            int a = Integer.parseInt(JOptionPane.showInputDialog("Enter ID no: "));
        // TAKING INPUT FOR RELATIONSHIP
        JFrame frame = new JFrame("Input Dialog Example #3");
        String Relationship =   (String) JOptionPane.showInputDialog(frame,"Select Your Relationship","Married",
                                JOptionPane.QUESTION_MESSAGE, null, relationship,relationship[0]);



        //PRINTING THE ID NUMBER
        System.out.println("ID no: "+a);
        // PRINTING RESULT FOR RELATIONSHIP INPUT
          System.out.printf("Mariitual Status: %s\n", Relationship);

        }
}

Read next word in java

You already get the next line in this line of your code:

 String line = sc.nextLine();  

To get the words of a line, I would recommend to use:

String[] words = line.split(" ");

How can I send an Ajax Request on button click from a form with 2 buttons?

function sendAjaxRequest(element,urlToSend) {
             var clickedButton = element;
              $.ajax({type: "POST",
                  url: urlToSend,
                  data: { id: clickedButton.val(), access_token: $("#access_token").val() },
                  success:function(result){
                    alert('ok');
                  },
                 error:function(result)
                  {
                  alert('error');
                 }
             });
     }

       $(document).ready(function(){
          $("#button_1").click(function(e){
              e.preventDefault();
              sendAjaxRequest($(this),'/pages/test/');
          });

          $("#button_2").click(function(e){
              e.preventDefault();
              sendAjaxRequest($(this),'/pages/test/');
          });
        });
  1. created as separate function for sending the ajax request.
  2. Kept second parameter as URL because in future you want to send data to different URL

How do I disable a jquery-ui draggable?

Seems like no one looked at the original documentation. May be there was no it at that time))

Initialize a draggable with the disabled option specified.

$( ".selector" ).draggable({ disabled: true });

Get or set the disabled option, after init.

//getter
var disabled = $( ".selector" ).draggable( "option", "disabled" );
//setter
$( ".selector" ).draggable( "option", "disabled", true );

Support for "border-radius" in IE

Yes! When IE9 is released in Jan 2011.

Let's say you want an even 15px on all four sides:

.myclass {
 border-style: solid;
 border-width: 2px;
 -moz-border-radius: 15px;
 -webkit-border-radius: 15px;
 border-radius: 15px;
}

IE9 will use the default border-radius, so just make sure you include that in all your styles calling a border radius. Then your site will be ready for IE9.

-moz-border-radius is for Firefox, -webkit-border-radius is for Safari and Chrome.

Furthermore: don't forget to declare your IE coding is ie9:

<meta http-equiv="X-UA-Compatible" content="IE=9" />

Some lazy developers have <meta http-equiv="X-UA-Compatible" content="IE=7" />. If that tag exists, border-radius will never work in IE.

What is the difference between the kernel space and the user space?

In Linux there are two space 1st is user space and another one is kernal space. user space consist of only user application which u want to run. as the kernal service there is process management, file management, signal handling, memory management, thread management, and so many services are present there. if u run the application from the user space that appliction interact with only kernal service. and that service is interact with device driver which is present between hardware and kernal. the main benefit of kernal space and user space seperation is we can acchive a security by the virus.bcaz of all user application present in user space, and service is present in kernal space. thats why linux doesn,t affect from the virus.

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

PHP7, in php.ini file, remove the ";" before extension=openssl

How to automatically crop and center an image

Try this: Set your image crop dimensions and use this line in your CSS:

object-fit: cover;

Getting error "The package appears to be corrupt" while installing apk file

None of the answer is working for me.

As the error message is package corrupt , I will have to run

  1. adb uninstall <package name>
  2. Run app again / use adb install

How to Convert a Text File into a List in Python

This looks like a CSV file, so you could use the python csv module to read it. For example:

import csv

crimefile = open(fileName, 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]

Using the csv module allows you to specify how things like quotes and newlines are handled. See the documentation I linked to above.

Using stored procedure output parameters in C#

In your C# code, you are using transaction for the command. Just commit the transaction and after that access your parameter value, you will get the value. Worked for me. :)

Selecting non-blank cells in Excel with VBA

The following VBA code should get you started. It will copy all of the data in the original workbook to a new workbook, but it will have added 1 to each value, and all blank cells will have been ignored.

Option Explicit

Public Sub exportDataToNewBook()
    Dim rowIndex As Integer
    Dim colIndex As Integer
    Dim dataRange As Range
    Dim thisBook As Workbook
    Dim newBook As Workbook
    Dim newRow As Integer
    Dim temp

    '// set your data range here
    Set dataRange = Sheet1.Range("A1:B100")

    '// create a new workbook
    Set newBook = Excel.Workbooks.Add

    '// loop through the data in book1, one column at a time
    For colIndex = 1 To dataRange.Columns.Count
        newRow = 0
        For rowIndex = 1 To dataRange.Rows.Count
            With dataRange.Cells(rowIndex, colIndex)

            '// ignore empty cells
            If .value <> "" Then
                newRow = newRow + 1
                temp = doSomethingWith(.value)
                newBook.ActiveSheet.Cells(newRow, colIndex).value = temp
                End If

            End With
        Next rowIndex
    Next colIndex
End Sub


Private Function doSomethingWith(aValue)

    '// This is where you would compute a different value
    '// for use in the new workbook
    '// In this example, I simply add one to it.
    aValue = aValue + 1

    doSomethingWith = aValue
End Function

Automatically deleting related rows in Laravel (Eloquent ORM)

Or you can do this if you wanted, just another option:

try {
    DB::connection()->pdo->beginTransaction();

    $photos = Photo::where('user_id', '=', $user_id)->delete(); // Delete all photos for user
    $user = Geofence::where('id', '=', $user_id)->delete(); // Delete users

    DB::connection()->pdo->commit();

}catch(\Laravel\Database\Exception $e) {
    DB::connection()->pdo->rollBack();
    Log::exception($e);
}

Note if you are not using the default laravel db connection then you need to do the following:

DB::connection('connection_name')->pdo->beginTransaction();
DB::connection('connection_name')->pdo->commit();
DB::connection('connection_name')->pdo->rollBack();

Large WCF web service request failing with (400) HTTP Bad Request

For what it is worth, an additional consideration when using .NET 4.0 is that if a valid endpoint is not found in your configuration, a default endpoint will be automatically created and used.

The default endpoint will use all default values so if you think you have a valid service configuration with a large value for maxReceivedMessageSize etc., but there is something wrong with the configuration, you would still get the 400 Bad Request since a default endpoint would be created and used.

This is done silently so it is hard to detect. You will see messages to this effect (e.g. 'No Endpoint found for Service, creating Default Endpoint' or similar) if you turn on tracing on the server but there is no other indication (to my knowledge).

Rotating a point about another point (2D)

This is the answer by Nils Pipenbrinck, but implemented in c# fiddle.

https://dotnetfiddle.net/btmjlG

using System;

public class Program
{
    public static void Main()
    {   
        var angle = 180 * Math.PI/180;
        Console.WriteLine(rotate_point(0,0,angle,new Point{X=10, Y=10}).Print());
    }

    static Point rotate_point(double cx, double cy, double angle, Point p)
    {
        double s = Math.Sin(angle);
        double c = Math.Cos(angle);
        // translate point back to origin:
        p.X -= cx;
        p.Y -= cy;
        // rotate point
        double Xnew = p.X * c - p.Y * s;
        double Ynew = p.X * s + p.Y * c;
        // translate point back:
        p.X = Xnew + cx;
        p.Y = Ynew + cy;
        return p;
    }

    class Point
    {
        public double X;
        public double Y;

        public string Print(){
            return $"{X},{Y}";
        }
    }
}

Ps: Apparently I can’t comment, so I’m obligated to post it as an answer ...

set dropdown value by text using jquery

var myText = 'GOOGLE';

$('#HowYouKnow option').map(function() {
    if ($(this).text() == myText) return this;
}).attr('selected', 'selected');

Check if a key is down?

This works in Firefox and Chrome.

I had a need to open a special html file locally (by pressing Enter when the file is selected in the file explorer in Windows), either just for viewing the file or for editing it in a special online editor.

So I wanted to distinguish between these two options by holding down the Ctrl-key or not, while pressing Enter.

As you all have understood from all the answers here, this seems to be not really possible, but here is a way that mimics this behaviour in a way that was acceptable for me.

The way this works is like this:

If you hold down the Ctrl-key when opening the file then a keydown event will never fire in the javascript code. But a keyup event will fire (when you finally release the Ctrl-key). The code captures that.

The code also turns off keyevents (both keyup and keydown) as soon as one of them occurs. So if you press the Ctrl-key after the file has opened, nothing will happen.

window.onkeyup = up;
window.onkeydown = down;
function up(e) {
  if (e.key === 'F5') return; // if you want this to work also on reload with F5.

  window.onkeyup = null;
  window.onkeyup = null;
  if (e.key === 'Control') {
    alert('Control key was released. You must have held it down while opening the file, so we will now load the file into the editor.');
  }         
}
function down() {
  window.onkeyup = null;
  window.onkeyup = null;
}

Reading from a text file and storing in a String

How can we read data from a text file and store in a String Variable?

Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.

Is it possible to pass the filename in a method and it would return the String which is the text from the file.

Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.

Calculate mean and standard deviation from a vector of samples in C++ using Boost

If performance is important to you, and your compiler supports lambdas, the stdev calculation can be made faster and simpler: In tests with VS 2012 I've found that the following code is over 10 X quicker than the Boost code given in the chosen answer; it's also 5 X quicker than the safer version of the answer using standard libraries given by musiphil.

Note I'm using sample standard deviation, so the below code gives slightly different results (Why there is a Minus One in Standard Deviations)

double sum = std::accumulate(std::begin(v), std::end(v), 0.0);
double m =  sum / v.size();

double accum = 0.0;
std::for_each (std::begin(v), std::end(v), [&](const double d) {
    accum += (d - m) * (d - m);
});

double stdev = sqrt(accum / (v.size()-1));

Regular expression to match DNS hostname or IP Address?

It's worth noting that there are libraries for most languages that do this for you, often built into the standard library. And those libraries are likely to get updated a lot more often than code that you copied off a Stack Overflow answer four years ago and forgot about. And of course they'll also generally parse the address into some usable form, rather than just giving you a match with a bunch of groups.

For example, detecting and parsing IPv4 in (POSIX) C:

#include <arpa/inet.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
  for (int i=1; i!=argc; ++i) {
    struct in_addr addr = {0};
    printf("%s: ", argv[i]);
    if (inet_pton(AF_INET, argv[i], &addr) != 1)
      printf("invalid\n");
    else
      printf("%u\n", addr.s_addr);
  }
  return 0;
}

Obviously, such functions won't work if you're trying to, e.g., find all valid addresses in a chat message—but even there, it may be easier to use a simple but overzealous regex to find potential matches, and then use the library to parse them.

For example, in Python:

>>> import ipaddress
>>> import re
>>> msg = "My address is 192.168.0.42; 192.168.0.420 is not an address"
>>> for maybeip in re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', msg):
...     try:
...         print(ipaddress.ip_address(maybeip))
...     except ValueError:
...         pass

Server.MapPath - Physical path given, virtual path expected

var files = Directory.GetFiles(@"E:\ftproot\sales");

OnItemClickListener using ArrayAdapter for ListView

Ok, after the information that your Activity extends ListActivity here's a way to implement OnItemClickListener:

public class newListView extends ListView {

    public newListView(Context context) {
        super(context);
    }

    @Override
    public void setOnItemClickListener(
            android.widget.AdapterView.OnItemClickListener listener) {
        super.setOnItemClickListener(listener);
        //do something when item is clicked

    }

}

How can I run PowerShell with the .NET 4 runtime?

If you only need to execute a single command, script block, or script file in .NET 4, try using Activation Configuration Files from .NET 4 to start only a single instance of PowerShell using version 4 of the CLR.

Full details:

http://blog.codeassassin.com/2011/03/23/executing-individual-powershell-commands-using-net-4/

An example PowerShell module:

https://gist.github.com/882528

How to pass data to view in Laravel?

You can also write for passing multiple data from your controller to a view

 return \View::make('myHome')
            ->with(compact('project'))
            ->with(['hello'=>$hello])
            ->with(['hello2'=>$hello2])
            ->with(['hello3'=>$hello3]);

SQL Query to search schema of all tables

You do not need to type SQL Query for this in SQL Server 2008.

In SSMS Object Explorer choose Databases or Tables of the required database (if you need to search in one database), open menu View--> Object Explorer Details (alternatively press F7), type %CreatedDate% in Search textbox, ENTER, enjoy

Can inner classes access private variables?

An inner class is a friend of the class it is defined within.
So, yes; an object of type Outer::Inner can access the member variable var of an object of type Outer.

Unlike Java though, there is no correlation between an object of type Outer::Inner and an object of the parent class. You have to make the parent child relationship manually.

#include <string>
#include <iostream>

class Outer
{
    class Inner
    {
        public:
            Inner(Outer& x): parent(x) {}
            void func()
            {
                std::string a = "myconst1";
                std::cout << parent.var << std::endl;

                if (a == MYCONST)
                {   std::cout << "string same" << std::endl;
                }
                else
                {   std::cout << "string not same" << std::endl;
                }
            }
        private:
            Outer&  parent;
    };

    public:
        Outer()
            :i(*this)
            ,var(4)
        {}
        Outer(Outer& other)
            :i(other)
            ,var(22)
        {}
        void func()
        {
            i.func();
        }
    private:
        static const char* const MYCONST;
        Inner i;
        int var;
};

const char* const Outer::MYCONST = "myconst";

int main()
{

    Outer           o1;
    Outer           o2(o1);
    o1.func();
    o2.func();
}

Convert string to binary then back again using PHP

Strings in PHP are always BLOBs. So you can use a string to hold the value for your database BLOB. All of this stuff base-converting and so on has to do with presenting that BLOB.

If you want a nice human-readable representation of your BLOB then it makes sense to show the bytes it contains, and probably to use hex rather than decimal. Hence, the string "41 42 43" is a good way to present the byte array that in C# would be

var bytes = new byte[] { 0x41, 0x42, 0x43 };

but it is obviously not a good way to represent those bytes! The string "ABC" is an efficient representation, because it is in fact the same BLOB (only it's not so Large in this case).

In practice you will typically get your BLOBs from functions that return string - such as that hashing function, or other built-in functions like fread.

In the rare cases (but not so rare when just trying things out/prototyping) that you need to just construct a string from some hard-coded bytes I don't know of anything more efficient than converting a "hex string" to what is often called a "binary string" in PHP:

$myBytes = "414243";
$data = pack('H*', $myBytes);

If you var_dump($data); it'll show you string(3) "ABC". That's because 0x41 = 65 decimal = 'A' (in basically all encodings).

Since looking at binary data by interpreting it as a string is not exactly intuitive, you may want to make a basic wrapper to make debugging easier. One possible such wrapper is

class blob
{
    function __construct($hexStr = '')
    {
        $this->appendHex($hexStr);
    }

    public $value;

    public function appendHex($hexStr)
    {
        $this->value .= pack('H*', $hexStr);
    }

    public function getByte($index)
    {
        return unpack('C', $this->value{$index})[1];
    }

    public function setByte($index, $value)
    {
        $this->value{$index} = pack('C', $value);
    }

    public function toArray()
    {
        return unpack('C*', $this->value);
    }
}

This is something I cooked up on the fly, and probably just a starting point for your own wrapper. But the idea is to use a string for storage since this is the most efficient structure available in PHP, while providing methods like toArray() for use in debugger watches/evaluations when you want to examine the contents.

Of course you may use a perfectly straightforward PHP array instead and pack it to a string when interfacing with something that uses strings for binary data. Depending on the degree to which you are actually going to modify the blob this may prove easier, and although it isn't space efficient I think you'd get acceptable performance for many tasks.

An example to illustrate the functionality:

// Construct a blob with 3 bytes: 0x41 0x42 0x43.
$b = new blob("414243");

// Append 3 more bytes: 0x44 0x45 0x46.
$b->appendHex("444546");

// Change the second byte to 0x41 (so we now have 0x41 0x41 0x43 0x44 0x45 0x46).
$b->setByte(1, 0x41); // or, equivalently, setByte(1, 65)

// Dump the first byte.
var_dump($b->getByte(0));

// Verify the result. The string "AACDEF", because it's only ASCII characters, will have the same binary representation in basically any encoding.
$ok = $b->value == "AACDEF";

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

If you have issue with writing into an existing xls file because it is already created you need to put checking part like below:

PATH='filename.xlsx'
if os.path.isfile(PATH):
    print "File exists and will be overwrite NOW"
else:
    print "The file is missing, new one is created"

... and here part with the data you want to add

Upload files with HTTPWebrequest (multipart/form-data)

Not sure if this was posted before but I got this working with WebClient. i read the documentation for the WebClient. A key point they make is

If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString property is not an empty string, it is appended to address.

So all I did was wc.QueryString.Add("source", generatedImage) to add the different query parameters and somehow it matches the property name with the image I uploaded. Hope it helps

    public void postImageToFacebook(string generatedImage, string fbGraphUrl)
    {
        WebClient wc = new WebClient();
        byte[] bytes = System.IO.File.ReadAllBytes(generatedImage);

        wc.QueryString.Add("source", generatedImage);
        wc.QueryString.Add("message", "helloworld");

        wc.UploadFile(fbGraphUrl, generatedImage);

        wc.Dispose();

    }

is there a 'block until condition becomes true' function in java?

As nobody published a solution with CountDownLatch. What about:

public class Lockeable {
    private final CountDownLatch countDownLatch = new CountDownLatch(1);

    public void doAfterEvent(){
        countDownLatch.await();
        doSomething();
    }

    public void reportDetonatingEvent(){
        countDownLatch.countDown();
    }
}

Remove Primary Key in MySQL

I believe Quassnoi has answered your direct question. Just a side note: Maybe this is just some awkward wording on your part, but you seem to be under the impression that you have three primary keys, one on each field. This is not the case. By definition, you can only have one primary key. What you have here is a primary key that is a composite of three fields. Thus, you cannot "drop the primary key on a column". You can drop the primary key, or not drop the primary key. If you want a primary key that only includes one column, you can drop the existing primary key on 3 columns and create a new primary key on 1 column.

Using Get-childitem to get a list of files modified in the last 3 days

Try this:

(Get-ChildItem -Path c:\pstbak\*.* -Filter *.pst | ? {
  $_.LastWriteTime -gt (Get-Date).AddDays(-3) 
}).Count

how to change php version in htaccess in server

Try this to switch to php4:

AddHandler application/x-httpd-php4 .php

Upd. Looks like I didn't understand your question correctly. This will not help if you have only php 4 on your server.

Detecting when user scrolls to bottom of div with jQuery

not sure if it is any help but this is how I do it.

I have an index panel that is larger that the window and I let it scroll until the end this index is reached. Then I fix it in position. The process is reversed once you scroll toward the top of the page.

Regards.

<style type="text/css">
    .fixed_Bot {    
            position: fixed;     
            bottom: 24px;    
        }     
</style>

<script type="text/javascript">
    $(document).ready(function () {
        var sidebarheight = $('#index').height();
        var windowheight = $(window).height();


        $(window).scroll(function () {
            var scrollTop = $(window).scrollTop();

            if (scrollTop >= sidebarheight - windowheight){
                $('#index').addClass('fixed_Bot');
            }
            else {
                $('#index').removeClass('fixed_Bot');
            }                   
        });
    });

</script>

WPF Button with Image

Most simple approach would be using the Image tag.

<Button Name="btn" Width="26" Height="26" Click="btnClick"> 
   <Image Source="Resource/btn-icon.png"/>
</Button>

Suppose your image file is added in Resource folder

Disable developer mode extensions pop up in Chrome

1) Wait for the popup balloon to appear.

2) Open a new tab.

3) Close the a new tab. The popup will be gone from the original tab.

A small Chrome extension can automate these steps:

manifest.json

{
  "name": "Open and close tab",
  "description": "After Chrome starts, open and close a new tab.",
  "version": "1.0",
  "manifest_version": 2,
  "permissions": ["tabs"],
  "background": {
    "scripts": ["background.js"], 
    "persistent": false
  }
}

background.js

// This runs when Chrome starts up
chrome.runtime.onStartup.addListener(function() {

  // Execute the inner function after a few seconds
  setTimeout(function() {

    // Open new tab
    chrome.tabs.create({url: "about:blank"});

    // Get tab ID of newly opened tab, then close the tab
    chrome.tabs.query({'currentWindow': true}, function(tabs) {
      var newTabId = tabs[1].id;
      chrome.tabs.remove(newTabId);
    });

  }, 5000);

});

With this extension installed, launch Chrome and immediately switch apps before the popup appears... a few seconds later, the popup will be gone and you won't see it when you switch back to Chrome.

Download a file by jQuery.Ajax

In Rails, I do it this way:

function download_file(file_id) {
  let url       = '/files/' + file_id + '/download_file';
    $.ajax({
    type: 'GET',
    url: url,
    processData: false,
    success: function (data) {
       window.location = url;
    },
    error: function (xhr) {
     console.log(' Error:  >>>> ' + JSON.stringify(xhr));
    }
   });
 }

The trick is the window.location part. The controller's method looks like:

# GET /files/{:id}/download_file/
def download_file
    send_file(@file.file,
          :disposition => 'attachment',
          :url_based_filename => false)
end

Does java have a int.tryparse that doesn't throw an exception for bad data?

No. You have to make your own like this:

boolean tryParseInt(String value) {  
     try {  
         Integer.parseInt(value);  
         return true;  
      } catch (NumberFormatException e) {  
         return false;  
      }  
}

...and you can use it like this:

if (tryParseInt(input)) {  
   Integer.parseInt(input);  // We now know that it's safe to parse
}

EDIT (Based on the comment by @Erk)

Something like follows should be better

public int tryParse(String value, int defaultVal) {
    try {
        return Integer.parseInt(value);
    } catch (NumberFormatException e) {
        return defaultVal;
    }
}

When you overload this with a single string parameter method, it would be even better, which will enable using with the default value being optional.

public int tryParse(String value) {
    return tryParse(value, 0)
}

Android: Background Image Size (in Pixel) which Support All Devices

Android Devices Matrices

                            ldpi     mdpi     hdpi    xhdpi    xxhdpi      xxxhdpi
Launcher And Home           36*36    48*48   72*72    96*96    144*144     192*192
Toolbar And Tab             24*24    32*32   48*48    64*64    96*96       128*128
Notification                18*18    24*24   36*36    48*48    72*72       96*96 
Background                 240*320  320*480 480*800  768*1280  1080 *1920  1440*2560 

(For good approach minus Toolbar Size From total height of Background Screen and then Design Graphics of Screens )

For More Help (This link includes tablets also):

https://design.google.com/devices/

Android Native Icons (Recommended) You can change color of these icons programmatically. https://design.google.com/icons/

babel-loader jsx SyntaxError: Unexpected token

For me the solution was to create the file .babelrc with this content:

{
  "presets": ["react", "es2015", "stage-1"]
}

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

You should avoid setting LD_LIBRARY_PATH in your .bashrc. See "Why LD_LIBRARY_PATH is bad" for more information.

Use the linker option -rpath while linking so that the dynamic linker knows where to find libsync.so during runtime.

gcc ... -Wl,-rpath /path/to/library -L/path/to/library -lsync -o sync_test

EDIT:

Another way would be to use a wrapper like this

#!/bin/bash

LD_LIBRARY_PATH=/path/to/library sync_test "$@"

If sync_test starts any other programs, they might end up using the libs in /path/to/library which may or may not be intended.

Select all occurrences of selected word in VSCode

What if you want to select just a few?

No problem, first:

  1. Ctrl+F find the letters by typing them
  2. ESC to quit searching (you need to this even when using Ctrl+Shift+L to select all occurences)

OR

  1. just select those letters with your mouse or keyboard (Shift+arrows)

Now that the mouse cursor is blinking on your first selection, using a few more Key Bindings (thanks for the ref j08691) you may:

  • Ctrl+D select the next occurrence
  • Ctrl+K+Ctrl+D skip the next occurrence
  • Ctrl+U undo one of the above

TypeError: 'list' object is not callable while trying to access a list

To get elements of a list you have to use list[i] instead of list(i).

How to open a specific port such as 9090 in Google Compute Engine

Here is the command-line approach to answer this question:

gcloud compute firewall-rules create <rule-name> --allow tcp:9090 --source-tags=<list-of-your-instances-names> --source-ranges=0.0.0.0/0 --description="<your-description-here>"

This will open the port 9090 for the instances that you name. Omitting --source-tags and --source-ranges will apply the rule to all instances. More details are in the Gcloud documentation and the firewall-rule create command manual

The previous answers are great, but Google recommends using the newer gcloud commands instead of the gcutil commands.

PS: To get an idea of Google's firewall rules, run gcloud compute firewall-rules list and view all your firewall rules

Django DoesNotExist

Nice way to handle not found error in Django.

https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#get-object-or-404

from django.shortcuts import get_object_or_404

def get_data(request):
    obj = get_object_or_404(Model, pk=1)

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

You may want to check that your project has Microsoft.AspNet.WebApi.WebHost installed. As it turns out, in my case, Microsoft.AspNet.WebApi.WebHost was installed in another project, but not the particular project that needed it. In your packages.config, check that a line like this is there:

<package id="Microsoft.AspNet.WebApi.WebHost" version="5.1.1" targetFramework="net45" />

If that is not present, you don't have Microsoft.AspNet.WebApi.WebHost installed in your project. You can either install using Nuget Package Manager or through the Package Manager Console. To install from the Package Manager Console, run this command:

Install-Package Microsoft.AspNet.WebApi.WebHost

Display encoded html with razor

I store encoded HTML in the database.

Imho you should not store your data html-encoded in the database. Just store in plain text (not encoded) and just display your data like this and your html will be automatically encoded:

<div class='content'>
    @Model.Content
</div>

Windows 7 - Add Path

I founded the problem: Just insert the folder without the executable file.
so Instead of:

C:\Program Files (x86)\SumatraPDF\SumatraPDF.exe

you have to write this:

C:\Program Files (x86)\SumatraPDF\

Call removeView() on the child's parent first

Ok, call me paranoid but I suggest:

  final android.view.ViewParent parent = view.getParent ();

  if (parent instanceof android.view.ViewManager)
  {
     final android.view.ViewManager viewManager = (android.view.ViewManager) parent;

     viewManager.removeView (view);
  } // if

casting without instanceof just seems wrong. And (thanks IntelliJ IDEA for telling me) removeView is part of the ViewManager interface. And one should not cast to a concrete class when a perfectly suitable interface is available.

How to thoroughly purge and reinstall postgresql on ubuntu?

I just ran into the same issue for Ubuntu 13.04. These commands removed Postgres 9.1:

sudo apt-get purge postgresql
sudo apt-get autoremove postgresql

It occurs to me that perhaps only the second command is necessary, but from there I was able to install Postgres 9.2 (sudo apt-get install postgresql-9.2).

MySQL Workbench - Connect to a Localhost

I had this problem and I just realized that if in the server you see the user in the menu SERVER -> USERS AND PRIVILEGES and find the user who has % as HOSTNAME, you can use it instead the root user.

That's all

How to merge a Series and DataFrame

If df is a pandas.DataFrame then df['new_col']= Series list_object of length len(df) will add the or Series list_object as a column named 'new_col'. df['new_col']= scalar (such as 5 or 6 in your case) also works and is equivalent to df['new_col']= [scalar]*len(df)

So a two-line code serves the purpose:

df = pd.DataFrame({'a':[1, 2], 'b':[3, 4]})
s = pd.Series({'s1':5, 's2':6})
for x in s.index:    
    df[x] = s[x]

Output: 
   a  b  s1  s2
0  1  3   5   6
1  2  4   5   6

What is the largest TCP/IP network port number allowable for IPv4?

Valid numbers for ports are: 0 to 2^16-1 = 0 to 65535
That is because a port number is 16 bit length.

However ports are divided into:
Well-known ports: 0 to 1023 (used for system services e.g. HTTP, FTP, SSH, DHCP ...)
Registered/user ports: 1024 to 49151 (you can use it for your server, but be careful some famous applications: like Microsoft SQL Server database management system (MSSQL) server or Apache Derby Network Server are already taking from this range i.e. it is not recommended to assign the port of MSSQL to your server otherwise if MSSQL is running then your server most probably will not run because of port conflict )
Dynamic/private ports: 49152 to 65535. (not used for the servers rather the clients e.g. in NATing service)

In programming you can use any numbers 0 to 65535 for your server, however you should stick to the ranges mentioned above, otherwise some system services or some applications will not run because of port conflict.
Check the list of most ports here: https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

How to replace list item in best way

I don't if it is best or not but you can use it also

List<string> data = new List<string>
(new string[]   { "Computer", "A", "B", "Computer", "B", "A" });
int[] indexes = Enumerable.Range(0, data.Count).Where
                 (i => data[i] == "Computer").ToArray();
Array.ForEach(indexes, i => data[i] = "Calculator");

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

In Python, what happens when you import inside of a function?

It imports once when the function is called for the first time.

I could imagine doing it this way if I had a function in an imported module that is used very seldomly and is the only one requiring the import. Looks rather far-fetched, though...

What does Visual Studio mean by normalize inconsistent line endings?

There'a an add-in for Visual Studio 2008 that converts the end of line format when a file is saved. You can download it here: http://grebulon.com/software/stripem.php

PHP - Move a file into a different folder on the server

I using shell read all data file then assign to array. Then i move file in top position.

i=0 
for file in /home/*.gz; do
    $file
    arr[i]=$file
    i=$((i+1)) 
done 
mv -f "${arr[0]}" /var/www/html/

Cannot start session without errors in phpMyAdmin

Problem usually lies on your browser end.

You need to flush your browser cache, delete the cookies for the server/host and then retry loading phpMyAdmin.

If you want to go all out, clear out the session folder on the server as well.

One possible reason for this is a session data mismatch between the browser and the webserver causing it to not be able to pull out the required session info and dumping this error dialogue on your lap.

Count of "Defined" Array Elements

An array length is not the number of elements in a array, it is the highest index + 1. length property will report correct element count only if there are valid elements in consecutive indices.

var a = [];
a[23] = 'foo';
a.length;  // 24

Saying that, there is no way to exclude undefined elements from count without using any form of a loop.

Calculating the sum of two variables in a batch script

here is mine

echo Math+ 
ECHO First num:
 SET /P a= 
ECHO Second num:
 SET /P b=
 set /a s=%a%+%b% 
echo Result: %s%

What is the difference between `new Object()` and object literal notation?

I have found one difference, for ES6/ES2015. You cannot return an object using the shorthand arrow function syntax, unless you surround the object with new Object().

> [1, 2, 3].map(v => {n: v});
[ undefined, undefined, undefined ]
> [1, 2, 3].map(v => new Object({n: v}));
[ { n: 1 }, { n: 2 }, { n: 3 } ]

This is because the compiler is confused by the {} brackets and thinks n: i is a label: statement construct; the semicolon is optional so it doesn't complain about it.

If you add another property to the object it will finally throw an error.

$ node -e "[1, 2, 3].map(v => {n: v, m: v+1});"
[1, 2, 3].map(v => {n: v, m: v+1});
                           ^

SyntaxError: Unexpected token :

Decode Hex String in Python 3

import codecs

decode_hex = codecs.getdecoder("hex_codec")

# for an array
msgs = [decode_hex(msg)[0] for msg in msgs]

# for a string
string = decode_hex(string)[0]

How to express a One-To-Many relationship in Django

To handle One-To-Many relationships in Django you need to use ForeignKey.

The documentation on ForeignKey is very comprehensive and should answer all the questions you have:

https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey

The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).

If you want the reverse relationship, you would need to add two ForeignKey fields to your PhoneNumber model, one to Dude and one to Business. This would allow each number to belong to either one Dude or one Business, and have Dudes and Businesses able to own multiple Numbers. I think this might be what you are after.

class Business(models.Model):
    ...
class Dude(models.Model):
    ...
class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)
    business = models.ForeignKey(Business)

Target elements with multiple classes, within one rule

.border-blue.background { ... } is for one item with multiple classes.
.border-blue, .background { ... } is for multiple items each with their own class.
.border-blue .background { ... } is for one item where '.background' is the child of '.border-blue'.

See Chris' answer for a more thorough explanation.

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

HTML:

<div class="container">
    <div class="box">
        <img src="http://lorempixel.com/1600/1200/" alt="">
    </div>
</div>

CSS:

.container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: stretch;

  width: 100%;
  height: 100%;

  border-radius: 4px;
  background-color: hsl(0, 0%, 96%);
}

.box {
  border-radius: 4px;
  display: flex;
}

.box img {
  width: 100%;
  object-fit: contain;
  border-radius: 4px;
}

Convert PEM traditional private key to PKCS8 private key

Try using following command. I haven't tried it but I think it should work.

openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt

How to access a preexisting collection with Mongoose?

Here's an abstraction of Will Nathan's answer if anyone just wants an easy copy-paste add-in function:

function find (name, query, cb) {
    mongoose.connection.db.collection(name, function (err, collection) {
       collection.find(query).toArray(cb);
   });
}

simply do find(collection_name, query, callback); to be given the result.

for example, if I have a document { a : 1 } in a collection 'foo' and I want to list its properties, I do this:

find('foo', {a : 1}, function (err, docs) {
            console.dir(docs);
        });
//output: [ { _id: 4e22118fb83406f66a159da5, a: 1 } ]

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

How to add app icon within phonegap projects?

In cordova 3.3.1-0.1.2 the expected behavior is not working right.

in

http://cordova.apache.org/docs/en/3.3.0/config_ref_images.md.html#Icons%20and%20Splash%20Screens

it clearly states you're suppose to put them into your main www folder in a folder called res and icons that follow a particular naming convention instead of the original customizable config.xml specified way (in which you point to a file of your choosing, which was/is much better). it should take then from there for each platform and put them into the platforms/?android?/res/drawable-?dpi/icon.png but it does no such correct behavior at this time... bug.

so I guess we have to manually put them there for each platform. it would of course need to remove that from duplicating it into the www folder again. for me I had to totally replace the contents in the main www folder anyway because it simply didn't work with even hello world without hacking a redirect index.html to find some weird random folder there. Putting the res folder beside www makes the most sense but what ever it seems to be for me caused by this series of cascading and confusing design choices/flaws.

How do I simulate a hover with a touch in touch enabled browsers?

A mix of native Javascript and jQuery:

var gFireEvent = function (oElem,sEvent) 
{
 try {
 if( typeof sEvent == 'string' && o.isDOM( oElem ))
 {
  var b = !!(document.createEvent),
     evt = b?document.createEvent("HTMLEvents"):document.createEventObject();
  if( b )    
  {  evt.initEvent(sEvent, true, true ); 
    return !oElem.dispatchEvent(evt);
  }
  return oElem.fireEvent('on'+sEvent,evt);
 }
 } catch(e) {}
 return false;
};


// Next you can do is (bIsMob etc you have to determine yourself):

   if( <<< bIsMob || bIsTab || bisTouch >>> )
   {
     $(document).on('mousedown', function(e)
     {
       gFireEvent(e.target,'mouseover' );
     }).on('mouseup', function(e)
     {
       gFireEvent(e.target,'mouseout' );
     });
   }

How do I create a comma delimited string from an ArrayList?

foo.ToArray().Aggregate((a, b) => (a + "," + b)).ToString()

or

string.Concat(foo.ToArray().Select(a => a += ",").ToArray())

Updating, as this is extremely old. You should, of course, use string.Join now. It didn't exist as an option at the time of writing.

Bootstrap: align input with button

Bootstrap 4:

<div class="input-group">
  <input type="text" class="form-control">
  <div class="input-group-append">
    <button class="btn btn-success" type="button">Button</button>
  </div>
</div>

https://getbootstrap.com/docs/4.0/components/input-group/

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Just Follow Simple 1-2-3 Steps :

1) Go to Taskbar

2) Click on WAMP icon (Left Click)

enter image description here

3) Now Go to Apache > Services > Apache Module and check Rewrite_module is enable or not ! if its not then click on it ! WAMP will be automatically restarted and you're done !

enter image description here

How to blur background images in Android

You can have a view with Background color as black and set alpha for the view as 0.7 or whatever as per your requirement.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/onboardingimg1">
    <View
        android:id="@+id/opacityFilter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/black"
        android:layout_alignParentBottom="true"
        android:alpha="0.7">
    </View>


</RelativeLayout>

AngularJS - How to use $routeParams in generating the templateUrl?

I was having a similar issue and used $stateParams instead of routeParam

Difference between signed / unsigned char

A signed char is a signed value which is typically smaller than, and is guaranteed not to be bigger than, a short. An unsigned char is an unsigned value which is typically smaller than, and is guaranteed not to be bigger than, a short. A type char without a signed or unsigned qualifier may behave as either a signed or unsigned char; this is usually implementation-defined, but there are a couple of cases where it is not:

  1. If, in the target platform's character set, any of the characters required by standard C would map to a code higher than the maximum `signed char`, then `char` must be unsigned.
  2. If `char` and `short` are the same size, then `char` must be signed.

Part of the reason there are two dialects of "C" (those where char is signed, and those where it is unsigned) is that there are some implementations where char must be unsigned, and others where it must be signed.

Parsing Json rest api response in C#

  1. Create classes that match your data,
  2. then use JSON.NET to convert the JSON data to regular C# objects.

Step 1: a great tool - http://json2csharp.com/ - the results generated by it are below

Step 2: JToken.Parse(...).ToObject<RootObject>().

public class Meta
{
    public int code { get; set; }
    public string status { get; set; }
    public string method_name { get; set; }
}

public class Photos
{
    public int total_count { get; set; }
}

public class Storage
{
    public int used { get; set; }
}

public class Stats
{
    public Photos photos { get; set; }
    public Storage storage { get; set; }
}

public class From
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public List<object> external_accounts { get; set; }
    public string email { get; set; }
    public string confirmed_at { get; set; }
    public string username { get; set; }
    public string admin { get; set; }
    public Stats stats { get; set; }
}

public class ParticipateUser
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public List<object> external_accounts { get; set; }
    public string email { get; set; }
    public string confirmed_at { get; set; }
    public string username { get; set; }
    public string admin { get; set; }
    public Stats stats { get; set; }
}

public class ChatGroup
{
    public string id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string message { get; set; }
    public List<ParticipateUser> participate_users { get; set; }
}

public class Chat
{
    public string id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string message { get; set; }
    public From from { get; set; }
    public ChatGroup chat_group { get; set; }
}

public class Response
{
    public List<Chat> chats { get; set; }
}

public class RootObject
{
    public Meta meta { get; set; }
    public Response response { get; set; }
}

Best way to check for null values in Java?

I would say method 4 is the most general idiom from the code that I've looked at. But this always feels a bit smelly to me. It assumes foo == null is the same as foo.bar() == false.

That doesn't always feel right to me.

Format a Go string without printing?

I've created go project for string formatting from template (it allow to format strings in C# or Python style, just first version for very simple cases), you could find it here https://github.com/Wissance/stringFormatter

it works in following manner:


func TestStrFormat(t *testing.T) {
    strFormatResult, err := Format("Hello i am {0}, my age is {1} and i am waiting for {2}, because i am {0}!",
                              "Michael Ushakov (Evillord666)", "34", "\"Great Success\"")
    assert.Nil(t, err)
    assert.Equal(t, "Hello i am Michael Ushakov (Evillord666), my age is 34 and i am waiting for \"Great Success\", because i am Michael Ushakov (Evillord666)!", strFormatResult)

    strFormatResult, err = Format("We are wondering if these values would be replaced : {5}, {4}, {0}", "one", "two", "three")
    assert.Nil(t, err)
    assert.Equal(t, "We are wondering if these values would be replaced : {5}, {4}, one", strFormatResult)

    strFormatResult, err = Format("No args ... : {0}, {1}, {2}")
    assert.Nil(t, err)
    assert.Equal(t, "No args ... : {0}, {1}, {2}", strFormatResult)
}

func TestStrFormatComplex(t *testing.T) {
    strFormatResult, err := FormatComplex("Hello {user} what are you doing here {app} ?", map[string]string{"user":"vpupkin", "app":"mn_console"})
    assert.Nil(t, err)
    assert.Equal(t, "Hello vpupkin what are you doing here mn_console ?", strFormatResult)
}

What is the time complexity of indexing, inserting and removing from common data structures?

I guess I will start you off with the time complexity of a linked list:

Indexing---->O(n)
Inserting / Deleting at end---->O(1) or O(n)
Inserting / Deleting in middle--->O(1) with iterator O(n) with out

The time complexity for the Inserting at the end depends if you have the location of the last node, if you do, it would be O(1) other wise you will have to search through the linked list and the time complexity would jump to O(n).

Jquery mouseenter() vs mouseover()

The mouseenter event differs from mouseover in the way it handles event bubbling. The mouseenter event, only triggers its handler when the mouse enters the element it is bound to, not a descendant. Refer: https://api.jquery.com/mouseenter/

The mouseleave event differs from mouseout in the way it handles event bubbling. The mouseleave event, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. Refer: https://api.jquery.com/mouseleave/

Which tool to build a simple web front-end to my database

The most rapid option is to hand out MS Access or SQL Sever Management Studio (there's a free express edition) along with a read only account.

PHP is simple and has a well earned reputation for getting stuff done. PHP is excellent for copying and pasting code, and you can iterate insanely fast in PHP. PHP can lead to hard-to-maintain applications, and it can be difficult to set up a visual debugger.

Given that you use SQL Server, ASP.NET is also a good option. This is somewhat harder to setup; you'll need an IIS server, with a configured application. Iterations are a bit slower. ASP.NET is easier to maintain and Visual Studio is the best visual debugger around.

Background color on input type=button :hover state sticks in IE

You need to make sure images come first and put in a comma after the background image call. then it actually does work:

    background:url(egg.png) no-repeat 70px 2px #82d4fe; /* Old browsers */
background:url(egg.png) no-repeat 70px 2px, -moz-linear-gradient(top, #82d4fe 0%, #1db2ff 78%) ; /* FF3.6+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-gradient(linear, left top, left bottom, color-stop(0%,#82d4fe), color-stop(78%,#1db2ff)); /* Chrome,Safari4+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Chrome10+,Safari5.1+ */
background:url(egg.png) no-repeat 70px 2px, -o-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Opera11.10+ */
background:url(egg.png) no-repeat 70px 2px, -ms-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#82d4fe', endColorstr='#1db2ff',GradientType=0 ); /* IE6-9 */
background:url(egg.png) no-repeat 70px 2px, linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* W3C */

Comparing object properties in c#

This works even if the objects are different. you could customize the methods in the utilities class maybe you want to compare private properties as well...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class ObjectA
{
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }
    public string PropertyC { get; set; }
    public DateTime PropertyD { get; set; }

    public string FieldA;
    public DateTime FieldB;
}

class ObjectB
{
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }
    public string PropertyC { get; set; }
    public DateTime PropertyD { get; set; }


    public string FieldA;
    public DateTime FieldB;


}

class Program
{
    static void Main(string[] args)
    {
        // create two objects with same properties
        ObjectA a = new ObjectA() { PropertyA = "test", PropertyB = "test2", PropertyC = "test3" };
        ObjectB b = new ObjectB() { PropertyA = "test", PropertyB = "test2", PropertyC = "test3" };

        // add fields to those objects
        a.FieldA = "hello";
        b.FieldA = "Something differnt";

        if (a.ComparePropertiesTo(b))
        {
            Console.WriteLine("objects have the same properties");
        }
        else
        {
            Console.WriteLine("objects have diferent properties!");
        }


        if (a.CompareFieldsTo(b))
        {
            Console.WriteLine("objects have the same Fields");
        }
        else
        {
            Console.WriteLine("objects have diferent Fields!");
        }

        Console.Read();
    }
}

public static class Utilities
{
    public static bool ComparePropertiesTo(this Object a, Object b)
    {
        System.Reflection.PropertyInfo[] properties = a.GetType().GetProperties(); // get all the properties of object a

        foreach (var property in properties)
        {
            var propertyName = property.Name;

            var aValue = a.GetType().GetProperty(propertyName).GetValue(a, null);
            object bValue;

            try // try to get the same property from object b. maybe that property does
                // not exist! 
            {
                bValue = b.GetType().GetProperty(propertyName).GetValue(b, null);
            }
            catch
            {
                return false;
            }

            if (aValue == null && bValue == null)
                continue;

            if (aValue == null && bValue != null)
                return false;

            if (aValue != null && bValue == null)
               return false;

            // if properties do not match return false
            if (aValue.GetHashCode() != bValue.GetHashCode())
            {
                return false;
            }
        }

        return true;
    }



    public static bool CompareFieldsTo(this Object a, Object b)
    {
        System.Reflection.FieldInfo[] fields = a.GetType().GetFields(); // get all the properties of object a

        foreach (var field in fields)
        {
            var fieldName = field.Name;

            var aValue = a.GetType().GetField(fieldName).GetValue(a);

            object bValue;

            try // try to get the same property from object b. maybe that property does
            // not exist! 
            {
                bValue = b.GetType().GetField(fieldName).GetValue(b);
            }
            catch
            {
                return false;
            }

            if (aValue == null && bValue == null)
               continue;

            if (aValue == null && bValue != null)
               return false;

            if (aValue != null && bValue == null)
               return false;


            // if properties do not match return false
            if (aValue.GetHashCode() != bValue.GetHashCode())
            {
                return false;
            }
        }

        return true;
    }


}

What is the difference between a URI, a URL and a URN?

URIs came about from the need to identify resources on the Web, and other Internet resources such as electronic mailboxes in a uniform and coherent way. So, one can introduce a new type of widget: URIs to identify widget resources or use tel: URIs to have web links cause telephone calls to be made when invoked.

Some URIs provide information to locate a resource (such as a DNS host name and a path on that machine), while some are used as pure resource names. The URL is reserved for identifiers that are resource locators, including 'http' URLs such as http://stackoverflow.com, which identifies the web page at the given path on the host. Another example is 'mailto' URLs, such as mailto:[email protected], which identifies the mailbox at the given address.

URNs are URIs that are used as pure resource names rather than locators. For example, the URI: mid:[email protected] is a URN that identifies the email message containing it in its 'Message-Id' field. The URI serves to distinguish that message from any other email message. But it does not itself provide the message's address in any store.

Change priorityQueue to max priorityqueue

The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time.

The Comparator should override the compare method.

int compare(T o1, T o2)

Default compare method returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

The Default PriorityQueue provided by Java is Min-Heap, If you want a max heap following is the code

public class Sample {
    public static void main(String[] args) {
        PriorityQueue<Integer> q = new PriorityQueue<Integer>(new Comparator<Integer>() {

            public int compare(Integer lhs, Integer rhs) {
                if(lhs<rhs) return +1;
                if(lhs>rhs) return -1;
                return 0;
            }
        });
        q.add(13);
        q.add(4);q.add(14);q.add(-4);q.add(1);
        while (!q.isEmpty()) {
            System.out.println(q.poll());
        }
    }

}

Reference :https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html#comparator()

How do I create a message box with "Yes", "No" choices and a DialogResult?

MessageBox.Show(title, text, messageboxbuttons.yes/no)

This returns a DialogResult which you can check.

For example,

if(MessageBox.Show("","",MessageBoxButtons.YesNo) == DialogResult.Yes)
{
   //do something
}

Constraint Layout Vertical Align Center

 <TextView
        android:id="@+id/tvName"
        style="@style/textViewBoldLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Welcome"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

Why is Node.js single threaded?

Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.

And you know what? In my opinion that theory's been borne out. A node.js app that isn't doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.

The single threaded, async nature does make things complicated. But do you honestly think it's more complicated than threading? One race condition can ruin your entire month! Or empty out your thread pool due to some setting somewhere and watch your response time slow to a crawl! Not to mention deadlocks, priority inversions, and all the other gyrations that go with multithreading.

In the end, I don't think it's universally better or worse; it's different, and sometimes it's better and sometimes it's not. Use the right tool for the job.

Angular 2 Cannot find control with unspecified name attribute on formArrays

Remove the brackets from

[formArrayName]="areas" 

and use only

formArrayName="areas"

This, because with [ ] you are trying to bind a variable, which this is not. Also notice your submit, it should be:

(ngSubmit)="onSubmit(areasForm.value)"

instead of areasForm.values.

How to keep a git branch in sync with master

Run the following commands:

$ git checkout mobiledevice
$ git pull origin master 

This would merge all the latest commits to your branch. If the merge results in some conflicts, you'll need to fix them.

I don't know if this is the best practice but works for me.

How to use LDFLAGS in makefile

Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:

CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm

.PHONY: all
all: client

.PHONY: clean
clean:
    $(RM) *~ *.o client

OBJECTS=client.o
client: $(OBJECTS)
    $(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)

In the line defining the client target change the order of $(LDFLAGS) as needed.

Keras model.summary() result - Understanding the # of Parameters

The number of parameters is 7850 because with every hidden unit you have 784 input weights and one weight of connection with bias. This means that every hidden unit gives you 785 parameters. You have 10 units so it sums up to 7850.

The role of this additional bias term is really important. It significantly increases the capacity of your model. You can read details e.g. here Role of Bias in Neural Networks.

Write Base64-encoded image to file

Assuming the image data is already in the format you want, you don't need image ImageIO at all - you just need to write the data to the file:

// Note preferred way of declaring an array variable
byte[] data = Base64.decodeBase64(crntImage);
try (OutputStream stream = new FileOutputStream("c:/decode/abc.bmp")) {
    stream.write(data);
}

(I'm assuming you're using Java 7 here - if not, you'll need to write a manual try/finally statement to close the stream.)

If the image data isn't in the format you want, you'll need to give more details.

How to shrink/purge ibdata1 file in MySQL

In a new version of mysql-server recipes above will crush "mysql" database. In old version it works. In new some tables switches to table type INNODB, and by doing so you will damage them. The easiest way is to:

  • dump all you databases
  • uninstall mysql-server,
  • add in remained my.cnf:
    [mysqld]
    innodb_file_per_table=1
  • erase all in /var/lib/mysql
  • install mysql-server
  • restore users and databases

Convert date formats in bash

Just with bash:

convert_date () {
    local months=( JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC )
    local i
    for (( i=0; i<11; i++ )); do
        [[ $2 = ${months[$i]} ]] && break
    done
    printf "%4d%02d%02d\n" $3 $(( i+1 )) $1
}

And invoke it like this

d=$( convert_date 27 JUN 2011 )

Or if the "old" date string is stored in a variable

d_old="27 JUN 2011"
d=$( convert_date $d_old )  # not quoted

Send mail via CMD console

A couple more command-line mailer programs:

Both support SSL too.

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

How do you compare two version Strings in Java?

/**  
 *  written by: Stan Towianski - May 2018 
 * notes: I make assumption each of 3 version sections a.b.c is not longer then 4 digits: aaaa.bbbb.cccc-MODWORD1(-)modnum2
 * 5.10.13-release-1 becomes 0000500100013.501     6.0-snapshot becomes 0000600000000.100
 * MODWORD1 = -xyz/NotMatching, -SNAPSHOT, -ALPHA, -BETA, -RC, -RELEASE/nothing  return:  .0, .1, .2, .3, .4, .5
 * modnum2 = up to 2 digit/chars second version
 * */
public class VersionCk {

    private static boolean isVersionHigher( String baseVersion, String testVersion )
        {
        System.out.println( "versionToComparable( baseVersion ) =" + versionToComparable( baseVersion ) );
        System.out.println( "versionToComparable( testVersion ) =" + versionToComparable( testVersion ) + " is this higher ?" );
        return versionToComparable( testVersion ).compareTo( versionToComparable( baseVersion ) ) > 0;
        }

    //----  not worrying about += for something so small
    private static String versionToComparable( String version )
        {
//        System.out.println("version - " + version);
        String versionNum = version;
        int at = version.indexOf( '-' );
        if ( at >= 0 )
            versionNum = version.substring( 0, at );

        String[] numAr = versionNum.split( "\\." );
        String versionFormatted = "0";
        for ( String tmp : numAr )
            {
            versionFormatted += String.format( "%4s", tmp ).replace(' ', '0');
            }
        while ( versionFormatted.length() < 12 )  // pad out to aaaa.bbbb.cccc
            {
            versionFormatted += "0000";
            }
//        System.out.println( "converted min version =" + versionFormatted + "=   : " + versionNum );
        return versionFormatted + getVersionModifier( version, at );
        }

    //----  use order low to high: -xyz, -SNAPSHOT, -ALPHA, -BETA, -RC, -RELEASE/nothing  returns: 0, 1, 2, 3, 4, 5
    private static String getVersionModifier( String version, int at )
        {
//        System.out.println("version - " + version );
        String[] wordModsAr = { "-SNAPSHOT", "-ALPHA", "-BETA", "-RC", "-RELEASE" };        

        if ( at < 0 )
            return "." + wordModsAr.length + "00";   // make nothing = RELEASE level

        int i = 1;
        for ( String word : wordModsAr )
            {
            if ( ( at = version.toUpperCase().indexOf( word ) ) > 0 )
                return "." + i + getSecondVersionModifier( version.substring( at + word.length() ) );
            i++;
            }

        return ".000";
        }

    //----  add 2 chars for any number after first modifier.  -rc2 or -rc-2   returns 02
    private static String getSecondVersionModifier( String version )
        {
        System.out.println( "second modifier =" + version + "=" );
        Matcher m = Pattern.compile("(.*?)(\\d+).*").matcher( version );
//        if ( m.matches() )
//            System.out.println( "match ? =" + m.matches() + "=   m.group(1) =" + m.group(1) + "=   m.group(2) =" + m.group(2) + "=   m.group(3) =" + (m.groupCount() >= 3 ? m.group(3) : "x") );
//        else
//            System.out.println( "No match" );
        return m.matches() ? String.format( "%2s", m.group(2) ).replace(' ', '0') : "00";
        }

    public static void main(String[] args) 
        {
        checkVersion( "3.10.0", "3.4.0");
        checkVersion( "5.4.2", "5.4.1");
        checkVersion( "5.4.4", "5.4.5");
        checkVersion( "5.4.9", "5.4.12");
        checkVersion( "5.9.222", "5.10.12");
        checkVersion( "5.10.12", "5.10.12");
        checkVersion( "5.10.13", "5.10.14");
        checkVersion( "6.7.0", "6.8");
        checkVersion( "6.7", "2.7.0");
        checkVersion( "6", "6.3.1");
        checkVersion( "4", "4.0.0");
        checkVersion( "6.3.0", "6");
        checkVersion( "5.10.12-Alpha", "5.10.12-beTA");
        checkVersion( "5.10.13-release", "5.10.14-beta");
        checkVersion( "6.7.0", "6.8-snapshot");
        checkVersion( "6.7.1", "6.7.0-release");
        checkVersion( "6-snapshot", "6.0.0-beta");
        checkVersion( "6.0-snapshot", "6.0.0-whatthe");
        checkVersion( "5.10.12-Alpha-1", "5.10.12-alpha-2");
        checkVersion( "5.10.13-release-1", "5.10.13-release2");
        checkVersion( "10-rc42", "10.0.0-rc53");
        }

    private static void checkVersion(String baseVersion, String testVersion) 
        {
        System.out.println( "baseVersion - " + baseVersion );
        System.out.println( "testVersion - " + testVersion );
        System.out.println( "isVersionHigher = " + isVersionHigher( baseVersion, testVersion ) );
        System.out.println( "---------------");
        }

    }

some output:

---------------
baseVersion - 6.7
testVersion - 2.7.0
versionToComparable( baseVersion ) =0000600070000.500
versionToComparable( testVersion ) =0000200070000.500 is this higher ?
isVersionHigher = false
---------------
baseVersion - 6
testVersion - 6.3.1
versionToComparable( baseVersion ) =0000600000000.500
versionToComparable( testVersion ) =0000600030001.500 is this higher ?
isVersionHigher = true
---------------
baseVersion - 4
testVersion - 4.0.0
versionToComparable( baseVersion ) =0000400000000.500
versionToComparable( testVersion ) =0000400000000.500 is this higher ?
isVersionHigher = false
---------------
baseVersion - 6.3.0
testVersion - 6
versionToComparable( baseVersion ) =0000600030000.500
versionToComparable( testVersion ) =0000600000000.500 is this higher ?
isVersionHigher = false
---------------
baseVersion - 5.10.12-Alpha
testVersion - 5.10.12-beTA
second modifier ==
versionToComparable( baseVersion ) =0000500100012.200
second modifier ==
versionToComparable( testVersion ) =0000500100012.300 is this higher ?
second modifier ==
second modifier ==
isVersionHigher = true
---------------
baseVersion - 5.10.13-release
testVersion - 5.10.14-beta
second modifier ==
versionToComparable( baseVersion ) =0000500100013.500
second modifier ==
versionToComparable( testVersion ) =0000500100014.300 is this higher ?
second modifier ==
second modifier ==
isVersionHigher = true
---------------
baseVersion - 6.7.0
testVersion - 6.8-snapshot
versionToComparable( baseVersion ) =0000600070000.500
second modifier ==
versionToComparable( testVersion ) =0000600080000.100 is this higher ?
second modifier ==
isVersionHigher = true
---------------
baseVersion - 6.7.1
testVersion - 6.7.0-release
versionToComparable( baseVersion ) =0000600070001.500
second modifier ==
versionToComparable( testVersion ) =0000600070000.500 is this higher ?
second modifier ==
isVersionHigher = false
---------------
baseVersion - 6-snapshot
testVersion - 6.0.0-beta
second modifier ==
versionToComparable( baseVersion ) =0000600000000.100
second modifier ==
versionToComparable( testVersion ) =0000600000000.300 is this higher ?
second modifier ==
second modifier ==
isVersionHigher = true
---------------
baseVersion - 6.0-snapshot
testVersion - 6.0.0-whatthe
second modifier ==
versionToComparable( baseVersion ) =0000600000000.100
versionToComparable( testVersion ) =0000600000000.000 is this higher ?
second modifier ==
isVersionHigher = false
---------------
baseVersion - 5.10.12-Alpha-1
testVersion - 5.10.12-alpha-2
second modifier =-1=
versionToComparable( baseVersion ) =0000500100012.201
second modifier =-2=
versionToComparable( testVersion ) =0000500100012.202 is this higher ?
second modifier =-2=
second modifier =-1=
isVersionHigher = true
---------------
baseVersion - 5.10.13-release-1
testVersion - 5.10.13-release2
second modifier =-1=
versionToComparable( baseVersion ) =0000500100013.501
second modifier =2=
versionToComparable( testVersion ) =0000500100013.502 is this higher ?
second modifier =2=
second modifier =-1=
isVersionHigher = true
---------------
baseVersion - 10-rc42
testVersion - 10.0.0-rc53
second modifier =42=
versionToComparable( baseVersion ) =0001000000000.442
second modifier =53=
versionToComparable( testVersion ) =0001000000000.453 is this higher ?
second modifier =53=
second modifier =42=
isVersionHigher = true
---------------

Python: convert string from UTF-8 to Latin-1

data="UTF-8 data"
udata=data.decode("utf-8")
data=udata.encode("latin-1","ignore")

Should do it.

How to margin the body of the page (html)?

Try using CSS.

body {
   margin: 0 0 auto 0;
}

The order is clockwise from the top, so top right bottom left.

ORA-01008: not all variables bound. They are bound

I'd a similar problem in a legacy application, but de "--" was string parameter.

Ex.:

Dim cmd As New OracleCommand("INSERT INTO USER (name, address, photo) VALUES ('User1', '--', :photo)", oracleConnection)
Dim fs As IO.FileStream = New IO.FileStream("c:\img.jpg", IO.FileMode.Open)
Dim br As New IO.BinaryReader(fs)
cmd.Parameters.Add(New OracleParameter("photo", OracleDbType.Blob)).Value = br.ReadBytes(fs.Length)
cmd.ExecuteNonQuery() 'here throws ORA-01008

Changing address parameter value '--' to '00' or other thing, works.

Why is it bad style to `rescue Exception => e` in Ruby?

The real rule is: Don't throw away exceptions. The objectivity of the author of your quote is questionable, as evidenced by the fact that it ends with

or I will stab you

Of course, be aware that signals (by default) throw exceptions, and normally long-running processes are terminated through a signal, so catching Exception and not terminating on signal exceptions will make your program very hard to stop. So don't do this:

#! /usr/bin/ruby

while true do
  begin
    line = STDIN.gets
    # heavy processing
  rescue Exception => e
    puts "caught exception #{e}! ohnoes!"
  end
end

No, really, don't do it. Don't even run that to see if it works.

However, say you have a threaded server and you want all exceptions to not:

  1. be ignored (the default)
  2. stop the server (which happens if you say thread.abort_on_exception = true).

Then this is perfectly acceptable in your connection handling thread:

begin
  # do stuff
rescue Exception => e
  myLogger.error("uncaught #{e} exception while handling connection: #{e.message}")
    myLogger.error("Stack trace: #{backtrace.map {|l| "  #{l}\n"}.join}")
end

The above works out to a variation of Ruby's default exception handler, with the advantage that it doesn't also kill your program. Rails does this in its request handler.

Signal exceptions are raised in the main thread. Background threads won't get them, so there is no point in trying to catch them there.

This is particularly useful in a production environment, where you do not want your program to simply stop whenever something goes wrong. Then you can take the stack dumps in your logs and add to your code to deal with specific exception further down the call chain and in a more graceful manner.

Note also that there is another Ruby idiom which has much the same effect:

a = do_something rescue "something else"

In this line, if do_something raises an exception, it is caught by Ruby, thrown away, and a is assigned "something else".

Generally, don't do that, except in special cases where you know you don't need to worry. One example:

debugger rescue nil

The debugger function is a rather nice way to set a breakpoint in your code, but if running outside a debugger, and Rails, it raises an exception. Now theoretically you shouldn't be leaving debug code lying around in your program (pff! nobody does that!) but you might want to keep it there for a while for some reason, but not continually run your debugger.

Note:

  1. If you've run someone else's program that catches signal exceptions and ignores them, (say the code above) then:

    • in Linux, in a shell, type pgrep ruby, or ps | grep ruby, look for your offending program's PID, and then run kill -9 <PID>.
    • in Windows, use the Task Manager (CTRL-SHIFT-ESC), go to the "processes" tab, find your process, right click it and select "End process".
  2. If you are working with someone else's program which is, for whatever reason, peppered with these ignore-exception blocks, then putting this at the top of the mainline is one possible cop-out:

    %W/INT QUIT TERM/.each { |sig| trap sig,"SYSTEM_DEFAULT" }
    

    This causes the program to respond to the normal termination signals by immediately terminating, bypassing exception handlers, with no cleanup. So it could cause data loss or similar. Be careful!

  3. If you need to do this:

    begin
      do_something
    rescue Exception => e
      critical_cleanup
      raise
    end
    

    you can actually do this:

    begin
      do_something
    ensure
      critical_cleanup
    end
    

    In the second case, critical cleanup will be called every time, whether or not an exception is thrown.